text
stringlengths 0
3.34M
|
---|
function qr=v_rotqc2qr(qc)
%V_ROTQC2QR converts a matrix of complex quaternion row vectors into real form
%
% Inputs:
%
% QC(2m,...) array of complex-valued quaternions
%
% Outputs:
%
% QR(4m,...) array of real-valued quaternions
%
% The complex-valued quaternion [r+j*b a+j*c] becomes [r a b c]
%
% Copyright (C) Mike Brookes 2000-2018
% Version: $Id: v_rotqc2qr.m 10865 2018-09-21 17:22:45Z dmb $
%
% 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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent a b
if isempty(a)
a=[1 3 2 4];
end
s=size(qc);
s(1)=2*s(1); % each complex number needs two reals
qr=reshape([real(qc(:).'); imag(qc(:).')],4,[]);
qr=reshape(qr(a,:),s);
if ~nargout
qr=qr(1:4); % just select the first one
v_rotqr2ro(qr(:)); % plot a rotated cube
end
|
If $f(x) = o(g(x))$, then $|f(x)|^p = o(|g(x)|^p)$ for any $p > 0$. |
Formal statement is: lemma analytic_on_UN: "f analytic_on (\<Union>i\<in>I. S i) \<longleftrightarrow> (\<forall>i\<in>I. f analytic_on (S i))" Informal statement is: A function is analytic on the union of a collection of sets if and only if it is analytic on each set in the collection. |
(*
Copyright (C) 2017 M.A.L. Marques
2019 Susi Lehtola
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
(* type: gga_exc *)
(* prefix:
gga_x_am05_params *params;
assert(p->params != NULL);
params = (gga_x_am05_params * )(p->params);
*)
am05_d := 28.23705740248932030511071641312341561894: (* POW(CBRT(4/3) * 2*M_PI/3, 4) *)
am05_csi := s -> (3/2 * LambertW(s^(3/2) / (2*sqrt(6))))^(2/3):
am05_fb := s -> Pi/3 * s/(am05_csi(s) * (am05_d + am05_csi(s)^2)^(1/4)):
am05_flaa := s -> (1 + params_a_c*s^2)/(1 + params_a_c*s^2/am05_fb(s)):
am05_XX := s -> 1 - params_a_alpha*s^2/(1 + params_a_alpha*s^2):
am05_f := x -> am05_XX(X2S*x) + (1 - am05_XX(X2S*x))*am05_flaa(X2S*x):
f := (rs, zeta, xt, xs0, xs1) -> gga_exchange(am05_f, rs, zeta, xs0, xs1):
|
section \<open>Operation Identification Phase\<close>
theory Sepref_Id_Op
imports
Main
Automatic_Refinement.Refine_Lib
Automatic_Refinement.Autoref_Tagging
Refine_Imperative_HOL.Named_Theorems_Rev
begin
text \<open>
The operation identification phase is adapted from the Autoref tool.
The basic idea is to have a type system, which works on so called
interface types (also called conceptual types). Each conceptual type
denotes an abstract data type, e.g., set, map, priority queue.
Each abstract operation, which must be a constant applied to its arguments,
is assigned a conceptual type. Additionally, there is a set of
{\emph pattern rewrite rules},
which are applied to subterms before type inference takes place, and
which may be backtracked over.
This way, encodings of abstract operations in Isabelle/HOL, like
@{term [source] "\<lambda>_. None"} for the empty map,
or @{term [source] "fun_upd m k (Some v)"} for map update, can be rewritten
to abstract operations, and get properly typed.
\<close>
subsection "Proper Protection of Term"
text \<open> The following constants are meant to encode abstraction and
application as proper HOL-constants, and thus avoid strange effects with
HOL's higher-order unification heuristics and automatic
beta and eta-contraction.
The first step of operation identification is to protect the term
by replacing all function applications and abstractions be
the constants defined below.
\<close>
definition [simp]: "PROTECT2 x (y::prop) \<equiv> x"
consts DUMMY :: "prop"
abbreviation PROTECT2_syn ("'(#_#')") where "PROTECT2_syn t \<equiv> PROTECT2 t DUMMY"
abbreviation (input)ABS2 :: "('a\<Rightarrow>'b)\<Rightarrow>'a\<Rightarrow>'b" (binder "\<lambda>\<^sub>2" 10)
where "ABS2 f \<equiv> (\<lambda>x. PROTECT2 (f x) DUMMY)"
lemma beta: "(\<lambda>\<^sub>2x. f x)$x \<equiv> f x" by simp
text \<open>
Another version of @{const "APP"}. Treated like @{const APP} by our tool.
Required to avoid infinite pattern rewriting in some cases, e.g., map-lookup.
\<close>
definition APP' (infixl "$''" 900) where [simp, autoref_tag_defs]: "f$'a \<equiv> f a"
text \<open>
Sometimes, whole terms should be protected from being processed by our tool.
For example, our tool should not look into numerals. For this reason,
the \<open>PR_CONST\<close> tag indicates terms that our tool shall handle as
atomic constants, an never look into them.
The special form \<open>UNPROTECT\<close> can be used inside pattern rewrite rules.
It has the effect to revert the protection from its argument, and then wrap
it into a \<open>PR_CONST\<close>.
\<close>
definition [simp, autoref_tag_defs]: "PR_CONST x \<equiv> x" \<comment> \<open>Tag to protect constant\<close>
definition [simp, autoref_tag_defs]: "UNPROTECT x \<equiv> x" \<comment> \<open>Gets
converted to @{term PR_CONST}, after unprotecting its content\<close>
subsection \<open>Operation Identification\<close>
text \<open> Indicator predicate for conceptual typing of a constant \<close>
definition intf_type :: "'a \<Rightarrow> 'b itself \<Rightarrow> bool" (infix "::\<^sub>i" 10) where
[simp]: "c::\<^sub>iI \<equiv> True"
lemma itypeI: "c::\<^sub>iI" by simp
lemma itypeI': "intf_type c TYPE('T)" by (rule itypeI)
lemma itype_self: "(c::'a) ::\<^sub>i TYPE('a)" by simp
definition CTYPE_ANNOT :: "'b \<Rightarrow> 'a itself \<Rightarrow> 'b" (infix ":::\<^sub>i" 10) where
[simp]: "c:::\<^sub>iI \<equiv> c"
text \<open> Wrapper predicate for an conceptual type inference \<close>
definition ID :: "'a \<Rightarrow> 'a \<Rightarrow> 'c itself \<Rightarrow> bool"
where [simp]: "ID t t' T \<equiv> t=t'"
subsubsection \<open>Conceptual Typing Rules\<close>
lemma ID_unfold_vars: "ID x y T \<Longrightarrow> x\<equiv>y" by simp
lemma ID_PR_CONST_trigger: "ID (PR_CONST x) y T \<Longrightarrow> ID (PR_CONST x) y T" .
lemma pat_rule:
"\<lbrakk> p\<equiv>p'; ID p' t' T \<rbrakk> \<Longrightarrow> ID p t' T" by simp
lemma app_rule:
"\<lbrakk> ID f f' TYPE('a\<Rightarrow>'b); ID x x' TYPE('a)\<rbrakk> \<Longrightarrow> ID (f$x) (f'$x') TYPE('b)"
by simp
lemma app'_rule:
"\<lbrakk> ID f f' TYPE('a\<Rightarrow>'b); ID x x' TYPE('a)\<rbrakk> \<Longrightarrow> ID (f$'x) (f'$x') TYPE('b)"
by simp
lemma abs_rule:
"\<lbrakk> \<And>x x'. ID x x' TYPE('a) \<Longrightarrow> ID (t x) (t' x x') TYPE('b) \<rbrakk> \<Longrightarrow>
ID (\<lambda>\<^sub>2x. t x) (\<lambda>\<^sub>2x'. t' x' x') TYPE('a\<Rightarrow>'b)"
by simp
lemma id_rule: "c::\<^sub>iI \<Longrightarrow> ID c c I" by simp
lemma annot_rule: "ID t t' I \<Longrightarrow> ID (t:::\<^sub>iI) t' I"
by simp
lemma fallback_rule:
"ID (c::'a) c TYPE('c)"
by simp
lemma unprotect_rl1: "ID (PR_CONST x) t T \<Longrightarrow> ID (UNPROTECT x) t T"
by simp
subsection \<open> ML-Level code \<close>
ML \<open>
infix 0 THEN_ELSE_COMB'
signature ID_OP_TACTICAL = sig
val SOLVE_FWD: tactic' -> tactic'
val DF_SOLVE_FWD: bool -> tactic' -> tactic'
end
structure Id_Op_Tactical :ID_OP_TACTICAL = struct
fun SOLVE_FWD tac i st = SOLVED' (
tac
THEN_ALL_NEW_FWD (SOLVE_FWD tac)) i st
(* Search for solution with DFS-strategy. If dbg-flag is given,
return sequence of stuck states if no solution is found.
*)
fun DF_SOLVE_FWD dbg tac = let
val stuck_list_ref = Unsynchronized.ref []
fun stuck_tac _ st = if dbg then (
stuck_list_ref := st :: !stuck_list_ref;
Seq.empty
) else Seq.empty
fun rec_tac i st = (
(tac THEN_ALL_NEW_FWD (SOLVED' rec_tac))
ORELSE' stuck_tac
) i st
fun fail_tac _ _ = if dbg then
Seq.of_list (rev (!stuck_list_ref))
else Seq.empty
in
rec_tac ORELSE' fail_tac
end
end
\<close>
named_theorems_rev id_rules "Operation identification rules"
named_theorems_rev pat_rules "Operation pattern rules"
named_theorems_rev def_pat_rules "Definite operation pattern rules (not backtracked over)"
ML \<open>
structure Id_Op = struct
fun id_a_conv cnv ct = case Thm.term_of ct of
@{mpat "ID _ _ _"} => Conv.fun_conv (Conv.fun_conv (Conv.arg_conv cnv)) ct
| _ => raise CTERM("id_a_conv",[ct])
fun
protect env (@{mpat "?t:::\<^sub>i?I"}) = let
val t = protect env t
in
@{mk_term env: "?t:::\<^sub>i?I"}
end
| protect _ (t as @{mpat "PR_CONST _"}) = t
| protect env (t1$t2) = let
val t1 = protect env t1
val t2 = protect env t2
in
@{mk_term env: "?t1.0 $ ?t2.0"}
end
| protect env (Abs (x,T,t)) = let
val t = protect (T::env) t
in
@{mk_term env: "\<lambda>v_x::?'v_T. PROTECT2 ?t DUMMY"}
end
| protect _ t = t
fun protect_conv ctxt = Refine_Util.f_tac_conv ctxt
(protect [])
(simp_tac
(put_simpset HOL_basic_ss ctxt addsimps @{thms PROTECT2_def APP_def}) 1)
fun unprotect_conv ctxt
= Simplifier.rewrite (put_simpset HOL_basic_ss ctxt
addsimps @{thms PROTECT2_def APP_def})
fun do_unprotect_tac ctxt =
resolve_tac ctxt @{thms unprotect_rl1} THEN'
CONVERSION (Refine_Util.HOL_concl_conv (fn ctxt => id_a_conv (unprotect_conv ctxt)) ctxt)
val cfg_id_debug =
Attrib.setup_config_bool @{binding id_debug} (K false)
val cfg_id_trace_fallback =
Attrib.setup_config_bool @{binding id_trace_fallback} (K false)
fun dest_id_rl thm = case Thm.concl_of thm of
@{mpat (typs) "Trueprop (?c::\<^sub>iTYPE(?'v_T))"} => (c,T)
| _ => raise THM("dest_id_rl",~1,[thm])
val add_id_rule = snd oo Thm.proof_attributes [Named_Theorems_Rev.add @{named_theorems_rev id_rules}]
datatype id_tac_mode = Init | Step | Normal | Solve
fun id_tac ss ctxt = let
open Id_Op_Tactical
val certT = Thm.ctyp_of ctxt
val cert = Thm.cterm_of ctxt
val thy = Proof_Context.theory_of ctxt
val id_rules = Named_Theorems_Rev.get ctxt @{named_theorems_rev id_rules}
val pat_rules = Named_Theorems_Rev.get ctxt @{named_theorems_rev pat_rules}
val def_pat_rules = Named_Theorems_Rev.get ctxt @{named_theorems_rev def_pat_rules}
val rl_net = Tactic.build_net (
(pat_rules |> map (fn thm => thm RS @{thm pat_rule}))
@ @{thms annot_rule app_rule app'_rule abs_rule}
@ (id_rules |> map (fn thm => thm RS @{thm id_rule}))
)
val def_rl_net = Tactic.build_net (
(def_pat_rules |> map (fn thm => thm RS @{thm pat_rule}))
)
val id_pr_const_rename_tac =
resolve_tac ctxt @{thms ID_PR_CONST_trigger} THEN'
Subgoal.FOCUS (fn { context=ctxt, prems, ... } =>
let
fun is_ID @{mpat "Trueprop (ID _ _ _)"} = true | is_ID _ = false
val prems = filter (Thm.prop_of #> is_ID) prems
val eqs = map (fn thm => thm RS @{thm ID_unfold_vars}) prems
val conv = Conv.rewrs_conv eqs
val conv = fn ctxt => (Conv.top_sweep_conv (K conv) ctxt)
val conv = fn ctxt => Conv.fun2_conv (Conv.arg_conv (conv ctxt))
val conv = Refine_Util.HOL_concl_conv conv ctxt
in CONVERSION conv 1 end
) ctxt THEN'
resolve_tac ctxt @{thms id_rule} THEN'
resolve_tac ctxt id_rules
val ityping = id_rules
|> map dest_id_rl
|> filter (is_Const o #1)
|> map (apfst (#1 o dest_Const))
|> Symtab.make_list
val has_type = Symtab.defined ityping
fun mk_fallback name cT =
case try (Sign.the_const_constraint thy) name of
SOME T => try (Thm.instantiate'
[SOME (certT cT), SOME (certT T)] [SOME (cert (Const (name,cT)))])
@{thm fallback_rule}
| NONE => NONE
fun trace_fallback thm =
Config.get ctxt cfg_id_trace_fallback
andalso let
open Pretty
val p = block [str "ID_OP: Applying fallback rule: ", Thm.pretty_thm ctxt thm]
in
string_of p |> tracing;
false
end
val fallback_tac = CONVERSION Thm.eta_conversion THEN' IF_EXGOAL (fn i => fn st =>
case Logic.concl_of_goal (Thm.prop_of st) i of
@{mpat "Trueprop (ID (mpaq_STRUCT (mpaq_Const ?name ?cT)) _ _)"} => (
if not (has_type name) then
case mk_fallback name cT of
SOME thm => (trace_fallback thm; resolve_tac ctxt [thm] i st)
| NONE => Seq.empty
else Seq.empty
)
| _ => Seq.empty)
val init_tac = CONVERSION (
Refine_Util.HOL_concl_conv (fn ctxt => (id_a_conv (protect_conv ctxt)))
ctxt
)
val step_tac = (FIRST' [
assume_tac ctxt,
eresolve_tac ctxt @{thms id_rule},
resolve_from_net_tac ctxt def_rl_net,
resolve_from_net_tac ctxt rl_net,
id_pr_const_rename_tac,
do_unprotect_tac ctxt,
fallback_tac])
val solve_tac = DF_SOLVE_FWD (Config.get ctxt cfg_id_debug) step_tac
in
case ss of
Init => init_tac
| Step => step_tac
| Normal => init_tac THEN' solve_tac
| Solve => solve_tac
end
end
\<close>
subsection \<open>Default Setup\<close>
subsubsection \<open>Numerals\<close>
lemma pat_numeral[def_pat_rules]: "numeral$x \<equiv> UNPROTECT (numeral$x)" by simp
lemma id_nat_const[id_rules]: "(PR_CONST (a::nat)) ::\<^sub>i TYPE(nat)" by simp
lemma id_int_const[id_rules]: "(PR_CONST (a::int)) ::\<^sub>i TYPE(int)" by simp
(*subsection \<open>Example\<close>
schematic_lemma
"ID (\<lambda>a b. (b(1::int\<mapsto>2::nat) |`(-{3})) a, Map.empty, \<lambda>a. case a of None \<Rightarrow> Some a | Some _ \<Rightarrow> None) (?c) (?T::?'d itself)"
(*"TERM (?c,?T)"*)
using [[id_debug]]
apply (tactic {* Id_Op.id_tac Id_Op.Normal @{context} 1 *})
done
*)
end
|
(* Title: HOL/Auth/n_g2kAbsAfter_lemma_on_inv__5.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_g2kAbsAfter Protocol Case Study*}
theory n_g2kAbsAfter_lemma_on_inv__5 imports n_g2kAbsAfter_base
begin
section{*All lemmas on causal relation between inv__5 and some rule r*}
lemma n_n_Store_i1Vsinv__5:
assumes a1: "(\<exists> d. d\<le>N\<and>r=n_n_Store_i1 d)" and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain d where a1:"d\<le>N\<and>r=n_n_Store_i1 d" apply fastforce done
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (neg (eqn (IVar (Field (Ident ''ACache_1'') ''State'')) (Const I))) (eqn (IVar (Field (Ident ''Cache_1'') ''State'')) (Const E))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_AStore_i1Vsinv__5:
assumes a1: "(\<exists> d. d\<le>N\<and>r=n_n_AStore_i1 d)" and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain d where a1:"d\<le>N\<and>r=n_n_AStore_i1 d" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ASendInvAck_i1Vsinv__5:
assumes a1: "(r=n_n_ASendInvAck_i1 )" and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ARecvGntS_i1Vsinv__5:
assumes a1: "(r=n_n_ARecvGntS_i1 )" and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (neg (eqn (IVar (Field (Ident ''AChan2_1'') ''Data'')) (IVar (Ident ''AuxData'')))) (eqn (IVar (Field (Ident ''AChan2_1'') ''Cmd'')) (Const GntS))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_ARecvGntE_i1Vsinv__5:
assumes a1: "(r=n_n_ARecvGntE_i1 )" and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
have "?P3 s"
apply (cut_tac a1 a2 , simp, rule_tac x="(neg (andForm (neg (eqn (IVar (Field (Ident ''AChan2_1'') ''Data'')) (IVar (Ident ''AuxData'')))) (eqn (IVar (Field (Ident ''AChan2_1'') ''Cmd'')) (Const GntE))))" in exI, auto) done
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_n_RecvReq_i1Vsinv__5:
assumes a1: "r=n_n_RecvReq_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendInvS_i1Vsinv__5:
assumes a1: "r=n_n_SendInvS_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqEI_i1Vsinv__5:
assumes a1: "r=n_n_SendReqEI_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqEI_i1Vsinv__5:
assumes a1: "r=n_n_ASendReqEI_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqIS_j1Vsinv__5:
assumes a1: "r=n_n_ASendReqIS_j1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendGntE_i1Vsinv__5:
assumes a1: "r=n_n_SendGntE_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqES_i1Vsinv__5:
assumes a1: "r=n_n_ASendReqES_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendGntS_i1Vsinv__5:
assumes a1: "r=n_n_ASendGntS_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendInvE_i1Vsinv__5:
assumes a1: "r=n_n_ASendInvE_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendGntS_i1Vsinv__5:
assumes a1: "r=n_n_SendGntS_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendInvS_i1Vsinv__5:
assumes a1: "r=n_n_ASendInvS_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqES_i1Vsinv__5:
assumes a1: "r=n_n_SendReqES_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendInvE_i1Vsinv__5:
assumes a1: "r=n_n_SendInvE_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendReqSE_j1Vsinv__5:
assumes a1: "r=n_n_ASendReqSE_j1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_RecvGntS_i1Vsinv__5:
assumes a1: "r=n_n_RecvGntS_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqEE_i1Vsinv__5:
assumes a1: "r=n_n_SendReqEE_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_RecvInvAck_i1Vsinv__5:
assumes a1: "r=n_n_RecvInvAck_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_RecvGntE_i1Vsinv__5:
assumes a1: "r=n_n_RecvGntE_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ARecvReq_i1Vsinv__5:
assumes a1: "r=n_n_ARecvReq_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendReqS_j1Vsinv__5:
assumes a1: "r=n_n_SendReqS_j1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ARecvInvAck_i1Vsinv__5:
assumes a1: "r=n_n_ARecvInvAck_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_SendInvAck_i1Vsinv__5:
assumes a1: "r=n_n_SendInvAck_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_n_ASendGntE_i1Vsinv__5:
assumes a1: "r=n_n_ASendGntE_i1 " and
a2: "(f=inv__5 )"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
+incdir+${UEX}/impl/sv/svsrc
${UEX}/impl/sv/svsrc/uex_pkg.sv
|
###################################################################
# ELECTRONICS.PY
#
# A library of functions, constants and more that are related
# to Power-Electronics and converters in Electrical Engineering.
#
# April 10th, 2019
#
# Written by Joe Stanley
#
# Special Thanks To:
# Dr. Brian Johnson - Faculty University of Idaho
#
# Included Functions:
# - VSC DC Bus Voltage Calculator: vscdcbus
# - PLL-VSC Gains Calculator: vscgains
####################################################################
# Import the Necessary Library
import numpy as np
# Define function to find VDC setpoint
def vscdcbus(VLL,Zs,P,Q=0,mmax=0.8,debug=False):
"""
VSCDCBUS Function:
Purpose:
--------
The purpose of this function is to calculate the
required DC-bus voltage for a Voltage-Sourced-
Converter (VSC) given the desired P/Q parameters
and the known source impedance (Vs) of the VSC.
Required Arguments:
-------------------
VLL: Line-to-Line voltage on the line-side of
the source impedance.
Zs: The source impedance of the VSC
P: The desired real-power output
Optional Arguments:
Q: The desired reactive-power output, default=0
mmax: The maximum of the m value for the converter
default=0.8
debug: Control value to enable printing stages of
the calculation, default=False
Return:
-------
VDC: The DC bus voltage.
"""
# Determine the Load Current
Iload = np.conj((P+1j*Q) / (VLL*np.sqrt(3)))
# Evaluate the Terminal Voltage
Vtln = abs(VLL/np.sqrt(3) + Iload*Zs)
# Find the Peak Terminal Voltage
Vtpk = np.sqrt(2)*Vtln
# Calculate the VDC value
VDC = 2*Vtpk / mmax
if debug:
print("Iload", Iload)
print("Vtln", Vtln)
print("Vtpk", Vtpk)
print("VDC", VDC)
return(VDC)
# Define kp/ki/w0L calculating function
def vscgains(Rs,Ls,tau=0.005,f=60):
"""
VSCGAINS Function:
Purpose:
--------
This function is designed to calculate the kp, ki,
and omega-not-L values for a Phase-Lock-Loop based VSC.
Required Arguments:
-------------------
Rs: The equiv-resistance (in ohms) of the VSC
Ls: The equiv-inductance (in Henrys) of the VSC
Optional Arguments:
-------------------
tau: The desired time-constant, default=0.005
f: The system frequency (in Hz), default=60
Returns:
--------
kp: The Kp-Gain Value
ki: The Ki-Gain Value
w0L: The omega-not-L gain value
"""
# Calculate kp
kp = Ls / tau
# Calculate ki
ki = kp*Rs/Ls
# Calculate w0L
w0L = 2*np.pi*f*Ls
return(kp,ki,w0L) |
#pragma once
#include <gsl/span>
#include "simple_math.h"
constexpr auto VECTOR_SIZE = sizeof(float) * 4;
class CBufferBase;
struct CBufferAlign
{
size_t size;
explicit CBufferAlign(size_t size_ = VECTOR_SIZE) : size(size_) {}
};
__forceinline CBufferAlign cbuff_align(size_t size = VECTOR_SIZE)
{
return CBufferAlign(size);
}
class ICBuffer
{
public:
virtual ~ICBuffer() = default;
virtual void write(CBufferBase& cbuf) const = 0;
size_t cbuffer_size() const;
template <typename T>
static size_t cbuffer_size()
{
T t;
return t.cbuffer_size();
}
};
class CBufferBase
{
protected:
size_t offset_ = 0;
size_t alignment_ = 0;
public:
virtual ~CBufferBase() = default;
bool align(size_t size = VECTOR_SIZE);
void add(size_t size);
void reset();
size_t offset() const { return offset_; }
size_t alignment() const { return alignment_; }
template <typename T>
CBufferBase& operator<<(const T& data) = delete;
template <typename T>
CBufferBase& operator<<(const gsl::span<T>& data) = delete;
template <typename T>
CBufferBase& operator<<(const gsl::span<const T>& data) = delete;
CBufferBase& operator<<(const CBufferAlign& align_of);
template <typename T, size_t size>
__forceinline CBufferBase& operator<<(const std::array<T, size>& array)
{
return *this << gsl::span<const T>(array);
}
template <typename T, size_t size>
__forceinline CBufferBase& operator<<(const T(&array)[size])
{
return *this << gsl::span<const T>(array);
}
template <typename T>
__forceinline CBufferBase& operator<<(const dirty_t<T>& value)
{
return *this << value.data();
}
virtual void write(const void* data, size_t size)
{
align(size);
add(size);
}
};
template <>
CBufferBase& CBufferBase::operator<<(const int32_t& data);
template <>
CBufferBase& CBufferBase::operator<<(const uint32_t& data);
template <>
CBufferBase& CBufferBase::operator<<(const float& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Matrix& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector2& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector3& data);
template <>
CBufferBase& CBufferBase::operator<<(const DirectX::SimpleMath::Vector4& data);
template <>
CBufferBase& CBufferBase::operator<<(const gsl::span<float>& data);
template <>
CBufferBase& CBufferBase::operator<<(const gsl::span<const float>& data);
template <>
__forceinline CBufferBase& CBufferBase::operator<<(const DWORD& data)
{
return *this << static_cast<uint32_t>(data);
}
template <>
__forceinline CBufferBase& CBufferBase::operator<<(const bool& data)
{
return *this << (data ? 1 : 0);
}
class CBufferWriter : public CBufferBase
{
uint8_t* ptr = nullptr;
public:
CBufferWriter(uint8_t* ptr_);
private:
void write(const void* data, size_t size) override;
};
|
# Homework 5
## Due Date: Tuesday, October 3rd at 11:59 PM
# Problem 1
We discussed documentation and testing in lecture and also briefly touched on code coverage. You must write tests for your code for your final project (and in life). There is a nice way to automate the testing process called continuous integration (CI).
This problem will walk you through the basics of CI and show you how to get up and running with some CI software.
### Continuous Integration
The idea behind continuous integration is to automate away the testing of your code.
We will be using it for our projects.
The basic workflow goes something like this:
1. You work on your part of the code in your own branch or fork
2. On every commit you make and push to GitHub, your code is automatically tested on a fresh machine on Travis CI. This ensures that there are no specific dependencies on the structure of your machine that your code needs to run and also ensures that your changes are sane
3. Now you submit a pull request to `master` in the main repo (the one you're hoping to contribute to). The repo manager creates a branch off `master`.
4. This branch is also set to run tests on Travis. If all tests pass, then the pull request is accepted and your code becomes part of master.
We use GitHub to integrate our roots library with Travis CI and Coveralls. Note that this is not the only workflow people use. Google git..github..workflow and feel free to choose another one for your group.
### Part 1: Create a repo
Create a public GitHub repo called `cs207test` and clone it to your local machine.
**Note:** No need to do this in Jupyter.
### Part 2: Create a roots library
Use the example from lecture 7 to create a file called `roots.py`, which contains the `quad_roots` and `linear_roots` functions (along with their documentation).
Also create a file called `test_roots.py`, which contains the tests from lecture.
All of these files should be in your newly created `cs207test` repo. **Don't push yet!!!**
```python
%%file cs207test/roots.py
def linear_roots(a=1.0, b=0.0):
"""Returns the roots of a linear equation: ax+ b = 0.
INPUTS
=======
a: float, optional, default value is 1
Coefficient of linear term
b: float, optional, default value is 0
Coefficient of constant term
RETURNS
========
roots: 1-tuple of real floats
Has the form (root) unless a = 0
in which case a ValueError exception is raised
EXAMPLES
=========
>>> linear_roots(1.0, 2.0)
-2.0
"""
if a == 0:
raise ValueError("The linear coefficient is zero. This is not a linear equation.")
else:
return ((-b / a))
def quad_roots(a=1.0, b=2.0, c=0.0):
"""Returns the roots of a quadratic equation: ax^2 + bx + c = 0.
INPUTS
=======
a: float, optional, default value is 1
Coefficient of quadratic term
b: float, optional, default value is 2
Coefficient of linear term
c: float, optional, default value is 0
Constant term
RETURNS
========
roots: 2-tuple of complex floats
Has the form (root1, root2) unless a = 0
in which case a ValueError exception is raised
EXAMPLES
=========
>>> quad_roots(1.0, 1.0, -12.0)
((3+0j), (-4+0j))
"""
import cmath # Can return complex numbers from square roots
if a == 0:
raise ValueError("The quadratic coefficient is zero. This is not a quadratic equation.")
else:
sqrtdisc = cmath.sqrt(b * b - 4.0 * a * c)
r1 = -b + sqrtdisc
r2 = -b - sqrtdisc
return (r1 / 2.0 / a, r2 / 2.0 / a)
```
```python
%%file cs207test/test_roots.py
import roots
def test_quadroots_result():
assert roots.quad_roots(1.0, 1.0, -12.0) == ((3+0j), (-4+0j))
def test_quadroots_types():
try:
roots.quad_roots("", "green", "hi")
except TypeError as err:
assert(type(err) == TypeError)
def test_quadroots_zerocoeff():
try:
roots.quad_roots(a=0.0)
except ValueError as err:
assert(type(err) == ValueError)
def test_linearoots_result():
assert roots.linear_roots(2.0, -3.0) == 1.5
def test_linearroots_types():
try:
roots.linear_roots("ocean", 6.0)
except TypeError as err:
assert(type(err) == TypeError)
def test_linearroots_zerocoeff():
try:
roots.linear_roots(a=0.0)
except ValueError as err:
assert(type(err) == ValueError)
```
### Part 3: Create an account on Travis CI and Start Building
#### Part A:
Create an account on Travis CI and set your `cs207test` repo up for continuous integration once this repo can be seen on Travis.
#### Part B:
Create an instruction to Travis to make sure that
1. python is installed
2. its python 3.5
3. pytest is installed
The file should be called `.travis.yml` and should have the contents:
```yml
language: python
python:
- "3.5"
before_install:
- pip install pytest pytest-cov
script:
- pytest
```
You should also create a configuration file called `setup.cfg`:
```cfg
[tool:pytest]
addopts = --doctest-modules --cov-report term-missing --cov roots
```
#### Part C:
Push the new changes to your `cs207test` repo.
At this point you should be able to see your build on Travis and if and how your tests pass.
```python
%%file cs207test/.travis.yml
language: python
python:
- "3.5"
before_install:
- pip install pytest pytest-cov
script:
- pytest
```
```python
%%file cs207test/setup.cfg
[tool:pytest]
addopts = --doctest-modules --cov-report term-missing --cov roots
```
### Part 4: Coveralls Integration
In class, we also discussed code coverage. Just like Travis CI runs tests automatically for you, Coveralls automatically checks your code coverage. One minor drawback of Coveralls is that it can only work with public GitHub accounts. However, this isn't too big of a problem since your projects will be public.
#### Part A:
Create an account on [`Coveralls`](https://coveralls.zendesk.com/hc/en-us), connect your GitHub, and turn Coveralls integration on.
#### Part B:
Update your the `.travis.yml` file as follows:
```yml
language: python
python:
- "3.5"
before_install:
- pip install pytest pytest-cov
- pip install coveralls
script:
- py.test
after_success:
- coveralls
```
Be sure to push the latest changes to your new repo.
```python
%%file cs207test/.travis.yml
language: python
python:
- "3.5"
before_install:
- pip install pytest pytest-cov
- pip install coveralls
script:
- py.test
after_success:
- coveralls
```
### Part 5: Update README.md in repo
You can have your GitHub repo reflect the build status on Travis CI and the code coverage status from Coveralls. To do this, you should modify the `README.md` file in your repo to include some badges. Put the following at the top of your `README.md` file:
```
[](https://travis-ci.org/dsondak/cs207testing.svg?branch=master)
[](https://coveralls.io/github/dsondak/cs207testing?branch=master)
```
Of course, you need to make sure that the links are to your repo and not mine. You can find embed code on the Coveralls and Travis CI sites.
```python
```
---
# Problem 2
Write a Python module for reaction rate coefficients. Your module should include functions for constant reaction rate coefficients, Arrhenius reaction rate coefficients, and modified Arrhenius reaction rate coefficients. Here are their mathematical forms:
\begin{align}
&k_{\textrm{const}} = k \tag{constant} \\
&k_{\textrm{arr}} = A \exp\left(-\frac{E}{RT}\right) \tag{Arrhenius} \\
&k_{\textrm{mod arr}} = A T^{b} \exp\left(-\frac{E}{RT}\right) \tag{Modified Arrhenius}
\end{align}
Test your functions with the following paramters: $A = 10^7$, $b=0.5$, $E=10^3$. Use $T=10^2$.
A few additional comments / suggestions:
* The Arrhenius prefactor $A$ is strictly positive
* The modified Arrhenius parameter $b$ must be real
* $R = 8.314$ is the ideal gas constant. It should never be changed (except to convert units)
* The temperature $T$ must be positive (assuming a Kelvin scale)
* You may assume that units are consistent
* Document each function!
* You might want to check for overflows and underflows
**Recall:** A Python module is a `.py` file which is not part of the main execution script. The module contains several functions which may be related to each other (like in this problem). Your module will be importable via the execution script. For example, suppose you have called your module `reaction_coeffs.py` and your execution script `kinetics.py`. Inside of `kinetics.py` you will write something like:
```python
import reaction_coeffs
# Some code to do some things
# :
# :
# :
# Time to use a reaction rate coefficient:
reaction_coeffs.const() # Need appropriate arguments, etc
# Continue on...
# :
# :
# :
```
Be sure to include your module in the same directory as your execution script.
```python
```
```python
%%file reaction_coeffs.py
def const(k=1.0):
"""Returns the constant coefficient k.
INPUTS
=======
a: float, optional, default value is 1.0
Constant reaction coefficient
RETURNS
========
Constant k
unless k is not an int or float
in which case a TypeError exception is raised
EXAMPLES
=========
>>> const(1.0)
1.0
"""
if type(k) != int and type(k) != float:
raise TypeError("Input needs to be a number!")
else:
return k
def arr(A=10^7,T=10^2,E=10^3,R=8.314):
"""Returns the constant coefficient k.
INPUTS
=======
A: float, optional, default value is 10^7
Arhenieus constant, needs to be positive
T: float, optional, default value is 10^2
temperature, must be positive
R: float, fixed value 8.314, should not change
RETURNS
========
Constant k
unless any of A,T, and E are not numbers
in which case a TypeError exception is raised
EXAMPLES
=========
>>> arr(10^7,10^2,10^2)
11.526748719357375
"""
if A < 0:
raise ValueError("The Arrhenius constant must be strictly positive")
elif T < 0:
raise ValueError("Temperature must be positive")
elif R != 8.314:
raise ValueError("Unless in a stargate, the universal gas constant is 8.314")
elif type(A) != int and type(A) != float:
raise TypeError("parameters need to be either type int or type float")
elif type(T) !=int and type(T) != int:
raise TypeError("parameters need to be either type int or type float")
elif type(E) != int and type(E) != float:
raise TypeError("parameters need to be either type int or type float")
else:
import numpy as np
k=(A)*np.exp(-E/(R*T))
return k
def mod_arr(A=10^7,b=0.5,T=10^2,E=10^3,R=8.314):
"""Returns the constant coefficient k.
INPUTS
=======
A: float, optional, default value is 10^7
Arhenieus constant, needs to be positive
T: float, optional, default value is 10^2
temperature, must be positive
R: float, fixed value 8.314, should not change
b: float, optional, default value is 0.5, must be a real number
RETURNS
========
Constant k
unless any of A,T,b and E are not numbers
in which case a TypeError exception is raised
EXAMPLES
=========
>>> mod_arr()
32.116059468138779
"""
if A < 0:
raise ValueError("The Arrhenius constant must be strictly positive")
elif T < 0:
raise ValueError("Temperature must be positive")
elif isinstance(b,complex):
raise ValueError("b must be a real number")
elif R != 8.314:
raise ValueError("Unless in a stargate, the universal gas constant is 8.314")
elif type(A) != int and type(A) != float:
raise TypeError("parameters need to be either type int or type float")
elif type(T) !=int and type(T) != int:
raise TypeError("parameters need to be either type int or type float")
elif type(E) != int and type(E) != float:
raise TypeError("parameters need to be either type int or type float")
else:
import numpy as np
k=(A)*(T**b)*np.exp(-E/(R*T))
return k
```
Overwriting reaction_coeffs.py
```python
import reaction_coeffs
print(reaction_coeffs.const())
print(reaction_coeffs.arr())
print(reaction_coeffs.mod_arr())
```
1.0
11.3547417175
32.1160594681
```python
!pytest
```
[1m============================= test session starts ==============================[0m
platform darwin -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /Users/filipmichalsky/cs207_filip_michalsky/homeworks/HW5, inifile:
collected 13 items [0m[1m
[0m
test_multi_progress_r.py ..
test_multi_reaction_r.py ...
test_single_progress_r.py ..
cs207test/test_roots.py ......
[32m[1m========================== 13 passed in 0.24 seconds ===========================[0m
---
# Problem 3
Write a function that returns the **progress rate** for a reaction of the following form:
\begin{align}
\nu_{A} A + \nu_{B} B \longrightarrow \nu_{C} C.
\end{align}
Order your concentration vector so that
\begin{align}
\mathbf{x} =
\begin{bmatrix}
\left[A\right] \\
\left[B\right] \\
\left[C\right]
\end{bmatrix}
\end{align}
Test your function with
\begin{align}
\nu_{i} =
\begin{bmatrix}
2.0 \\
1.0 \\
0.0
\end{bmatrix}
\qquad
\mathbf{x} =
\begin{bmatrix}
1.0 \\
2.0 \\
3.0
\end{bmatrix}
\qquad
k = 10.
\end{align}
You must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests.
```python
import numpy as np
```
```python
%%file single_progress_r.py
def progress_rate(v_i,x,k):
"""Returns the progress rate of a reaction
INPUTS
=======
v_i: vector of stochiometric coefficients
x: vector of concentrations (first dimension needs to match v_i),second dimension is 1
k: float, fixed value 8.314, should not change
RETURNS
========
Progress rate of the reaction
k*[A]^v_i[a]*[B]*v_i[b]*[C]^v_i[c]
unless first dimension of x does not match first dimension of v_i
in which case a ValueError exception is raised
EXAMPLES
=========
>>> import numpy as np
>>> progress_rate(np.array([2,1,0]),np.array([1,2,3]),10)
20
"""
#v_i=np.array([2,1,0])
#x=np.array([1,2,3])
#k=10
import numpy as np
#check that the first dimension matches
if x.shape[0] != v_i.shape[0]:
raise ValueError("First dimension of x and v_i need to match")
else:
product_X_to_vi=1
#loop through the rows to multiply each x by its stochiometric coeffs
for i,j in zip(v_i,x):
product_X_to_vi=product_X_to_vi*(j**i)
progress_rate=k*product_X_to_vi
return progress_rate
if __name__ == "__main__":
import doctest
doctest.testmod()
```
Overwriting single_progress_r.py
```python
import single_progress_r
import numpy as np
single_progress_r.progress_rate(np.array([2,1,0]),np.array([1,2,3]),10)
```
20
```python
import single_progress_r
import numpy as np
single_progress_r.progress_rate(np.array([2,1]),np.array([[2,1],[2,1],[2,1]]),10)
```
```python
%%file test_single_progress_r.py
import single_progress_r
import numpy as np
#!pytest --doctest-modules
def test_progress_rate_result():
assert single_progress_r.progress_rate(np.array([2,1,0]),np.array([1,2,3]),10) == 20
def test_progress_rate_shapes():
try:
single_progress_r.progress_rate(np.array([2,1]),np.array([[2,1],[2,1],[2,1]]),10)
except ValueError as err:
assert(type(err) == ValueError)
#def test_arr_result():
# assert reaction_coeffs.arr(A=10^7,E=10^3,T=10^2) == XX
```
Overwriting test_single_progress_r.py
```bash
%%bash
python -m pytest -v test_single_progress_r.py
```
============================= test session starts ==============================
platform darwin -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /Users/filipmichalsky/anaconda/bin/python
cachedir: .cache
rootdir: /Users/filipmichalsky/cs207_filip_michalsky/homeworks/HW5, inifile:
collecting ... collected 2 items
test_single_progress_r.py::test_progress_rate_result PASSED
test_single_progress_r.py::test_progress_rate_shapes PASSED
=========================== 2 passed in 0.19 seconds ===========================
```bash
%%bash
python multi_progress_r.py -v
#doctest of created file
```
Trying:
import numpy as np
Expecting nothing
ok
Trying:
progress_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]]),np.array([1.0,2.0,1.0]),10)[0]
Expecting:
40.0
ok
Trying:
progress_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]]),np.array([1.0,2.0,1.0]),10)[1]
Expecting:
10.0
ok
1 items had no tests:
__main__
1 items passed all tests:
3 tests in __main__.progress_rate_multi
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
---
# Problem 4
Write a function that returns the **progress rate** for a system of reactions of the following form:
\begin{align}
\nu_{11}^{\prime} A + \nu_{21}^{\prime} B \longrightarrow \nu_{31}^{\prime\prime} C \\
\nu_{12}^{\prime} A + \nu_{32}^{\prime} C \longrightarrow \nu_{22}^{\prime\prime} B + \nu_{32}^{\prime\prime} C
\end{align}
Note that $\nu_{ij}^{\prime}$ represents the stoichiometric coefficient of reactant $i$ in reaction $j$ and $\nu_{ij}^{\prime\prime}$ represents the stoichiometric coefficient of product $i$ in reaction $j$. Therefore, in this convention, I have ordered my vector of concentrations as
\begin{align}
\mathbf{x} =
\begin{bmatrix}
\left[A\right] \\
\left[B\right] \\
\left[C\right]
\end{bmatrix}.
\end{align}
Test your function with
\begin{align}
\nu_{ij}^{\prime} =
\begin{bmatrix}
1.0 & 2.0 \\
2.0 & 0.0 \\
0.0 & 2.0
\end{bmatrix}
\qquad
\nu_{ij}^{\prime\prime} =
\begin{bmatrix}
0.0 & 0.0 \\
0.0 & 1.0 \\
2.0 & 1.0
\end{bmatrix}
\qquad
\mathbf{x} =
\begin{bmatrix}
1.0 \\
2.0 \\
1.0
\end{bmatrix}
\qquad
k = 10.
\end{align}
You must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests.
Please note I have already generalized the progress rate formula, I only need to subtract now the v_ij product from v_ij reactants to get the correct v_ij's
```python
%%file multi_progress_r.py
import numpy as np
def progress_rate_multi(v_ij_reac,v_ij_proc,x,k):
"""Returns the progress rate of a set of reactions
INPUTS
=======
v_ij_reac: vector of stochiometric coefficients of reactants
v_ij_proc: vector of stochiometric coefficients of products
x: vector of concentrations (first dimension needs to match v_i),second dimension is 1
k: float
RETURNS
========
Progress rates of the reactions (a string based on number of reactions)
according to the formula k*[A]^v_i[a]*[B]*v_i[b]*[C]^v_i[c]
unless v_ij = v_ij_proc-v_ij_reac has the first dimension not matching
the first dimension of x which returns a ValueError
unless shape of v_ij_proc does not match the shape of x, which will return ValueError as well
EXAMPLES
=========
>>> import numpy as np
>>> progress_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]]),np.array([1.0,2.0,1.0]),10)[0]
40.0
>>> progress_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]]),np.array([1.0,2.0,1.0]),10)[1]
10.0
"""
import numpy as np
#calculate the effective stochiometric coefficients on the reactants side
#check length of product coeffs and reac coeffs is the same
if v_ij_proc.shape != v_ij_reac.shape:
raise ValueError("Dimensions of stochiometric coeffs need to match")
#check that the first dimension matches
elif x.shape[0] != v_ij_proc.shape[0]:
raise ValueError("First dimension of x and v_i need to match")
else:
v_ij = v_ij_reac
product_X_to_vij = 1
#loop through the rows to multiply each x by its stochiometric coeffs
for i,j in zip(v_ij,x):
#print("i,j")
#print(i,j)
#print("j**i")
#print(j**i)
product_X_to_vij=product_X_to_vij*(j**i)
#print("product")
#print(product_X_to_vij)
progress_rate_multi=k*product_X_to_vij
return progress_rate_multi
if __name__ == "__main__":
import doctest
doctest.testmod()
```
Overwriting multi_progress_r.py
```python
import multi_progress_r
multi_progress_r.progress_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]]),np.array([1.0,2.0,1.0]),10)
```
array([ 40., 10.])
```python
a=np.array([0.25,2.0])
b=np.array([1.,1.])
a*b
```
array([ 0.25, 2. ])
```python
import multi_progress_r
v_ij_reac = np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]])
v_ij_proc = np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]])
x = np.array([1.0,2.0,1.0])
k = 10
assert multi_progress_r.progress_rate_multi(v_ij_reac , v_ij_proc, x , k )[0] == 40
assert multi_progress_r.progress_rate_multi(v_ij_reac , v_ij_proc, x , k )[1] == 10
```
```python
```
```python
#sample fail of the function based on wrong input
import multi_progress_r
multi_progress_r.progress_rate_multi(np.array([2,1,1]),np.array([2,1]),np.array([[2,1],[2,1],[2,1]]),10)
```
```python
%%file test_multi_progress_r.py
import multi_progress_r
import numpy as np
import doctest
doctest.testmod(verbose=True)
def progress_rate_result():
#test the result og the function
v_ij_reac = np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]])
v_ij_proc = np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]])
x = np.array([1.0,2.0,1.0])
k = 10
assert multi_progress_r.progress_rate_multi(v_ij_reac , v_ij_proc, x , k )[0] == 40.0
assert progress_rate_multi(v_ij_reac , v_ij_proc, x , k )[1] == 10.0
def test_progress_rate_shapes_with_x():
#test whether shape of coeffs v_i matches shape of concentrations x
try:
multi_progress_r.progress_rate_multi(np.array([2,1]),np.array([2,1]),np.array([[2,1],[2,1],[2,1]]),10)
except ValueError as err:
assert(type(err) == ValueError)
def test_progress_rate_shapes_coeffs():
#test whether the shape of v_ij's matches
try:
multi_progress_r.progress_rate_multi(np.array([2,1,1]),np.array([2,1]),np.array([[2,1],[2,1],[2,1]]),10)
except ValueError as err:
assert(type(err) == ValueError)
```
Overwriting test_multi_progress_r.py
```bash
%%bash
python multi_progress_r.py -v
```
Trying:
import numpy as np
Expecting nothing
ok
Trying:
progress_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]]),np.array([1.0,2.0,1.0]),10)[0]
Expecting:
40.0
ok
Trying:
progress_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,0.0],[0.0,1.0],[2.0,1.0]]),np.array([1.0,2.0,1.0]),10)[1]
Expecting:
10.0
ok
1 items had no tests:
__main__
1 items passed all tests:
3 tests in __main__.progress_rate_multi
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
```python
!pytest
```
[1m============================= test session starts ==============================[0m
platform darwin -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /Users/filipmichalsky/cs207_filip_michalsky/homeworks/HW5, inifile:
collected 13 items [0m[1m
[0m
test_multi_progress_r.py ..
test_multi_reaction_r.py ...
test_single_progress_r.py ..
cs207test/test_roots.py ......
[32m[1m========================== 13 passed in 0.23 seconds ===========================[0m
---
# Problem 5
Write a function that returns the **reaction rate** of a system of irreversible reactions of the form:
\begin{align}
\nu_{11}^{\prime} A + \nu_{21}^{\prime} B &\longrightarrow \nu_{31}^{\prime\prime} C \\
\nu_{32}^{\prime} C &\longrightarrow \nu_{12}^{\prime\prime} A + \nu_{22}^{\prime\prime} B
\end{align}
Once again $\nu_{ij}^{\prime}$ represents the stoichiometric coefficient of reactant $i$ in reaction $j$ and $\nu_{ij}^{\prime\prime}$ represents the stoichiometric coefficient of product $i$ in reaction $j$. In this convention, I have ordered my vector of concentrations as
\begin{align}
\mathbf{x} =
\begin{bmatrix}
\left[A\right] \\
\left[B\right] \\
\left[C\right]
\end{bmatrix}
\end{align}
Test your function with
\begin{align}
\nu_{ij}^{\prime} =
\begin{bmatrix}
1.0 & 0.0 \\
2.0 & 0.0 \\
0.0 & 2.0
\end{bmatrix}
\qquad
\nu_{ij}^{\prime\prime} =
\begin{bmatrix}
0.0 & 1.0 \\
0.0 & 2.0 \\
1.0 & 0.0
\end{bmatrix}
\qquad
\mathbf{x} =
\begin{bmatrix}
1.0 \\
2.0 \\
1.0
\end{bmatrix}
\qquad
k = 10.
\end{align}
You must document your function and write some tests in addition to the one suggested. You choose the additional tests, but you must have at least one doctest in addition to a suite of unit tests.
```python
#%%file multi_reaction_r.py
import numpy as np
def reaction_rate_multi(v_ij_reac,v_ij_proc,x,k):
"""Returns the rection rate for a set of species
INPUTS
=======
v_ij_reac: vector of stochiometric coefficients of reactants
v_ij_proc: vector of stochiometric coefficients of products
x: vector of concentrations (first dimension needs to match v_i),second dimension is 1
k: float
RETURNS
========
Reaction rates of the species (a string based on number of species)
according to the formula k*[A]^v_i[a]*[B]*v_i[b]*[C]^v_i[c] for progress rate and
dXi/dt = sum(v_ij_proc-v_ij_reac)*progress rate
unless v_ij = v_ij_proc-v_ij_reac has the first dimension not matching
the first dimension of x which returns a ValueError
unless shape of v_ij_proc does not match the shape of x, which will return ValueError as well
EXAMPLES
=========
>>> import numpy as np
>>> reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[0][0]
-50.0
>>> reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[1][0]
-60.0
>>> reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[2][0]
20.0
"""
import numpy as np
#calculate the effective stochiometric coefficients on the reactants side
#check length of product coeffs and reac coeffs is the same
if v_ij_proc.shape != v_ij_reac.shape:
raise ValueError("Dimensions of stochiometric coeffs need to match")
#check that the first dimension matches
elif x.shape[0] != v_ij_proc.shape[0]:
raise ValueError("First dimension of x and v_i need to match")
else:
v_ij = v_ij_reac
product_X_to_vij = 1
#loop through the rows to multiply each x by its stochiometric coeffs
for i,j in zip(v_ij,x):
product_X_to_vij=product_X_to_vij*(j**i)
product_X_to_vij=product_X_to_vij.reshape(len(product_X_to_vij),1)
progress_rate_multi=k*product_X_to_vij
reaction_rates=np.dot((v_ij_proc-v_ij_reac),progress_rate_multi)
return reaction_rates
if __name__ == "__main__":
import doctest
doctest.testmod()
```
```python
k=np.array([[10],[10],[10]])
w_ij=np.array([[1],[2],[3]])
print(k.shape,w_ij.shape)
```
(3, 1) (3, 1)
```python
#from multi_reaction_r import reaction_rate_multi
import multi_reaction_r
multi_reaction_r.reaction_rate_multi(np.array([[1.0,0.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),np.array([[10],[10]]))
```
array([[-30.],
[-60.],
[ 20.]])
```bash
%%bash
python multi_reaction_r.py -v
```
Trying:
import numpy as np
Expecting nothing
ok
Trying:
reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[0][0]
Expecting:
-50.0
ok
Trying:
reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[1][0]
Expecting:
-60.0
ok
Trying:
reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[2][0]
Expecting:
20.0
ok
1 items had no tests:
__main__
1 items passed all tests:
4 tests in __main__.reaction_rate_multi
4 tests in 2 items.
4 passed and 0 failed.
Test passed.
```python
%%file test_multi_reaction_r.py
import multi_reaction_r as mr
import numpy as np
#import doctest
#doctest.testmod(verbose=True)
def test_reaction_rate_result():
#test the result og the function
v_ij_reac = np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]])
v_ij_proc = np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]])
x = np.array([1.0,2.0,1.0])
k = 10
assert mr.reaction_rate_multi(v_ij_reac , v_ij_proc, x , k )[0][0] == -50.0
assert mr.reaction_rate_multi(v_ij_reac , v_ij_proc, x , k )[1][0] == -60.0
assert mr.reaction_rate_multi(v_ij_reac , v_ij_proc, x , k )[2][0] == 20.0
def test_progress_rate_shapes_with_x():
#test whether shape of coeffs v_i matches shape of concentrations x
try:
mr.reaction_rate_multi(np.array([2,1]),np.array([2,1]),np.array([[2,1],[2,1],[2,1]]),10)
except ValueError as err:
assert(type(err) == ValueError)
def test_progress_rate_shapes_coeffs():
#test whether the shape of v_ij's matches
try:
mr.reaction_rate_multi(np.array([2,1,1]),np.array([2,1]),np.array([[2,1],[2,1],[2,1]]),10)
except ValueError as err:
assert(type(err) == ValueError)
```
Overwriting test_multi_reaction_r.py
```bash
%%bash
python -m pytest -v test_multi_reaction_r.py
```
============================= test session starts ==============================
platform darwin -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /Users/filipmichalsky/anaconda/bin/python
cachedir: .cache
rootdir: /Users/filipmichalsky/cs207_filip_michalsky/homeworks/HW5, inifile:
collecting ... collected 3 items
test_multi_reaction_r.py::test_reaction_rate_result PASSED
test_multi_reaction_r.py::test_progress_rate_shapes_with_x PASSED
test_multi_reaction_r.py::test_progress_rate_shapes_coeffs PASSED
=========================== 3 passed in 0.22 seconds ===========================
---
# Problem 6
Put parts 3, 4, and 5 in a module called `chemkin`.
Next, pretend you're a client who needs to compute the reaction rates at three different temperatures ($T = \left\{750, 1500, 2500\right\}$) of the following system of irreversible reactions:
\begin{align}
2H_{2} + O_{2} \longrightarrow 2OH + H_{2} \\
OH + HO_{2} \longrightarrow H_{2}O + O_{2} \\
H_{2}O + O_{2} \longrightarrow HO_{2} + OH
\end{align}
The client also happens to know that reaction 1 is a modified Arrhenius reaction with $A_{1} = 10^{8}$, $b_{1} = 0.5$, $E_{1} = 5\times 10^{4}$, reaction 2 has a constant reaction rate parameter $k = 10^{4}$, and reaction 3 is an Arrhenius reaction with $A_{3} = 10^{7}$ and $E_{3} = 10^{4}$.
You should write a script that imports your `chemkin` module and returns the reaction rates of the species at each temperature of interest given the following species concentrations:
\begin{align}
\mathbf{x} =
\begin{bmatrix}
H_{2} \\
O_{2} \\
OH \\
HO_{2} \\
H_{2}O
\end{bmatrix} =
\begin{bmatrix}
2.0 \\
1.0 \\
0.5 \\
1.0 \\
1.0
\end{bmatrix}
\end{align}
You may assume that these are elementary reactions.
```python
%%file chemkin1.py
import numpy as np
def const(k=1.0):
"""Returns the constant coefficient k.
INPUTS
=======
a: float, optional, default value is 1.0
Constant reaction coefficient
RETURNS
========
Constant k
unless k is not an int or float
in which case a TypeError exception is raised
EXAMPLES
=========
>>> const(1.0)
1.0
"""
if type(k) != int and type(k) != float:
raise TypeError("Input needs to be a number!")
else:
return k
def arr(A=10^7,T=10^2,E=10^3,R=8.314):
"""Returns the constant coefficient k.
INPUTS
=======
A: float, optional, default value is 10^7
Arhenieus constant, needs to be positive
T: float, optional, default value is 10^2
temperature, must be positive
R: float, fixed value 8.314, should not change
RETURNS
========
Constant k
unless any of A,T, and E are not numbers
in which case a TypeError exception is raised
EXAMPLES
=========
>>> arr(10^7,10^2,10^2)
11.526748719357375
"""
if A < 0:
raise ValueError("The Arrhenius constant must be strictly positive")
elif T < 0:
raise ValueError("Temperature must be positive")
elif R != 8.314:
raise ValueError("Unless in a stargate, the universal gas constant is 8.314")
elif type(A) != int and type(A) != float:
raise TypeError("parameters need to be either type int or type float")
elif type(T) !=int and type(T) != int:
raise TypeError("parameters need to be either type int or type float")
elif type(E) != int and type(E) != float:
raise TypeError("parameters need to be either type int or type float")
else:
import numpy as np
k=(A)*np.exp(-E/(R*T))
return k
def mod_arr(A=10^7,b=0.5,T=10^2,E=10^3,R=8.314):
"""Returns the constant coefficient k.
INPUTS
=======
A: float, optional, default value is 10^7
Arhenieus constant, needs to be positive
T: float, optional, default value is 10^2
temperature, must be positive
R: float, fixed value 8.314, should not change
b: float, optional, default value is 0.5, must be a real number
RETURNS
========
Constant k
unless any of A,T,b and E are not numbers
in which case a TypeError exception is raised
EXAMPLES
=========
>>> mod_arr()
32.116059468138779
"""
if A < 0:
raise ValueError("The Arrhenius constant must be strictly positive")
elif T < 0:
raise ValueError("Temperature must be positive")
elif isinstance(b,complex):
raise ValueError("b must be a real number")
elif R != 8.314:
raise ValueError("Unless in a stargate, the universal gas constant is 8.314")
elif type(A) != int and type(A) != float:
raise TypeError("parameters need to be either type int or type float")
elif type(T) !=int and type(T) != int:
raise TypeError("parameters need to be either type int or type float")
elif type(E) != int and type(E) != float:
raise TypeError("parameters need to be either type int or type float")
else:
import numpy as np
k=(A)*(T**b)*np.exp(-E/(R*T))
return k
def reaction_rate_multi(v_ij_reac,v_ij_proc,x,k):
"""Returns the rection rate for a set of species
INPUTS
=======
v_ij_reac: vector of stochiometric coefficients of reactants
v_ij_proc: vector of stochiometric coefficients of products
x: vector of concentrations (first dimension needs to match v_i),second dimension is 1
k: float
RETURNS
========
Reaction rates of the species (a string based on number of species)
according to the formula k*[A]^v_i[a]*[B]*v_i[b]*[C]^v_i[c] for progress rate and
dXi/dt = sum(v_ij_proc-v_ij_reac)*progress rate
unless v_ij = v_ij_proc-v_ij_reac has the first dimension not matching
the first dimension of x which returns a ValueError
unless shape of v_ij_proc does not match the shape of x, which will return ValueError as well
EXAMPLES
=========
>>> import numpy as np
>>> reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[0][0]
-50.0
>>> reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[1][0]
-60.0
>>> reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[2][0]
20.0
"""
import numpy as np
#calculate the effective stochiometric coefficients on the reactants side
#check length of product coeffs and reac coeffs is the same
if v_ij_proc.shape != v_ij_reac.shape:
raise ValueError("Dimensions of stochiometric coeffs need to match")
#check that the first dimension matches
elif x.shape[0] != v_ij_proc.shape[0]:
raise ValueError("First dimension of x and v_i need to match")
else:
v_ij = v_ij_reac
product_X_to_vij = 1
#loop through the rows to multiply each x by its stochiometric coeffs
for i,j in zip(v_ij,x):
product_X_to_vij=product_X_to_vij*(j**i)
product_X_to_vij=product_X_to_vij.reshape(len(product_X_to_vij),1)
progress_rate_multi=k*product_X_to_vij
reaction_rates=np.dot((v_ij_proc-v_ij_reac),progress_rate_multi)
return reaction_rates
if __name__ == "__main__":
import doctest
doctest.testmod()
```
Overwriting chemkin1.py
```bash
%%bash
python chemkin1.py -v
```
Trying:
arr(10^7,10^2,10^2)
Expecting:
11.526748719357375
ok
Trying:
const(1.0)
Expecting:
1.0
ok
Trying:
mod_arr()
Expecting:
32.116059468138779
ok
Trying:
import numpy as np
Expecting nothing
ok
Trying:
reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[0][0]
Expecting:
-50.0
ok
Trying:
reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[1][0]
Expecting:
-60.0
ok
Trying:
reaction_rate_multi(np.array([[1.0,2.0],[2.0,0.0],[0.0,2.0]]),np.array([[0.0,1.0],[0.0,2.0],[1.0,0.0]]),np.array([1.0,2.0,1.0]),10)[2][0]
Expecting:
20.0
ok
1 items had no tests:
__main__
4 items passed all tests:
1 tests in __main__.arr
1 tests in __main__.const
1 tests in __main__.mod_arr
4 tests in __main__.reaction_rate_multi
7 tests in 5 items.
7 passed and 0 failed.
Test passed.
```python
import chemkin1
import numpy as np
vij_reac = np.array([[2.0,0.0,0.0],[1.0,0.0,1.0],[0.0,1.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]])
vij_proc = np.array([[1.0,0.0,0.0],[0.0,1.0,0.0],[2.0,0.0,1.0],[0.0,0.0,1.0],[0.0,1.0,0.0]])
x = np.array([2.0,1.0,0.5,1.0,1.0])
species = np.array([['H2'],['O2'],['OH'],['OH2'],['H20']])
reaction_rate =[]
T = [750,1500,2500]
for temp in T:
k1= chemkin1.mod_arr(A=10**7,b=0.5,T=temp,E=(5*(10**4)),R=8.314)
k2= chemkin1.const(10**4)
k3= chemkin1.arr(A=10**8,T=temp,E=5*(10**4),R=8.314)
k=np.array([[k1],[k2],[k3]])
this_reaction_rate = chemkin1.reaction_rate_multi(vij_reac,vij_proc,x,k)
reaction_rate.append(this_reaction_rate)
print("Temperature ",temp)
print("Reaction rates of species")
for i,j in zip(species,this_reaction_rate):
print(i[0],': ',j[0])
```
Temperature 750
Reaction rates of species
H2 : -360707.78728
O2 : -388635.752574
OH : 749343.539854
OH2 : 27927.9652935
H20 : -27927.9652935
Temperature 1500
Reaction rates of species
H2 : -28111762.0765
O2 : -29921368.5157
OH : 58033130.5922
OH2 : 1809606.43925
H20 : -1809606.43925
Temperature 2500
Reaction rates of species
H2 : -180426142.596
O2 : -189442449.726
OH : 369868592.322
OH2 : 9016307.12982
H20 : -9016307.12982
---
# Problem 7
Get together with your project team, form a GitHub organization (with a descriptive team name), and give the teaching staff access. You can have has many repositories as you like within your organization. However, we will grade the repository called **`cs207-FinalProject`**.
Within the `cs207-FinalProject` repo, you must set up Travis CI and Coveralls. Make sure your `README.md` file includes badges indicating how many tests are passing and the coverage of your code.
|
!
! CalculiX - A 3-dimensional finite element program
! Copyright (C) 1998-2018 Guido Dhondt
!
! 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(version 2);
!
!
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with this program; if not, write to the Free Software
! Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
!
!
! Subroutine x_interpolate.f
!
! Triangulates the face and interpolates xstate variables according to
! the plane equations of these planes
!
! by: Jaro Hokkanen
!
!
subroutine interpolateinface(kk,xstate,xstateini,numpts,nstate_,
& mi,islavsurf,pslavsurf,
& ne0,islavsurfold,pslavsurfold)
!
implicit none
!
integer numpts,i_int,n_int,i,j,k,kk,l,ll,nn,
& koncont(3,2*numpts+1),itri,kflag,neigh(1),kneigh,
& imastop(3,2*numpts+1),indexcj,nopespringj,list(numpts),
& igauss,mi(*),nstate_,itriangle(100),itriold,
& ifaceq(8,6),ip(numpts),ne0,itrinew,ntriangle,
& ifacet(6,4),ifacew1(4,5),ifacew2(8,5),n,islavsurf(2,*),
& ibin(numpts),ivert1,ntriangle_,nterms,m,islavsurfold(2,*),
& nx(2*numpts+1),ny(2*numpts+1),isol,id
!
real*8 xstate(nstate_,mi(1),*),p(3),pslavsurfold(3,*),
& xstateini(nstate_,mi(1),*),coi(2,numpts+3),pneigh(3,3),
& cg(2,2*numpts+1),xdist,pslavsurf(3,*),xil,etl,ratio(3),
& z(9,3),x(2*numpts+1),xo(2*numpts+1),
& y(2*numpts+1),yo(2*numpts+1),straight(9,2*numpts+1),dist
!
! nodes per face for hex elements
!
data ifaceq /4,3,2,1,11,10,9,12,
& 5,6,7,8,13,14,15,16,
& 1,2,6,5,9,18,13,17,
& 2,3,7,6,10,19,14,18,
& 3,4,8,7,11,20,15,19,
& 4,1,5,8,12,17,16,20/
!
! nodes per face for tet elements
!
data ifacet /1,3,2,7,6,5,
& 1,2,4,5,9,8,
& 2,3,4,6,10,9,
& 1,4,3,8,10,7/
!
! nodes per face for linear wedge elements
!
data ifacew1 /1,3,2,0,
& 4,5,6,0,
& 1,2,5,4,
& 2,3,6,5,
& 3,1,4,6/
!
! nodes per face for quadratic wedge elements
!
data ifacew2 /1,3,2,9,8,7,0,0,
& 4,5,6,10,11,12,0,0,
& 1,2,5,4,7,14,10,13,
& 2,3,6,5,8,15,11,14,
& 3,1,4,6,9,13,12,15/
!
kneigh=1
!
do i=1,numpts
list(i)=i
enddo
!
! Loop over the old integration points within the face
!
ll=0
do l=islavsurfold(2,kk)+1,islavsurfold(2,kk+1)
ll=ll+1
coi(1,ll)=pslavsurfold(1,l)
coi(2,ll)=pslavsurfold(2,l)
ip(ll)=ne0+l
enddo
!
! Calling deltri for triangulation
!
kflag=2
!
call deltri(numpts,numpts,coi(1,1:numpts+3),coi(2,1:numpts+3),
& list,ibin,koncont,imastop,n)
!
! Arranging imastop field corresponding to "imastop"
!
nn=0
do i=1,n
ivert1=imastop(1,i)
imastop(1,i)=imastop(2,i)
imastop(2,i)=imastop(3,i)
imastop(3,i)=ivert1
enddo
!
! determining the center of gravity and the bounding planes
! of the triangles
!
call updatecont2d(koncont,n,coi,cg,straight)
!
! sorting the centers of gravity
!
do l=1,n
xo(l)=cg(1,l)
x(l)=xo(l)
nx(l)=l
yo(l)=cg(2,l)
y(l)=yo(l)
ny(l)=l
enddo
kflag=2
call dsort(x,nx,n,kflag)
call dsort(y,ny,n,kflag)
!
! Loop over the new integration points
!
do igauss=islavsurf(2,kk)+1,islavsurf(2,kk+1)
xdist=9.d0
!
! coordinates of the new integration point
!
p(1)=pslavsurf(1,igauss)
p(2)=pslavsurf(2,igauss)
!
! closest triangle center of gravity
!
call near2d(xo,yo,x,y,nx,ny,p(1),p(2),
& n,neigh,kneigh)
!
isol=0
!
itriold=0
itri=neigh(1)
ntriangle=0
ntriangle_=100
!
loop1: do
do l=1,3
ll=3*l-2
dist=straight(ll,itri)*p(1)+
& straight(ll+1,itri)*p(2)+
& straight(ll+2,itri)
!
if(dist.gt.0.d0) then
itrinew=imastop(l,itri)
if(itrinew.eq.0) then
c write(*,*) '**border reached'
exit loop1
elseif(itrinew.eq.itriold) then
c write(*,*) '**solution in between triangles'
isol=itri
exit loop1
else
call nident(itriangle,itrinew,ntriangle,id)
if(id.gt.0) then
if(itriangle(id).eq.itrinew) then
c write(*,*) '**circular path;no solution'
exit loop1
endif
endif
ntriangle=ntriangle+1
if(ntriangle.gt.ntriangle_) then
c write(*,*) '**too many iterations'
exit loop1
endif
do k=ntriangle,id+2,-1
itriangle(k)=itriangle(k-1)
enddo
itriangle(id+1)=itrinew
itriold=itri
itri=itrinew
cycle loop1
endif
elseif(l.eq.3) then
c write(*,*) '**regular solution'
isol=itri
exit loop1
endif
enddo
enddo loop1
!
if(isol.eq.0) then
!
! mapping the new integration point onto the nearest
! triangle
!
do k=1,3
do m=1,2
pneigh(m,k)=coi(m,koncont(k,itri))
enddo
pneigh(3,k)=0.d0
enddo
p(3)=0.d0
nterms=3
!
call attach_2d(pneigh,p,nterms,ratio,dist,xil,etl)
!
do m=1,2
p(m)=0.d0
do k=1,3
p(m)=p(m)+ratio(k)*pneigh(m,k)
enddo
enddo
endif
!
! Assigning xstate values from the vertices of the triangle
! to the field z (integration point values from xstateini)
!
do k=1,3
do i=1,9
z(i,k)=xstateini(i,1,ip(koncont(k,itri)))
enddo
enddo
!
! Calling plane_eq to interpolate values using plane equation
!
do i=1,9
call plane_eq(
& coi(1,koncont(1,itri)),coi(2,koncont(1,itri)),z(i,1),
& coi(1,koncont(2,itri)),coi(2,koncont(2,itri)),z(i,2),
& coi(1,koncont(3,itri)),coi(2,koncont(3,itri)),z(i,3),
& p(1),p(2),xstate(i,1,ne0+igauss))
enddo
!
enddo
!
return
end
|
Require Import Crypto.Specific.Framework.RawCurveParameters.
Require Import Crypto.Util.LetIn.
(***
Modulus : 2^383 - 421
Base: 32
***)
Definition curve : CurveParameters :=
{|
sz := 12%nat;
base := 32;
bitwidth := 32;
s := 2^383;
c := [(1, 421)];
carry_chains := None;
a24 := None;
coef_div_modulus := None;
goldilocks := None;
karatsuba := None;
montgomery := true;
freeze := Some false;
ladderstep := false;
mul_code := None;
square_code := None;
upper_bound_of_exponent_loose := None;
upper_bound_of_exponent_tight := None;
allowable_bit_widths := None;
freeze_extra_allowable_bit_widths := None;
modinv_fuel := None
|}.
Ltac extra_prove_mul_eq _ := idtac.
Ltac extra_prove_square_eq _ := idtac.
|
module Main
import Oyster.Core
%default total
{-
EBNF grammar:
expr ::= term ( + expr | - expr | epsilon )
term ::= factor ( * expr | / expr | epsilon )
factor ::= ( expr ) | integer
integer ::= ... -2 | -1 | 0 | 1 | 2 | ...
-}
mutual
partial
expr : Parser Int
expr = do t <- term
do symbol "+"
e <- expr
pure (t + e)
<|> do symbol "-"
e <- expr
pure (t - e)
<|> pure t
partial
term : Parser Int
term = do f <- factor
do symbol "*"
t <- term
pure (f * t)
<|> do symbol "/"
t <- term
pure (f `div` t)
<|> pure f
partial
factor : Parser Int
factor = do symbol "("
e <- expr
symbol ")"
pure e
<|> integer
eval : String -> Maybe Int
eval inp = case parse expr inp of
[(n, "")] => Just n
_ => Nothing
main : IO ()
main = do expr <- getLine
pure ()
|
= = = Loan in = = =
|
module Numeral.Natural.Oper.FlooredDivision where
import Lvl
open import Data
open import Data.Boolean.Stmt
open import Logic.Propositional.Theorems
open import Numeral.Natural
open import Numeral.Natural.Oper.Comparisons
open import Numeral.Natural.Oper.Comparisons.Proofs
open import Numeral.Natural.Relation.Order
open import Relator.Equals
infixl 10100 _⌊/⌋_
-- Inductive definition of an algorithm for division.
-- `[ d , b ] a' div b'` should be interpreted as following:
-- `d` is the result of the algorithm that is being incremented as it runs.
-- `b` is the predecessor of the original denominator. This is constant throughout the whole process.
-- `a'` is the numerator. This is decremented as it runs.
-- `b'` is the predecessor of the temporary denominator. This is decremented as it runs.
-- By decrementing both `a'` and `b'`, and incrementing `d` when 'b`' reaches 0, it counts how many times `b` "fits into" `a`.
-- Note: See Numeral.Natural.Oper.Modulo for a similiar algorithm used to determine the modulo.
[_,_]_div_ : ℕ → ℕ → ℕ → ℕ → ℕ
[ d , _ ] 𝟎 div _ = d
[ d , b ] 𝐒(a') div 𝟎 = [ 𝐒(d) , b ] a' div b
[ d , b ] 𝐒(a') div 𝐒(b') = [ d , b ] a' div b'
{-# BUILTIN NATDIVSUCAUX [_,_]_div_ #-}
-- Floored division operation.
_⌊/⌋_ : ℕ → (m : ℕ) → .⦃ _ : IsTrue(positive?(m)) ⦄ → ℕ
a ⌊/⌋ 𝐒(m) = [ 𝟎 , m ] a div m
_⌊/⌋₀_ : ℕ → ℕ → ℕ
_ ⌊/⌋₀ 𝟎 = 𝟎
a ⌊/⌋₀ 𝐒(m) = a ⌊/⌋ 𝐒(m)
{-# INLINE _⌊/⌋₀_ #-}
|
module Decidable.Finite.Fin
import Data.Nat
import Data.Nat.Order
import Data.Fin
import Decidable.Decidable.Extra
import Data.Fin.Extra
||| Given a decidable predicate on Fin n,
||| it's decidable whether any number in Fin n satisfies it.
public export
finiteDecEx : {n : Nat} -> {0 p : Fin n -> Type} ->
(pdec : (k : Fin n) -> Dec (p k)) ->
Dec (k ** p k)
finiteDecEx {n = Z} pdec = No (absurd . fst)
finiteDecEx {n = S n} pdec =
case pdec FZ of
Yes pz => Yes (FZ ** pz)
No npz => case finiteDecEx {n = n} (\ k => pdec (FS k)) of
Yes (k ** pk) => Yes (FS k ** pk)
No npk => No $ \case
(FZ ** pz) => absurd (npz pz)
(FS k ** pk) => absurd (npk (k ** pk))
||| Given a decidable predicate on Fin n,
||| it's decidable whether all numbers in Fin n satisfy it.
public export
finiteDecAll : {n : Nat} -> {0 p : Fin n -> Type} ->
(pdec : (k : Fin n) -> Dec (p k)) ->
Dec ((k : Fin n) -> p k)
finiteDecAll pdec = notExistsNotForall pdec $ finiteDecEx (\ x => negateDec (pdec x))
|
[STATEMENT]
lemma lesub_step_typeD:
"A {\<sqsubseteq>\<^bsub>r\<^esub>} B \<Longrightarrow> (x,y) \<in> A \<Longrightarrow> \<exists>y'. (x, y') \<in> B \<and> y \<sqsubseteq>\<^sub>r y'"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>A {\<sqsubseteq>\<^bsub>r\<^esub>} B; (x, y) \<in> A\<rbrakk> \<Longrightarrow> \<exists>y'. (x, y') \<in> B \<and> y \<sqsubseteq>\<^bsub>r\<^esub> y'
[PROOF STEP]
(*<*)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>A {\<sqsubseteq>\<^bsub>r\<^esub>} B; (x, y) \<in> A\<rbrakk> \<Longrightarrow> \<exists>y'. (x, y') \<in> B \<and> y \<sqsubseteq>\<^bsub>r\<^esub> y'
[PROOF STEP]
by (unfold lesubstep_type_def) blast |
```python
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
import scqubits as qubit
import numpy as np
```
# Defining circuit topology
```python
flux_qubit = qubit.Circuit()
flux_qubit.add_element(qubit.Capacitance('Cg1'), ['g1', '1'])
flux_qubit.add_element(qubit.Capacitance('Cg2'), ['g2', '2'])
flux_qubit.add_element(qubit.Capacitance('CJ1'), ['GND', '1'])
flux_qubit.add_element(qubit.Capacitance('CJ2'), ['GND', '2'])
flux_qubit.add_element(qubit.Capacitance('CJ3'), ['1', '3'])
flux_qubit.add_element(qubit.JosephsonJunction('J1'), ['GND', '1'])
flux_qubit.add_element(qubit.JosephsonJunction('J2'), ['GND', '2'])
flux_qubit.add_element(qubit.JosephsonJunction('J3'), ['1', '3'])
```
# Parametrizing Hamiltonian
```python
ϕ1 = qubit.Variable('ϕ_1')
ϕ2 = qubit.Variable('ϕ_2')
f = qubit.Variable('f')
g1 = qubit.Variable('g_1')
g2 = qubit.Variable('g_2')
flux_qubit.add_variable(ϕ1)
flux_qubit.add_variable(ϕ2)
flux_qubit.add_variable(f)
flux_qubit.add_variable(g1)
flux_qubit.add_variable(g2)
```
# Mapping nodal phases to variables
```python
flux_qubit.map_nodes_linear(['GND', '1', '2', '3', 'g1', 'g2'],
['ϕ_1', 'ϕ_2', 'f', 'g_1', 'g_2'],
np.asarray([[0, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 1, -1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]]))
```
# Separating variables into external controls and degrees of freedom
```python
ϕ1.create_grid(21, 1) # 21 charge states, 2pi wavefunction periodicity
ϕ2.create_grid(21, 1) # 21 charge states, 2pi wavefunction periodicity
f.set_parameter(0.4*2*np.pi, 0) # external flux: 0.4 quantum, external voltage: 0
g1.set_parameter(0, 0) # external flux: 0 quanta, external voltage: 0
g2.set_parameter(0, 0) # external flux: 0 quanta, external voltage: 0
```
# Printing symbolic Hamiltonian (using sympy)
This part is a bit ugly, but in principle we could improve it so it uses better notation
```python
import sympy
C_g1, C_g2, C_J1, C_J2, C_J3, E_J1, E_J2, E_J3 = \
sympy.symbols('C_g1, C_g2, C_J1, C_J2, C_J3, E_J1, E_J2, E_J3')
flux_qubit.find_element('Cg1').set_capacitance(C_g1)
flux_qubit.find_element('Cg2').set_capacitance(C_g2)
flux_qubit.find_element('CJ1').set_capacitance(C_J1)
flux_qubit.find_element('CJ2').set_capacitance(C_J2)
flux_qubit.find_element('CJ3').set_capacitance(C_J3)
flux_qubit.find_element('J1').set_critical_current(E_J1)
flux_qubit.find_element('J2').set_critical_current(E_J2)
flux_qubit.find_element('J3').set_critical_current(E_J3)
```
## capacitance matrix in terms of the nodal parameterization
```python
flux_qubit.capacitance_matrix(symbolic=True)
```
$\displaystyle \left[\begin{matrix}C_{J1} + C_{J2} & 0.0 & - C_{J1} & 0.0 & - C_{J2} & 0.0\\0.0 & C_{g1} & - C_{g1} & 0.0 & 0.0 & 0.0\\- C_{J1} & - C_{g1} & C_{J1} + C_{J3} + C_{g1} & 0.0 & 0.0 & - C_{J3}\\0.0 & 0.0 & 0.0 & C_{g2} & - C_{g2} & 0.0\\- C_{J2} & 0.0 & 0.0 & - C_{g2} & C_{J2} + C_{g2} & 0.0\\0.0 & 0.0 & - C_{J3} & 0.0 & 0.0 & C_{J3}\end{matrix}\right]$
## Legendre transform of the capacitance matrix (inverse wrt to degrees of freedom)
```python
flux_qubit.capacitance_matrix_legendre_transform(symbolic=True)
```
$\displaystyle \left[\begin{matrix}\frac{C_{J2} + C_{J3} + C_{g2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{g1} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3} C_{g2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\\\frac{C_{J3}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J1} + C_{J3} + C_{g1}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & - \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3} C_{g1}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{g2} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\\\frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & - \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & C_{J3} \left(- \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - C_{J3} \left(\frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) & - C_{g1} \left(- \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) & - C_{g2} \left(\frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right)\\\frac{C_{g1} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3} C_{g1}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3}^{2} C_{g1}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} C_{g1} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{g1}^{2} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3} C_{g1} C_{g2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\\\frac{C_{J3} C_{g2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{g2} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & - \frac{C_{J3}^{2} C_{g2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} C_{g2} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{J3} C_{g1} C_{g2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} & \frac{C_{g2}^{2} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\end{matrix}\right]$
## Symbolic lagrangian
```python
sympy.nsimplify(flux_qubit.symbolic_lagrangian())
```
$\displaystyle - E_{J1} \left(1 - \cos{\left(ϕ_{1} \right)}\right) - E_{J2} \left(1 - \cos{\left(ϕ_{2} \right)}\right) - E_{J3} \left(1 - \cos{\left(f + ϕ_{1} - ϕ_{2} \right)}\right) + \partial_tg_1 \left(\frac{C_{g1} \partial_tg_1}{2} - \frac{C_{g1} \partial_tϕ_1}{2}\right) + \partial_tg_2 \left(\frac{C_{g2} \partial_tg_2}{2} - \frac{C_{g2} \partial_tϕ_2}{2}\right) + \partial_tϕ_1 \left(- C_{J3} \left(- \frac{\partial_tf}{2} + \frac{\partial_tϕ_2}{2}\right) - \frac{C_{g1} \partial_tg_1}{2} + \frac{\partial_tϕ_1 \left(C_{J1} + C_{J3} + C_{g1}\right)}{2}\right) + \partial_tϕ_2 \left(- \frac{C_{g2} \partial_tg_2}{2} + \frac{\partial_tϕ_2 \left(C_{J2} + C_{g2}\right)}{2}\right) + \left(- \partial_tf + \partial_tϕ_2\right) \left(- \frac{C_{J3} \partial_tϕ_1}{2} + C_{J3} \left(- \frac{\partial_tf}{2} + \frac{\partial_tϕ_2}{2}\right)\right)$
## Symbolic hamiltonian
```python
sympy.nsimplify(flux_qubit.symbolic_hamiltonian())
```
$\displaystyle E_{J1} \left(1 - \cos{\left(ϕ_{1} \right)}\right) + E_{J2} \left(1 - \cos{\left(ϕ_{2} \right)}\right) + E_{J3} \left(1 - \cos{\left(f + ϕ_{1} - ϕ_{2} \right)}\right) + \frac{\partial_tf \left(\partial_tf \left(C_{J3} \left(- \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - C_{J3} \left(\frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right)\right) + \partial_tg_1 \left(\frac{C_{J3}^{2} C_{g1}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} C_{g1} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) + \partial_tg_2 \left(- \frac{C_{J3}^{2} C_{g2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} C_{g2} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - i \partial_{ϕ_1} \left(\frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - i \partial_{ϕ_2} \left(- \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right)\right)}{2} + \frac{\partial_tg_1 \left(\frac{C_{J3} C_{g1} C_{g2} \partial_tg_2}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{i C_{J3} C_{g1} \partial_{ϕ_2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{g1}^{2} \partial_tg_1 \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - C_{g1} \partial_tf \left(- \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - \frac{i C_{g1} \partial_{ϕ_1} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right)}{2} + \frac{\partial_tg_2 \left(\frac{C_{J3} C_{g1} C_{g2} \partial_tg_1}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{i C_{J3} C_{g2} \partial_{ϕ_1}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{g2}^{2} \partial_tg_2 \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - C_{g2} \partial_tf \left(\frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - \frac{i C_{g2} \partial_{ϕ_2} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right)}{2} - \frac{i \partial_{ϕ_1} \left(\frac{C_{J3} C_{g2} \partial_tg_2}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{i C_{J3} \partial_{ϕ_2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{g1} \partial_tg_1 \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \partial_tf \left(\frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{C_{J3} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - \frac{i \partial_{ϕ_1} \left(C_{J2} + C_{J3} + C_{g2}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right)}{2} - \frac{i \partial_{ϕ_2} \left(\frac{C_{J3} C_{g1} \partial_tg_1}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} - \frac{i C_{J3} \partial_{ϕ_1}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{g2} \partial_tg_2 \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \partial_tf \left(- \frac{C_{J3}^{2}}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)} + \frac{C_{J3} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right) - \frac{i \partial_{ϕ_2} \left(C_{J1} + C_{J3} + C_{g1}\right)}{- C_{J3}^{2} + \left(C_{J1} + C_{J3} + C_{g1}\right) \left(C_{J2} + C_{J3} + C_{g2}\right)}\right)}{2}$
# Replacing symbolic circuit parameters with some numbers
```python
RATIO = 60.0
ALPHA = 0.8
flux_qubit.find_element('J1').set_critical_current(1.0)
flux_qubit.find_element('J2').set_critical_current(1.0)
flux_qubit.find_element('J3').set_critical_current(1.0*ALPHA)
flux_qubit.find_element('CJ1').set_capacitance(1/(8*1.0/RATIO))
flux_qubit.find_element('CJ2').set_capacitance(1/(8*1.0/RATIO))
flux_qubit.find_element('CJ3').set_capacitance(1/(8*1.0/RATIO/ALPHA))
flux_qubit.find_element('Cg1').set_capacitance(1/(8*50.0/RATIO))
flux_qubit.find_element('Cg2').set_capacitance(1/(8*50.0/RATIO))
```
# Eigenvalues and eigensystem using scqubit tools
```python
flux_qubit.plot_potential()
```
(<Figure size 750x750 with 2 Axes>,
<matplotlib.axes._subplots.AxesSubplot at 0x23542ad3490>)
```python
vals, vecs= flux_qubit.eigensys()
```
```python
vals
#vecs_phase = np.conj(unitary).T@vecs
vals - vals[0]
```
array([0. , 0.26299666, 0.29339598, 0.50146767, 0.55310417,
0.57154646])
# Eigenvalues using circuit tools
```python
flux_qubit.calculate_potentials()
vals, vecs = flux_qubit.diagonalize_phase(num_states=6)
```
```python
np.real(vals-vals[0])
```
array([0. , 0.26299666, 0.29339598, 0.50146767, 0.55310417,
0.57154646])
```python
import matplotlib.pyplot as plt
vecs = np.reshape(vecs, (21,21,6))
plt.pcolormesh(ϕ1.get_phase_grid(), ϕ2.get_phase_grid(), np.abs(vecs[:,:,0])**2)
plt.colorbar()
np.sum(np.abs(vecs[:,:,0])**2)
```
1.0000000000000113
```python
```
|
eZTrack is an enterprise-wide, Platform-as-a-Service (PaaS) platform that enables businesses & organizations to manage both their fixed and mobile assets fast and effectively. Our platform allows us to offer intelligent machine-to-machine (M2M) products and services to customers to enhance their productivity, improve operation efficiencies, control costs and increase their revenue.
Our smart & sophisticated communication and data platform can meet the growing challenges of ever increasing devices added into its ecosystem. Our platform is agnostic and can work with a wide range of M2M hardware from a variety of manufacturers.
The platform works with range of mobile devices, equipments, smartphones and sensors with a choice of global network connectivity options. It supports a wide range of applications. The platform is real-time, user-friendly, scalable, robust and customizable.
Insiqa Technologies Private Limited is an innovative solution provider and a fast-growing company, backed by SCMC Private Limited, a company with strong & extensive 15 years of experience of having developed & delivered enterprise wide products & solution from ground up for Fortune 1000 clients across the globe. |
abstract type JSONLD <: DataRepo
end
include("JSONLD_Web.jl")
include("JSONLD_DOI.jl")
data_fullname(::JSONLD, mainpage) = mainpage["name"]
website(::JSONLD, mainpage_url, mainpage) = mainpage_url
description(repo::JSONLD, mainpage) = filter_html(getfirst(mainpage, "description"))
function author(repo::JSONLD, mainpage)
inner(authors::Vector) = map(inner, authors)
inner(::Missing) = missing
inner(author::Dict) = getfirst(author, "name")
authors = getfirst(mainpage, "author", "creator") |> inner
if !(authors isa AbstractVector) # then there was just one
return [authors]
end
authors
end
function published_date(repo::JSONLD, mainpage)
rawdate = getfirst(mainpage, "datePublished", "dateCreated", "dateModified")
# Dates can be like '2007' or '2016-12-20'. Need to account for all.
try
return Dates.format(Dates.DateTime(rawdate), "U d, yyyy")
catch err
if err isa MethodError || err isa ArgumentError
# `MethodError` occurs if `rawdate==missing`
# `ArgumentError` can occur if it is a weirdly formatted string
# Either way, it is probably alright
return rawdate
else
rethrow()
end
end
end
function license(::JSONLD, mainpage)
license = getfirst(mainpage, "license")
if license isa Dict
license = getfirst(license, "url", "text")
end
filter_html(license)
end
function get_urls(repo::JSONLD, page)
lift(getfirst(page, "distribution")) do url_list
urls = collect(skipmissing(getfirst.(url_list, "contentUrl")))
end
end
|
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl
-/
import order.hom.basic
import algebra.order.sub.defs
import algebra.order.monoid.cancel.defs
/-!
# Ordered groups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file develops the basics of ordered groups.
## Implementation details
Unfortunately, the number of `'` appended to lemmas in this file
may differ between the multiplicative and the additive version of a lemma.
The reason is that we did not want to change existing names in the library.
-/
set_option old_structure_cmd true
open function
universe u
variable {α : Type u}
/-- An ordered additive commutative group is an additive commutative group
with a partial order in which addition is strictly monotone. -/
@[protect_proj, ancestor add_comm_group partial_order]
class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α :=
(add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b)
/-- An ordered commutative group is an commutative group
with a partial order in which multiplication is strictly monotone. -/
@[protect_proj, ancestor comm_group partial_order]
class ordered_comm_group (α : Type u) extends comm_group α, partial_order α :=
(mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b)
attribute [to_additive] ordered_comm_group
@[to_additive]
instance ordered_comm_group.to_covariant_class_left_le (α : Type u) [ordered_comm_group α] :
covariant_class α α (*) (≤) :=
{ elim := λ a b c bc, ordered_comm_group.mul_le_mul_left b c bc a }
@[priority 100, to_additive] -- See note [lower instance priority]
instance ordered_comm_group.to_ordered_cancel_comm_monoid [ordered_comm_group α] :
ordered_cancel_comm_monoid α :=
{ le_of_mul_le_mul_left := λ a b c, le_of_mul_le_mul_left',
..‹ordered_comm_group α› }
example (α : Type u) [ordered_add_comm_group α] : covariant_class α α (swap (+)) (<) :=
add_right_cancel_semigroup.covariant_swap_add_lt_of_covariant_swap_add_le α
/-- A choice-free shortcut instance. -/
@[to_additive "A choice-free shortcut instance."]
instance ordered_comm_group.to_contravariant_class_left_le (α : Type u) [ordered_comm_group α] :
contravariant_class α α (*) (≤) :=
{ elim := λ a b c bc, by simpa using mul_le_mul_left' bc a⁻¹, }
/-- A choice-free shortcut instance. -/
@[to_additive "A choice-free shortcut instance."]
instance ordered_comm_group.to_contravariant_class_right_le (α : Type u) [ordered_comm_group α] :
contravariant_class α α (swap (*)) (≤) :=
{ elim := λ a b c bc, by simpa using mul_le_mul_right' bc a⁻¹, }
section group
variables [group α]
section typeclasses_left_le
variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α}
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.neg_nonpos_iff "Uses `left` co(ntra)variant."]
lemma left.inv_le_one_iff :
a⁻¹ ≤ 1 ↔ 1 ≤ a :=
by { rw [← mul_le_mul_iff_left a], simp }
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.nonneg_neg_iff "Uses `left` co(ntra)variant."]
lemma left.one_le_inv_iff :
1 ≤ a⁻¹ ↔ a ≤ 1 :=
by { rw [← mul_le_mul_iff_left a], simp }
@[simp, to_additive]
lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c :=
by { rw ← mul_le_mul_iff_left a, simp }
@[simp, to_additive]
lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c :=
by rw [← mul_le_mul_iff_left b, mul_inv_cancel_left]
@[to_additive neg_le_iff_add_nonneg']
lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b :=
(mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma le_inv_iff_mul_le_one_left : a ≤ b⁻¹ ↔ b * a ≤ 1 :=
(mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma le_inv_mul_iff_le : 1 ≤ b⁻¹ * a ↔ b ≤ a :=
by rw [← mul_le_mul_iff_left b, mul_one, mul_inv_cancel_left]
@[to_additive]
lemma inv_mul_le_one_iff : a⁻¹ * b ≤ 1 ↔ b ≤ a :=
trans (inv_mul_le_iff_le_mul) $ by rw mul_one
end typeclasses_left_le
section typeclasses_left_lt
variables [has_lt α] [covariant_class α α (*) (<)] {a b c : α}
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.neg_pos_iff "Uses `left` co(ntra)variant."]
lemma left.one_lt_inv_iff :
1 < a⁻¹ ↔ a < 1 :=
by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one]
/-- Uses `left` co(ntra)variant. -/
@[simp, to_additive left.neg_neg_iff "Uses `left` co(ntra)variant."]
lemma left.inv_lt_one_iff :
a⁻¹ < 1 ↔ 1 < a :=
by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one]
@[simp, to_additive]
lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c :=
by { rw [← mul_lt_mul_iff_left a], simp }
@[simp, to_additive]
lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c :=
by rw [← mul_lt_mul_iff_left b, mul_inv_cancel_left]
@[to_additive]
lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b :=
(mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 :=
(mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self
@[to_additive]
lemma lt_inv_mul_iff_lt : 1 < b⁻¹ * a ↔ b < a :=
by rw [← mul_lt_mul_iff_left b, mul_one, mul_inv_cancel_left]
@[to_additive]
lemma inv_mul_lt_one_iff : a⁻¹ * b < 1 ↔ b < a :=
trans (inv_mul_lt_iff_lt_mul) $ by rw mul_one
end typeclasses_left_lt
section typeclasses_right_le
variables [has_le α] [covariant_class α α (swap (*)) (≤)] {a b c : α}
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.neg_nonpos_iff "Uses `right` co(ntra)variant."]
lemma right.inv_le_one_iff :
a⁻¹ ≤ 1 ↔ 1 ≤ a :=
by { rw [← mul_le_mul_iff_right a], simp }
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.nonneg_neg_iff "Uses `right` co(ntra)variant."]
lemma right.one_le_inv_iff :
1 ≤ a⁻¹ ↔ a ≤ 1 :=
by { rw [← mul_le_mul_iff_right a], simp }
@[to_additive neg_le_iff_add_nonneg]
lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a :=
(mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self
@[to_additive]
lemma le_inv_iff_mul_le_one_right : a ≤ b⁻¹ ↔ a * b ≤ 1 :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self
@[simp, to_additive]
lemma mul_inv_le_iff_le_mul : a * b⁻¹ ≤ c ↔ a ≤ c * b :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right
@[simp, to_additive]
lemma le_mul_inv_iff_mul_le : c ≤ a * b⁻¹ ↔ c * b ≤ a :=
(mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right
@[simp, to_additive]
lemma mul_inv_le_one_iff_le : a * b⁻¹ ≤ 1 ↔ a ≤ b :=
mul_inv_le_iff_le_mul.trans $ by rw one_mul
@[to_additive]
lemma le_mul_inv_iff_le : 1 ≤ a * b⁻¹ ↔ b ≤ a :=
by rw [← mul_le_mul_iff_right b, one_mul, inv_mul_cancel_right]
@[to_additive]
lemma mul_inv_le_one_iff : b * a⁻¹ ≤ 1 ↔ b ≤ a :=
trans (mul_inv_le_iff_le_mul) $ by rw one_mul
end typeclasses_right_le
section typeclasses_right_lt
variables [has_lt α] [covariant_class α α (swap (*)) (<)] {a b c : α}
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.neg_neg_iff "Uses `right` co(ntra)variant."]
lemma right.inv_lt_one_iff :
a⁻¹ < 1 ↔ 1 < a :=
by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul]
/-- Uses `right` co(ntra)variant. -/
@[simp, to_additive right.neg_pos_iff "Uses `right` co(ntra)variant."]
lemma right.one_lt_inv_iff :
1 < a⁻¹ ↔ a < 1 :=
by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul]
@[to_additive]
lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a :=
(mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self
@[to_additive]
lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 :=
(mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self
@[simp, to_additive]
lemma mul_inv_lt_iff_lt_mul : a * b⁻¹ < c ↔ a < c * b :=
by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right]
@[simp, to_additive]
lemma lt_mul_inv_iff_mul_lt : c < a * b⁻¹ ↔ c * b < a :=
(mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right
@[simp, to_additive]
lemma inv_mul_lt_one_iff_lt : a * b⁻¹ < 1 ↔ a < b :=
by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right, one_mul]
@[to_additive]
lemma lt_mul_inv_iff_lt : 1 < a * b⁻¹ ↔ b < a :=
by rw [← mul_lt_mul_iff_right b, one_mul, inv_mul_cancel_right]
@[to_additive]
lemma mul_inv_lt_one_iff : b * a⁻¹ < 1 ↔ b < a :=
trans (mul_inv_lt_iff_lt_mul) $ by rw one_mul
end typeclasses_right_lt
section typeclasses_left_right_le
variables [has_le α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)]
{a b c d : α}
@[simp, to_additive]
lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by { rw [← mul_le_mul_iff_left a, ← mul_le_mul_iff_right b], simp }
alias neg_le_neg_iff ↔ le_of_neg_le_neg _
@[to_additive]
lemma mul_inv_le_inv_mul_iff : a * b⁻¹ ≤ d⁻¹ * c ↔ d * a ≤ c * b :=
by rw [← mul_le_mul_iff_left d, ← mul_le_mul_iff_right b, mul_inv_cancel_left, mul_assoc,
inv_mul_cancel_right]
@[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b :=
by simp [div_eq_mul_inv]
@[simp, to_additive] lemma le_div_self_iff (a : α) {b : α} : a ≤ a / b ↔ b ≤ 1 :=
by simp [div_eq_mul_inv]
alias sub_le_self_iff ↔ _ sub_le_self
end typeclasses_left_right_le
section typeclasses_left_right_lt
variables [has_lt α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)]
{a b c d : α}
@[simp, to_additive]
lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a :=
by { rw [← mul_lt_mul_iff_left a, ← mul_lt_mul_iff_right b], simp }
@[to_additive neg_lt]
lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a :=
by rw [← inv_lt_inv_iff, inv_inv]
@[to_additive lt_neg]
lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ :=
by rw [← inv_lt_inv_iff, inv_inv]
alias lt_inv' ↔ lt_inv_of_lt_inv _
attribute [to_additive] lt_inv_of_lt_inv
alias inv_lt' ↔ inv_lt_of_inv_lt' _
attribute [to_additive neg_lt_of_neg_lt] inv_lt_of_inv_lt'
@[to_additive]
lemma mul_inv_lt_inv_mul_iff : a * b⁻¹ < d⁻¹ * c ↔ d * a < c * b :=
by rw [← mul_lt_mul_iff_left d, ← mul_lt_mul_iff_right b, mul_inv_cancel_left, mul_assoc,
inv_mul_cancel_right]
@[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b :=
by simp [div_eq_mul_inv]
alias sub_lt_self_iff ↔ _ sub_lt_self
end typeclasses_left_right_lt
section pre_order
variable [preorder α]
section left_le
variables [covariant_class α α (*) (≤)] {a : α}
@[to_additive]
lemma left.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a :=
le_trans (left.inv_le_one_iff.mpr h) h
alias left.neg_le_self ← neg_le_self
@[to_additive]
lemma left.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ :=
le_trans h (left.one_le_inv_iff.mpr h)
end left_le
section left_lt
variables [covariant_class α α (*) (<)] {a : α}
@[to_additive]
lemma left.inv_lt_self (h : 1 < a) : a⁻¹ < a :=
(left.inv_lt_one_iff.mpr h).trans h
alias left.neg_lt_self ← neg_lt_self
@[to_additive]
lemma left.self_lt_inv (h : a < 1) : a < a⁻¹ :=
lt_trans h (left.one_lt_inv_iff.mpr h)
end left_lt
section right_le
variables [covariant_class α α (swap (*)) (≤)] {a : α}
@[to_additive]
lemma right.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a :=
le_trans (right.inv_le_one_iff.mpr h) h
@[to_additive]
lemma right.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ :=
le_trans h (right.one_le_inv_iff.mpr h)
end right_le
section right_lt
variables [covariant_class α α (swap (*)) (<)] {a : α}
@[to_additive]
lemma right.inv_lt_self (h : 1 < a) : a⁻¹ < a :=
(right.inv_lt_one_iff.mpr h).trans h
@[to_additive]
lemma right.self_lt_inv (h : a < 1) : a < a⁻¹ :=
lt_trans h (right.one_lt_inv_iff.mpr h)
end right_lt
end pre_order
end group
section comm_group
variables [comm_group α]
section has_le
variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α}
@[to_additive]
lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c :=
by rw [inv_mul_le_iff_le_mul, mul_comm]
@[simp, to_additive]
lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c :=
by rw [← inv_mul_le_iff_le_mul, mul_comm]
@[to_additive add_neg_le_add_neg_iff]
lemma mul_inv_le_mul_inv_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b :=
by rw [mul_comm c, mul_inv_le_inv_mul_iff, mul_comm]
end has_le
section has_lt
variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α}
@[to_additive]
lemma inv_mul_lt_iff_lt_mul' : c⁻¹ * a < b ↔ a < b * c :=
by rw [inv_mul_lt_iff_lt_mul, mul_comm]
@[simp, to_additive]
lemma mul_inv_lt_iff_le_mul' : a * b⁻¹ < c ↔ a < b * c :=
by rw [← inv_mul_lt_iff_lt_mul, mul_comm]
@[to_additive add_neg_lt_add_neg_iff]
lemma mul_inv_lt_mul_inv_iff' : a * b⁻¹ < c * d⁻¹ ↔ a * d < c * b :=
by rw [mul_comm c, mul_inv_lt_inv_mul_iff, mul_comm]
end has_lt
end comm_group
alias left.inv_le_one_iff ↔ one_le_of_inv_le_one _
attribute [to_additive] one_le_of_inv_le_one
alias left.one_le_inv_iff ↔ le_one_of_one_le_inv _
attribute [to_additive nonpos_of_neg_nonneg] le_one_of_one_le_inv
alias inv_lt_inv_iff ↔ lt_of_inv_lt_inv _
attribute [to_additive] lt_of_inv_lt_inv
alias left.inv_lt_one_iff ↔ one_lt_of_inv_lt_one _
attribute [to_additive] one_lt_of_inv_lt_one
alias left.inv_lt_one_iff ← inv_lt_one_iff_one_lt
attribute [to_additive] inv_lt_one_iff_one_lt
alias left.inv_lt_one_iff ← inv_lt_one'
attribute [to_additive neg_lt_zero] inv_lt_one'
alias left.one_lt_inv_iff ↔ inv_of_one_lt_inv _
attribute [to_additive neg_of_neg_pos] inv_of_one_lt_inv
alias left.one_lt_inv_iff ↔ _ one_lt_inv_of_inv
attribute [to_additive neg_pos_of_neg] one_lt_inv_of_inv
alias le_inv_mul_iff_mul_le ↔ mul_le_of_le_inv_mul _
attribute [to_additive] mul_le_of_le_inv_mul
alias le_inv_mul_iff_mul_le ↔ _ le_inv_mul_of_mul_le
attribute [to_additive] le_inv_mul_of_mul_le
alias inv_mul_le_iff_le_mul ↔ _ inv_mul_le_of_le_mul
attribute [to_additive] inv_mul_le_iff_le_mul
alias lt_inv_mul_iff_mul_lt ↔ mul_lt_of_lt_inv_mul _
attribute [to_additive] mul_lt_of_lt_inv_mul
alias lt_inv_mul_iff_mul_lt ↔ _ lt_inv_mul_of_mul_lt
attribute [to_additive] lt_inv_mul_of_mul_lt
alias inv_mul_lt_iff_lt_mul ↔ lt_mul_of_inv_mul_lt inv_mul_lt_of_lt_mul
attribute [to_additive] lt_mul_of_inv_mul_lt
attribute [to_additive] inv_mul_lt_of_lt_mul
alias lt_mul_of_inv_mul_lt ← lt_mul_of_inv_mul_lt_left
attribute [to_additive] lt_mul_of_inv_mul_lt_left
alias left.inv_le_one_iff ← inv_le_one'
attribute [to_additive neg_nonpos] inv_le_one'
alias left.one_le_inv_iff ← one_le_inv'
attribute [to_additive neg_nonneg] one_le_inv'
alias left.one_lt_inv_iff ← one_lt_inv'
attribute [to_additive neg_pos] one_lt_inv'
alias mul_lt_mul_left' ← ordered_comm_group.mul_lt_mul_left'
attribute [to_additive ordered_add_comm_group.add_lt_add_left] ordered_comm_group.mul_lt_mul_left'
alias le_of_mul_le_mul_left' ← ordered_comm_group.le_of_mul_le_mul_left
attribute [to_additive ordered_add_comm_group.le_of_add_le_add_left]
ordered_comm_group.le_of_mul_le_mul_left
alias lt_of_mul_lt_mul_left' ← ordered_comm_group.lt_of_mul_lt_mul_left
attribute [to_additive ordered_add_comm_group.lt_of_add_lt_add_left]
ordered_comm_group.lt_of_mul_lt_mul_left
/- Most of the lemmas that are primed in this section appear in ordered_field. -/
/- I (DT) did not try to minimise the assumptions. -/
section group
variables [group α] [has_le α]
section right
variables [covariant_class α α (swap (*)) (≤)] {a b c d : α}
@[simp, to_additive]
lemma div_le_div_iff_right (c : α) : a / c ≤ b / c ↔ a ≤ b :=
by simpa only [div_eq_mul_inv] using mul_le_mul_iff_right _
@[to_additive sub_le_sub_right]
lemma div_le_div_right' (h : a ≤ b) (c : α) : a / c ≤ b / c :=
(div_le_div_iff_right c).2 h
@[simp, to_additive sub_nonneg]
lemma one_le_div' : 1 ≤ a / b ↔ b ≤ a :=
by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le
@[simp, to_additive sub_nonpos]
lemma div_le_one' : a / b ≤ 1 ↔ a ≤ b :=
by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le
@[to_additive]
lemma le_div_iff_mul_le : a ≤ c / b ↔ a * b ≤ c :=
by rw [← mul_le_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right]
alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le
@[to_additive]
lemma div_le_iff_le_mul : a / c ≤ b ↔ a ≤ b * c :=
by rw [← mul_le_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right]
-- TODO: Should we get rid of `sub_le_iff_le_add` in favor of
-- (a renamed version of) `tsub_le_iff_right`?
@[priority 100] -- see Note [lower instance priority]
instance add_group.to_has_ordered_sub {α : Type*} [add_group α] [has_le α]
[covariant_class α α (swap (+)) (≤)] : has_ordered_sub α :=
⟨λ a b c, sub_le_iff_le_add⟩
end right
section left
variables [covariant_class α α (*) (≤)]
variables [covariant_class α α (swap (*)) (≤)] {a b c : α}
@[simp, to_additive]
lemma div_le_div_iff_left (a : α) : a / b ≤ a / c ↔ c ≤ b :=
by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_le_mul_iff_left a⁻¹, inv_mul_cancel_left,
inv_mul_cancel_left, inv_le_inv_iff]
@[to_additive sub_le_sub_left]
lemma div_le_div_left' (h : a ≤ b) (c : α) : c / b ≤ c / a :=
(div_le_div_iff_left c).2 h
end left
end group
section comm_group
variables [comm_group α]
section has_le
variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α}
@[to_additive sub_le_sub_iff]
lemma div_le_div_iff' : a / b ≤ c / d ↔ a * d ≤ c * b :=
by simpa only [div_eq_mul_inv] using mul_inv_le_mul_inv_iff'
@[to_additive]
lemma le_div_iff_mul_le' : b ≤ c / a ↔ a * b ≤ c :=
by rw [le_div_iff_mul_le, mul_comm]
alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le
@[to_additive]
lemma div_le_iff_le_mul' : a / b ≤ c ↔ a ≤ b * c :=
by rw [div_le_iff_le_mul, mul_comm]
alias sub_le_iff_le_add' ↔ le_add_of_sub_left_le sub_left_le_of_le_add
@[simp, to_additive]
lemma inv_le_div_iff_le_mul : b⁻¹ ≤ a / c ↔ c ≤ a * b :=
le_div_iff_mul_le.trans inv_mul_le_iff_le_mul'
@[to_additive]
lemma inv_le_div_iff_le_mul' : a⁻¹ ≤ b / c ↔ c ≤ a * b :=
by rw [inv_le_div_iff_le_mul, mul_comm]
@[to_additive]
lemma div_le_comm : a / b ≤ c ↔ a / c ≤ b := div_le_iff_le_mul'.trans div_le_iff_le_mul.symm
@[to_additive]
lemma le_div_comm : a ≤ b / c ↔ c ≤ b / a := le_div_iff_mul_le'.trans le_div_iff_mul_le.symm
end has_le
section preorder
variables [preorder α] [covariant_class α α (*) (≤)] {a b c d : α}
@[to_additive sub_le_sub]
lemma div_le_div'' (hab : a ≤ b) (hcd : c ≤ d) :
a / d ≤ b / c :=
begin
rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_le_inv_mul_iff, mul_comm],
exact mul_le_mul' hab hcd
end
end preorder
end comm_group
/- Most of the lemmas that are primed in this section appear in ordered_field. -/
/- I (DT) did not try to minimise the assumptions. -/
section group
variables [group α] [has_lt α]
section right
variables [covariant_class α α (swap (*)) (<)] {a b c d : α}
@[simp, to_additive]
lemma div_lt_div_iff_right (c : α) : a / c < b / c ↔ a < b :=
by simpa only [div_eq_mul_inv] using mul_lt_mul_iff_right _
@[to_additive sub_lt_sub_right]
lemma div_lt_div_right' (h : a < b) (c : α) : a / c < b / c :=
(div_lt_div_iff_right c).2 h
@[simp, to_additive sub_pos]
lemma one_lt_div' : 1 < a / b ↔ b < a :=
by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt
@[simp, to_additive sub_neg]
lemma div_lt_one' : a / b < 1 ↔ a < b :=
by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_neg ↔ lt_of_sub_neg sub_neg_of_lt
alias sub_neg ← sub_lt_zero
@[to_additive]
lemma lt_div_iff_mul_lt : a < c / b ↔ a * b < c :=
by rw [← mul_lt_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right]
alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt
@[to_additive]
lemma div_lt_iff_lt_mul : a / c < b ↔ a < b * c :=
by rw [← mul_lt_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right]
alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add
end right
section left
variables [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c : α}
@[simp, to_additive]
lemma div_lt_div_iff_left (a : α) : a / b < a / c ↔ c < b :=
by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_lt_mul_iff_left a⁻¹, inv_mul_cancel_left,
inv_mul_cancel_left, inv_lt_inv_iff]
@[simp, to_additive]
lemma inv_lt_div_iff_lt_mul : a⁻¹ < b / c ↔ c < a * b :=
by rw [div_eq_mul_inv, lt_mul_inv_iff_mul_lt, inv_mul_lt_iff_lt_mul]
@[to_additive sub_lt_sub_left]
lemma div_lt_div_left' (h : a < b) (c : α) : c / b < c / a :=
(div_lt_div_iff_left c).2 h
end left
end group
section comm_group
variables [comm_group α]
section has_lt
variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α}
@[to_additive sub_lt_sub_iff]
lemma div_lt_div_iff' : a / b < c / d ↔ a * d < c * b :=
by simpa only [div_eq_mul_inv] using mul_inv_lt_mul_inv_iff'
@[to_additive]
lemma lt_div_iff_mul_lt' : b < c / a ↔ a * b < c :=
by rw [lt_div_iff_mul_lt, mul_comm]
alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt
@[to_additive]
lemma div_lt_iff_lt_mul' : a / b < c ↔ a < b * c :=
by rw [div_lt_iff_lt_mul, mul_comm]
alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add
@[to_additive]
lemma inv_lt_div_iff_lt_mul' : b⁻¹ < a / c ↔ c < a * b :=
lt_div_iff_mul_lt.trans inv_mul_lt_iff_lt_mul'
@[to_additive]
lemma div_lt_comm : a / b < c ↔ a / c < b := div_lt_iff_lt_mul'.trans div_lt_iff_lt_mul.symm
@[to_additive]
lemma lt_div_comm : a < b / c ↔ c < b / a := lt_div_iff_mul_lt'.trans lt_div_iff_mul_lt.symm
end has_lt
section preorder
variables [preorder α] [covariant_class α α (*) (<)] {a b c d : α}
@[to_additive sub_lt_sub]
lemma div_lt_div'' (hab : a < b) (hcd : c < d) :
a / d < b / c :=
begin
rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_lt_inv_mul_iff, mul_comm],
exact mul_lt_mul_of_lt_of_lt hab hcd
end
end preorder
end comm_group
section linear_order
variables [group α] [linear_order α]
@[simp, to_additive cmp_sub_zero]
lemma cmp_div_one' [covariant_class α α (swap (*)) (≤)] (a b : α) : cmp (a / b) 1 = cmp a b :=
by rw [← cmp_mul_right' _ _ b, one_mul, div_mul_cancel']
variables [covariant_class α α (*) (≤)]
section variable_names
variables {a b c : α}
@[to_additive]
lemma le_of_forall_one_lt_lt_mul (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b :=
le_of_not_lt (λ h₁, lt_irrefl a (by simpa using (h _ (lt_inv_mul_iff_lt.mpr h₁))))
@[to_additive]
lemma le_iff_forall_one_lt_lt_mul : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε :=
⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul⟩
/- I (DT) introduced this lemma to prove (the additive version `sub_le_sub_flip` of)
`div_le_div_flip` below. Now I wonder what is the point of either of these lemmas... -/
@[to_additive]
lemma div_le_inv_mul_iff [covariant_class α α (swap (*)) (≤)] :
a / b ≤ a⁻¹ * b ↔ a ≤ b :=
begin
rw [div_eq_mul_inv, mul_inv_le_inv_mul_iff],
exact ⟨λ h, not_lt.mp (λ k, not_lt.mpr h (mul_lt_mul_of_lt_of_lt k k)), λ h, mul_le_mul' h h⟩,
end
/- What is the point of this lemma? See comment about `div_le_inv_mul_iff` above. -/
@[simp, to_additive]
lemma div_le_div_flip {α : Type*} [comm_group α] [linear_order α] [covariant_class α α (*) (≤)]
{a b : α}:
a / b ≤ b / a ↔ a ≤ b :=
begin
rw [div_eq_mul_inv b, mul_comm],
exact div_le_inv_mul_iff,
end
end variable_names
end linear_order
/-!
### Linearly ordered commutative groups
-/
/-- A linearly ordered additive commutative group is an
additive commutative group with a linear order in which
addition is monotone. -/
@[protect_proj, ancestor ordered_add_comm_group linear_order]
class linear_ordered_add_comm_group (α : Type u) extends ordered_add_comm_group α, linear_order α
/-- A linearly ordered commutative monoid with an additively absorbing `⊤` element.
Instances should include number systems with an infinite element adjoined.` -/
@[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial]
class linear_ordered_add_comm_group_with_top (α : Type*)
extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α :=
(neg_top : - (⊤ : α) = ⊤)
(add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0)
/-- A linearly ordered commutative group is a
commutative group with a linear order in which
multiplication is monotone. -/
@[protect_proj, ancestor ordered_comm_group linear_order, to_additive]
class linear_ordered_comm_group (α : Type u) extends ordered_comm_group α, linear_order α
section linear_ordered_comm_group
variables [linear_ordered_comm_group α] {a b c : α}
@[to_additive linear_ordered_add_comm_group.add_lt_add_left]
lemma linear_ordered_comm_group.mul_lt_mul_left'
(a b : α) (h : a < b) (c : α) : c * a < c * b :=
mul_lt_mul_left' h c
@[to_additive eq_zero_of_neg_eq]
lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 :=
match lt_trichotomy a 1 with
| or.inl h₁ :=
have 1 < a, from h ▸ one_lt_inv_of_inv h₁,
absurd h₁ this.asymm
| or.inr (or.inl h₁) := h₁
| or.inr (or.inr h₁) :=
have a < 1, from h ▸ inv_lt_one'.mpr h₁,
absurd h₁ this.asymm
end
@[to_additive exists_zero_lt]
lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a :=
begin
obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α),
cases hy.lt_or_lt,
{ exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ },
{ exact ⟨y, h⟩ }
end
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_no_max_order [nontrivial α] :
no_max_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt',
exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩
end ⟩
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_no_min_order [nontrivial α] : no_min_order α :=
⟨ begin
obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt',
exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩
end ⟩
@[priority 100, to_additive] -- See note [lower instance priority]
instance linear_ordered_comm_group.to_linear_ordered_cancel_comm_monoid :
linear_ordered_cancel_comm_monoid α :=
{ ..‹linear_ordered_comm_group α›, ..ordered_comm_group.to_ordered_cancel_comm_monoid }
end linear_ordered_comm_group
namespace add_comm_group
/-- A collection of elements in an `add_comm_group` designated as "non-negative".
This is useful for constructing an `ordered_add_commm_group`
by choosing a positive cone in an exisiting `add_comm_group`. -/
@[nolint has_nonempty_instance]
structure positive_cone (α : Type*) [add_comm_group α] :=
(nonneg : α → Prop)
(pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (-a))
(pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac)
(zero_nonneg : nonneg 0)
(add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b))
(nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0)
/-- A positive cone in an `add_comm_group` induces a linear order if
for every `a`, either `a` or `-a` is non-negative. -/
@[nolint has_nonempty_instance]
structure total_positive_cone (α : Type*) [add_comm_group α] extends positive_cone α :=
(nonneg_decidable : decidable_pred nonneg)
(nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a))
/-- Forget that a `total_positive_cone` is total. -/
add_decl_doc total_positive_cone.to_positive_cone
end add_comm_group
namespace ordered_add_comm_group
open add_comm_group
/-- Construct an `ordered_add_comm_group` by
designating a positive cone in an existing `add_comm_group`. -/
def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : positive_cone α) :
ordered_add_comm_group α :=
{ le := λ a b, C.nonneg (b - a),
lt := λ a b, C.pos (b - a),
lt_iff_le_not_le := λ a b, by simp; rw [C.pos_iff]; simp,
le_refl := λ a, by simp [C.zero_nonneg],
le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg];
rw ← sub_add_sub_cancel; exact C.add_nonneg nbc nab,
le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $
C.nonneg_antisymm nba (by rw neg_sub; exact nab),
add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab,
..‹add_comm_group α› }
end ordered_add_comm_group
namespace linear_ordered_add_comm_group
open add_comm_group
/-- Construct a `linear_ordered_add_comm_group` by
designating a positive cone in an existing `add_comm_group`
such that for every `a`, either `a` or `-a` is non-negative. -/
def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : total_positive_cone α) :
linear_ordered_add_comm_group α :=
{ le_total := λ a b, by { convert C.nonneg_total (b - a), change C.nonneg _ = _, congr, simp, },
decidable_le := λ a b, C.nonneg_decidable _,
..ordered_add_comm_group.mk_of_positive_cone C.to_positive_cone }
end linear_ordered_add_comm_group
section norm_num_lemmas
/- The following lemmas are stated so that the `norm_num` tactic can use them with the
expected signatures. -/
variables [ordered_comm_group α] {a b : α}
@[to_additive neg_le_neg]
lemma inv_le_inv' : a ≤ b → b⁻¹ ≤ a⁻¹ :=
inv_le_inv_iff.mpr
@[to_additive neg_lt_neg]
lemma inv_lt_inv' : a < b → b⁻¹ < a⁻¹ :=
inv_lt_inv_iff.mpr
/- The additive version is also a `linarith` lemma. -/
@[to_additive]
theorem inv_lt_one_of_one_lt : 1 < a → a⁻¹ < 1 :=
inv_lt_one_iff_one_lt.mpr
/- The additive version is also a `linarith` lemma. -/
@[to_additive]
lemma inv_le_one_of_one_le : 1 ≤ a → a⁻¹ ≤ 1 :=
inv_le_one'.mpr
@[to_additive neg_nonneg_of_nonpos]
lemma one_le_inv_of_le_one : a ≤ 1 → 1 ≤ a⁻¹ :=
one_le_inv'.mpr
end norm_num_lemmas
section
variables {β : Type*}
[group α] [preorder α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)]
[preorder β] {f : β → α} {s : set β}
@[to_additive] lemma monotone.inv (hf : monotone f) : antitone (λ x, (f x)⁻¹) :=
λ x y hxy, inv_le_inv_iff.2 (hf hxy)
@[to_additive] lemma antitone.inv (hf : antitone f) : monotone (λ x, (f x)⁻¹) :=
λ x y hxy, inv_le_inv_iff.2 (hf hxy)
@[to_additive] lemma monotone_on.inv (hf : monotone_on f s) :
antitone_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_le_inv_iff.2 (hf hx hy hxy)
@[to_additive] lemma antitone_on.inv (hf : antitone_on f s) :
monotone_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_le_inv_iff.2 (hf hx hy hxy)
end
section
variables {β : Type*}
[group α] [preorder α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)]
[preorder β] {f : β → α} {s : set β}
@[to_additive] lemma strict_mono.inv (hf : strict_mono f) : strict_anti (λ x, (f x)⁻¹) :=
λ x y hxy, inv_lt_inv_iff.2 (hf hxy)
@[to_additive] lemma strict_anti.inv (hf : strict_anti f) : strict_mono (λ x, (f x)⁻¹) :=
λ x y hxy, inv_lt_inv_iff.2 (hf hxy)
@[to_additive] lemma strict_mono_on.inv (hf : strict_mono_on f s) :
strict_anti_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_lt_inv_iff.2 (hf hx hy hxy)
@[to_additive] lemma strict_anti_on.inv (hf : strict_anti_on f s) :
strict_mono_on (λ x, (f x)⁻¹) s :=
λ x hx y hy hxy, inv_lt_inv_iff.2 (hf hx hy hxy)
end
|
% This is a test file to cofirm if Conceal features are enabled and work well.
% This file does not aim at checking TeX-compilability.
% <DO NOT TRY TO COMPILE THIS FILE!>
% Edited by N-yam-my, Dec 7 2021.
\documentclass{standalone}
\begin{document}
% Symbols
\[
\alpha, \Omega, \nabla, \emptyset, \Re, \Rightarrow, \to, \mapsto,
\P, \S, \aleph, \amalg, \angle, \approx, \cup, \bigcup, \circ,
\odot, \bigsqcup, \bot, \bullet, \cdots, \exists, \mp, \parallel,
\because, \geq, \hslash, \nparallel, \Uppsi
\]
% Big Operators
\[
\int, \iint, \iiint, \oint, \sum, \prod,
\]
% Mathfonts
\[
\mathbb{1}, \mathbb{a}, \mathbb{Z}, \mathrm{A}, \mathrm{z},
\bm{A}, \bm{z}, \mathscr{A}, \mathfrak{S},
\]
% Text
\textbf{Bold}, \textit{Italic}, \underline{Underline},
\begin{itemize}
\item
\end{itemize}
``abcDEF.''
%% if let g:vimtex_syntax_conceal = {'sections':1}
\section{Section}
\subsection{Subsection}
\end{document} |
# Musterlösung zu Übungsblatt 1
* [Aufgabe 1](#Aufgabe-1)
* [Aufgabe 2](#Aufgabe-2)
* [Aufgabe 3](#Aufgabe-3)
```python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
plt.style.use('ggplot')
```
---
## Aufgabe 1
Gegeben sei eine parametrische Funktion $y = f(x)$, $y = 1 + a_1x + a_2x^2$ mit Parametern $a_1 = 2.0 ± 0.2$, $a_2 = 1.0 ± 0.1$ und Korrelationskoeffizient $ρ = −0.8$.
---
```python
a1, a1_err = 2.0, 0.2
a2, a2_err = 1.0, 0.1
rho = -0.8
```
---
### 1.1
Geben Sie die Kovarianzmatrix von $a_1$ und $a_2$ an.
---
Die Kovarianzmatrix von $a_1$ und $a_2$ lässt sich wie folgt berechnen:
$$\mathrm{Cov}(a) = \pmatrix{\sigma^2_{a_1} & \rho\sigma_{a_1}\sigma_{a_2} \\
\rho\sigma_{a_1}\sigma_{a_2} & \sigma^2_{a_2}}$$
```python
c12 = rho * a1_err * a2_err
covariance = np.matrix([[a1_err ** 2, c12], [c12, a2_err ** 2]])
covariance
```
matrix([[ 0.04 , -0.016],
[-0.016, 0.01 ]])
---
### 1.2
Bestimmen Sie analytisch die Unsicherheit von $y$ als Funktion von $x$:
---
Dazu bestimmen wir zunaechst die Ableitungen von $y$ nach $a_1$ und $a_2$
$$\frac{\partial{}y}{\partial{}a_1} = x \,,\quad \frac{\partial{}y}{\partial{}a_2} = x^2 \,.$$
Daraus können wir die Kovarianz von $y$ nach
$$\sigma^2_y = \mathrm{Cov}(y) = \sum_{ij}\frac{\partial{}y}{\partial{}a_i}\frac{\partial{}y}{\partial{}a_j}\mathrm{Cov}(a)_{ij}$$
bestimmen. Einsetzen der eingangs bestimmten Ableitungen liefert
$$\sigma^2_y = c_{11}x^2 + 2c_{12}x^3 + c_{22}x^4$$
wobei die $c_{ij}$ die Einträge von $\mathrm{Cov}(a)$ sind. Der Ausdruck lässt sich weiter vereinfachen zu
$$\sigma^2_y = x^2\left(\sigma^2_{a_1} + \sigma^2_{a_2}x^2 + 2\rho\sigma_{a_1}\sigma_{a_2}x\right) \,.$$
Daraus ergibt sich für die Unsicherheit
$$ \sigma_y = \lvert{}x\rvert\sqrt{\sigma^2_{a_1} + \sigma^2_{a_2}x^2 + 2\rho\sigma_{a_1}\sigma_{a_2}x} \,.$$
---
#### 1.2.1
unter Vernachlässigung der Korrelation
---
(also für $\rho = 0$) vereinfacht sich der obige Ausdruck zu
$$\sigma_y = \lvert{}x\rvert\sqrt{\sigma^2_{a_1} + \sigma^2_{a_2}x^2} \,.$$
Mit den eingangs berechneten Werten aus `covariance` ergibt sich also
$$\sigma_y = \lvert{}x\rvert\sqrt{0.04 + 0.01x^2} = 0.2\lvert{}x\rvert{}\sqrt{1 + 0.25x^2} \,.$$
```python
def err_ana_wo(x):
return 0.2 * np.abs(x) * np.sqrt(1 + 0.25 * x ** 2)
xs = np.linspace(-10, 10, 10000)
ys = 1 + a1 * xs + a2 * xs ** 2
errs = err_ana_wo(xs)
plt.plot(xs, ys)
plt.fill_between(xs, ys - errs, ys + errs, alpha=0.5)
plt.show()
```
---
#### 1.2.2
mit Berücksichtigung der Korrelation
---
$$\sigma_y = \lvert{}x\rvert\sqrt{0.04 + 0.01x^2 - 0.016x} = 0.2\lvert{}x\rvert\sqrt{1 + 0.25x^2 - 0.4x} \,.$$
```python
def err_ana(x):
return 0.2 * np.abs(x) * np.sqrt(1 + 0.25 * x ** 2 - 0.4 * x)
errs = err_ana(xs)
plt.plot(xs, ys)
plt.fill_between(xs, ys - errs, ys + errs, alpha=0.5)
plt.show()
```
---
### 1.3
Bestimmen Sie per Monte Carlo die Unsicherheit von $y$ als Funktion von $x$:
#### 1.3.1
Generieren Sie Wertepaare $(a_1, a_2)$ gemäß ihrer Kovarianzmatrix und visualisieren Sie diese, z.B. mit einem Scatter-Plot.
_Hinweis_: Wenn $x_1$ und $x_2$ zwei gaussverteilte Zufallszahlen mit Mittelwert null und Varianz eins sind, erhält man ein Paar korrelierter gaussverteilter Zufallszahlen $(y_1, y_2)$ mit Mittelwert null und Varianz eins durch $(y_1 = x_1; y_2 = x_1ρ + x_2\sqrt{1 − \rho^2})$.
---
```python
x1s, x2s = np.random.normal(size=(2, 10000))
plt.hist2d(x1s, x2s, bins=40)
plt.title('2-dim Normalverteilung')
plt.xlabel('$x_1$')
plt.ylabel('$x_2$')
plt.show()
y1s = x1s
y2s = x1s * rho + x2s * np.sqrt(1 - rho ** 2)
plt.hist2d(y1s, y2s, bins=40)
plt.title('2-dim Normalverteilung mit Korrelation')
plt.xlabel('$y_1$')
plt.ylabel('$y_2$')
plt.show()
a1s = a1 + y1s * a1_err
a2s = a2 + y2s * a2_err
plt.hist2d(a1s, a2s, bins=40)
plt.title('Verteilung der $a_1$ und $a_2$')
plt.xlabel('$a_1$')
plt.ylabel('$a_2$')
plt.show()
```
---
#### 1.3.2
Bestimmen Sie die Verteilung von $y$ für $x = \{−1, 0, +1\}$ und vergleichen Sie Mittelwert und Varianz (Standardabweichung) mit den Resultaten der analytischen Rechnung.
---
```python
def y(x, a1, a2):
return 1 + a1 * x + a2 * x ** 2
def var_analytical(x):
xx = x ** 2
return 0.04 * xx * (1 + 0.25 * xx - 0.16 * x)
for x in (-1, 0, 1):
ys = y(x, a1s, a2s)
mean = np.mean(ys)
var = np.var(ys)
print('〈y({})〉= {:.3f}'.format(x, mean))
print(' σ² = {:.3f}'.format(var))
print(' analytical = {:.3f}'.format(var_analytical(x)))
plt.hist(ys, bins=100)
plt.xlabel('y({})'.format(x))
plt.ylabel('Absolute Häufigkeit')
plt.show()
```
Der Fall $x = 0$ ist hier besonders. Da alle Koeffizienten vor Potenzen von $x$ stehen, ergibt sich für den Fall immer $y=0$ unabhängig von den $a_i$. Wir können also keine Aussage über die Varianz treffen.
---
## Aufgabe 2
Betrachten Sie folgende Reparametrisierung von $y = f(x)$:
$$y = 1 + \frac{x(1+x)}{b_1} + \frac{x(1-x)}{b_2}$$
### 2.1
Bestimmen Sie analytisch die transformierten Parameter $b_1$ und $b_2$ und deren Kovarianzmatrix
---
Wir lösen die Reparametrisierung nach Koeffizienten von Potenzen von $x$ auf. Dabei können wir den Term $1$ vernachlässigen, weil er in beiden Definitionen gleichermaßen auftritt.
\begin{align}
a_1 x + a_2 x^2 &= \frac{x(1 + x)}{b_1} + \frac{x(1 - x)}{b_2} \\
&= \frac{x}{b_1} + \frac{x^2}{b_1} + \frac{x}{b_2} - \frac{x^2}{b_2} \\
&= x\left(\frac{1}{b_1} + \frac{1}{b_2}\right) + x^2\left(\frac{1}{b_1} - \frac{1}{b_2}\right)
\end{align}
Damit ist
$$a_1 = \left(\frac{1}{b_1} + \frac{1}{b_2}\right) \quad\text{und}\quad a_2 = \left(\frac{1}{b_1} - \frac{1}{b_2}\right)$$
also
$$b_1 = \frac{2}{a_1 + a_2} \quad\text{und}\quad b_2 = \frac{2}{a_1 - a_2} \,.$$
Für die Jacobimatrix der Transformation ergibt sich
\begin{equation}
M = \pmatrix{
\frac{-2}{(a_1 + a_2)^2} & \frac{-2}{(a_1 + a_2)^2} \\
\frac{-2}{(a_1 - a_2)^2} & \frac{+2}{(a_1 - a_2)^2}
} \quad\text{wobei}\quad m_{ij} = \frac{\partial b_i}{\partial a_j}
\end{equation}
\begin{equation}
M^T = \pmatrix{
\frac{-2}{(a_1 + a_2)^2} & \frac{-2}{(a_1 - a_2)^2} \\
\frac{-2}{(a_1 + a_2)^2} & \frac{+2}{(a_1 - a_2)^2}
}
\end{equation}
Die transformierte Kovarianzmatrix ist dann $\mathrm{Cov}(b) = M\mathrm{Cov}(a)M^T$.
```python
b1 = 2 / (a1 + a2)
b2 = 2 / (a1 - a2)
denom1 = (a1 + a2) ** 2
denom2 = (a1 - a2) ** 2
M = np.matrix([[-2 / denom1, -2 / denom1], [-2 / denom2, 2 / denom2]])
cov_b = M * covariance * M.T
cov_b
```
matrix([[ 0.00088889, 0.01333333],
[ 0.01333333, 0.328 ]])
---
### 2.2
Bestimmen Sie die Kovarianzmatrix der transformierten Parameter per Monte Carlo
---
```python
b1s = 2 / (a1s + a2s)
b2s = 2 / (a1s - a2s)
print('b1 = {}'.format(np.mean(b1s)))
print('var = {}'.format(np.var(b1s)))
print('b2 = {}'.format(np.mean(b2s)))
print('var = {}'.format(np.var(b2s)))
plt.hist(b1s, bins=100)
plt.show()
plt.hist(b2s, bins=100)
plt.show()
```
Dabei tritt das Problem auf, dass für einige Kombinationen von Werten für $a_1$ und $a_2$ der Nenner sehr nah an `0` kommt. Dadurch ergeben sich sehr große (unrealistische) Werte für $b_2$. Wir können dem entgegenwirken, indem wir einen Bereich festlegen in dem wir die Werte für $b_2$ erwarten.
```python
cut = np.logical_and(b2s < 5, b2s > 0)
b1s_ = b1s[cut]
b2s_ = b2s[cut]
print('b2 gefiltert = {}'.format(np.mean(b2s_)))
print('var = {}'.format(np.var(b2s_)))
plt.hist(b1s_, bins=100)
plt.show()
plt.hist2d(b1s_, b2s_, bins=100)
plt.show()
```
Wenn wir uns das Leben etwas erleichtern wollen, koennen wir auch einfach die Funktion `cov` aus Numpy verwenden, die uns fuer zwei Arrays direkt die Kovarianzmatrix ausrechnet
```python
ncov_b = np.cov(b1s_, b2s_)
ncov_b
```
array([[ 0.0008353 , 0.01402655],
[ 0.01402655, 0.45535159]])
---
### 2.3
Bestimmen Sie analytisch die Unsicherheit von $y$ als Funktion von $x$:
#### 2.3.1
unter Verwendung der analytisch bestimmten Kovarianzmatrix von $(b_1, b_2)$
---
Zunächst berechnen wir die partiellen Ableitungen von $y$ nach den Koeffizienten $b_1$ und $b_2$.
\begin{equation}
\frac{\partial y}{\partial b_1} = \frac{-x(1+x)}{b_1^2} \quad\text{und}{\quad} \frac{\partial y}{\partial b_2} = \frac{-x(1-x)}{b_2^2}
\end{equation}
Damit ergibt sich für die Varianz
\begin{align}
\sigma_y^2 &= \sum_{ij}\frac{\partial y}{\partial b_i}\frac{\partial y}{\partial b_j}\mathrm{Cov}(b)_{ij} \\
&= \frac{x^2(1+x)^2}{b_1^4}\sigma_{b_1}^2 + 2\frac{x^2 - x^3}{b_1^2b_2^2}\rho\sigma_{b_1}\sigma_{b_2} + \frac{x^2(1-x)^2}{b_2^4}\sigma_{b_2}^2 \\
&= x^2\left[(\alpha+\beta)x^2 + (2\alpha - 2\beta - \gamma)x + (\alpha + \beta + \gamma)\right] \\
&= x^2\left(c_2x^2 + c_1x + c_0\right)
\end{align}
mit den Koeffizienten
\begin{equation}
\alpha = \frac{\sigma_{b_1}^2}{b_1^4} \quad,\quad
\beta = \frac{\sigma_{b_2}^2}{b_2^4} \quad\text{und}\quad
\gamma = \frac{\rho\sigma_{b_1}\sigma_{b_2}}{b_1^2b_2^2} \,.
\end{equation}
In Zahlen ausgedrückt sind die Koeffizienten
```python
s2_b1 = cov_b[0, 0]
s2_b2 = cov_b[1, 1]
rho12 = cov_b[0, 1]
alpha = s2_b1 / b1 ** 4
beta = s2_b2 / b2 ** 4
gamma = rho12 / b1 ** 2 / b2 ** 2
c2 = alpha + beta
c1 = 2 * c2 - gamma
c0 = c2 + gamma
c2, c1, c0
```
(0.025000000000000005, 0.04250000000000001, 0.032500000000000008)
Es ist also
\begin{equation}
\sigma_y^2 = x^2\left(0.025x^2 + 0.0425x + 0.0325\right)
\end{equation}
und damit
\begin{equation}
\sigma_y = \lvert{}x\rvert\sqrt{0.025x^2 + 0.0425x + 0.0325}
\end{equation}
```python
def err_ana(x):
return np.abs(x) * np.sqrt(c2 * x ** 2 + c1 * x + c0)
xs = np.linspace(-10, 10, 10000)
ys = 1 + xs * (xs + 1) / b1 + xs * (xs - 1) / b2
errs = err_ana(xs)
plt.plot(xs, ys)
plt.fill_between(xs, ys - errs, ys + errs, alpha=0.5)
plt.show()
```
---
#### 2.3.2
unter Verwendung der numerisch bestimmten Kovarianzmatrix von $(b_1, b_2)$
---
Die gleiche Rechnung mit den per Monte Carlo bestimmten Werten
```python
s2_b1 = ncov_b[0, 0]
s2_b2 = ncov_b[1, 1]
rho12 = ncov_b[0, 1]
alpha = s2_b1 / b1 ** 4
beta = s2_b2 / b2 ** 4
gamma = rho12 / b1 ** 2 / b2 ** 2
c2n = alpha + beta
c1n = 2 * c2 - gamma
c0n = c2 + gamma
c2n, c1n, c0n
```
(0.032688177932642684, 0.042110063518531804, 0.032889936481468214)
liefert also ein etwas überschätzte Ungenauigkeit von
\begin{equation}
\sigma_y = \lvert{}x\rvert\sqrt{0.0320x^2 + 0.0563x + 0.0398}
\end{equation}
```python
def err_num(x):
return np.abs(x) * np.sqrt(c2n * x ** 2 + c1n * x + c0n)
errs = err_num(xs)
plt.plot(xs, ys)
plt.fill_between(xs, ys - errs, ys + errs, alpha=0.5)
plt.show()
```
---
## Aufgabe 3
Lösen Sie die obigen Teilaufgaben für $y = f(x)$ mit
$$y = \ln\left(1 + a_1x + a_2x^2\right) \quad \text{bzw.} \quad y = \ln\left(1 + \frac{x(1+x)}{b_1} + \frac{x(x-1)}{b_2}\right)$$
Im folgenden nennen wir das neue $y$ der Einfachheit halber $z$.
\begin{equation}
z = \ln(1 + a_1x + a_2x^2) = \ln(y)
\end{equation}
Für die Unsicherheit von $z$ ergibt sich
\begin{align}
\sigma_z &= \sqrt{\left(\frac{\partial z}{\partial y}\right)^2\sigma_y^2} \\
&= \sqrt{\left(\frac{1}{y}\right)^2\sigma_y^2} \\
&= \left\lvert\frac{\sigma_y}{y}\right\rvert \\
&= \frac{0.2\lvert x\rvert\sqrt{1 + 0.25x^2 - 0.4x}}{\lvert 1 + a_1 x + a_2 x^2 \rvert} \,.
\end{align}
Völlig analog ist die Rechnung für die Reparametrisierung. Hier ergibt sich
\begin{align}
\sigma_z &= \left\lvert\frac{\sigma_y}{y}\right\rvert \\
&= \frac{\lvert{}x\rvert\sqrt{0.025x^2 + 0.0425x + 0.0325}}{\left\lvert 1 + \frac{x(1+x)}{b_1} + \frac{x(x-1)}{b_2}\right\rvert} \,.
\end{align}
```python
def err1(x):
return 0.2 * np.abs(x) * np.sqrt(1 + 0.25 * x ** 2 - 0.4 * x) / np.abs(1)
def err2(x):
return np.abs(x) * np.sqrt(c2 * x ** 2 + c1 * x + c0) / np.abs(1 + xs * (xs + 1) / b1 + xs * (xs - 1) / b2)
xs = np.linspace(-10, 10, 10000)
ys1 = 1 + a1 * xs + a2 * xs ** 2
ys2 = np.log(1 + xs * (xs + 1) / b1 + xs * (xs - 1) / b2)
errs1 = err1(xs)
errs2 = err2(xs)
plt.plot(xs, ys1)
plt.fill_between(xs, ys1 - errs1, ys1 + errs1, alpha=0.5)
plt.show()
plt.plot(xs, ys2)
plt.fill_between(xs, ys2 - errs2, ys2 + errs2, alpha=0.5)
plt.show()
```
|
function [c]=findcntr(H)
%
% [Center]=findcntr(Handle)
% Returns the geometric center of Handle
%
% This can be used as the ORIGIN input in ROTATE to rotate
% an object about its geometric center.
%
% See also ROTATE, TRNSLATE, SCALHAND
%
% Richard G. Cobb 3/96
%
c=[0 0 0];
tmp=(max(get(H,'Xdata'))+min(get(H,'Xdata')))/2;
if tmp ~= []
c(1)=tmp;
else
set(H,'Xdata',zeros(size(get(H,'Ydata'))))
end
tmp=(max(get(H,'Ydata'))+min(get(H,'Ydata')))/2;
if tmp ~= []
c(2)=tmp;
else
set(H,'Ydata',zeros(size(get(H,'Xdata'))))
end
tmp=(max(get(H,'Zdata'))+min(get(H,'Zdata')))/2;
if tmp ~= []
c(3)=tmp;
else
set(H,'Zdata',zeros(size(get(H,'Ydata'))))
end
%eof
|
/-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import number_theory.class_number.admissible_card_pow_degree
import number_theory.class_number.finite
import number_theory.function_field
/-!
# Class numbers of function fields
This file defines the class number of a function field as the (finite) cardinality of
the class group of its ring of integers. It also proves some elementary results
on the class number.
## Main definitions
- `function_field.class_number`: the class number of a function field is the (finite)
cardinality of the class group of its ring of integers
-/
namespace function_field
open_locale polynomial
variables (Fq F : Type) [field Fq] [fintype Fq] [field F]
variables [algebra Fq[X] F] [algebra (ratfunc Fq) F]
variables [is_scalar_tower Fq[X] (ratfunc Fq) F]
variables [function_field Fq F] [is_separable (ratfunc Fq) F]
open_locale classical
namespace ring_of_integers
open function_field
noncomputable instance : fintype (class_group (ring_of_integers Fq F) F) :=
class_group.fintype_of_admissible_of_finite (ratfunc Fq) F
(polynomial.card_pow_degree_is_admissible : absolute_value.is_admissible
(polynomial.card_pow_degree : absolute_value Fq[X] ℤ))
end ring_of_integers
/-- The class number in a function field is the (finite) cardinality of the class group. -/
noncomputable def class_number : ℕ := fintype.card (class_group (ring_of_integers Fq F) F)
/-- The class number of a function field is `1` iff the ring of integers is a PID. -/
theorem class_number_eq_one_iff :
class_number Fq F = 1 ↔ is_principal_ideal_ring (ring_of_integers Fq F) :=
card_class_group_eq_one_iff
end function_field
|
# Let E be the surjection operad, as explained by Berger and Fresse
# following McClure. We represent a basis element of E(A) by
# expressions S(...), where the arguments are elements of A,
# each element appears at least once, and no two adjacent elements
# are the same.
`is_element/surjections` := (A::set) -> proc(x)
global reason;
local i,y,z;
if x = 0 then return true; fi;
if type(x,`+`) then
return `and`(op(map(`is_element/surjections`(A),[op(x)])));
fi;
if type(x,`*`) then
y,z := selectremove(type,[op(x)],integer);
return (nops(z) = 1 and `is_element/surjections`(A)(z[1]));
fi;
if not type(x,specfunc(S)) then return false; fi;
if {op(x)} <> A then return false; fi;
for i from 1 to nops(x) - 1 do
if x[i] = x[i+1] then return false; fi;
od;
return true;
end:
`is_equal/surjections` := (A::set) -> (x0,x1) -> evalb(expand(x0 - x1) = 0);
`is_equal_unsigned/surjections` := (A::set) -> (x0,x1) -> evalb(modp(expand(x0 - x1),2) = 0);
`random_basis_element/surjections` := (A) -> proc(m_)
local n,m,i,x,ok;
n := nops(A);
if n = 0 then return FAIL; fi;
if n = 1 then
if nargs = 0 or m_ = 1 then
return S(op(A));
else
return FAIL;
fi;
fi;
if nargs > 0 then
m := m_;
else
m := rand(0..5)();
end:
ok := false;
while not(ok) do
x := [op(A),seq(random_element_of(A),i=1..m)];
x := combinat[randperm](x);
ok := true;
for i from 1 to n + m - 1 do
if x[i] = x[i+1] then
ok := false;
break;
fi;
od;
od;
x := S(op(x));
return x;
end:
`random_element/surjections` := (A) -> proc(coeff_range_,num_terms_)
local coeff_range,num_terms;
coeff_range := -3..3;
num_terms := 5;
if nargs > 0 then coeff_range := args[1]; fi;
if nargs > 1 then num_terms := args[2]; fi;
add(rand(coeff_range)() * `random_basis_element/surjections`(A)(),i=1..num_terms);
end:
# Let u be a basis element of E(A), of length n say. A gap means
# a pair (i,i+1) with 1 <= i < i+1 <= n. The gap is bound if
# u[i] = u[j] for some j > i. Here we represent a bound gap
# (i,i+1) by its initial index i. The following function
# returns the ordered list of bound gaps.
`bound_gaps/surjections` := (A) -> proc(u)
local G,N,M,a;
G := NULL;
N := [seq(i,i=1..nops(u))];
for a in A do
M := select(i -> op(i,u) = a,N);
G := G,op(1..-2,M);
od:
G := sort([G]);
return(G);
end:
# Auxiliary function feeding into `diff/surjections`
`diff0/surjections` := (A::set) -> proc(x)
local i,j,m,y,z,s,ss,t,l,r;
i := [op(x)];
m := nops(i);
y := 0;
s := 1;
ss := table();
for j from 1 to m do
l := [op(1..j-1,i)];
r := [op(j+1..m,i)];
if member(i[j],r) then
t := s;
ss[i[j]] := t;
s := -s;
elif member(i[j],l) then
t := -ss[i[j]];
ss[i[j]] := t;
else
t := 0;
fi;
if 1 < j and j < m and op(j-1,i) = op(j + 1,i) then
t := 0;
fi;
y := y + t * S(op(1..j-1,i),op(j+1..m,i));
od:
end:
# Differential on the surjection chain complex
`diff/surjections` := (A::set) -> apply_linear(`diff0/surjections`(A));
# Auxilary function feeding into `deg/surjections`
`deg0/surjections` := (A) -> (u) -> nops(u) - nops(A);
# Degree function for the surjection chain complex.
`deg/surjections` := (A) -> apply_deg(`deg0/surjections`(A));
`reflect/surjections` := (A) -> proc(u)
local c,v;
if type(u,`+`) then
return map(`reflect/surjections`(A),u);
fi;
c,v := op(coeff_split(u));
if not(type(v,specfunc(S))) then return FAIL; fi;
return (-1)^(nops(v) - nops(A)) * u;
end:
# This is the circle product for the operad structure.
# It is assumed that B is a subset of A and u is in E(A/B) and v is in E(B),
# where A/B is implemented as A \ B u {B}.
`o0/surjections` := (A,B) -> proc(u,v)
local AB,nu,nv,Nu,Nv,M,l,m,JJ,w,J,k,p,i,j,s;
AB := A minus B union {B};
nu := nops(u);
nv := nops(v);
Nu := [seq(i,i=1..nu)];
Nv := [seq(i,i=1..nv)];
M := select(i -> op(i,u) = B,Nu);
m := nops(M);
JJ := combinat[choose]([seq(i,i=2..nv+m-1)],m-1);
JJ := map(J -> [1,seq(J[i]-i,i=1..m-1),nv],JJ);
w := 0;
for J in JJ do
k := NULL;
l := NULL;
p := 1;
for i from 1 to nu do
if op(i,u) = B then
k := k,seq(op(j,v),j=J[p]..J[p+1]);
l := l,seq([i,j],j=J[p]..J[p+1]);
p := p+1;
else
k := k,op(i,u);
l := l,[i,0];
fi;
od;
l := [l];
s := NULL;
for i in `bound_gaps/surjections`(AB)(u) do
j := nops(l);
while j > 1 and l[j][1] <> i do j := j - 1; od;
s := s,j;
od;
for i in `bound_gaps/surjections`(B)(v) do
j := nops(l);
while j > 1 and l[j][2] <> i do j := j - 1; od;
s := s,j;
od;
w := w + sgn([s]) * S(k);
od:
return w;
end:
`o/surjections` := (A,B) -> apply_bilinear(`o0/surjections`(A,B));
`gamma0/surjections` := (A::set,B::set) -> (p) -> proc(y,x)
local F,J,I0,J0,b,L,m,n,S0,s;
F := fibres(A,B)(p);
J := [seq(i,i=0..nops(y)-1)];
I0 := table():
J0 := table():
for b in B do
I0[b] := [seq(i,i=0..nops(x[b])-1)];
J0[b] := select(j -> op(j+1,y) = b,J);
od:
L := [[]];
for b in B do
m := nops(J0[b]) - 1;
n := nops(I0[b]) - 1;
S0 := map(`to_grid_path/shuffles`(m,n),`list_elements/shuffles`(m,n));
S0 := map(s -> [seq(s[i],i=0..n+m)],S0);
S0 := map(s -> map(ji -> [J0[b][ji[1]+1],ji[2]],s),S0);
L := [seq(seq([op(l),op(s)],s in S0),l in L)];
od:
L := map(sort,L);
L := map(l -> S(op(map(ji -> op(ji[2]+1,x[op(ji[1]+1,y)]),l))),L);
return `+`(op(L));
end:
`gamma/surjections` := eval(extend_gamma_linear(`gamma0/surjections`)):
# We now have various functions related to an interesting filtration
# of the surjections operad.
`flip_count/surjections` := (A::set) -> proc(u,s_)
local r,m,a,b,c,u0,i;
if nargs > 1 then
r := `rank_table/ord`(A)(s_);
else
r := NULL;
fi;
m := table():
for a in A do
for b in A do
m[a,b] := 0;
u0 := select(p -> p = a or p = b,[op(u)]);
for i from 1 to nops(u0) - 1 do
if u0[i+1] <> u0[i] then m[a,b] := m[a,b] + 1; fi;
od;
if m[a,b] > 0 and r <> NULL then
c := `if`(r[a] < r[b],a,b);
if u0[-1] = c then m[a,b] := m[a,b] + 1; fi;
fi;
od;
od;
return eval(m);
end:
`flip_count_matrix/surjections` := (A::set) -> proc(u,s_)
local m;
m := `flip_count/surjections`(A)(args);
return Matrix([seq([seq(m[a,b],b in A)],a in A)]);
end:
`max_flip_count/surjections` := (A::set) -> proc(u)
local m,mm,a,b;
m := `flip_count/surjections`(A)(u);
mm := 0;
for a in A do
for b in A do
mm := max(mm,m[a,b]);
od;
od;
return mm;
end:
`is_cell_member/surjections` := (A::set) -> (ms) -> proc(u)
local m0,m1,s,r,i,j,a,b,c,u0,k,l,y,z;
if x = 0 then return true; fi;
if type(x,`+`) then
return `and`(seq(`is_cell_member/surjections`(A)(ms)(y),y in x));
fi;
if type(x,`*`) then
y,z := selectremove(type,[op(x)],integer);
if nops(z) = 1 then
return `is_cell_member/surjections`(A)(ms)(z[1]);
else
return false;
fi;
fi;
m0,s := op(ms);
m1 := `flip_count/surjections`(A)(u,s);
for a in A do
for b in A do
if m1[a,b] > m0[a,b] then return false; fi;
od;
od;
return true;
end:
`filtration0/surjections` := (A::set) -> proc(u)
local m,m_max,s,rr,k,i,r0,r1,a,b;
if type(u,integer) then return 0; fi;
return 1 + `max_flip_count/surjections`(A)(u);
end:
`filtration/surjections` := (A::set) ->
apply_max_deg(`filtration0/surjections`(A));
`rho0/barratt_eccles/surjections` := (A::set) -> proc(x)
local rr,d,R,r,y,z,z0,ok,i,m;
rr := nops(A);
d := nops(x) - 1;
R := combinat[choose]([seq(i,i=1..d+rr-1)],d);
R := map(r -> [0,op(r),d+rr],R);
R := map(r -> [seq(r[i+1]-r[i],i=1..d+1)],R);
y := 0;
for r in R do
z := NULL;
z0 := NULL;
ok := true;
for i from 1 to d+1 do
m := select(j -> not(member(j,[z0])),op(i,x));
if nops(m) >= r[i] and ([z] = [] or [z][-1] <> m[1]) then
z := z,op(1..r[i],m);
z0 := z0,op(1..r[i]-1,m);
else
ok := false;
break;
fi;
od;
if ok then y := y + S(z); fi;
od;
return y;
end:
`rho/barratt_eccles/surjections` := (A::set) ->
apply_linear(`rho0/barratt_eccles/surjections`(A));
# We now define a map from the surjections operad to the
# Barratt-Eccles operad. This is not an operad morphism,
# but it is a section of the map in the opposite direction.
`sigma0/surjections/barratt_eccles` := (A::set) -> proc(x)
local i,j,k,l,r,t,p,m,d,w,ww;
i := [op(x)];
m := nops(i);
d := m - nops(A);
ww := NULL;
for k from 0 to d do
w := NULL;
p := 0;
for j from 1 to m do
l := [op(1..j-1,i)];
r := [op(j+1..m,i)];
if member(i[j],r) then
t := false;
p := p + 1;
else
t := true;
fi;
if not(member(i[j],[w])) then
if t or (p > k) then
w := w,i[j];
fi;
fi;
od:
w := [w];
ww := ww,w;
od;
return T(ww);
end:
`sigma/surjections/barratt_eccles` := (A::set) ->
apply_linear(`sigma0/surjections/barratt_eccles`(A));
# The cut operation construction gives a morphism from the surjection
# operad to the Eilenberg-Zilber operad. Unfortunately the EZ operad
# cannot be represented properly in our framework because each set
# EZ(A) is an infinite product over the natural numbers. To deal with
# this we insert natural number indices in various places.
`cut_operation0/surjections` := (n::nonnegint) -> (A::set) -> proc(x)
local A0,m,d,N,J,p,q,r,j,c,t,a,is_degen;
A0 := sort([op(A)]);
m := nops(A);
d := nops(x) - m;
N := [seq(i,i=0..n)];
J := [[0]];
for p from 1 to m + d - 1 do
J := [seq(seq([op(j),q],q=j[-1]..n),j in J)];
od:
J := map(j -> [op(j),n],J);
c := 0;
for j in J do
t := table():
for a in A0 do t[a] := []: od:
for p from 1 to m+d do
a := op(p,x);
t[a] := [op(t[a]),seq(r,r=j[p]..j[p+1])];
od:
is_degen := false;
for a in A0 do
if nops(t[a]) > nops({op(t[a])}) then
is_degen := true;
break;
fi;
od:
if not(is_degen) then
c := c + `detranspose/eilenberg_zilber`(A)(t);
fi;
od:
return c;
end:
`cut_operation1/surjections` := (n::nonnegint) -> (A::set) -> proc(x)
add(`cut_operation0/surjections`(k)(A)(x),k=0..n);
end:
`cut_operation/surjections` := (n::nonnegint) -> (A::set) ->
apply_linear(`cut_operation1/surjections`(n)(A));
`multiplicity_table/surjections` := (A::set) -> proc(x)
local t,a;
t := table():
for a in A do t[a] := 0; od:
for a in [op(x)] do
t[a] := t[a] + 1;
od:
return eval(t);
end:
`max_multiplicity/surjections` := (A::set) -> proc(x)
local t,m,a;
t := `multiplicity_table/surjections`(A)(x);
m := 0;
for a in A do m := max(m,t[a]); od;
return m;
end:
`is_biased/surjections` := (A::set) -> proc(x,a0_)
local a,a0,t;
a0 := NULL;
if nargs > 1 then a0 := a0_; fi;
t := `multiplicity_table/surjections`(A)(x);
for a in A do
if t[a] > 1 then
if a0 = NULL then
a0 := a;
else
if a0 <> a then
return false;
fi;
fi;
fi;
od:
return true;
end:
`is_strongly_biased/surjections` := (A::set) -> proc(x,a0_)
local a,a0,t;
a0 := NULL;
if nargs > 1 then a0 := a0_; fi;
t := `multiplicity_table/surjections`(A)(x);
for a in A do
if t[a] > 1 then
if a0 = NULL then
a0 := a;
else
if a0 <> a then
return false;
fi;
fi;
fi;
od:
if a0 = NULL or t[a0] <= 1 then return false; fi;
return true;
end:
|
/*
** Task-related edge density, main algorithm
**
** Ref: Lohmann et al (2016) PLoS One, 11(6):e0158185
**
** G.Lohmann, MPI-KYB, Jan 2015
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_sort_float.h>
#include "viaio/Vlib.h"
#include "viaio/VImage.h"
#include "viaio/mu.h"
#include "viaio/option.h"
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
#define SQR(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
extern VImage *VImagePointer(VAttrList list,int *nt);
extern void VReadImagePointer(VAttrList list,VImage *src);
extern VImage VoxelMap(VImage mask,size_t *nvoxels);
extern void VDataMatrix(VImage *src,int first,int len,VImage map,gsl_matrix_float *X);
extern void VCheckMatrix(gsl_matrix_float *X);
extern long VMaskCoverage(VAttrList list,VImage mask);
extern float ZMatrix(gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,
VImage roi,VImage map,VImage,int,float elength,float quantile,int,int);
extern void GetSNR(gsl_matrix_float **X1,gsl_matrix_float **X2,int *,int n,gsl_matrix_float *SNR,int);
extern void GetMedian(gsl_matrix_float **X1,gsl_matrix_float **X2,int *,int n,gsl_matrix_float *SNR,int);
extern void VPrintHistogram(gsl_histogram *histogram,int numperm,VString filename);
extern void HistoUpdate(float *A,size_t nvox,gsl_histogram *hist);
extern size_t EdgeDensity(float *C,int *I,int *J,size_t nedges,
gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,
VImage roi,VImage map,VImage,int,float,float,int,int,int,float,int);
extern size_t EstimateEdges(float *E,int *I,int *J,size_t fulldim,
gsl_histogram *TedHist,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,
VImage roi,VImage map,VImage mapimage,int adjdef,float elength,float zthreshold,float,int);
/* generate permutation table */
int genperm(gsl_rng *rx,int *table,int n,int numperm)
{
int s=0;
int ks = 0;
int kc=3;
if (numperm < 10) {
if (n%2==0) kc = n/2;
else kc = n/2-1;
}
int iter=0;
while ((ks < kc || ks > n-kc)) {
if (iter > 100) VError(" not possible to generate random permutations, perhaps not enough input data ?");
ks=0;
for (s=0; s<n; s++) {
table[s] = 0;
if (gsl_ran_bernoulli (rx,(double)0.5) == 1) {
table[s] = 1;
ks++;
}
}
iter++;
}
return ks;
}
void VReleaseStorage(VAttrList list)
{
VImage src;
VAttrListPosn posn;
for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
if(VGetAttrRepn(& posn) != VImageRepn) continue;
VGetAttrValue(& posn, NULL, VImageRepn, & src);
VDestroyImage(src);
src = NULL;
}
}
/* Check mask coverage */
VAttrList VCheckMaskCoverage(VStringConst *in_filenames,size_t n,VImage mask)
{
size_t i;
VAttrList list=NULL;
VAttrList geolist = NULL;
FILE *fp=NULL;
for (i=0; i<n; i++) {
fp = VOpenInputFile (in_filenames[i], TRUE);
list = VReadFile (fp, NULL);
if (! list) VError("Error reading image");
fclose(fp);
/* read geometry info, if unknown */
if (geolist == NULL) geolist = VGetGeoInfo(list);
long count = VMaskCoverage(list,mask);
if (count > 100) fprintf(stderr," incomplete mask_coverage %s: %ld\n",in_filenames[i],count);
VReleaseStorage(list);
list = NULL;
}
return geolist;
}
gsl_matrix_float **VReadImageData(VStringConst *in_filenames,VImage *src,VImage map,size_t n,size_t nvox,size_t first,size_t len)
{
size_t i;
VAttrList list=NULL;
FILE *fp=NULL;
/* allocate data struct */
gsl_matrix_float **X = VCalloc(n,sizeof(gsl_matrix_float));
for (i=0; i<n; i++) {
X[i] = gsl_matrix_float_calloc(nvox,len);
if (!X[i]) VError(" err allocating data matrix");
}
/* read data */
for (i=0; i<n; i++) {
fp = VOpenInputFile (in_filenames[i], TRUE);
list = VReadFile (fp, NULL);
if (! list) VError("Error reading image");
fclose(fp);
VReadImagePointer(list,src);
VDataMatrix(src,(int)first,(int)len,map,X[i]);
VCheckMatrix(X[i]);
VReleaseStorage(list);
list = NULL;
}
return X;
}
VDictEntry ADJDict[] = {
{ "6", 0 },
{ "18", 1 },
{ "26", 2 },
{ NULL }
};
VDictEntry TypeDict[] = {
{ "SNR", 0 },
{ "median", 1 },
{ NULL }
};
VDictEntry MetricDict[] = {
{ "pearson", 0 },
{ "spearman", 1 },
{ NULL }
};
int main (int argc,char *argv[])
{
static VArgVector in_files1;
static VArgVector in_files2;
static VString out_filename = "";
static VString mask_filename = "";
static VString roi_filename = "";
static VString hist_filename= "";
static VShort first = 0;
static VShort len = 0;
static VLong seed = 99402622;
static VFloat qthreshold = 0.99;
static VFloat elength = 5;
static VFloat noise_cutoff = 0.01;
static VShort adjdef = 2;
static VShort numperm = 0;
static VShort type = 0;
static VShort metric = 0;
static VShort nproc = 10;
static VShort step = 2;
static VOptionDescRec options[] = {
{"in1", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,"Input files 1" },
{"in2", VStringRepn, 0, & in_files2, VRequiredOpt, NULL,"Input files 2" },
{"out", VStringRepn, 1, & out_filename, VOptionalOpt, NULL,"Output file" },
{"mask", VStringRepn, 1, & mask_filename, VRequiredOpt, NULL,"Mask file" },
{"roi", VStringRepn, 1, & roi_filename, VOptionalOpt, NULL,"ROI file" },
{"histogram",VStringRepn,1,(VPointer) &hist_filename,VRequiredOpt,NULL,"Output histogram filename"},
{"permutations",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,"Number of permutations"},
{"qthreshold",VFloatRepn,1,(VPointer) &qthreshold,VOptionalOpt,NULL,"Initial quantile threshold"},
{"adj",VShortRepn,1,(VPointer) &adjdef,VOptionalOpt,ADJDict,"Definition of adjacency"},
{"seed",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,"Seed for random number generator"},
{"first",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,"First timepoint to use within trial"},
{"len",VShortRepn,1,(VPointer) &len,VOptionalOpt,NULL,"Number of timepoints to use, '0' to use all"},
{"type",VShortRepn,1,(VPointer) &type,VOptionalOpt,TypeDict,"Type of trial average"},
{"metric",VShortRepn,1,(VPointer) &metric,VOptionalOpt,MetricDict,"Correlation metric"},
{"edgelength",VFloatRepn,1,(VPointer) &elength,VOptionalOpt,NULL,"Minimal edge length in voxels"},
{"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"},
/* {"noisecutoff",VFloatRepn,1,(VPointer) &noise_cutoff,VOptionalOpt,NULL,"estimate of noisy edges"}, */
/* {"step",VShortRepn,1,(VPointer) &step,VOptionalOpt,NULL,"first iteration ZMatrix step size"} */
};
FILE *fp=NULL;
VAttrList list=NULL,list1=NULL,geolist=NULL;
VAttrListPosn posn;
VImage mask=NULL;
size_t nvox=0,i=0;
/* parse command line */
if (! VParseCommand (VNumber (options), options, & argc, argv)) {
VReportUsage (argv[0], VNumber (options), options, NULL);
exit (EXIT_FAILURE);
}
if (argc > 1) {
VReportBadArgs (argc, argv);
exit (EXIT_FAILURE);
}
/* whether to produce output file, or only compute histogram */
VBoolean histonly = FALSE;
if (strlen(out_filename) < 2) histonly = TRUE;
/* omp-stuff */
#ifdef _OPENMP
int num_procs=omp_get_num_procs();
int jprocs = num_procs;
if (nproc > 0 && nproc < num_procs) jprocs = nproc;
fprintf(stderr," using %d cores of %d\n",(int)jprocs,(int)num_procs);
omp_set_num_threads(jprocs);
#endif /* _OPENMP */
/* input filenames */
size_t n1 = (size_t)in_files1.number;
size_t n2 = (size_t)in_files2.number;
if (n1 != n2) VError(" n1 != n2, %d %d",n1,n2);
VStringConst *in_filenames1 = (VStringConst *) VCalloc(n1,sizeof(VStringConst));
for (i=0; i<n1; i++) {
in_filenames1[i] = ((VStringConst *) in_files1.vector)[i];
}
VStringConst *in_filenames2 = (VStringConst *) VCalloc(n2,sizeof(VStringConst));
for (i=0; i<n2; i++) {
in_filenames2[i] = ((VStringConst *) in_files2.vector)[i];
}
/* read mask */
fp = VOpenInputFile (mask_filename, TRUE);
list1 = VReadFile (fp, NULL);
if (! list1) VError("Error reading mask file");
fclose(fp);
for (VFirstAttr (list1, & posn); VAttrExists (& posn); VNextAttr (& posn)) {
if (VGetAttrRepn (& posn) != VImageRepn) continue;
VGetAttrValue (& posn, NULL,VImageRepn, & mask);
if (VPixelRepn(mask) == VFloatRepn || VPixelRepn(mask) == VDoubleRepn) {
mask = NULL;
continue;
}
}
if (mask == NULL) VError(" no mask found");
int nslices = VImageNBands(mask);
int nrows = VImageNRows(mask);
int ncols = VImageNColumns(mask);
/* read ROI */
VAttrList list2 = NULL;
VImage roi = NULL;
if (strlen(roi_filename) > 1) {
fp = VOpenInputFile (roi_filename, TRUE);
list2 = VReadFile (fp, NULL);
if (! list2) VError("Error reading roi file");
fclose(fp);
for (VFirstAttr (list2, & posn); VAttrExists (& posn); VNextAttr (& posn)) {
if (VGetAttrRepn (& posn) != VImageRepn) continue;
VGetAttrValue (& posn, NULL,VImageRepn, & roi);
if (VPixelRepn(roi) == VFloatRepn || VPixelRepn(roi) == VDoubleRepn) {
roi = NULL;
continue;
}
}
if (roi == NULL) VError(" no roi found");
}
/* Check mask coverage */
VAttrList geo=NULL;
geo = VCheckMaskCoverage(in_filenames1,n1,mask);
geo = VCheckMaskCoverage(in_filenames2,n2,mask);
if (geolist == NULL) geolist = geo;
/* voxel map */
VImage map = VoxelMap(mask,&nvox);
/* get image dimensions */
fp = VOpenInputFile (in_filenames1[0], TRUE);
list = VReadFile (fp, NULL);
if (! list) VError("Error reading image");
fclose(fp);
int nt=0;
VImage *src = VImagePointer(list,&nt);
if (first >= nt || first < 0) VError(" illegal value, first= %d, nt= %d",first,nt);
if (len <= 0) len = nt-first;
if (first + len >= nt) len = nt-first;
if (len < 2) VError(" len= %d",len);
fprintf(stderr," image: %d x %d x %d, nt: %d, nvox: %ld\n",(int)nslices,(int)nrows,(int)ncols,nt,nvox);
/* read image data */
gsl_matrix_float **X1 = VReadImageData(in_filenames1,src,map,n1,nvox,first,len);
gsl_matrix_float **X2 = VReadImageData(in_filenames2,src,map,n2,nvox,first,len);
/* voxel addresses */
VImage mapimage = VCreateImage(nslices,nrows,ncols,VIntegerRepn);
VFillImage(mapimage,VAllBands,(VInteger)(-1));
for (i=0; i<nvox; i++) {
int b = VPixel(map,0,0,i,VShort);
int r = VPixel(map,0,1,i,VShort);
int c = VPixel(map,0,2,i,VShort);
VPixel(mapimage,b,r,c,VInteger) = (VInteger)i;
}
/* tmp storage for SNR time courses */
int dim=0;
if (type < 3) dim = len;
else if (type == 3) dim = len*n1;
else VError(" illegal type %d",type);
gsl_matrix_float *SNR1 = gsl_matrix_float_calloc(nvox,dim);
gsl_matrix_float *SNR2 = gsl_matrix_float_calloc(nvox,dim);
/* ini zhist */
size_t hbins = 10000;
double hmin = 0.0,hmax = 1.001;
gsl_histogram *TedHist = gsl_histogram_alloc (hbins);
gsl_histogram_set_ranges_uniform (TedHist,hmin,hmax);
gsl_histogram_reset(TedHist);
/* fuer z-threshold */
size_t nbins = 25000;
hmin = -1.001,hmax = 1.001;
gsl_histogram *ZvalHist = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (ZvalHist,hmin,hmax);
gsl_histogram_reset(ZvalHist);
/* ini random */
size_t n = n1;
gsl_rng_env_setup();
const gsl_rng_type *T = gsl_rng_default;
gsl_rng *rx = gsl_rng_alloc(T);
gsl_rng_set(rx,(unsigned long int)seed);
int *table = (int *) VCalloc(n,sizeof(int));
for (i=0; i<n; i++) table[i] = 0;
/* allocate output structure */
size_t nedges=0;
size_t fulldim = (nvox*(nvox+1)/2);
double qx = 1.0-qthreshold;
qx += 0.001;
size_t nedges_estimated = (size_t) (qx*(double)fulldim);
/* ini matrices */
float *E=NULL; /* matrix of edge densities */
int *I=NULL; /* row indices in matrix E */
int *J=NULL; /* col indices in matrix E */
if (histonly == FALSE && noise_cutoff < 0.00001) {
E = VCalloc(nedges_estimated,sizeof(float)); /* matrix of edge densities */
I = VCalloc(nedges_estimated,sizeof(int)); /* row indices in matrix E */
J = VCalloc(nedges_estimated,sizeof(int)); /* col indices in matrix E */
}
/* main loop */
size_t s;
int ks=0,nperm=0;
int startperm=0;
if (numperm > 0) startperm = 1;
for (nperm = startperm; nperm <= numperm; nperm++) {
fprintf(stderr,"\n perm %3d: ",nperm);
if (nperm > 0) {
ks = genperm(rx,table,n,(int)numperm);
}
for (s=0; s<n; s++) {
fprintf(stderr,"%d",table[s]);
}
fprintf(stderr," %3d\n",ks);
/* get SNR data */
if (type == 0) {
GetSNR(X1,X2,table,n,SNR1,metric);
GetSNR(X2,X1,table,n,SNR2,metric);
}
if (type == 1) {
GetMedian(X1,X2,table,n,SNR1,metric);
GetMedian(X2,X1,table,n,SNR2,metric);
}
/* corr matrices */
float zthr = ZMatrix(ZvalHist,SNR1,SNR2,n1,n2,roi,map,mapimage,(int)adjdef,
(float)elength,(float)qthreshold,(int)step,(int)metric);
/* estimate number of truly needed edges, estimate noise */
if (noise_cutoff > 0.0 && nperm == numperm && histonly == FALSE) {
size_t old_estimate = nedges_estimated;
nedges_estimated = EstimateEdges(E,I,J,old_estimate,TedHist,SNR1,SNR2,n1,n2,roi,map,mapimage,
(int)adjdef,elength,zthr,noise_cutoff,(int)metric);
E = VCalloc(nedges_estimated,sizeof(float)); /* matrix of edge densities */
I = VCalloc(nedges_estimated,sizeof(int)); /* row indices in matrix E */
J = VCalloc(nedges_estimated,sizeof(int)); /* col indices in matrix E */
}
/* edge densities */
fprintf(stderr," Computing edge densities...\n");
nedges = EdgeDensity(E,I,J,nedges_estimated,TedHist,SNR1,SNR2,n1,n2,roi,map,mapimage,(int)adjdef,
elength,zthr,nperm,numperm,(int)1,noise_cutoff,(int)metric);
}
/* free storage */
for (i=0; i<n; i++) {
gsl_matrix_float_free(X1[i]);
gsl_matrix_float_free(X2[i]);
}
gsl_matrix_float_free(SNR1);
gsl_matrix_float_free(SNR2);
VFree(table);
/* print histogram */
VPrintHistogram(TedHist,(int)numperm,hist_filename);
if (histonly == TRUE) {
fprintf (stderr," %s: done.\n", argv[0]);
exit(0);
}
/* write edge density matrix in triplet sparse format */
size_t edim = nedges*3;
float filesize1 = (float)(edim*sizeof(float))/(1000.0*1000.0);
float filesize2 = (float)(edim*sizeof(float))/(1000.0*1000.0*1000.0);
fprintf(stderr," nedges= %ld, filesize= %.3f MByte (%.3f GByte)\n",nedges,filesize1,filesize2);
/* output */
VAttrList elist = VCreateAttrList();
VAttrList ilist = VCreateAttrList();
VAttrList jlist = VCreateAttrList();
VBundle edgedens = VCreateBundle ("data",elist,nedges*sizeof(float),(VPointer)E);
VBundle rowindex = VCreateBundle ("data",ilist,nedges*sizeof(int),(VPointer)I);
VBundle colindex = VCreateBundle ("data",jlist,nedges*sizeof(int),(VPointer)J);
VAttrList out_list = VCreateAttrList();
VSetGeoInfo(geolist,out_list);
VAppendAttr(out_list,"EdgeDensity",NULL,VBundleRepn,(VBundle)edgedens);
VAppendAttr(out_list,"RowIndex",NULL,VBundleRepn,(VBundle)rowindex);
VAppendAttr(out_list,"ColIndex",NULL,VBundleRepn,(VBundle)colindex);
VAppendAttr(out_list,"nedges",NULL,VLongRepn,(VLong)nedges);
VAppendAttr(out_list,"map",NULL,VImageRepn,map);
VAppendAttr(out_list,"qthreshold",NULL,VFloatRepn,(VFloat)qthreshold);
FILE *fp_out = VOpenOutputFile (out_filename, TRUE);
if (! VWriteFile (fp_out, out_list)) exit (1);
fclose(fp_out);
fprintf (stderr," %s: done.\n\n", argv[0]);
exit(0);
}
|
module lambda.hw7 where
open import Data.Product
open import Relation.Nullary
open import Relation.Nullary.Negation
open import Relation.Binary.PropositionalEquality hiding (subst)
open import Data.Nat
open import Data.Fin hiding (lift)
open import lambda.untyped
open import lambda.vec
open import lambda.system-f renaming (⊢_∶_ to ⊢F_∶_; type to typeF)
hiding (subst; ↑; lift; subst₁)
open import lambda.system-d renaming (⊢_∶_ to ⊢D_∶_; type to typeD;
_⊢_∶_ to _⊢D_∶_; context to contextD)
-- Peio BORTHELLE -- Homework 7
-- Maybe it's a bit unusual to present things like this, we didn't do any Agda
-- but it would really have been more hassle formalizing the homework in Coq.
-- So here it is, there are some utilities in the other files and also some
-- bonus simply-typed lambda calculus. It was a bit more fun for me than to
-- write again some long derivation tree with no guarantee at all that there
-- isn't a stupid mistake kicking in. I tried to get the notations close to
-- what we had in the lesson, hope this doesn't look too alien.
-- Utilities
A B C : typeD
A = base 0
B = base 1
C = base 1
V₀ : ∀ {n} → typeF (suc n)
V₀ = var zero
V₁ : ∀ {n} → typeF (suc (suc n))
V₁ = var (suc zero)
module Q₁ where
-- Source terms
t₁ t₂ t₃ t₄ : term 0
t₁ = lam (app (var zero) (var zero))
t₂ = app t₁ (lam (var zero))
t₃ = app t₁ t₁
t₄ = lam (lam (app (var (suc zero)) (app (var zero) (var (suc zero)))))
-- a) system F
F₁ F₂ F₄ : typeF 0
F₁ = (∀' V₀ ⇒ V₀) ⇒ (∀' V₀ ⇒ V₀)
F₂ = ∀' V₀ ⇒ V₀
F₄ = ∀' ∀' (V₀ ⇒ V₁) ⇒ ((V₀ ⇒ V₁) ⇒ V₀) ⇒ V₁
F₁-p : ⊢F t₁ ∶ F₁
F₁-p = lam (∀' V₀ ⇒ V₀) (app (sub (∀' V₀ ⇒ V₀) ax) ax)
F₂-p : ⊢F t₂ ∶ F₂
F₂-p = app (lam (∀' V₀ ⇒ V₀) (app (sub (∀' V₀ ⇒ V₀) ax) ax)) (gen (lam V₀ ax))
-- t₃ is not normalizing: it has a non-trivial beta-reduction to itself.
-- Because system F is strongly normalizing this prooves that it has no valid
-- typing judgment.
t₃-no-norm : t₃ β* t₃
t₃-no-norm = β-beta ← ε
F₄-p : ⊢F t₄ ∶ F₄
F₄-p = gen (gen (lam (V₀ ⇒ V₁) (lam ((V₀ ⇒ V₁) ⇒ V₀) (app ax (app ax ax)))))
-- b) system D
σ₁ σ₂ σ₄ : typeD
σ₁ = (A ∧ A ⇒ B) ⇒ B
σ₂ = A ⇒ A
σ₄ = (A ⇒ B) ⇒ ((A ⇒ B) ⇒ A) ⇒ B
σ₁-p : ⊢D t₁ ∶ σ₁
σ₁-p = lam (app (∧ᵉʳ ax) (∧ᵉˡ ax))
σ₂-p : ⊢D t₂ ∶ σ₂
σ₂-p = app (lam (app (∧ᵉʳ ax) (∧ᵉˡ ax))) (∧ⁱ (lam ax) (lam ax))
-- Same as system F for t₃ because of the strongly normalizing property.
σ₄-p : ⊢D t₄ ∶ σ₄
σ₄-p = lam (lam (app ax (app ax ax)))
module Q₂ where
--
σ₁ σ₂ σ₃ σ₄ : typeD
σ₁ = ((A ∧ B) ⇒ C) ⇒ A ⇒ B ⇒ C
σ₂ = (A ⇒ B ⇒ C) ⇒ (A ∧ B) ⇒ C
σ₃ = (C ⇒ A ∧ C ⇒ B) ⇒ C ⇒ (A ∧ B)
σ₄ = C ⇒ (A ∧ B) ⇒ (C ⇒ A ∧ C ⇒ B)
σ₁-p : ∀ {t} → ¬ ⊢D t ∶ σ₁
σ₁-p p = {!!}
σ₂-p : ⊢D lam (lam (app (app (var (suc zero)) (var zero)) (var zero))) ∶ σ₂
σ₂-p = lam (lam (app (app ax (∧ᵉˡ ax)) (∧ᵉʳ ax)))
σ₃-p : ⊢D lam (lam (app (var (suc zero)) (var zero))) ∶ σ₃
σ₃-p = lam (lam (∧ⁱ (app (∧ᵉˡ ax) ax) (app (∧ᵉʳ ax) ax)))
σ₄-p : ⊢D lam (lam (lam (var (suc zero)))) ∶ σ₄
σ₄-p = lam (lam (∧ⁱ (lam (∧ᵉˡ ax)) (lam (∧ᵉʳ ax))))
module Q₃ where
-- I got stuck on applying the substitution lemma on function type that are
-- not lambda abstractions but ∧ eliminations. I don't manage to get from
-- a proof of that type to a proof with the argument type on the top of the
-- context. Maybe the substitution lemma is not well choosen.
subj-red : ∀ {n T} → {x y : term n} → {Γ : contextD n} → Γ ⊢D x ∶ T → x →β y → Γ ⊢D y ∶ T
subj-red ax ()
subj-red (∧ⁱ x₁ x₂) p = ∧ⁱ (subj-red x₁ p) (subj-red x₂ p)
subj-red (∧ᵉˡ x) p = ∧ᵉˡ (subj-red x p)
subj-red (∧ᵉʳ x) p = ∧ᵉʳ (subj-red x p)
subj-red (app (lam x) y) β-beta = subst-p x (λ { zero → y; (suc i) → ax })
subj-red (app (∧ᵉˡ x) y) β-beta = {! !}
subj-red (app (∧ᵉʳ x) y) β-beta = {! !}
subj-red (app x y) (β-app₁ p) = app (subj-red x p) y
subj-red (app x y) (β-app₂ p) = app x (subj-red y p)
subj-red (lam x) (β-lam p) = lam (subj-red x p)
module Q₄ where
-- The BNF grammar i use is:
--
-- <NF> ::= "λ" <VAR> "." <NF> | <NE>
-- <NE> ::= <NE> <NF> | <VAR>
--
-- I implemented this grammar as a judgment on untyped lambda terms
-- with the datatypes `lambda.untyped.norm` and `lambda.untyped.neut`.
-- Proof that NF and NE don't allow further derivation
-- This proof as well as the reciprocical were quite mechanized but still
-- a bit cumbersome.
nf-last : ∀ {n} → {x : term n} → norm x → ¬ ∃[ y ] (x →β y)
ne-last : ∀ {n} → {x : term n} → neut x → ¬ ∃[ y ] (x →β y)
nf-last (lam x) (lam y , β-lam p) = nf-last x (y , p)
nf-last (gnd x) (lam y , p) = ne-last x (lam y , p)
nf-last (gnd x) (var i , p) = ne-last x (var i , p)
nf-last (gnd x) (app a b , p) = ne-last x (app a b , p)
ne-last var (y , ())
ne-last (app () y) (_ , β-beta)
ne-last (app x y) (app a b , β-app₁ p) = ne-last x (a , p)
ne-last (app x y) (app a b , β-app₂ p) = nf-last y (b , p)
-- Proof that terms with no further derivation are in NF
last-nf : ∀ {n} → (x : term n) → ¬ ∃[ y ] (x →β y) → norm x
last-ne : ∀ {n y} → (x : term n) → ¬ ∃[ z ] (app x y →β z) → neut x
last-nf (lam x) p = lam (last-nf x λ { (y , p₂) → p (lam y , β-lam p₂) })
last-nf (var x) p = gnd var
last-nf (app x y) p = gnd (app
(last-ne x λ { (z , p₁) → p (z , p₁) })
(last-nf y λ { (a , b) → p (app x a , β-app₂ b) }))
last-ne {y = y} (lam x) p with p (subst₁ x y , β-beta)
... | ()
last-ne (var x) p = var
last-ne {y = y} (app x z) p = app
(last-ne x λ { (a , b) → p (app a y , β-app₁ b) })
(last-nf z λ { (a , b) → p (app (app x a) y , (β-app₁ (β-app₂ b))) })
const : ∀ {n} → contextD n
const {zero} = ε
const {suc n} = const ▸ base 0
-- Again because i messed up the renaming/substitution on ⊢D terms, i
-- did not get to formalize the typing properly here.
type-n : ∀ {n} → {x : term n} → norm x → ∃ (λ Γ → ∃ (λ T → Γ ⊢D x ∶ T))
type-e : ∀ {n} → {x : term n} → neut x → ∃ (λ Γ → ∃ (λ T → Γ ⊢D x ∶ T))
-- Here we compute inductively on the subterm, then "unload" the top of
-- the context A and the result type B into the type A ⇒ B.
type-n (lam x) = {! !}
type-n (gnd x) = type-e x
-- Here we create a context with fresh base types, assigning the matching
-- one to the term.
type-e (var {i}) = {! !}
-- Here we compute inductively on both subterms:
-- Γx ⊢D x ∶ Tx Γy ⊢D y ∶ Ty
-- x is a neutral term so it has a type looking like
-- T ⇒ A₁ ∧ T ⇒ A₁ ⇒ A₂ ∧ …
-- We then simply extend it with An = Ty. This requires some proof
-- rewriting with ∧ᵉ*.
type-e (app x y) = {! !}
-- Question 5
-- a) The definition of the conjunction in system F is:
-- conjⁱ : Γ ⊢F x ∶ A → Γ ⊢F y ∶ B → Γ ⊢F (x , y) ∶ A ∧F B
-- conjᵉʳ : Γ ⊢F x ∶ A ∧F B → Γ ⊢F π₀ x ∶ A
-- conjᵉˡ : Γ ⊢F x : A ∧F B → Γ ⊢F π₁ x ∶ B
-- The difference is that in system D, the conjunction is more of
-- an intersection: if a single term has 2 type judgements, then
-- it has a judgment for the intersection, whereas for system F
-- it is a couple of 2 different terms.
|
//==================================================================================================
/*!
@file
@copyright 2016 J.T.Lapreste
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_DIV_INCLUDED
#define BOOST_SIMD_FUNCTION_DIV_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-operator
Perform the quotient of two parameters of the same type with or without options.
@par Semantic
For any value @c a and @c b of type @c T,
@code
T r = div(a, b{, option});
@endcode
returns the quotient of @c a by @c b according to the option
if there is no option the call is equivalent to divides(a, b), else
option can be ceil, floor, fix, round, round2even (in the namespace booost::simd)
and provide the same result as the calls divceil(a, b), divfloor(a, b),
divfix(a, b), divround(a, b).
@param a First parameter of the quotient
@param b Second parameter of the quotient
@param option is the option
@return The quotient of the two parameters.
**/
template<typename T> auto div(T const& a, T const& b);
namespace functional
{
/*!
@ingroup group-callable-operator
Perform the quotient of two parameters of the same type.
Function object tied to boost::simd::div
@see boost::simd::div
**/
const boost::dispatch::functor<tag::div_> div = {};
}
} }
#endif
#include <boost/simd/function/scalar/div.hpp>
#endif
|
""" periodic_porous script. """
import numpy as np
from generate_mesh import MESHES_DIR, store_mesh_HDF5, line_points, \
rad_points, round_trip_connect, numpy_to_dolfin
from utilities.plot import plot_edges, plot_faces
from meshpy import triangle as tri
from common import info
import os
import dolfin as df
import matplotlib.pyplot as plt
def description(**kwargs):
info("")
def method(Lx=6., Ly=4., Lx_inner=4., num_obstacles=32,
rad=0.2, R=0.3, dx=0.05, seed=121, show=False, **kwargs):
N = int(np.ceil(Lx/dx))
x_min, x_max = -Lx/2, Lx/2
y_min, y_max = -Ly/2, Ly/2
y = np.linspace(y_min, y_max, N).flatten()
pts = np.zeros((num_obstacles, 2))
diam2 = 4*R**2
np.random.seed(seed)
for i in range(num_obstacles):
while True:
pt = (np.random.rand(2)-0.5) * np.array([Lx_inner, Ly])
if i == 0:
break
dist = pts[:i, :] - np.outer(np.ones(i), pt)
for j in range(len(dist)):
if abs(dist[j, 1]) > Ly/2:
dist[j, 1] = abs(dist[j, 1])-Ly
dist2 = dist[:, 0]**2 + dist[:, 1]**2
if all(dist2 > diam2):
break
pts[i, :] = pt
pts = pts[pts[:, 0].argsort(), :]
obstacles = [tuple(row) for row in pts]
line_segments_top = []
line_segments_btm = []
x_prev = x_min
curve_segments_top = []
curve_segments_btm = []
interior_obstacles = []
exterior_obstacles = []
for x_c in obstacles:
# Close to the top of the domain
if x_c[1] > y_max-rad:
# identify intersection
theta = np.arcsin((y_max-x_c[1])/rad)
rx = rad*np.cos(theta)
x_left = x_c[0]-rx
x_right = x_c[0]+rx
line_segments_top.append(line_points((x_prev, y_max),
(x_left, y_max), dx))
line_segments_btm.append(line_points((x_prev, y_min),
(x_left, y_min), dx))
curve_btm = rad_points((x_c[0], x_c[1]-Ly), rad, dx,
theta_start=np.pi-theta,
theta_stop=theta)[1:-1]
curve_top = rad_points(x_c, rad, dx,
theta_start=np.pi-theta,
theta_stop=2*np.pi+theta)[1:-1]
curve_segments_btm.append(curve_btm)
curve_segments_top.append(curve_top)
x_prev = x_right
exterior_obstacles.append(x_c)
exterior_obstacles.append((x_c[0], x_c[1]-Ly))
# Close to the bottom of the domain
elif x_c[1] < y_min+rad:
# identify intersection
theta = np.arcsin((-y_min+x_c[1])/rad)
rx = rad*np.cos(theta)
x_left = x_c[0]-rx
x_right = x_c[0]+rx
line_segments_top.append(line_points((x_prev, y_max),
(x_left, y_max), dx))
line_segments_btm.append(line_points((x_prev, y_min),
(x_left, y_min), dx))
curve_btm = rad_points(x_c, rad, dx,
theta_start=np.pi+theta,
theta_stop=-theta)[1:-1]
curve_top = rad_points((x_c[0], x_c[1]+Ly), rad, dx,
theta_start=np.pi+theta,
theta_stop=2*np.pi-theta)[1:-1]
curve_segments_btm.append(curve_btm)
curve_segments_top.append(curve_top)
x_prev = x_right
exterior_obstacles.append(x_c)
exterior_obstacles.append((x_c[0], x_c[1]+Ly))
else:
interior_obstacles.append(x_c)
line_segments_top.append(line_points((x_prev, y_max),
(x_max, y_max), dx))
line_segments_btm.append(line_points((x_prev, y_min),
(x_max, y_min), dx))
assert(len(line_segments_top) == len(curve_segments_top)+1)
assert(len(line_segments_btm) == len(curve_segments_btm)+1)
pts_top = list(line_segments_top[0])
for i in range(len(curve_segments_top)):
pts_top.extend(curve_segments_top[i])
pts_top.extend(line_segments_top[i+1])
pts_top = pts_top[::-1]
pts_btm = list(line_segments_btm[0])
for i in range(len(curve_segments_btm)):
pts_btm.extend(curve_segments_btm[i])
pts_btm.extend(line_segments_btm[i+1])
y_side = y[1:-1]
pts_right = list(zip(x_max*np.ones(N-2), y_side))
pts_left = list(zip(x_min*np.ones(N-2), y_side[::-1]))
pts = pts_btm + pts_right + pts_top + pts_left
edges = round_trip_connect(0, len(pts)-1)
for interior_obstacle in interior_obstacles:
pts_obstacle = rad_points(interior_obstacle, rad, dx)[1:]
edges_obstacle = round_trip_connect(len(pts),
len(pts)+len(pts_obstacle)-1)
pts.extend(pts_obstacle)
edges.extend(edges_obstacle)
if show:
plot_edges(pts, edges)
mi = tri.MeshInfo()
mi.set_points(pts)
mi.set_facets(edges)
mi.set_holes(interior_obstacles)
max_area = 0.5*dx**2
mesh = tri.build(mi, max_volume=max_area, min_angle=25,
allow_boundary_steiner=False)
coords = np.array(mesh.points)
faces = np.array(mesh.elements)
# pp = [tuple(point) for point in mesh.points]
# print "Number of points:", len(pp)
# print "Number unique points:", len(set(pp))
if show:
plot_faces(coords, faces)
msh = numpy_to_dolfin(coords, faces)
mesh_path = os.path.join(
MESHES_DIR,
"periodic_porous_Lx{}_Ly{}_rad{}_N{}_dx{}".format(
Lx, Ly, rad, num_obstacles, dx))
store_mesh_HDF5(msh, mesh_path)
obstacles_path = os.path.join(
MESHES_DIR,
"periodic_porous_Lx{}_Ly{}_rad{}_N{}_dx{}.dat".format(
Lx, Ly, rad, num_obstacles, dx))
if len(exterior_obstacles) > 0 and len(interior_obstacles) > 0:
all_obstacles = np.vstack((np.array(exterior_obstacles),
np.array(interior_obstacles)))
elif len(exterior_obstacles) > 0:
all_obstacles = np.array(exterior_obstacles)
else:
all_obstacles = np.array(interior_obstacles)
np.savetxt(obstacles_path,
np.hstack((all_obstacles,
np.ones((len(all_obstacles), 1))*rad)))
if show:
df.plot(msh)
plt.show()
|
/- CONJUNCTION -/
variable (p q : Prop)
-- `and.intro h1 h2` builds proof of `p ∧ q` using proofs `h1 : p` and `h2 : p`
-- is described as the AND-INTRODUCTION rule\
example (hp : p) (hq : q) : p ∧ q := And.intro hp hq
#check fun (hp : p) (hq : q) => And.intro hp hq
-- `example` command states a theorem w/o naming or storing permanently - convinient for illustration
/-left and right AND-ELIMINATION rules-/
-- `and.left h` creates proof of `p` from proof `h : p ∧ q`
-- `and.right h` is proof of `q`
example (h : p ∧ q) : p := And.left h
example (h : p ∧ q) : q := And.right h
example (h : p ∧ q) : q ∧ p :=
And.intro (And.right h) (And.left h)
-- note: and-introduction and end-elimination are similar to pairing and projection operations for cartesian product.
-- difference is given `hp : p` and `hq : q`:
-- `And.intro hp hq` has type `p ∧ q : Prop`
-- `Prod hp hq` has type `p × q : Type`
-- similarity between ∧ and × is another instance of the Curry-Howard isomorphism tho treated separatedly in Lean.
-- certain types in lean are STRUCTURES: defined w single conanical CONSTRUCTOR which builds an element of the type from a sequence of suitable arguments
-- ie. For every `p q : Prop`, `p ∧ q` is an example
-- canonical way to construct is to apply `And.intro` to suitable args `hp : p` amd `hq : q`
-- lean lets us use anonymous constructor notation notation `⟨arg1, arg2, ...⟩` when relevant type is inductive type and can be inferred from context
-- in particular, can often write `⟨hp, hq⟩` instead of `And.intro hp hq`
variable (hp : p) (hq : q)
#check (⟨hp, hq⟩ : p ∧ q)
-- thus given shorthand syntax, can rewrite as
variable (p q : Prop)
example (h : p ∧ q) : q ∧ p :=
⟨h.right, h.left⟩
3
|
Formal statement is: lemma real_lim: fixes l::complex assumes "(f \<longlongrightarrow> l) F" and "\<not> trivial_limit F" and "eventually P F" and "\<And>a. P a \<Longrightarrow> f a \<in> \<real>" shows "l \<in> \<real>" Informal statement is: If $f$ converges to $l$ and $f$ is eventually real, then $l$ is real. |
# Polynomials
Some of the equations we've looked at so far include expressions that are actually *polynomials*; but what *is* a polynomial, and why should you care?
A polynomial is an algebraic expression containing one or more *terms* that each meet some specific criteria. Specifically:
- Each term can contain:
- Numeric values that are coefficients or constants (for example 2, -5, <sup>1</sup>/<sub>7</sub>)
- Variables (for example, x, y)
- Non-negative integer exponents (for example <sup>2</sup>, <sup>64</sup>)
- The terms can be combined using arithmetic operations - but **not** division by a variable.
For example, the following expression is a polynomial:
\begin{equation}12x^{3} + 2x - 16 \end{equation}
When identifying the terms in a polynomial, it's important to correctly interpret the arithmetic addition and subtraction operators as the sign for the term that follows. For example, the polynomial above contains the following three terms:
- 12x<sup>3</sup>
- 2x
- -16
The terms themselves include:
- Two coefficients(12 and 2) and a constant (-16)
- A variable (x)
- An exponent (<sup>3</sup>)
A polynomial that contains three terms is also known as a *trinomial*. Similarly, a polynomial with two terms is known as a *binomial* and a polynomial with only one term is known as a *monomial*.
So why do we care? Well, polynomials have some useful properties that make them easy to work with. for example, if you multiply, add, or subtract a polynomial, the result is always another polynomial.
## Standard Form for Polynomials
Techbnically, you can write the terms of a polynomial in any order; but the *standard form* for a polynomial is to start with the highest *degree* first and constants last. The degree of a term is the highest order (exponent) in the term, and the highest order in a polynomial determines the degree of the polynomial itself.
For example, consider the following expression:
\begin{equation}3x + 4xy^{2} - 3 + x^{3} \end{equation}
To express this as a polynomial in the standard form, we need to re-order the terms like this:
\begin{equation}x^{3} + 4xy^{2} + 3x - 3 \end{equation}
## Simplifying Polynomials
We saw previously how you can simplify an equation by combining *like terms*. You can simplify polynomials in the same way.
For example, look at the following polynomial:
\begin{equation}x^{3} + 2x^{3} - 3x - x + 8 - 3 \end{equation}
In this case, we can combine x<sup>3</sup> and 2x<sup>3</sup> by adding them to make 3x<sup>3</sup>. Then we can add -3x and -x (which is really just a shorthand way to say -1x) to get -4x, and then add 8 and -3 to get 5. Our simplified polynomial then looks like this:
\begin{equation}3x^{3} - 4x + 5 \end{equation}
We can use Python to compare the original and simplified polynomials to check them - using an arbitrary random value for ***x***:
```python
from random import randint
x = randint(1,100)
(x**3 + 2*x**3 - 3*x - x + 8 - 3) == (3*x**3 - 4*x + 5)
```
True
## Adding Polynomials
When you add two polynomials, the result is a polynomial. Here's an example:
\begin{equation}(3x^{3} - 4x + 5) + (2x^{3} + 3x^{2} - 2x + 2) \end{equation}
because this is an addition operation, you can simply add all of the like terms from both polynomials. To make this clear, let's first put the like terms together:
\begin{equation}3x^{3} + 2x^{3} + 3x^{2} - 4x -2x + 5 + 2 \end{equation}
This simplifies to:
\begin{equation}5x^{3} + 3x^{2} - 6x + 7 \end{equation}
We can verify this with Python:
```python
from random import randint
x = randint(1,100)
(3*x**3 - 4*x + 5) + (2*x**3 + 3*x**2 - 2*x + 2) == 5*x**3 + 3*x**2 - 6*x + 7
```
True
## Subtracting Polynomials
Subtracting polynomials is similar to adding them but you need to take into account that one of the polynomials is a negative.
Consider this expression:
\begin{equation}(2x^{2} - 4x + 5) - (x^{2} - 2x + 2) \end{equation}
The key to performing this calculation is to realize that the subtraction of the second polynomial is really an expression that adds -1(x<sup>2</sup> - 2x + 2); so you can use the distributive property to multiply each of the terms in the polynomial by -1 (which in effect simply reverses the sign for each term). So our expression becomes:
\begin{equation}(2x^{2} - 4x + 5) + (-x^{2} + 2x - 2) \end{equation}
Which we can solve as an addition problem. First place the like terms together:
\begin{equation}2x^{2} + -x^{2} + -4x + 2x + 5 + -2 \end{equation}
Which simplifies to:
\begin{equation}x^{2} - 2x + 3 \end{equation}
Let's check that with Python:
```python
from random import randint
x = randint(1,100)
(2*x**2 - 4*x + 5) - (x**2 - 2*x + 2) == x**2 - 2*x + 3
```
True
## Multiplying Polynomials
To multiply two polynomials, you need to perform the following two steps:
1. Multiply each term in the first polynomial by each term in the second polynomial.
2. Add the results of the multiplication operations, combining like terms where possible.
For example, consider this expression:
\begin{equation}(x^{4} + 2)(2x^{2} + 3x - 3) \end{equation}
Let's do the first step and multiply each term in the first polynomial by each term in the second polynomial. The first term in the first polynomial is x<sup>4</sup>, and the first term in the second polynomial is 2x<sup>2</sup>, so multiplying these gives us 2x<sup>6</sup>. Then we can multiply the first term in the first polynomial (x<sup>4</sup>) by the second term in the second polynomial (3x), which gives us 3x<sup>5</sup>, and so on until we've multipled all of the terms in the first polynomial by all of the terms in the second polynomial, which results in this:
\begin{equation}2x^{6} + 3x^{5} - 3x^{4} + 4x^{2} + 6x - 6 \end{equation}
We can verify a match between this result and the original expression this with the following Python code:
```python
from random import randint
x = randint(1,100)
(x**4 + 2)*(2*x**2 + 3*x - 3) == 2*x**6 + 3*x**5 - 3*x**4 + 4*x**2 + 6*x - 6
```
True
## Dividing Polynomials
When you need to divide one polynomial by another, there are two approaches you can take depending on the number of terms in the divisor (the expression you're dividing by).
### Dividing Polynomials Using Simplification
In the simplest case, division of a polynomial by a monomial, the operation is really just simplification of a fraction.
For example, consider the following expression:
\begin{equation}(4x + 6x^{2}) \div 2x \end{equation}
This can also be written as:
\begin{equation}\frac{4x + 6x^{2}}{2x} \end{equation}
One approach to simplifying this fraction is to split it it into a separate fraction for each term in the dividend (the expression we're dividing), like this:
\begin{equation}\frac{4x}{2x} + \frac{6x^{2}}{2x}\end{equation}
Then we can simplify each fraction and add the results. For the first fraction, 2x goes into 4x twice, so the fraction simplifies to 2; and for the second, 6x<sup>2</sup> is 2x mutliplied by 3x. So our answer is 2 + 3x:
\begin{equation}2 + 3x\end{equation}
Let's use Python to compare the original fraction with the simplified result for an arbitrary value of ***x***:
```python
from random import randint
x = randint(1,100)
(4*x + 6*x**2) / (2*x) == 2 + 3*x
```
True
### Dividing Polynomials Using Long Division
Things get a little more complicated for divisors with more than one term.
Suppose we have the following expression:
\begin{equation}(x^{2} + 2x - 3) \div (x - 2) \end{equation}
Another way of writing this is to use the long-division format, like this:
\begin{equation} x - 2 |\overline{x^{2} + 2x - 3} \end{equation}
We begin long-division by dividing the highest order divisor into the highest order dividend - so in this case we divide x into x<sup>2</sup>. X goes into x<sup>2</sup> x times, so we put an x on top and then multiply it through the divisor:
\begin{equation} \;\;\;\;x \end{equation}
\begin{equation}x - 2 |\overline{x^{2} + 2x - 3} \end{equation}
\begin{equation} \;x^{2} -2x \end{equation}
Now we'll subtract the remaining dividend, and then carry down the -3 that we haven't used to see what's left:
\begin{equation} \;\;\;\;x \end{equation}
\begin{equation}x - 2 |\overline{x^{2} + 2x - 3} \end{equation}
\begin{equation}- (x^{2} -2x) \end{equation}
\begin{equation}\;\;\;\;\;\overline{\;\;\;\;\;\;\;\;\;\;4x -3} \end{equation}
OK, now we'll divide our highest order divisor into the highest order of the remaining dividend. In this case, x goes into 4x four times, so we'll add a 4 to the top line, multiply it through the divisor, and subtract the remaining dividend:
\begin{equation} \;\;\;\;\;\;\;\;x + 4 \end{equation}
\begin{equation}x - 2 |\overline{x^{2} + 2x - 3} \end{equation}
\begin{equation}- (x^{2} -2x) \end{equation}
\begin{equation}\;\;\;\;\;\overline{\;\;\;\;\;\;\;\;\;\;4x -3} \end{equation}
\begin{equation}- (\;\;\;\;\;\;\;\;\;\;\;\;4x -8) \end{equation}
\begin{equation}\;\;\;\;\;\overline{\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;5} \end{equation}
We're now left with just 5, which we can't divide further by x - 2; so that's our remainder, which we'll add as a fraction.
The solution to our division problem is:
\begin{equation}x + 4 + \frac{5}{x-2} \end{equation}
Once again, we can use Python to check our answer:
```python
from random import randint
x = randint(3,100)
(x**2 + 2*x -3)/(x-2) == x + 4 + (5/(x-2))
```
True
```python
```
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from numba import cuda
from numba.cuda.cudadrv.error import CudaSupportError
def get_number_gpus():
"""Get the number of GPUs in the system.
Returns:
int: Number of GPUs.
"""
try:
return len(cuda.gpus)
except CudaSupportError:
return 0
def clear_memory_all_gpus():
"""Clear memory of all GPUs.
"""
try:
for gpu in cuda.gpus:
with gpu:
cuda.current_context().deallocations.clear()
except CudaSupportError:
print("No CUDA available")
|
If $p$ is a prime number, then $p^k$ is an $n$th power if and only if $n$ divides $k$. |
module Test.Parser
import Test.Assertions
import Idrlisp.Sexp
import Idrlisp.Parser
%default covering
export
test : IO ()
test = describe "Idrlisp.Parser" $ do
describe "parseToEnd" $ do
let parseSyn = parseToEnd {ty = SSyn ()}
parseSyn "123"
`shouldBe` Right (Num 123)
parseSyn " \n\t ; comment \n 3.14 "
`shouldBe` Right (Num 3.14)
parseSyn "*foo-bar+baz"
`shouldBe` Right (Sym "*foo-bar+baz")
parseSyn (show "Hello, World!\n")
`shouldBe` Right (Str "Hello, World!\n")
parseSyn "()"
`shouldBe` Right Nil
parseSyn "(#t)"
`shouldBe` Right (App [Bool True])
parseSyn "(#t #f)"
`shouldBe` Right (App [Bool True, Bool False])
parseSyn "(#t #f . 0)"
`shouldBe` Right ([Bool True, Bool False] :.: Num 0)
parseSyn "(#t #f . 0 1)"
`shouldSatisfy` isLeft
parseSyn "(foo [bar baz])"
`shouldBe` Right (App [Sym "foo", App [Sym "bar", Sym "baz"]])
parseSyn "`(foo ,bar ,@(hoge 'fuga))"
`shouldBe` Right (Quasiquote (App [Sym "foo", Unquote (Sym "bar"), UnquoteSplicing (App [Sym "hoge", Quote (Sym "fuga")])]))
parseToEnd {ty = List (SSyn ())} "123 () foo ; test \n \"bar\""
`shouldBe` Right [Num 123.0, Nil, Sym "foo", Str "bar"]
|
Require Import Crypto.Specific.Framework.RawCurveParameters.
Require Import Crypto.Util.LetIn.
(***
Modulus : 2^213 - 3
Base: 32
***)
Definition curve : CurveParameters :=
{|
sz := 7%nat;
base := 32;
bitwidth := 32;
s := 2^213;
c := [(1, 3)];
carry_chains := None;
a24 := None;
coef_div_modulus := None;
goldilocks := None;
karatsuba := None;
montgomery := true;
freeze := Some false;
ladderstep := false;
mul_code := None;
square_code := None;
upper_bound_of_exponent_loose := None;
upper_bound_of_exponent_tight := None;
allowable_bit_widths := None;
freeze_extra_allowable_bit_widths := None;
modinv_fuel := None
|}.
Ltac extra_prove_mul_eq _ := idtac.
Ltac extra_prove_square_eq _ := idtac.
|
[STATEMENT]
lemma (in group) pow_int_mod_ord:
assumes [simp]:"a \<in> carrier G" "ord a \<noteq> 0"
shows "a [^] (n::int) = a [^] (n mod ord a)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
obtain q r where d: "q = n div ord a" "r = n mod ord a" "n = q * ord a + r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>q r. \<lbrakk>q = n div int (ord a); r = n mod int (ord a); n = q * int (ord a) + r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
using mod_div_decomp
[PROOF STATE]
proof (prove)
using this:
(\<And>q r. \<lbrakk>q = ?a div ?b; r = ?a mod ?b; ?a = q * ?b + r\<rbrakk> \<Longrightarrow> ?thesis) \<Longrightarrow> ?thesis
goal (1 subgoal):
1. (\<And>q r. \<lbrakk>q = n div int (ord a); r = n mod int (ord a); n = q * int (ord a) + r\<rbrakk> \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
q = n div int (ord a)
r = n mod int (ord a)
n = q * int (ord a) + r
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
hence "a [^] n = (a [^] int (ord a)) [^] q \<otimes> a [^] r"
[PROOF STATE]
proof (prove)
using this:
q = n div int (ord a)
r = n mod int (ord a)
n = q * int (ord a) + r
goal (1 subgoal):
1. a [^] n = (a [^] int (ord a)) [^] q \<otimes> a [^] r
[PROOF STEP]
using assms(1) int_pow_mult int_pow_pow
[PROOF STATE]
proof (prove)
using this:
q = n div int (ord a)
r = n mod int (ord a)
n = q * int (ord a) + r
a \<in> carrier G
?x \<in> carrier G \<Longrightarrow> ?x [^] (?i + ?j) = ?x [^] ?i \<otimes> ?x [^] ?j
?x \<in> carrier G \<Longrightarrow> (?x [^] ?n) [^] ?m = ?x [^] (?n * ?m)
goal (1 subgoal):
1. a [^] n = (a [^] int (ord a)) [^] q \<otimes> a [^] r
[PROOF STEP]
by (metis mult_of_nat_commute)
[PROOF STATE]
proof (state)
this:
a [^] n = (a [^] int (ord a)) [^] q \<otimes> a [^] r
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
a [^] n = (a [^] int (ord a)) [^] q \<otimes> a [^] r
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
have "\<dots> = \<one> [^] q \<otimes> a [^] r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (a [^] int (ord a)) [^] q \<otimes> a [^] r = \<one> [^] q \<otimes> a [^] r
[PROOF STEP]
by (simp add: int_pow_int)
[PROOF STATE]
proof (state)
this:
(a [^] int (ord a)) [^] q \<otimes> a [^] r = \<one> [^] q \<otimes> a [^] r
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
(a [^] int (ord a)) [^] q \<otimes> a [^] r = \<one> [^] q \<otimes> a [^] r
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
have "\<dots> = a [^] r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<one> [^] q \<otimes> a [^] r = a [^] r
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
\<one> [^] q \<otimes> a [^] r = a [^] r
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
a [^] n = a [^] r
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
a [^] n = a [^] r
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
using d(2)
[PROOF STATE]
proof (prove)
using this:
a [^] n = a [^] r
r = n mod int (ord a)
goal (1 subgoal):
1. a [^] n = a [^] (n mod int (ord a))
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
a [^] n = a [^] (n mod int (ord a))
goal:
No subgoals!
[PROOF STEP]
qed |
chapter \<open>Names as a unique datatype\<close>
theory Name
imports Main
begin
text \<open>
I would like to model names as @{typ string}s. Unfortunately, there is no default order on lists,
as there could be multiple reasonable implementations: e.g.\ lexicographic and point-wise.
For both choices, users can import the corresponding instantiation.
In Isabelle, only at most one implementation of a given type class for a given type may be present
in the same theory. Consequently, I avoided importing a list ordering from the library, because it
may cause conflicts with users who use another ordering. The general approach for these situations
is to introduce a type copy.
The full flexibility of strings (i.e.\ string manipulations) is only required where fresh names
are being produced. Otherwise, only a linear order on terms is needed. Conveniently, Sternagel and
Thiemann @{cite sternagel2015deriving} provide tooling to automatically generate such a
lexicographic order.
\<close>
datatype name = Name (as_string: string)
\<comment> \<open>Mostly copied from \<open>List_Lexorder\<close>\<close>
instantiation name :: ord
begin
definition less_name where
"xs < ys \<longleftrightarrow> (as_string xs, as_string ys) \<in> lexord {(u, v). (of_char u :: nat) < of_char v}"
definition less_eq_name where
"(xs :: name) \<le> ys \<longleftrightarrow> xs < ys \<or> xs = ys"
instance ..
end
instance name :: order
proof
fix xs :: "name"
show "xs \<le> xs" by (simp add: less_eq_name_def)
next
fix xs ys zs :: "name"
assume "xs \<le> ys" and "ys \<le> zs"
then show "xs \<le> zs"
apply (auto simp add: less_eq_name_def less_name_def)
apply (rule lexord_trans)
apply (auto intro: transI)
done
next
fix xs ys :: "name"
assume "xs \<le> ys" and "ys \<le> xs"
then show "xs = ys"
apply (auto simp add: less_eq_name_def less_name_def)
apply (rule lexord_irreflexive [THEN notE])
defer
apply (rule lexord_trans)
apply (auto intro: transI)
done
next
fix xs ys :: "name"
show "xs < ys \<longleftrightarrow> xs \<le> ys \<and> \<not> ys \<le> xs"
apply (auto simp add: less_name_def less_eq_name_def)
defer
apply (rule lexord_irreflexive [THEN notE])
apply auto
apply (rule lexord_irreflexive [THEN notE])
defer
apply (rule lexord_trans)
apply (auto intro: transI)
done
qed
instance name :: linorder
proof
fix xs ys :: "name"
have "(as_string xs, as_string ys) \<in> lexord {(u, v). (of_char u::nat) < of_char v} \<or> xs = ys \<or> (as_string ys, as_string xs) \<in> lexord {(u, v). (of_char u::nat) < of_char v}"
by (metis (no_types, lifting) case_prodI lexord_linear linorder_neqE_nat mem_Collect_eq name.expand of_char_eq_iff)
then show "xs \<le> ys \<or> ys \<le> xs"
by (auto simp add: less_eq_name_def less_name_def)
qed
lemma less_name_code[code]:
"Name xs < Name [] \<longleftrightarrow> False"
"Name [] < Name (x # xs) \<longleftrightarrow> True"
"Name (x # xs) < Name (y # ys) \<longleftrightarrow> (of_char x::nat) < of_char y \<or> x = y \<and> Name xs < Name ys"
unfolding less_name_def by auto
lemma le_name_code[code]:
"Name (x # xs) \<le> Name [] \<longleftrightarrow> False"
"Name [] \<le> Name (x # xs) \<longleftrightarrow> True"
"Name (x # xs) \<le> Name (y # ys) \<longleftrightarrow> (of_char x::nat) < of_char y \<or> x = y \<and> Name xs \<le> Name ys"
unfolding less_eq_name_def less_name_def by auto
context begin
qualified definition append :: "name \<Rightarrow> name \<Rightarrow> name" where
"append v1 v2 = Name (as_string v1 @ as_string v2)"
lemma name_append_less:
assumes "xs \<noteq> Name []"
shows "append ys xs > ys"
proof -
have "Name (ys @ xs) > Name ys" if "xs \<noteq> []" for xs ys
using that
proof (induction ys)
case Nil
thus ?case
unfolding less_name_def
by (cases xs) auto
next
case (Cons y ys)
thus ?case
unfolding less_name_def
by auto
qed
with assms show ?thesis
unfolding append_def
by (cases xs, cases ys) auto
qed
end
end |
open import Common
open import Global
open import Projection
open import Local
open import Data.Fin
open import Data.Product
open import Data.Vec
open import Relation.Binary.PropositionalEquality
n = 4
Role = Fin n
p : Role
p = zero
q : Role
q = suc zero
r : Role
r = suc (suc zero)
s : Role
s = suc (suc (suc zero))
l : Label
l = 0
l′ : Label
l′ = 1
g₁ : Global n
g₁ = msgSingle′ p q l endG
lp : Local n
lp = sendSingle q l endL
g₁-proj-p-is-lp : project g₁ p ≡ lp
g₁-proj-p-is-lp = refl
lq : Local n
lq = recvSingle p l endL
g₁-proj-q-is-lq : project g₁ q ≡ lq
g₁-proj-q-is-lq = refl
p→q : Action n
p→q = action′ p q l
r→s : Action n
r→s = action′ r s l′
g₂ : Global n
g₂ = msgSingle′ r s l′ g₁
g₂′ : Global n
g₂′ = msgSingle′ r s l′ endG
g₁→end : g₁ - p→q →g endG
g₁→end = →g-prefix
g₂→g₁ : g₂ - r→s →g g₁
g₂→g₁ = →g-prefix
g₂→g₂′ : g₂ - p→q →g g₂′
g₂→g₂′ = →g-cont g₁→end (λ ()) (λ ()) (λ ()) (λ ())
g₁-proj-p→end : (p , project g₁ p) - p→q →l (p , endL)
g₁-proj-p→end = →l-send p refl λ ()
g₁-proj-q→end : (q , project g₁ q) - p→q →l (q , endL)
g₁-proj-q→end = →l-recv q refl λ ()
g₂-proj-p→g₂′-proj-p : (p , project g₂ p) - p→q →l (p , project g₂′ p)
g₂-proj-p→g₂′-proj-p = →l-send p refl λ ()
g₂-proj-q→g₂′-proj-q : (q , project g₂ q) - p→q →l (q , project g₂′ q)
g₂-proj-q→g₂′-proj-q = →l-recv q refl λ ()
c₁ : Configuration n
c₁ = lp ∷ lq ∷ endL ∷ endL ∷ []
cEnd : Configuration n
cEnd = endL ∷ endL ∷ endL ∷ endL ∷ []
c₁→cEnd : c₁ - p→q →c cEnd
c₁→cEnd = →c-comm c₁ (λ ()) refl refl refl g₁-proj-p→end g₁-proj-q→end
g₁↔c₁ : g₁ ↔ c₁
g₁↔c₁ = record { isProj = refls }
where
refls : (p : Fin n) -> lookup c₁ p ≡ project g₁ p
refls zero = refl
refls (suc zero) = refl
refls (suc (suc zero)) = refl
refls (suc (suc (suc zero))) = refl
|
(* Title: HOL/Auth/n_german_on_ini.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_german Protocol Case Study*}
theory n_german_on_ini imports n_german_base
begin
lemma iniImply_inv__1:
assumes a1: "(f=inv__1 )"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__2:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__2 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__3:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__3 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__4:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__4 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__5:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__5 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__6:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__6 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__7:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__7 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__8:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__8 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__9:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__9 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__10:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__10 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__11:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__11 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__12:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__12 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__13:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__13 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__14:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__14 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__15:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__15 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__16:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__16 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__17:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__17 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__18:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__18 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__19:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__19 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__20:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__20 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__21:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__21 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__22:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__22 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__23:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__23 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__24:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__24 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__25:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__25 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__26:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__26 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__27:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__27 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__28:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__28 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__29:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__29 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__30:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__30 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__31:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__31 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__32:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__32 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__33:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__33 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__34:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__34 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__35:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__35 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__36:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__36 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__37:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__37 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__38:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__38 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__39:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__39 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__40:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__40 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__41:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__41 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__42:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__42 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__43:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__43 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__44:
assumes a1: "(\<exists> p__Inv2. p__Inv2\<le>N\<and>f=inv__44 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__45:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__45 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__46:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__46 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__47:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__47 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__48:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__48 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__49:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__49 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__50:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__50 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
lemma iniImply_inv__51:
assumes a1: "(\<exists> p__Inv1 p__Inv2. p__Inv1\<le>N\<and>p__Inv2\<le>N\<and>p__Inv1~=p__Inv2\<and>f=inv__51 p__Inv1 p__Inv2)"
and a2: "formEval (andList (allInitSpecs N)) s"
shows "formEval f s"
using a1 a2 by auto
end
|
%% LyX 1.6.2 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{textcomp}
\usepackage{relsize}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
\def\labnb{0}
\usepackage{hyperref}
\usepackage{ulem}
\usepackage{latexsym}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{graphics}
\usepackage{lastpage}
\usepackage{titling}
\setlength{\droptitle}{-0.4in}
\linespread{1.1}
%%% HEADER
\usepackage[head=32pt,top=1in,bottom=1in,left=1in,right=1in]{geometry}
\usepackage{fancyhdr}
\setlength{\headheight}{24pt}
\pagestyle{fancy}
\lhead{CE 191: CEE Systems Analysis \\ University of California, Berkeley}
\rhead{Fall 2014 \\ Professor Scott Moura}
\cfoot{Page \thepage\ of \pageref{LastPage}}
\title{\Large Lab 2: Energy Portfolio Optimization}
\author{Due: Friday 10/3 at 2:00pm}
\date{}
\renewcommand{\headrulewidth}{0.5pt}
%\newcommand{\answer}[1]{\par\begin{center}\framebox{\parbox{5in}{{\bfseries \footnotesize Answer: }\textit{#1}}}\end{center}}
\newcommand{\answer}[1]{}
\newcommand{\inset}[2]{{\in\{{#1},\cdots,{#2}\} }}
\newcounter{question}
\setcounter{question}{1}
\def\newquestion{\textbf{Question \arabic{section}.\arabic{question}\ \ }\stepcounter{question}}
%\topmargin = -27 pt
%\leftmargin = -0.5 in
%\rightmargin= 1 in
%\oddsidemargin = -0.10 in \textheight = 8.5 in \textwidth = 6.5in
\setlength{\parindent}{0mm}
\addtolength{\parskip}{0.5\baselineskip}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\maketitle
\thispagestyle{fancy}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Lab Overview}
In this lab, you will learn to formulate a quadratic program to find a mix of energy supplies
which minimizes the variability of the price of energy. Section \ref{sec:problem} provides a description of
the full problem and the constraints. In Section \ref{sec:implementation}, you are asked to form the quadratic
program, and implement it in MATLAB. Finally, in Section \ref{sec:addanalysis}, you will modify the quadratic
program to analyze various scenarios. \textbf{Please remember to submit your MATLAB
code (.m files in one ZIP file), and explain in the report how to run the code.}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Energy Portfolio Investment Problem}\label{sec:problem}
The California Public Utilities Commission (CPUC) is charged with strategically planning its energy generation over
the next several years to meet its growing energy demand. Currently, California generates
199 \textit{megawatt hours} (MWh) from a combination of eight sources. This collection, or mix, of
energy sources is known as an \textit{energy portfolio}. The contributions of eight sources to
California's current portfolio is listed in Table \ref{tbl:energymix}.
\begin{table}[h]
\caption{Current sources of energy to California, and percent contribution to the current energy mix. Source: \url{http://energyalmanac.ca.gov/electricity/total_system_power.html}}
\begin{center}
\begin{tabular}{|c || c|c|c|c|c|c|c|c|}
\hline
{\bfseries Source} & Coal & Hydro & Natural Gas & Nuclear & Biomass & Geo & Solar & Wind \\ \hline
{\bfseries 2012 energy mix (\%)} & 7.5 & 8.3 & 43.4 & 9.0 & 2.3 & 4.4 & 0.9 & 6.3 \\ \hline
\end{tabular}
\end{center}
\label{tbl:energymix}
\end{table}
By the year 2020, California must generate a peak of 225 MWh to meet its growing demand for energy. The expected price in 2020 in dollars per megawatt hour (USD/MWh) is given in Table 2.
\begin{table}[h]
\caption{Expected price of energy in California in the year 2020. Adopted from: Adopted from \url{http://www.eia.gov/forecasts/aeo/pdf/electricity_generation.pdf}}
\begin{center}
\begin{tabular}{|c || c|c|c|c|c|c|c|c|}
\hline
{\bfseries Source} & Coal & Hydro & Natural Gas & Nuclear & Biomass & Geo & Solar & Wind \\ \hline
{\bfseries Expected Price (\$/MWh)} & 100 & 90 & 130 & 108 & 111 & 90 & 144 & 87 \\ \hline
\end{tabular}
\end{center}
\label{tbl:energyprice}
\end{table}
Through technology improvements, California can expand its resources as required to meet future demands. However, the price of each energy source contains uncertainty. Namely, variations in fuel costs, technology development, and future environmental regulations in 2020 impose uncertainty on the expected prices listed in Table \ref{tbl:energyprice}. Suppose the standard deviation $\sigma$ of the prices for each source is given in Table \ref{tbl:std}\footnote{For simplicity, we are ignoring correlations in prices between sources.}.
\begin{table}[h]
\caption{Standard deviation of energy source prices in 2020.}
\begin{center}
\begin{tabular}{|c || c|c|c|c|c|c|c|c|}
\hline
{\bfseries Source} & Coal & Hydro & Natural Gas & Nuclear & Biomass & Geo & Solar & Wind \\ \hline
{\bfseries $\sigma$ (\$/MWh)} & 22 & 30 & 15 & 20 & 30 & 36 & 32 & 40 \\ \hline
\end{tabular}
\end{center}
\label{tbl:std}
\end{table}
The variance in price of an uncertain good (for example 1 MWh of electricity) can be used as a measure of the \textit{risk} of that good. Recall that variance is
\begin{equation*}
\textrm{var} = \sigma^{2}.
\end{equation*}
Portfolio theory assumes that for a given level of risk, planners prefer lower costs to higher ones. Conversely, for a given expected cost, planners prefer less risk to more risk. By combining various goods in a portfolio, it is possible to create a portfolio with lower risk than any of the goods individually. This is known as \textit{diversification}. The same concepts hold for stock market portfolios.
To ensure competitive electricity rates, California must keep the expected cost of its energy portfolio under 100 USD/MWh. Therefore, California would like to determine an optimal energy portfolio. That is, determine the portfolio with the least risk for the given maximum expected cost.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Implementation}\label{sec:implementation}
\begin{enumerate}
\item Formulate a quadratic program (QP) that California can use to minimize the risk of obtaining its energy, while satisfying the maximum expected energy cost constraint described above.
\begin{enumerate}
\item Define your mathematical notation in a table. Be precise and organized.
\item Using this notation, formulate (i) the objective function and (ii) all the constraints.
\item Encode this formulation in matrices \texttt{Q, R, A, b}, where the QP is formulated as $\min \frac{1}{2} x^{T} Q x + R^{T} x$ subject to $A x \leq b$. Write down matrices \texttt{Q, R, A, b} in your report.
\item Is the Hessian $Q$ positive definite, negative definite, positive semi-definite, negative semi-definite, or indefinite? Note: the answer would not be trivial if we assumed correlations exist between the standard deviations of energy prices.
\end{enumerate}
\item Solve the QP that you have formulated using MATLAB's \texttt{quadprog} command (read the documentation). In your report, provide
\begin{itemize}
\item the value of the objective function, i.e. the risk,
\item the value of the decision variables at the optimum,
\item a qualitative description the optimal solution, including the active constraints.
\end{itemize}
\end{enumerate}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Additional Analysis}\label{sec:addanalysis}
The following questions study modifications to the original problem. Each question is independent from the other ones, i.e. the changes are not cumulative. Where applicable, provide (i) the objective function value, and (ii) the optimal decision variable values.
\begin{enumerate}
\setcounter{enumi}{2}
\item A concerned and conservative member of the CPUC (yup, they went to Leland StanfUrd JR. University), who is not familiar with portfolio optimization suggests the safest plan is to apply the current energy portfolio mix (Table \ref{tbl:energymix}) to the year 2020. \textbf{Note:} The mix in Table 1 does not add to 100\%. In practice, California imports the remaining energy supply from out-of-state. Apply the same percentages to 2020 as 2012. The total energy supply will not add to 225 MWh. What is the expected risk and expected cost of this portfolio? Note this is a lower bound, because the remaining energy must be imported. Is there a safer (in the sense of less variance) portfolio with at least as small expected cost? Explain.
\item The President of CPUC would like to know the minimal risk of each energy profile ranging in price 50 to 250 USD/MWh. Compute the minimal risk for each energy profile in this price range.
\begin{enumerate}
\item Summarize your results in a plot with max price [USD/MWh] on the $x-$axis and risk on the $y-$axis. Describe qualitatively the results.
\item Describe qualitatively the mix of the lowest risk energy portfolio in this price range. How much does it cost?
\end{enumerate}
\textbf{Remark:} Ideally, one wishes to both minimize expected cost and minimize risk. This is a multi-objective optimization problem. However, you'll find there exists a tradeoff between these two objectives. To assess multiple objectives we often create the plot above. This is known as \textit{Pareto optimization}\footnote{\url{http://en.wikipedia.org/wiki/Multi-objective_optimization}}.
\item By the year 2020, California must generate 225 MWh to meet its growing demand for energy. New information suggests that, due to resource limitations and future governmental regulations, the maximum energy supply of non-renewables sources in 2020 is constrained. The energy supply limits are given in Table \ref{tbl:limits}. Moreover, California has mandated a 33\% \textit{renewable portfolio standard} by 2020\footnote{\url{http://www.cpuc.ca.gov/PUC/energy/Renewables/index.htm}}, which includes wind, solar, biomass, and geothermal. Modify the original QP to include these additional constraints.
\begin{enumerate}
\item Formulate the appropriate constraints imposed by these limits, using the notation of Question 1. Describe any additional notation introduced.
\item Solve the original QP with these additional constraints. How does the new solution compare with your results from Question 1? Which constraints are active?
\end{enumerate}
\begin{table}[h]
\caption{Energy supply limits in 2020.}
\begin{center}
\begin{tabular}{|c || c|c|c|c|c|c|c|c|}
\hline
{\bfseries Source} & Coal & Hydro & Natural Gas & Nuclear & Biomass & Geo & Solar & Wind \\ \hline
{\bfseries Limit (MWh)} & 40 & 50 & 150 & 35 & 10 & 15 & 200 & 50 \\ \hline
\end{tabular}
\end{center}
\label{tbl:limits}
\end{table}
\end{enumerate}
%%%%%%%%%%%%%
\section*{Deliverables}
Submit the following on bSpace. Zip your code. Be sure that the function files are named exactly as specified (including spelling and case), and make sure the function declaration is exactly as specified.
\texttt{LASTNAME{\textunderscore}FIRSTNAME{\textunderscore}LAB2.PDF}\\
\texttt{LASTNAME{\textunderscore}FIRSTNAME{\textunderscore}LAB2.ZIP} which contains your respective Matlab files.
\end{document}
|
function alpha_pq = moment_normalized ( n, x, y, p, q )
%*****************************************************************************80
%
%% MOMENT_NORMALIZED computes a normalized moment of a polygon.
%
% Discussion:
%
% Alpha(P,Q) = Integral ( x, y in polygon ) x^p y^q dx dy / Area ( polygon )
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 03 October 2012
%
% Author:
%
% John Burkardt
%
% Reference:
%
% Carsten Steger,
% On the calculation of arbitrary moments of polygons,
% Technical Report FGBV-96-05,
% Forschungsgruppe Bildverstehen, Informatik IX,
% Technische Universitaet Muenchen, October 1996.
%
% Parameters:
%
% Input, integer N, the number of vertices of the polygon.
%
% Input, real X(N), Y(N), the vertex coordinates.
%
% Input, integer P, Q, the indices of the moment.
%
% Output, real ALPHA_PQ, the normalized moment Alpha(P,Q).
%
nu_pq = moment ( n, x, y, p, q );
nu_00 = moment ( n, x, y, 0, 0 );
alpha_pq = nu_pq / nu_00;
return
end
|
section \<open> Procedures \<close>
theory ITree_Procedure
imports ITree_Circus ITree_Hoare
keywords "over"
begin
datatype (discs_sels) ('inp, 'outp) methop = Call_C 'inp | Return_C 'outp
definition [lens_defs]: "Call = ctor_prism Call_C is_Call_C un_Call_C"
definition [lens_defs]: "Return = ctor_prism Return_C (Not \<circ> is_Call_C) un_Return_C"
record ('val, 'st) valst =
vval :: 'val
vst :: 'st
type_synonym ('e, 'inp, 'outp, 'st) "procedure" = "('e, ('inp, 'st) valst, ('outp, 'st) valst) ktree"
translations
(type) "('e, 'inp, 'outp, 'st) procedure" <= (type) "('inp, 'st) valst \<Rightarrow> ('e, ('outp, 'st') valst) itree"
definition procproc :: "(_, 'inp, 'outp, 'st::default) procedure \<Rightarrow> ('inp, 'outp) methop process" where
"procproc P = process [\<leadsto>] (\<lambda> s. inp Call \<bind> (\<lambda> inp. P \<lparr> vval = inp, vst = s \<rparr> \<bind> (\<lambda> vst. outp Return (vval vst) \<bind> Ret)))"
definition promote_proc :: "('e, 'inp, 'outp, 'ls) procedure \<Rightarrow> ('i \<Rightarrow> ('ls \<Longrightarrow> 's)) \<Rightarrow> ('e, 'i \<times> 'inp, 'outp, 's) procedure" where
"promote_proc P a = (\<lambda> v. P \<lparr> vval = snd (vval v), vst = get\<^bsub>a (fst (vval v))\<^esub> (vst v) \<rparr> \<bind> (\<lambda> v'. Ret \<lparr> vval = vval v', vst = put\<^bsub>a (fst (vval v))\<^esub> (vst v) (vst v')\<rparr>))"
lemma Call_wb_prism [simp, code_unfold]: "wb_prism Call" by (unfold_locales, auto simp add: lens_defs)
lemma Return_wb_prism [simp, code_unfold]: "wb_prism Return" by (unfold_locales, auto simp add: lens_defs)
definition "proc_ret e = (\<lambda> s. Ret \<lparr> vval = e s, vst = s \<rparr>)"
definition "procedure" :: "('inp \<Rightarrow> 'st \<Rightarrow> ('e, ('outp, 'st) valst) itree) \<Rightarrow> ('e, 'inp, 'outp, 'st) procedure" where
"procedure P = (\<lambda> vs. P (vval vs) (vst vs))"
definition proc_call :: "('o \<Longrightarrow> 's) \<Rightarrow> ('e, 'i, 'o, 'ls::default) procedure \<Rightarrow> ('i, 's) expr \<Rightarrow> ('e, 's) htree"
where "proc_call x P e = (\<lambda> s. P \<lparr> vval = e s, vst = default \<rparr> \<bind> (\<lambda> vs. Ret (put\<^bsub>x\<^esub> s (vval vs))))"
definition exec_proc :: "(unit, 'inp, 'out, 'st::default) procedure \<Rightarrow> 'inp \<Rightarrow> (unit, 'out) itree" where
"exec_proc P i = P \<lparr> vval = i, vst = default \<rparr> \<bind> (\<lambda> x. Ret (vval x))"
syntax
"_procedure" :: "pttrn \<Rightarrow> logic \<Rightarrow> logic" ("proc _./ _" [0, 20] 20)
"_call" :: "svid \<Rightarrow> logic \<Rightarrow> logic \<Rightarrow> logic" ("_ := call _ _" [61, 0, 61] 61)
"_return" :: "logic \<Rightarrow> logic" ("return")
translations
"_procedure x P" == "CONST procedure (\<lambda> x. P)"
"_return e" == "CONST proc_ret (e)\<^sub>e"
"_call x P e" == "CONST proc_call x P (e)\<^sub>e"
ML_file \<open>ITree_Procedure.ML\<close>
end |
@init PyObject_TryConvert_AddRules("juliaaa.As", [
(Any, PyAs_ConvertRule_tryconvert),
])
PyAs_ConvertRule_tryconvert(o, ::Type{S}) where {S} = begin
# get the type
to = PyObject_GetAttrString(o, "type")
isnull(to) && return -1
err = PyObject_Convert(to, Type)
Py_DecRef(to)
ism1(err) && return -1
t = takeresult(Type)
# get the value
vo = PyObject_GetAttrString(o, "value")
isnull(vo) && return -1
err = PyObject_Convert(vo, t)
Py_DecRef(vo)
ism1(err) && return -1
v = takeresult(t)
# convert
putresult(tryconvert(S, v))
end
|
lemma netlimit_at_vector: fixes a :: "'a::real_normed_vector" shows "netlimit (at a) = a" |
\section{Free Vibrations}
\noindent
Free damped vibrations, like in a massed spring system, are a common application of second order linear ODEs. In a massed spring system, there are three main forces acting on the mass that make up external forces.
\begin{enumerate}[label=\arabic*)]
\item Acceleration of The Mass -- Since acceleration is the 2nd derivative of position $y(t)$, and Newton's Second Law tells us that $F = ma$, the force from the acceleration of the mass is $my''$.
\item Dampening -- We'll assume that this term is proportional to the velocity, $y'$, and a term $b$. So, the force from dampening is $by'$.
\item Spring Stretch -- Hooke's Law tells us that the force from a spring is $ky$, where $k$ is some term that gives the spring's "stiffness"
\end{enumerate}
Since we assume that the net force is 0 (that's what free means), our equations is
\begin{equation*}
my'' + by' + ky = 0
\end{equation*}
\noindent
Extracting the coefficients and solving the auxiliary equation,
\begin{equation*}
mr^2 + br + k = 0 \implies r = \frac{-b \pm \sqrt{b^2 - 4mk}}{2m}
\end{equation*}
We will consider two cases. One in which there is no damping ($b = 0$), and one in which there is damping ($b > 0$).
\input{./higherOrder/freeVibrs/freeUndamped.tex}
\input{./higherOrder/freeVibrs/freeDamped.tex} |
The CPS men objected to the mistreatment and abuse of patients and determined to improve conditions in the psychiatric wards . They wanted to show other attendants alternatives to violence when dealing with patients .
|
lemma restrict_space_sets_cong: "A = B \<Longrightarrow> sets M = sets N \<Longrightarrow> sets (restrict_space M A) = sets (restrict_space N B)" |
# The Variational Quantum Eigensolver Algorithm
```python
import numpy as np
from VariationalForms import VariationalForms
from qiskit import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
```
```python
qasm_sim = QasmSimulator()
state_sim = StatevectorSimulator()
unit_sim = UnitarySimulator()
vf = VariationalForms()
```
# Variational Forms
### Rotation Gates
\begin{align}
\mathbf{R_z(\theta) = e^{-i\frac{\theta}{2}\sigma_z}}
\end{align}
\begin{align}
\mathbf{R_y(\phi) = e^{-i\frac{\phi}{2}\sigma_y}}
\end{align}
## $R(\theta, \phi)$
$R(\theta, \phi)$ Rotation gate, where:
$R(\theta, \phi) = $
```python
vf.draw(vf.R(0, 0))
```
```python
vf.decompose(vf.R(0, 0))
```
## $R(\theta, \phi)^\dagger$
$R(\theta, \phi)^\dagger$ Rotation gate
```python
vf.draw(vf.Rd(0, 0))
```
```python
vf.decompose(vf.Rd(0, 0))
```
## $A(\theta, \phi)$
$A(\theta, \phi)$ 2 Qubit A gate. Preserves **Particle-Number Symmetry** and **Time-Reversal Symmetry**
```python
vf.draw(vf.A(0, 0))
```
```python
vf.decompose(vf.A(0, 0))
```
```python
```
Figure(748.797x204.68)
|
/-
Copyright (c) 2018-2019 Minchao Wu. All rights reserved.
Released under MIT license as described in the file LICENSE.
Author: Minchao Wu
-/
import defs data.list.perm .data
open nnf tactic
meta def frame_restriction : tactic unit :=
do intro `a >> `[simp]
structure S4 (states : Type) extends kripke states :=
(refl : reflexive rel . frame_restriction)
(trans : transitive rel . frame_restriction)
instance inhabited_S4 : inhabited (S4 ℕ) :=
⟨ { val := λ a b, tt, rel := λ a b, tt } ⟩
@[simp] def force {states : Type} (k : S4 states) : states → nnf → Prop
| s (var n) := k.val n s
| s (neg n) := ¬ k.val n s
| s (and φ ψ) := force s φ ∧ force s ψ
| s (or φ ψ) := force s φ ∨ force s ψ
| s (box φ) := ∀ s', k.rel s s' → force s' φ
| s (dia φ) := ∃ s', k.rel s s' ∧ force s' φ
def sat {st} (k : S4 st) (s) (Γ : list nnf) : Prop :=
∀ φ ∈ Γ, force k s φ
def unsatisfiable (Γ : list nnf) : Prop :=
∀ (st) (k : S4 st) s, ¬ sat k s Γ
theorem unsat_singleton {φ} : unsatisfiable [φ] → ∀ (st) (k : S4 st) s, ¬ force k s φ
:=
begin
intros h _ _ _ hf,
apply h, intros ψ hψ, rw list.mem_singleton at hψ, rw hψ, exact hf
end
theorem sat_of_empty {st} (k : S4 st) (s) : sat k s [] :=
λ φ h, absurd h $ list.not_mem_nil _
theorem ne_empty_of_unsat {Γ} (h : unsatisfiable Γ): Γ ≠ [] :=
begin
intro heq, rw heq at h,
apply h, apply sat_of_empty, exact nat,
apply inhabited_S4.1, exact 0
end
open tmodel
@[simp] def minfo : Π m : tmodel, info
| (cons i l ba) := i
@[simp] def htk : Π m : tmodel, list nnf
| (cons i l ba) := i.htk
def hist : Π m : tmodel, list nnf
| (cons i l ba) := i.id.h
@[simp] def msig : Π m : tmodel, sig
| (cons i l ba) := i.id.s
@[simp] def manc : Π m : tmodel, list psig
| (cons i l ba) := i.id.a
def bhist : Π m : tmodel, list nnf
| (cons i l ba) := i.id.b
@[simp] def request : Π m : tmodel, list psig
| (cons i l ba) := ba
@[simp] def proper_request_box : Π m : tmodel, Prop
| (cons i l ba) := ∀ rq : psig, rq ∈ ba → ∀ φ, (box φ ∈ i.htk ∨ box φ ∈ i.id.b) → box φ ∈ rq.b
@[simp] def subset_request : Π m : tmodel, Prop
| (cons i l ba) := ba ⊆ i.id.a
@[simp] def tmodel_step_bhist : Π m : tmodel, Prop
| m@(cons i l ba) := ∀ s ∈ l, ∀ φ, box φ ∈ i.id.b → box φ ∈ htk s
@[simp] def tmodel_step_box : Π m : tmodel, Prop
| m@(cons i l ba) := ∀ s ∈ l, ∀ φ, box φ ∈ i.htk → box φ ∈ htk s
-- Can be strenghtened
@[simp] def tmodel_dia : Π m : tmodel, Prop
| m@(cons i l ba) := ∀ φ, dia φ ∈ i.htk → (∃ rq : psig, rq ∈ ba ∧ rq.d = φ) ∨ ∃ s ∈ l, φ ∈ htk s
@[simp] def child : tmodel → tmodel → bool
| s (cons i l ba) := s ∈ l
inductive tc' {α : Type} (r : α → α → Prop) : α → α → Prop
| base : ∀ a b, r a b → tc' a b
| step : ∀ a b c, r a b → tc' b c → tc' a c
theorem tc'.trans {α : Type} {r : α → α → Prop} {a b c : α} :
tc' r a b → tc' r b c → tc' r a c :=
begin
intros h₁ h₂,
induction h₁,
apply tc'.step, exact h₁_a_1, exact h₂,
apply tc'.step, exact h₁_a_1, apply h₁_ih, exact h₂
end
def desc : tmodel → tmodel → Prop := tc' (λ s m, child s m)
theorem desc_not_nil : Π c i ba m, m = cons i [] ba → desc c m → false :=
begin
intros c i ba m heq h,
induction h,
{rw heq at h_a_1, simp at h_a_1, exact h_a_1},
{apply h_ih, exact heq}
end
theorem desc_iff_eq_child_aux : Π i₁ i₂ s₁ s₂ l₁ l₂ m₁ m₂ m₃,
m₁ = cons i₁ l₁ s₁ → m₂ = cons i₂ l₂ s₂ → l₁ = l₂ →
(desc m₃ m₁ ↔ desc m₃ m₂) :=
begin
intros i₁ i₂ s₁ s₂ l₁ l₂ m₁ m₂ m₃ heq₁ heq₂ heq,
split,
{intro hd, induction hd,
{rw heq₁ at hd_a_1, simp at hd_a_1,
rw heq at hd_a_1,
apply tc'.base, rw heq₂, simp, exact hd_a_1},
{apply tc'.trans, apply tc'.base, exact hd_a_1, apply hd_ih, exact heq₁}},
{intro hd, induction hd,
{rw heq₂ at hd_a_1, simp at hd_a_1,
rw ←heq at hd_a_1,
apply tc'.base, rw heq₁, simp, exact hd_a_1},
{apply tc'.trans, apply tc'.base, exact hd_a_1, apply hd_ih, exact heq₂}}
end
theorem eq_desc_of_eq_children {i₁ i₂ s₁ s₂ l c} :
desc c (cons i₁ l s₁) = desc c (cons i₂ l s₂) :=
begin rw desc_iff_eq_child_aux, repeat {refl} end
theorem desc_step : Π c i l ba, c ∈ l → desc c (cons i l ba)
| c i [] ba h := absurd h $ list.not_mem_nil _
| c i (hd::tl) ba h :=
begin
constructor,
simp, cases h,
left, exact h, right, exact h
end
theorem desc_ex : Π c i l ba, (∃ m ∈ l, desc c m) → desc c (cons i l ba)
| c i [] ba h := begin rcases h with ⟨w, hmem, hw⟩, exact (absurd hmem $ list.not_mem_nil _) end
| c i (hd::tl) ba h :=
begin
rcases h with ⟨w, hmem, hw⟩,
cases hw,
{apply tc'.step,
swap 3, {exact w},
{exact hw_a_1},
{apply tc'.base, simp, cases hmem, left, exact hmem, right, exact hmem}},
{apply tc'.step, exact hw_a_1, apply tc'.trans, exact hw_a_2, apply tc'.base, simp, exact hmem}
end
theorem ex_desc : Π c i l ba m, m = (cons i l ba) → desc c m → (c ∈ l ∨ ∃ m ∈ l, desc c m) :=
begin
intros c i l ba m heq h,
induction h,
{left, rw heq at h_a_1, simp at h_a_1, exact h_a_1},
{cases h_ih heq,
{right, split, split, exact h, apply tc'.base, exact h_a_1},
{rcases h with ⟨w, hmem, hw⟩, right, split, split, exact hmem, apply tc'.step, exact h_a_1, exact hw}}
end
theorem ex_desc' : Π c i l ba, desc c (cons i l ba) → (c ∈ l ∨ ∃ m ∈ l, desc c m) :=
begin intros c i l ba h, apply ex_desc, repeat {refl}, exact h end
@[simp] def tmodel_anc : Π m : tmodel, Prop
| m@(cons i l ba) := ∀ s rq, desc s m → rq ∈ request s →
(rq ∈ manc m) ∨
(∃ d, desc d m ∧ some rq = msig d)
structure ptmodel (m : tmodel) : Prop :=
(bhist : tmodel_step_bhist m)
(sbox : tmodel_step_box m)
(pdia : tmodel_dia m)
(bdia : tmodel_anc m)
(reqb : proper_request_box m)
(sreq : subset_request m)
def global_pt (m : tmodel) := ∀ s, desc s m → ptmodel s
open subtype
def model : Type := {m : tmodel // ptmodel m ∧ global_pt m}
def rmodel : Type := {m : tmodel // ptmodel m}
inductive reach_step : rmodel → rmodel → Prop
| fwd_base (s : rmodel) (i l ba h) : s.1 ∈ l → reach_step ⟨(cons i l ba), h⟩ s
| bwd_base (s : rmodel) (i l ba h) : (∃ rq ∈ ba, some rq = msig s.1) → reach_step ⟨(cons i l ba), h⟩ s
theorem reach_step_box (s₁ s₂ φ) (h₁ : reach_step s₁ s₂) (h₂ : box φ ∈ htk s₁.1) : box φ ∈ htk s₂.1 :=
begin
cases h₁,
{cases s₂ with s₂ ps₂,
cases s₂ with i₂ l₂ sg₂,
simp,
have := h₁_h.sbox,
simp at this, simp at h₂,
have hmem := this _ h₁_a _ h₂,
simp at hmem, exact hmem },
{cases s₂ with s₂ ps₂,
cases s₂ with i₂ l₂ sg₂,
simp,
rcases h₁_a with ⟨w,hmem,hw⟩,
simp at hw,
apply i₂.mhtk,
have := i₂.id.ps₂,
rw ←hw at this,
have hneq : some w ≠ none,
{intro heq, contradiction},
have hsub := this hneq,
apply hsub,
have := h₁_h.reqb,
simp at this, simp at h₂,
have hc := this w hmem φ (or.inl h₂),
cases w,
dsimp [bsig], exact hc}
end
inductive rtc {α : Type} (r : α → α → Prop) : α → α → Prop
| refl : Π a, rtc a a
| step : Π a b c, r a b → rtc b c → rtc a c
theorem rtc.trans {α : Type} {r : α → α → Prop} {a b c : α} :
rtc r a b → rtc r b c → rtc r a c :=
begin
intros h₁ h₂,
induction h₁,
exact h₂,
apply rtc.step, exact h₁_a_1, apply h₁_ih, exact h₂
end
theorem rtc_step {α : Type} {r : α → α → Prop} {a b : α} (h : r a b) :
rtc r a b :=
by apply rtc.step _ _ _ h; apply rtc.refl
def reach (s₁ s₂ : rmodel) := rtc reach_step s₁ s₂
theorem refl_reach : Π s, reach s s := λ s, rtc.refl s
theorem trans_reach : Π s₁ s₂ s₃, reach s₁ s₂ → reach s₂ s₃ → reach s₁ s₃ := λ s₁ s₂ s₃ h₁ h₂, rtc.trans h₁ h₂
@[simp] def builder (m : tmodel) : S4 {x : rmodel // x.1 = m ∨ desc x.1 m} :=
{val := λ v s, var v ∈ htk s.1.1,
rel := λ s₁ s₂, reach s₁ s₂,
refl := λ s, refl_reach s,
trans := λ a b c, trans_reach a b c}
open rtc
theorem reach_box (s₁ s₂ φ) (h₁ : reach s₁ s₂) (h₂ : box φ ∈ htk s₁.1) : φ ∈ htk s₂.1 :=
begin
induction h₁ with m m₁ m₂ m₃ h₁₂ h₂₃ ih,
{cases m with tm hm, cases tm with i l sg,
simp,
apply i.hhtk.hbox,
simp at h₂, exact h₂},
{apply ih,
apply reach_step_box,
exact h₁₂, exact h₂}
end
theorem reach_step_dia (s : rmodel) (rt : model) (φ)
(h₁ : desc s.1 rt.1)
(h₂ : manc rt.1 = []) (h₃ : dia φ ∈ htk s.1) :
∃ s', reach_step s s' ∧ φ ∈ htk s'.1 ∧ desc s'.1 rt.1 :=
begin
cases s with s ps,
cases s with i l sg,
have := ps.pdia,
simp at this, simp at h₃,
have hc := this _ h₃,
cases hc,
{cases rt with rt prt,
cases rt with irt lrt sgrt,
rcases hc with ⟨w, hmem, hw⟩,
have := prt.1.bdia,
simp at this, simp at h₁,
have hcaux := this _ w h₁,
simp at hcaux,
have hcc := hcaux hmem,
simp at h₂,
cases hcc,
{rw h₂ at hcc, exfalso, apply list.not_mem_nil, exact hcc},
{rcases hcc with ⟨m, hml, hmr⟩,
have pm := prt.2 m hml,
split, split,
swap 3, exact ⟨m, pm⟩,
apply reach_step.bwd_base,
split, split, exact hmem, simp, exact hmr,
split,
{cases m with im lm sgm, simp,
apply im.mhtk,
have := im.id.ps₁,
simp at hmr, rw ←hmr at this,
have hneq : some w ≠ none, {intro, contradiction},
have hmem := this hneq,
cases w, dsimp [dsig] at hmem,
rw ←hw, exact hmem_1 },
{exact hml} } },
{rcases hc with ⟨m, pml, pmr⟩,
have hdm : desc m rt.1,
{apply tc'.trans, apply tc'.base,
swap 3, exact (⟨cons i l sg, ps⟩ : rmodel).val,
simp, exact pml, exact h₁},
cases rt with rt prt,
cases rt with irt lrt sgrt,
have pm := prt.2 m hdm,
split, split, swap 3,
exact ⟨m, pm⟩,
apply reach_step.fwd_base,
exact pml, split,
{exact pmr},
{exact hdm} }
end
theorem reach_dia (s : rmodel) (rt : model) (φ)
(h₁ : desc s.1 rt.1)
(h₂ : manc rt.1 = []) (h₃ : dia φ ∈ htk s.1) :
∃ s', reach s s' ∧ φ ∈ htk s'.1 ∧ desc s'.1 rt.1:=
begin
have := reach_step_dia s rt φ h₁ h₂ h₃,
rcases this with ⟨w, hwl, hwr⟩,
split, split, swap 3, exact w,
apply rtc_step hwl, exact hwr
end
theorem reach_step_dia_root (s : rmodel) (rt : model) (φ)
(h₁ : s.1 = rt.1)
(h₂ : manc rt.1 = []) (h₃ : dia φ ∈ htk s.1) :
∃ s', reach_step s s' ∧ φ ∈ htk s'.1 ∧ desc s'.1 rt.1 :=
begin
cases s with s ps,
cases s with is ls sgs,
have := ps.pdia,
simp at this, simp at h₃,
have hc := this _ h₃,
cases hc,
{have := ps.sreq, simp at this,
rcases hc with ⟨w, hmw, hw⟩,
have hmem := this hmw,
cases rt with rt prt,
rw ←h₁ at h₂,
simp at h₂, rw h₂ at hmem,
exfalso, apply list.not_mem_nil, exact hmem},
{cases rt with rt prt,
rcases hc with ⟨w, hwl, hwr⟩,
have ptw : ptmodel w,
{apply prt.2, apply tc'.base, simp at h₁, rw ←h₁, simp, exact hwl},
split, split, swap 3, exact ⟨w, ptw⟩,
apply reach_step.fwd_base, exact hwl, split,
{exact hwr},
{apply tc'.base, simp, simp at h₁, rw ←h₁, simp, exact hwl} }
end
theorem reach_dia_root (s : rmodel) (rt : model) (φ)
(h₁ : s.1 = rt.1)
(h₂ : manc rt.1 = []) (h₃ : dia φ ∈ htk s.1) :
∃ s', reach s s' ∧ φ ∈ htk s'.1 ∧ desc s'.1 rt.1 :=
begin
have := reach_step_dia_root s rt φ h₁ h₂ h₃,
rcases this with ⟨w, hwl, hwr⟩,
split, split, swap 3, exact w,
apply rtc_step hwl, exact hwr
end
theorem good_model (m : model) (hrt : manc m.1 = []):
Π (s : {x : rmodel // x.1 = m.1 ∨ desc x.1 m.1}) (φ : nnf),
φ ∈ htk s.1.1 → force (builder m.1) s φ
| s (var n) h := begin simp, exact h end
| s (neg n) h := begin
simp, intro hin,
cases s with s ps,
cases s with s pts,
cases s with i l sg,
have := i.hhtk.hno_contra,
simp at hin,
apply this hin, simp at h, exact h
end
| s (and φ ψ) h := begin
split,
{apply good_model,
cases s with s ps,
cases s with s pts,
cases s with i l sg,
have := i.hhtk.hand_left,
simp, apply this, simp at h, exact h},
{apply good_model,
cases s with s ps,
cases s with s pts,
cases s with i l sg,
have := i.hhtk.hand_right,
simp, apply this, simp at h, exact h}
end
| s (or φ ψ) h := begin
cases s with s ps,
cases s with s pts,
cases s with i l sg,
have := i.hhtk.hor,
simp at h,
have hc := this h,
cases hc,
{simp, left, apply good_model, simp, exact hc},
{simp, right, apply good_model, simp, exact hc}
end
| s (box φ) h := begin
intros m hm,
apply good_model,
apply reach_box,
exact hm,
exact h
end
| s (dia φ) h := begin
cases s with s ps,
cases ps,
{simp, simp at h,
have := reach_dia_root _ _ _ ps hrt h,
rcases this with ⟨s', hs'l, hs'm, hs'r⟩,
split, split,
exact hs'l, split, apply good_model, simp,
exact hs'm, right, exact hs'r },
{simp, simp at h,
have := reach_dia _ _ _ ps hrt h,
rcases this with ⟨s', hs'l, hs'm, hs'r⟩,
split, split,
exact hs'l, split, apply good_model, simp,
exact hs'm, right, exact hs'r}
end
|
c------------------------------------------------------------------------
function ffsigiut(xx1,xx2,jpp,je1,je2)
c------------------------------------------------------------------------
c
c \int(dt) \int(du) ffsig *s/sh**3 *2*pi*alpha**2 *delta(uh+th+sh)
c
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
include 'epos.inc'
double precision tmin,tmax,t,sh2,sqrtq2s
ig=3
s=engy**2
sh=s*xx1*xx2
ffsigiut=0.
if(sh.le.4.*q2min)return
sh2=dble(sh/2.)
c tmin=sh/2-sqrt(sh*sh/4-q2min*sh)
sqrtq2s=sqrt(dble(q2min*sh))
tmin=sh2-sqrt((sh2-sqrtq2s)*(sh2+sqrtq2s))
tmax=sh2
do i=1,ig
do m=1,2
t=2d0*tmin/(1d0+tmin/tmax-dble(tgss(ig,i)*(2*m-3))
& *(1d0-tmin/tmax))
qq=sngl(t*(1d0-t/dble(sh)))
ft=ffsigj(sngl(t),qq,xx1,xx2,jpp,je1,je2)/sh**3
* * (2*pi*pssalf(qq/qcdlam))**2
ffsigiut=ffsigiut+wgss(ig,i)*ft*sngl(t)**2
enddo
enddo
ffsigiut=ffsigiut
* *0.5*sngl(1d0/tmin-1d0/tmax)
* *2*pi*s
* /2 !CS for parton pair
return
end
c-----------------------------------------------------------------------
function ffsigj(t,qt,x1,x2,jpp,je1,je2)
c-----------------------------------------------------------------------
c
c \sum x1*f_i(x1,qt) * x2*f_k(x2,qt) * B_ik
c
c B_ik = psbori = contribution to Born xsection:
c dsigmaBorn/d2pt/dy
c = s/pi * delta(s+t+u) * 2*pi*alpha**2 /s**2 * B_ik
c
c qt = virtuality scale
c x1, x2 = light cone momentum fractions
c
c x*f_j(x,qt) = function fparton(x,qt,j)
c
c-----------------------------------------------------------------------
c jpp: type of Pomeron
c 1 ... sea-sea
c 2 ... val-sea
c 3 ... sea-val
c 4 ... val-val
c 5 ... all
c je = emission type
c 0 ... no emissions
c 1 ... emissions
c 2 ... all
c-----------------------------------------------------------------------
include 'epos.incsem'
include 'epos.inc'
s=engy**2*x1*x2
if(jpp.ne.5)then
ji1=mod(jpp+1,2)+1
ji2=(jpp+1)/2
sea1=pifpartone(x1,qt,-1,je1,ji1)
g1= pifpartone(x1,qt, 0,je1,ji1)
uv1= pifpartone(x1,qt, 1,je1,ji1)
dv1= pifpartone(x1,qt, 2,je1,ji1)
sea2=pifpartone(x2,qt,-1,je2,ji2)
g2= pifpartone(x2,qt, 0,je2,ji2)
uv2= pifpartone(x2,qt, 1,je2,ji2)
dv2= pifpartone(x2,qt, 2,je2,ji2)
else
sea1=pifpartone(x1,qt,-1,je1,1)+pifpartone(x1,qt,-1,je1,2)
g1= pifpartone(x1,qt, 0,je1,1)+pifpartone(x1,qt, 0,je1,2)
uv1= pifpartone(x1,qt, 1,je1,1)+pifpartone(x1,qt, 1,je1,2)
dv1= pifpartone(x1,qt, 2,je1,1)+pifpartone(x1,qt, 2,je1,2)
sea2=pifpartone(x2,qt,-1,je2,1)+pifpartone(x2,qt,-1,je2,2)
g2= pifpartone(x2,qt, 0,je2,1)+pifpartone(x2,qt, 0,je2,2)
uv2= pifpartone(x2,qt, 1,je2,1)+pifpartone(x2,qt, 1,je2,2)
dv2= pifpartone(x2,qt, 2,je2,1)+pifpartone(x2,qt, 2,je2,2)
endif
ffsigj= ffborn(s,t, g1*g2 !gg
* ,(uv1+dv1+2.*naflav*sea1)*g2+g1*(uv2+dv2+2.*naflav*sea2) !gq
* ,(uv1+sea1)*(uv2+sea2) !qq
* +(dv1+sea1)*(dv2+sea2)+sea1*sea2*(naflav-1)*2.
* ,(uv1+sea1)*sea2+(uv2+sea2)*sea1 !qa
* +(dv1+sea1)*sea2+(dv2+sea2)*sea1+sea1*sea2*(naflav-2)*2.
* ,dv1*uv2+dv2*uv1+(uv2+dv2)*sea1*(naflav-1)*2. !qqp
* +(uv1+dv1)*sea2*(naflav-1)*2.
* +sea1*sea2*naflav*(naflav-1)*4.
*)
end
c-----------------------------------------------------------------------
function ffsig(t,qt,x1,x2) !former psjy
c-----------------------------------------------------------------------
include 'epos.incsem'
include 'epos.inc'
s=engy**2*x1*x2
g1= pifpartone(x1,qt, 0,2,1)+pifpartone(x1,qt, 0,2,2)
uv1= pifpartone(x1,qt, 1,2,1)+pifpartone(x1,qt, 1,2,2)
dv1= pifpartone(x1,qt, 2,2,1)+pifpartone(x1,qt, 2,2,2)
sea1=pifpartone(x1,qt,-1,2,1)+pifpartone(x1,qt,-1,2,2)
g2= pifpartone(x2,qt, 0,2,1)+pifpartone(x2,qt, 0,2,2)
uv2= pifpartone(x2,qt, 1,2,1)+pifpartone(x2,qt, 1,2,2)
dv2= pifpartone(x2,qt, 2,2,1)+pifpartone(x2,qt, 2,2,2)
sea2=pifpartone(x2,qt,-1,2,1)+pifpartone(x2,qt,-1,2,2)
ffsig= ffborn(s,t, g1*g2 !gg
* ,(uv1+dv1+2.*naflav*sea1)*g2+g1*(uv2+dv2+2.*naflav*sea2) !gq
* ,(uv1+sea1)*(uv2+sea2) !qq
* +(dv1+sea1)*(dv2+sea2)+sea1*sea2*(naflav-1)*2.
* ,(uv1+sea1)*sea2+(uv2+sea2)*sea1 !qa
* +(dv1+sea1)*sea2+(dv2+sea2)*sea1+sea1*sea2*(naflav-2)*2.
* ,dv1*uv2+dv2*uv1+(uv2+dv2)*sea1*(naflav-1)*2. !qqp
* +(uv1+dv1)*sea2*(naflav-1)*2.
* +sea1*sea2*naflav*(naflav-1)*4.
*)
end
c------------------------------------------------------------------------
function ffborn(s,t,gg,gq,qq,qa,qqp)
c------------------------------------------------------------------------
ffborn=
*( psbori(s,t,0,0,1)+psbori(s,s-t,0,0,1)
* +psbori(s,t,0,0,2)+psbori(s,s-t,0,0,2)) /2. *gg !gg
*+(psbori(s,t,0,1,1)+psbori(s,s-t,0,1,1)) *gq !gq
*+(psbori(s,t,1,1,1)+psbori(s,s-t,1,1,1))/2. *qq !qq
*+(psbori(s,t,1,-1,1)+psbori(s,s-t,1,-1,1)+psbori(s,t,1,-1,2)+
* psbori(s,s-t,1,-1,2)+psbori(s,t,1,-1,3)+psbori(s,s-t,1,-1,3)) !qa
* *qa
*+(psbori(s,t,1,2,1)+psbori(s,s-t,1,2,1)) *qqp !qq'
end
c-----------------------------------------------------------------------
function pifpartone(xx,qq,j,je,ji) ! pol interpolation of partone
c-----------------------------------------------------------------------
include 'epos.incsem'
include 'epos.inc'
common/tabfptn/kxxmax,kqqmax,fptn(20,20,-1:2,0:2,2)
real wi(3),wj(3)
common /cpifpartone/npifpartone
data npifpartone /0/
npifpartone=npifpartone+1
if(npifpartone.eq.1)call MakeFpartonTable
qqmax=engy**2/4.
xxmin=0.01/engy
xxmax=1
xxk=1.+log(xx/xxmin)/log(xxmax/xxmin)*(kxxmax-1)
qqk=1.+log(qq/q2min)/log(qqmax/q2min)*(kqqmax-1)
kxx=int(xxk)
kqq=int(qqk)
if(kxx.lt.1)kxx=1
if(kqq.lt.1)kqq=1
if(kxx.gt.(kxxmax-2))kxx=kxxmax-2
if(kqq.gt.(kqqmax-2))kqq=kqqmax-2
wi(2)=xxk-kxx
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
wj(2)=qqk-kqq
wj(3)=wj(2)*(wj(2)-1.)*.5
wj(1)=1.-wj(2)+wj(3)
wj(2)=wj(2)-2.*wj(3)
pifpartone=0
do kx=1,3
do kq=1,3
pifpartone=pifpartone+fptn(kxx+kx-1,kqq+kq-1,j,je,ji)
* *wi(kx)*wj(kq)
enddo
enddo
end
c-----------------------------------------------------------------------
subroutine MakeFpartonTable
c-----------------------------------------------------------------------
include 'epos.incsem'
include 'epos.inc'
common/tabfptn/kxxmax,kqqmax,fptn(20,20,-1:2,0:2,2)
write (*,'(a,$)')'(Fparton table'
kxxmax=10
kqqmax=10
qqmax=engy**2/4.
xxmin=0.01/engy
xxmax=1
do ji=1,2
do je=0,2
write(*,'(a,$)')'.'
do j=-1,2
do kxx=1,kxxmax
xx=xxmin*(xxmax/xxmin)**((kxx-1.)/(kxxmax-1.))
do kqq=1,kqqmax
qq=q2min*(qqmax/q2min)**((kqq-1.)/(kqqmax-1.))
fptn(kxx,kqq,j,je,ji)= fpartone(xx,qq,j,je,ji)
enddo
enddo
enddo
enddo
enddo
write (*,'(a,$)')'done)'
end
c------------------------------------------------------------------------
function fpartone(xx,qq,j,je,ji) !former pspdf0 (sha)
c-----------------------------------------------------------------------
c
c parton distribution function for proton ( actually x*f(x) !!!!!!! )
c
c xx = light cone momentum fraction
c qq = virtuality scale
c j = parton type
c -1 ... sea (distribution function per flavor)
c 0 ... g
c 1 ... u
c 2 ... d
c je = emission type
c 0 ... no emissions
c 1 ... emissions
c 2 ... all
c ji = initial parton type
c 1 ... sea (q et g)
c 2 ... val
c-----------------------------------------------------------------------
double precision z,xmin,xm,zx,psuds
common/ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
fpartone=0
if(je.eq.1)goto888
c ...... f_0 * sudakov.........
if(j.eq.0.and.ji.eq.1)then
fpartone=fzeroGlu(xx,2,1) !hadron class 2, projectile side
elseif((j.eq.1.or.j.eq.2).and.ji.eq.2)then
fpartone=psdfh4(xx,q2min,0.,2,j)
elseif(j.eq.-1.and.ji.eq.1)then
fpartone=fzeroSea(xx,2,1)
endif
fpartone=fpartone*sngl(psuds(qq,j)/psuds(q2min,j))
if(je.eq.0)goto999
c......... integral f_0 E_qcd............
888 continue
xmin=dble(xx)/(1.d0-dble(q2ini/qq))
if(xmin.lt.1.d0)then
dpd1=0.
dpd2=0.
xm=max(xmin,0.3d0)
!numerical integration xm -> 1
do i=1,7
do m=1,2
zx=1.d0-(1.d0-xm)*(.5d0+(dble(m)-1.5d0)*dble(x1(i)))**.25d0
z=xx/zx
gl=fzeroGlu(sngl(zx),2,1)
uv=psdfh4(sngl(zx),q2min,0.,2,1)
dv=psdfh4(sngl(zx),q2min,0.,2,2)
sea=fzeroSea(sngl(zx),2,1)
fz=0
if(j.eq.0)then
if(ji.eq.1)
* fz=gl *psevi(q2min,qq,z,1,1)
* +sea*psevi(q2min,qq,z,2,1) !ccccc
if(ji.eq.2)
* fz=(uv+dv)*psevi(q2min,qq,z,2,1)
elseif(j.eq.1.and.ji.eq.2)then
fz=psevi(q2min,qq,z,3,2)*uv
elseif(j.eq.2.and.ji.eq.2)then
fz=psevi(q2min,qq,z,3,2)*dv
elseif(j.eq.-1)then
akns=psevi(q2min,qq,z,3,2) !nonsinglet contribution
aks=(psevi(q2min,qq,z,2,2)-akns) !singlet contribution
if(ji.eq.1)
* fz=psevi(q2min,qq,z,1,2)*gl
* +sea*aks+sea*akns !ccccc
if(ji.eq.2)
* fz=(uv+dv)*aks
endif
dpd1=dpd1+a1(i)*fz/sngl(zx)**2/sngl(1.d0-zx)**3
enddo
enddo
dpd1=dpd1*sngl(1.d0-xm)**4/8.*xx
!numerical integration xmin -> xm
if(xm.gt.xmin)then
do i=1,7
do m=1,2
zx=xx+(xm-xx)
& *((xmin-xx)/(xm-xx))**(.5d0-(dble(m)-1.5d0)*dble(x1(i)))
z=xx/zx
gl=fzeroGlu(sngl(zx),2,1)
uv=psdfh4(sngl(zx),q2min,0.,2,1)
dv=psdfh4(sngl(zx),q2min,0.,2,2)
sea=fzeroSea(sngl(zx),2,1)
fz=0
if(j.eq.0)then
if(ji.eq.1)
* fz=gl *psevi(q2min,qq,z,1,1)
* +sea*psevi(q2min,qq,z,2,1) !ccccc
if(ji.eq.2)
* fz=(uv+dv)*psevi(q2min,qq,z,2,1)
elseif(j.eq.1.and.ji.eq.2)then
fz=psevi(q2min,qq,z,3,2)*uv
elseif(j.eq.2.and.ji.eq.2)then
fz=psevi(q2min,qq,z,3,2)*dv
elseif(j.eq.-1)then
akns=psevi(q2min,qq,z,3,2) !nonsinglet contribution
aks=(psevi(q2min,qq,z,2,2)-akns) !singlet contribution
if(ji.eq.1)
* fz=psevi(q2min,qq,z,1,2)*gl
* +sea*aks+sea*akns !ccccc
if(ji.eq.2)
* fz=(uv+dv)*aks
endif
dpd2=dpd2+a1(i)*fz*sngl((1.d0-xx/zx)/zx)
enddo
enddo
dpd2=dpd2*sngl(log((xm-xx)/(xmin-xx))*.5d0*xx)
endif
fpartone=fpartone+dpd2+dpd1
endif
999 continue
if(j.lt.0)fpartone=fpartone/naflav/2.
return
end
c------------------------------------------------------------------------
function fparton(xx,qq,j) !former pspdf0 (sha)
c-----------------------------------------------------------------------
c
c parton distribution function for proton ( actually x*f(x) !!!!!!! )
c
c xx = light cone momentum fraction
c qq = virtuality scale
c j = parton type
c -1 ... sea (dsistribution fuction per flavor)
c 0 ... g
c 1 ... u
c 2 ... d
c
c-----------------------------------------------------------------------
c (see pages 105 - 107 of our report)
c
c fparton(xx) = xx * f(xx) !!!!!
c
c f_j(xx,qq) = \sum_k \int(xx<x<1) dx/x f0_k(x) Eqcd_k_j(xx/x,qq)
c
c f0_k = fzeroGlu or fzeroSea
c
c Eqcd=E~qcd+delta*sudakov, E~qcd: at least one emission
c
c-----------------------------------------------------------------------
double precision z,xmin,xm,zx,psuds
common/ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
c ...... f_0 * sudakov.........
if(j.eq.0)then
fparton=fzeroGlu(xx,2,1)
elseif(j.eq.1.or.j.eq.2)then
fparton=psdfh4(xx,q2min,0.,2,j)
else
fparton=fzeroSea(xx,2,1)
endif
fparton=fparton*sngl(psuds(qq,j)/psuds(q2min,j))
c......... integral f_0 E_qcd............
xmin=xx/(1.d0-dble(q2ini/qq))
if(xmin.lt.1.d0)then
dpd1=0.
dpd2=0.
xm=max(xmin,.3d0)
!numerical integration xm -> 1
do i=1,7
do m=1,2
zx=1.d0-(1.d0-xm)*(.5d0+(dble(m)-1.5d0)*dble(x1(i)))**.25d0
z=xx/zx
gl=fzeroGlu(sngl(zx),2,1)
uv=psdfh4(sngl(zx),q2min,0.,2,1)
dv=psdfh4(sngl(zx),q2min,0.,2,2)
sea=fzeroSea(sngl(zx),2,1)
if(j.eq.0)then
fz=psevi(q2min,qq,z,1,1)*gl
* +(uv+dv+sea)*psevi(q2min,qq,z,2,1)
elseif(j.eq.1)then
fz=psevi(q2min,qq,z,3,2)*uv
elseif(j.eq.2)then
fz=psevi(q2min,qq,z,3,2)*dv
else
akns=psevi(q2min,qq,z,3,2) !nonsinglet contribution
aks=(psevi(q2min,qq,z,2,2)-akns) !singlet contribution
fz=(psevi(q2min,qq,z,1,2)*gl+(uv+dv+sea)*aks+sea*akns)
endif
dpd1=dpd1+a1(i)*fz/sngl(zx)**2/sngl(1.d0-zx)**3
enddo
enddo
dpd1=dpd1*sngl((1.d0-xm)**4/8.*xx)
!numerical integration xmin -> xm
if(xm.gt.xmin)then
do i=1,7
do m=1,2
zx=xx+(xm-xx)*((xmin-xx)/(xm-xx))
* **(.5d0-(dble(m)-1.5)*dble(x1(i)))
z=xx/zx
gl=fzeroGlu(sngl(zx),2,1)
uv=psdfh4(sngl(zx),q2min,0.,2,1)
dv=psdfh4(sngl(zx),q2min,0.,2,2)
sea=fzeroSea(sngl(zx),2,1)
if(j.eq.0)then
fz=psevi(q2min,qq,z,1,1)*gl+(uv+dv+sea)*
* psevi(q2min,qq,z,2,1)
elseif(j.eq.1)then
fz=psevi(q2min,qq,z,3,2)*uv
elseif(j.eq.2)then
fz=psevi(q2min,qq,z,3,2)*dv
else
akns=psevi(q2min,qq,z,3,2) !nonsinglet contribution
aks=(psevi(q2min,qq,z,2,2)-akns) !singlet contribution
fz=(psevi(q2min,qq,z,1,2)*gl+(uv+dv+sea)*aks+sea*akns)
endif
dpd2=dpd2+a1(i)*fz*sngl((1.d0-xx/zx)/zx)
enddo
enddo
dpd2=dpd2*sngl(log((xm-xx)/(xmin-xx))*.5d0*xx)
endif
fparton=fparton+dpd2+dpd1
endif
if(j.lt.0)fparton=fparton/naflav/2.
return
end
c------------------------------------------------------------------------
function fzeroGlu(z,k,ipt)
c-----------------------------------------------------------------------
c
c x*f(x)
c
c f = F & EsoftGluon &=convolution
c
c F(x) = alpff(k)*x**betff(ipt)*(1-x)**alplea(k)
c
c EsoftGluon(x) = x**(-1-dels) * EsoftGluonTil(x)
c
c z - light cone x
c k - hadron class
c ipt - 1=proj 2=targ
c-----------------------------------------------------------------------
double precision xpmin,xp
include 'epos.inc'
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
fzeroGlu=0.
xpmin=z
xpmin=xpmin**(1+betff(ipt)+dels)
do i=1,7
do m=1,2
xp=(.5*(1.+xpmin+(2*m-3)*x1(i)*(1.-xpmin)))**(1./
* (1+betff(ipt)+dels))
zz=z/xp
fzeroGlu=fzeroGlu+a1(i)*(1.-xp)**alplea(k)*EsoftGluonTil(zz)
enddo
enddo
fzeroGlu=fzeroGlu*.5*(1.-xpmin)/(1+betff(ipt)+dels)
fzeroGlu=fzeroGlu *alpff(k) *z**(-dels)
end
c------------------------------------------------------------------------
function fzeroSea(z,k,ipt)
c-----------------------------------------------------------------------
c
c x*f(x)
c
c f = F & EsoftQuark &=convolution
c
c F(x) = alpff(k)*x**betff(ipt)*(1-x)**alplea(k)
c
c EsoftQuark(x) = x**(-1-dels) * EsoftQuarkTil(x)
c
c z - light cone x of the quark,
c k - hadron class
c-----------------------------------------------------------------------
double precision xpmin,xp
common /ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
fzeroSea=0.
xpmin=z
xpmin=xpmin**(1+betff(ipt)+dels)
do i=1,7
do m=1,2
xp=(.5*(1.+xpmin+(2*m-3)*x1(i)*(1.-xpmin)))**(1./
* (1+betff(ipt)+dels))
zz=z/xp
fzeroSea=fzeroSea+a1(i)*(1.-xp)**alplea(k)*EsoftQuarkTil(zz)
enddo
enddo
fzeroSea=fzeroSea*.5*(1.-xpmin)/(1+betff(ipt)+dels)
fzeroSea=fzeroSea *alpff(k) *z**(-dels)
end
c------------------------------------------------------------------------
function EsoftGluonTil(zz)
c-----------------------------------------------------------------------
c EsoftGluon = zz^(-1-dels) * EsoftGluonTil
c-----------------------------------------------------------------------
include 'epos.inc'
include 'epos.incsem'
EsoftGluonTil=gamsoft*(1-glusea)*(1.-zz)**betpom
end
c------------------------------------------------------------------------
function EsoftQuarkTil(zz)
c-----------------------------------------------------------------------
c EsoftQuark = zz^(-1-dels) * EsoftQuarkTil
c-----------------------------------------------------------------------
double precision zmin,z
common /ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
EsoftQuarkTil=0.
zmin=zz
zmin=zmin**(1.+dels)
do i=1,7
do m=1,2
z=(.5d0*(1.+zmin+(2*m-3)*x1(i)*(1.d0-zmin)))
* **(1.d0/(1.d0+dels))
EsoftQuarkTil=EsoftQuarkTil+a1(i)*max(1.d-5,(1.d0-zz/z))**betpom
* *(z**2+(1.-z)**2)
enddo
enddo
EsoftQuarkTil=EsoftQuarkTil*1.5*(1.d0-zmin)/(1.+dels)
!1.5=naflav/2 at Q0
EsoftQuarkTil=gamsoft*glusea*EsoftQuarkTil
end
c------------------------------------------------------------------------
function EsoftQZero(zz) ! former psftilf
c-----------------------------------------------------------------------
c
c EsoftQuark = EsoftQZero * wsplit * z^(-1-dels) * gamsoft
c
c zz - ratio of the quark and pomeron light cone x (zz=x_G/x_P)
c integration over quark to gluon light cone momentum ratio (z=x/x_G):
c
c EsoftQZero = int(dz) z^dels * (1-zz/z)^betpom * P_qG(z)
c
c-----------------------------------------------------------------------
double precision zmin,z
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
EsoftQZero=0.
zmin=zz
zmin=zmin**(1.+dels)
do i=1,7
do m=1,2
z=(.5d0*(1.+zmin+(2*m-3)*x1(i)*(1.d0-zmin)))
* **(1.d0/(1.d0+dels))
EsoftQZero=EsoftQZero+a1(i)*max(1.d-5,(1.d0-zz/z))**betpom
* *(z**2+(1.-z)**2)
enddo
enddo
EsoftQZero=EsoftQZero*1.5*(1.d0-zmin)/(1.+dels) !1.5=naflav/2 at Q0
return
end
c------------------------------------------------------------------------
function ffsigi(qq,y0) !former psjx1 (sto)
c------------------------------------------------------------------------
c
c dsigma/dpt_jet = \int dy \int dx1 ffsig(x1,x2(x1))
c
c x1=xplus, x2=xminus
c x2=x2(x1) due to u+t+s=0
c ( s=x1*x2*spp, t/spp=-x1*xt*exp(-y)/2, u/spp=-x2*xt*exp(y)/2 )
c
c qq = pt**2, xt=2.*sqrt(qq/s)
c rapidity range: 0 to y0
c
c ffsig = function ffsig(t,qq,x1,x2)
c
c-----------------------------------------------------------------------
include 'epos.incsem'
include 'epos.inc'
double precision xx1,xx2,xt,ymax,ymin,y,xmin,xmax
ig=3
ig1=3
s=engy**2
ffsigi=0.
if(s.le.4.*qq)return
if(qq.lt.q2min)return
xt=2d0*sqrt(dble(qq)/dble(s))
ymax=min(dble(y0),log(1d0/xt+sqrt((1d0/xt-1d0)*(1d0/xt+1d0))))
ymin=-ymax !final result must be divided by 2
do i=1,ig
do m=1,2
y=.5d0*(ymax+ymin+(ymin-ymax)*dble((2*m-3)*tgss(ig,i)))
!for xx1-integration, use variable x=xx1-xt*exp(y)/2.,with xmin<x<xmax
xmin=xt**2/2.d0/(2.d0-xt*exp(-y)) !condition x2<1
xmax=1.d0-xt*exp(y)/2.d0 !condition x1<1
fx=0.
do i1=1,ig1
do m1=1,2
xx1=xt*exp(y)/2.d0+xmin*(xmax/xmin)**dble(.5
& +tgss(ig1,i1)*(m1-1.5))
xx2=xt*exp(-y)*xx1/(2.d0*xx1-xt*exp(y))
z=sngl(xx1*xx2)
sh=z*s
aa=1.-4.*qq/sh
aa=max(1e-10,aa)
t=sh/2.*(1.-sqrt(aa)) !formula in parton-parton cms
ft=ffsig(t,qq,sngl(xx1),sngl(xx2))
fx=fx+wgss(ig1,i1)*ft/sh**2
enddo
enddo
fx=fx*0.5*sngl(log(xmax/xmin)) !dx/x=0.5*log(xmax/xmin)dt (gauss)
ffsigi=ffsigi+wgss(ig,i)*fx
enddo
enddo
ffsigi=ffsigi*0.5*sngl(ymax-ymin) !dy=0.5*(ymax-ymin)dt (gauss)
* *2*pi*(2*pi*pssalf(qq/qcdlam))**2 !alpha = 2*pi*pssalf
* *2*sqrt(qq) !d2pt=2*pi*pt*dpt
* /2 ! y interval 2 * Delta_y
* /2 ! condition t < sqrt(s)/2,
! since t > sqrt(s)/2 is automatically included,
! see psbori
return
end
c------------------------------------------------------------------------
function psbori(s,t,j,l,n)
c-----------------------------------------------------------------------
c contribution to the born cross-section:
c
c dsigmaBorn/d2pt/dy = s/pi * delta(s+t+u) * 2*pi*alpha**2 /s**2 *psbori
c
c s - c.m. energy squared for the born scattering,
c t - invariant variable for the born scattering |(p1-p3)**2|,
c j - parton type at current end of the ladder (0 - g, 1,-1,2,... - q)
c l - parton type at opposite end of the ladder (0 - g, 1,-1,2,... - q)
c n - subprocess number
c-----------------------------------------------------------------------
include 'epos.incsem'
psbori=0.
u=s-t
if(u.le.0.d0)return
if(iabs(j).ne.4)then !light quarks and gluons
if(n.eq.1)then
if(j.eq.0.and.l.eq.0)then !gg->gg
psbori=(3.-t*u/s**2+s*u/t**2+s*t/u**2)*4.5
elseif(j*l.eq.0)then !gq->gq
psbori=(s**2+u**2)/t**2+(s/u+u/s)/2.25
elseif(j.eq.l)then !qq->qq
psbori=((s**2+u**2)/t**2+(s**2+t**2)/u**2)/2.25
* -s**2/t/u/3.375
elseif(j.eq.-l)then !qq~->qq~
psbori=((s**2+u**2)/t**2+(u**2+t**2)/s**2)/2.25
* +u**2/t/s/3.375
else !qq'->qq'
psbori=(s**2+u**2)/t**2/2.25
endif
elseif(n.eq.2)then
if(j.eq.0.and.l.eq.0)then !gg->qq~
psbori=.5*(t/u+u/t)-1.125*(t*t+u*u)/s**2
elseif(j.eq.-l)then !qq~->q'q'~
psbori=(t*t+u*u)/s**2/1.125
else
psbori=0.
endif
elseif(n.eq.3)then
if(j.ne.0.and.j.eq.-l)then !qq~->gg
psbori=32./27.*(t/u+u/t)-(t*t+u*u)/s**2/.375
else
psbori=0.
endif
c............ n=4 for photon product processes, make e_q**2 =2/9.,
c the average value of charge squared for all types of quarks.
elseif(n.eq.4) then
if(j.ne.0.and.j.eq.-l)then !qq~->g+gamma
psbori=16*factgam*(u/t+t/u)/81.
elseif (j*l.eq.0.and.j+l.ne.0) then !q(q~)g->q(q~)+gamma
psbori=2*factgam*(u/s+s/u)/27.
else
psbori=0.
endif
ctp090305 temporary to avoid hard gamma which produce fragmentation problem in psahot
psbori=0. !????????????
elseif(n.eq.5) then
if(j.ne.0.and.j.eq.-l)then !qq~->gamma+gamma
psbori=4*factgam*(t/u+u/t)/81.
else
psbori=0.
endif
ctp090305 temporary to avoid hard gamma which produce fragmentation problem in psahot
psbori=0. !????????????
endif
elseif(n.eq.1)then !c-quark
if(l.eq.0)then !cg->cg
xm=qcmass**2/s/u
psbori=(s**2+u**2)/t**2+(s/u+u/s)/2.25
* -4.*qcmass**2/t+xm*(xm*t**2-t)/.5625+4.*qcmass**2*xm
else !cq->cq
psbori=(s**2+u**2)/t**2/2.25-qcmass**2/t/1.125
endif
else
psbori=0.
endif
return
end
c-----------------------------------------------------------------------
double precision function om51p(sy,xh,yp,b,iqq)
c-----------------------------------------------------------------------
c om5p - chi~(x,y)
c xh - fraction of the energy squared s for the pomeron;
c yp - rapidity for the pomeron;
c b - impact parameter between the pomeron ends;
c iqq =-1 - 0+1+2+3+4,
c iqq = 0 - soft pomeron,
c iqq = 1 - gg,
c iqq = 2 - qg,
c iqq = 3 - gq,
c iqq = 4 - qq,
c iqq = 5 - soft(int)|b,
c iqq = 6 - gg(int)|b,
c iqq = 7 - soft(proj)|b,
c iqq = 8 - gg(proj)|b,
c iqq = 9 - qg(proj)|b,
c iqq = 10 - total fro-uncut integrated,
c iqq = 11 - total uncut integrated,
c iqq = 12 - soft(int),
c iqq = 13 - gg(int),
c iqq = 14 - <b^2*soft(int)>,
c iqq = 15 - <b^2*gg(int)>,
c iqq = 16 - soft(proj-int),
c iqq = 17 - gg(proj-int),
c iqq = 18 - qg(proj-int),
c iqq = 19 - <b^2*soft(proj)>,
c iqq = 20 - <b^2*gg(proj)>,
c iqq = 21 - <b^2*qg(proj)>
c-----------------------------------------------------------------------
double precision xh,yp!,coefom1,coefom2
common /psar7/ delx,alam3p,gam3p
common /psar37/ coefom1,coefom2
include 'epos.inc'
include 'epos.incsem'
xp=dsqrt(xh)*exp(yp)
if(xh.ne.0.d0)then
xm=xh/xp
else
xm=0.
endif
rp=r2had(iclpro)+r2had(icltar)+slopom*log(max(1.,sy))
zb=exp(-b**2/(4.*.0389*rp))
rh=r2had(iclpro)+r2had(icltar)
if(iqq.eq.0)then !soft
c rp=r2hads(iclpro)+r2hads(icltar)+slopoms*log(max(1.,sy))
zb=exp(-b**2/(4.*.0389*rp))
om51p=chad(iclpro)*chad(icltar)*gamhads(iclpro)
* *gamhads(icltar)*sy**dels*(xp*xm)**(-alppar)*zb/rp
elseif(iqq.le.4)then !gg,qg,gq,qq
om51p=psvin(sy,xp,xm,zb,iqq)
elseif(iqq.eq.5)then !soft(int)|b
c rh=alam3p+slopoms*log(max(1.,sy))
om51p=sy**dels*zb**(rp/rh)/rh
elseif(iqq.eq.6)then !gg(int)|b
om51p=psvin(sy,xp,xm,zb,14)
elseif(iqq.eq.7)then !soft(proj)b
c rh=r2hads(iclpro)+.5*alam3p+slopoms*log(max(1.,sy))
om51p=chad(iclpro)*gamhads(iclpro)*sy**dels
* *xp**(-alppar)*zb**(rp/rh)/rh
elseif(iqq.eq.8)then !gg(proj)b
om51p=psvin(sy,xp,xm,zb,16)
elseif(iqq.eq.9)then !qg(proj)b
om51p=psvin(sy,xp,xm,zb,18)
elseif(iqq.eq.10)then !total fro-uncut integrated
om51p=0.d0
return
elseif(iqq.eq.11)then !total uncut integrated
om51p=psvin(sy,xp,xm,zb,9)
c om51p=om51p+dble(coefom1)/2.d0*om51p**2+dble(coefom2)/6.d0*om51p**3 !!!!!!!!!!
c if(om51p.gt.100.d0)om51p=100.d0
elseif(iqq.eq.12)then !soft(int)
om51p=sy**dels*4.*.0389
elseif(iqq.eq.13)then !gg(int)
om51p=psvin(sy,xp,xm,zb,5)
elseif(iqq.eq.14)then !<b^2*soft(int)>
c rh=alam3p+slopoms*log(max(1.,sy))
om51p=sy**dels*rh*(4.*.0389)**2
elseif(iqq.eq.15)then !<b^2*gg(int)>
om51p=psvin(sy,xp,xm,zb,15)
elseif(iqq.eq.16)then !soft(proj-int)
om51p=chad(iclpro)*gamhads(iclpro)*sy**dels
* *xp**(-alppar)*4.*.0389
elseif(iqq.eq.17)then !gg(proj-int)
om51p=psvin(sy,xp,xm,zb,6)
elseif(iqq.eq.18)then !qg(proj-int)
om51p=psvin(sy,xp,xm,zb,7)
elseif(iqq.eq.19)then !<b^2*soft(proj)>
c rh=r2hads(iclpro)+.5*alam3p+slopoms*log(max(1.,sy))
om51p=chad(iclpro)*gamhads(iclpro)*sy**dels
* *xp**(-alppar)*rh*(4.*.0389)**2
elseif(iqq.eq.20)then !<b^2*gg(proj)>
om51p=psvin(sy,xp,xm,zb,17)
elseif(iqq.eq.21)then !<b^2*qg(proj)>
om51p=psvin(sy,xp,xm,zb,19)
else
om51p=0.
call utstop("Unknown iqq in om51p !&")
endif
return
end
cc-----------------------------------------------------------------------
c double precision function om2p(xh,yp,xprem0,xmrem0,b,iqq)
cc-----------------------------------------------------------------------
cc om2p - chi~(x,y) for cut pomeron
cc xh - fraction of the energy squared s for the pomeron;
cc yp - rapidity for the pomeron;
cc xprem - x+ for the projectile remnant;
cc xmrem - x- for the target remnant;
cc b - impact parameter between the pomeron ends;
cc iqq = 0 - total,
cc iqq = 1 - 1-cut,
cc iqq = 2 - Y+,
cc iqq = -2 - Y-,
cc iqq = 3 - 1-cut(soft),
cc iqq = 4 - 1+(gg),
cc iqq = 5 - 1+(qg),
cc iqq = 6 - 1+(gq),
cc iqq = 7 - 1+(difr)
cc iqq = -7 - 1-(difr)
cc-----------------------------------------------------------------------
c double precision xh,yp,xprem0,xmrem0
c include 'epos.inc'
c include 'epos.incsem'
c
c om2p=0.d0
c sy=xh*engy**2
c xprem=sngl(xprem0)
c xmrem=sngl(xmrem0)
c xp=dsqrt(xh)*dexp(yp)
c if(xh.ne.0.d0)then
c xm=xh/xp
c else
c xm=0.
c endif
c rp=r2had(iclpro)+r2had(icltar)+slopom*log(max(1.,sy))
c zb=exp(-b**2/(4.*.0389*rp))
c
c if(iqq.eq.0)then
c om2p=psvy(xp,xprem,xm,xmrem,b,2)
c * +psvy(xp,xprem,xm,xmrem,b,-2)
c * +psvy(xp,xprem,xm,xmrem,b,3)
c * +psvy(xp,xprem,xm,xmrem,b,-3)
c * +psvy(xp,xprem,xm,xmrem,b,9)
c * +psvy(xp,xprem,xm,xmrem,b,-9)
c * +psvx(xp,xprem,xm,xmrem,b,1)
c * +psvx(xp,xprem,xm,xmrem,b,2)
c * +psvx(xp,xprem,xm,xmrem,b,-2)
c * +psvx(xp,xprem,xm,xmrem,b,6)
c * +psvx(xp,xprem,xm,xmrem,b,-6)
c om2p=om2p+(chad(iclpro)*chad(icltar)*gamhad(iclpro)
c * *gamhad(icltar)*sy**dels*(xp*xm)**(-alppar)*zb/rp
c * +psvin(sy,xp,xm,zb,1)+psvin(sy,xp,xm,zb,2)
c * +psvin(sy,xp,xm,zb,3)+psvin(sy,xp,xm,zb,4))
c elseif(iqq.eq.1)then
c om2p=psvy(xp,xprem,xm,xmrem,b,2)+psvy(xp,xprem,xm,xmrem,b,-2)
c * +psvx(xp,xprem,xm,xmrem,b,1)
c elseif(iqq.eq.2)then
c om2p=psvy(xp,xprem,xm,xmrem,b,3)
c * +psvx(xp,xprem,xm,xmrem,b,2)
c elseif(iqq.eq.-2)then
c om2p=psvy(xp,xprem,xm,xmrem,b,-3)
c * +psvx(xp,xprem,xm,xmrem,b,-2)
c elseif(iqq.eq.3)then
c om2p=psvy(xp,xprem,xm,xmrem,b,4)+psvy(xp,xprem,xm,xmrem,b,-4)
c * +psvx(xp,xprem,xm,xmrem,b,3)
c elseif(iqq.eq.4)then
c om2p=psvy(xp,xprem,xm,xmrem,b,5)+psvy(xp,xprem,xm,xmrem,b,7)
c * +psvy(xp,xprem,xm,xmrem,b,-5)+psvy(xp,xprem,xm,xmrem,b,-7)
c * +psvx(xp,xprem,xm,xmrem,b,4)+psvx(xp,xprem,xm,xmrem,b,-4)
c elseif(iqq.eq.5)then
c om2p=psvy(xp,xprem,xm,xmrem,b,6)+psvy(xp,xprem,xm,xmrem,b,-8)
c * +psvx(xp,xprem,xm,xmrem,b,5)
c elseif(iqq.eq.6)then
c om2p=psvy(xp,xprem,xm,xmrem,b,-6)+psvy(xp,xprem,xm,xmrem,b,8)
c * +psvx(xp,xprem,xm,xmrem,b,-5)
c elseif(iqq.eq.7)then
c om2p=psvy(xp,xprem,xm,xmrem,b,9)
c * +psvx(xp,xprem,xm,xmrem,b,6)
c elseif(iqq.eq.-7)then
c om2p=psvy(xp,xprem,xm,xmrem,b,-9)
c * +psvx(xp,xprem,xm,xmrem,b,-6)
c else
c stop'om2p-wrong iqq!!!'
c endif
c return
c end
c
cc-----------------------------------------------------------------------
c double precision function om3p(xh,yp,xleg,xprem,xmrem,xlrem
c *,b1,b2,b12,iqq)
cc-----------------------------------------------------------------------
cc om3p - chi~(x,y) for cut pomeron (nuclear effects)
cc xh - fraction of the energy squared s for the pomeron;
cc yp - rapidity for the pomeron;
cc xleg - x for the pomeron leg;
cc xprem - x+ for the projectile remnant;
cc xmrem - x- for the target remnant;
cc xlrem - x for the leg remnant;
cc b1 - impact parameter between the pomeron ends;
cc b2 - impact parameter for the second pomeron end;
cc iqq = 1 - uncut+,
cc iqq = 2 - cut+,
cc iqq = 3 - scr+,
cc iqq = 4 - diffr+,
cc iqq = 5 - uncut-,
cc iqq = 6 - cut-,
cc iqq = 7 - scr-,
cc iqq = 8 - diff-
cc iqq = 9 - uncut-h+,
cc iqq = 10 - uncut-h-,
cc iqq = 11 - uncut-YY+,
cc iqq = 12 - uncut-YY-,
cc-----------------------------------------------------------------------
c double precision xh,yp,xleg,xprem,xmrem,xlrem
c
c om3p=0.d0
c return !!!!!!!!!!!!!!!
cc if(iqq.ne.1.and.iqq.ne.5.and.iqq.ne.9.and.iqq.ne.10
cc *.and.iqq.ne.11.and.iqq.ne.12)return
c
cc$$$ xp=dsqrt(xh)*exp(yp)
cc$$$ if(xh.ne.0.d0)then
cc$$$ xm=xh/xp
cc$$$ else
cc$$$ xm=0.d0
cc$$$ endif
cc$$$
cc$$$ return
c end
c
cc-----------------------------------------------------------------------
c double precision function om4p(xx1,xx2,xx3,xx4
c *,b12,b13,b14,b23,b24,b34,iqq)
cc-----------------------------------------------------------------------
cc om4p - chi for 2-leg contributions
cc xx_i - x+- for pomeron ends;
cc b_ij - impact parameter diff. between pomeron ends;
cc iqq = 1 - uncut-H,
cc iqq = 2 - uncut-YY+,
cc iqq = 3 - uncut-YY-
cc-----------------------------------------------------------------------
c double precision xx1,xx2xx3,xx4
c om4p=0.d0
c return
c end
c
cc------------------------------------------------------------------------
c function omi5pp(sy,xpp,xpm,z,iqq) !former psfsh1
cc-----------------------------------------------------------------------
cc omi5pp - integrated semihard interaction eikonal
cc sy - energy squared for the hard interaction,
cc z - impact parameter factor, z=exp(-b**2/rp),
cc iqq - type of the hard interaction:
cc 0 - soft, 1 - gg, 2 - qg, 3 - gq
cc-----------------------------------------------------------------------
c common /ar3/ x1(7),a1(7)
c common /ar9/ x9(3),a9(3)
c include 'epos.inc'
c include 'epos.incsem'
c fsy(zsy)=zsy**dels !*(1.-1./zsy)**betpom
c
c omi5pp=0.
c if(iclpro.eq.4.and.iqq.eq.2.or.icltar.eq.4.and.iqq.eq.3)then
c spmin=4.*q2min+2.*qcmass**2
c elseif(iqq.ne.0)then
c spmin=4.*q2min
c else
c spmin=0.
c endif
c if(sy.le.spmin)return
c
c rp=r2had(iclpro)+r2had(icltar)+slopom*log(max(1.,sy))
c alpq=(alppar+1.)/2.
c if(iqq.eq.3)then
c iclt=iclpro
c iclp=icltar
c else
c iclp=iclpro
c iclt=icltar
c endif
c
c if(iqq.eq.0)then
c xpmax=(1.-spmin/sy)**(1.+alplea(iclp))
c do i=1,3
c do m=1,2
c xp=1.-(xpmax*(.5+x9(i)*(m-1.5)))**(1./(1.+alplea(iclp)))
c xmmax=(1.-spmin/sy/xp)**(1.+alplea(iclt))
c do i1=1,3
c do m1=1,2
c xm=1.-(xmmax*(.5+x9(i1)*(m1-1.5)))**(1./(1.+alplea(iclt)))
c
c sy1=sy*xp*xm
c rh=r2had(iclpro)+r2had(icltar)+slopom*log(max(1.,sy1))
c omi5pp=omi5pp+a9(i)*a9(i1)*fsy(sy1)*xmmax*z**(rp/rh)/rh
c * *(xp*xm)**(-alppar)
c enddo
c enddo
c enddo
c enddo
c omi5pp=omi5pp*xpmax/(1.+alplea(iclp))/(1.+alplea(iclt))
c * *chad(iclpro)*chad(icltar)*gamhad(iclpro)*gamhad(icltar)
c * *(xpp*xpm)**(1.-alppar)/4.
c return
c else
c
c xmin=(spmin/sy)**(delh-dels)
c do i=1,3
c do m=1,2
c zh=(.5*(1.+xmin-(2*m-3)*x9(i)*(1.-xmin)))**(1./(delh-dels))
c if(iclpro.eq.4.and.iqq.eq.2.or.icltar.eq.4.and.iqq.eq.3)then
c call psjti0(zh*sy,sgq,sgqb,4,0)
c call psjti0(zh*sy,sqq,sqqb,4,1)
c else
c call psjti0(zh*sy,sgg,sggb,0,0)
c call psjti0(zh*sy,sgq,sgqb,0,1)
c call psjti0(zh*sy,sqq,sqqb,1,1)
c call psjti0(zh*sy,sqaq,sqaqb,-1,1)
c call psjti0(zh*sy,sqqp,sqqpb,1,2)
c sqq=(sqq+sqaq+2.*(naflav-1)*sqqp)/naflav/2.
c endif
c
c if(iqq.eq.1)then
c stg=0.
c do i1=1,3
c do m1=1,2
c xx=.5+x9(i1)*(m1-1.5)
c xp=zh**xx
c xm=zh/xp
c
c xp1max=(1.-xp)**(1.+alplea(iclp))
c xm1max=(1.-xm)**(1.+alplea(iclt))
c do i2=1,3
c do m2=1,2
c xp1=1.-(xp1max*(.5+x9(i2)*(m2-1.5)))
c * **(1./(1.+alplea(iclp)))
c do i3=1,3
c do m3=1,2
c xm1=1.-(xm1max*(.5+x9(i3)*(m3-1.5)))
c * **(1./(1.+alplea(iclt)))
c if(xp1.lt.xp.or.xm1.lt.xm)write (*,*)'xp1,xm1,xp,xm'
c * ,xp1,xm1,xp,xm
c
c rh=r2had(iclpro)+r2had(icltar)+slopom
c * *log(xp1*xm1/xp/xm)
c glu1=(1.-xp/xp1)**betpom*(1.-glusea)
c sea1=EsoftQZero(xp/xp1)*glusea
c glu2=(1.-xm/xm1)**betpom*(1.-glusea)
c sea2=EsoftQZero(xm/xm1)*glusea
c stg=stg+a9(i1)*a9(i2)*a9(i3)*(glu1*glu2*sgg
c * +(glu1*sea2+sea1*glu2)*sgq+sea1*sea2*sqq)
c * *xp1max*xm1max*(xp1*xm1)**(dels-alppar)
c * *z**(rp/rh)/rh
c enddo
c enddo
c enddo
c enddo
c enddo
c enddo
c omi5pp=omi5pp-a9(i)*log(zh)*stg/zh**delh
c
c else
c stq=0.
c xpmin=zh**(dels+.5)
c do i1=1,3
c do m1=1,2
c xp=(.5*(1.+xpmin-(2*m1-3)*x9(i1)*(1.-xpmin)))
c * **(1./(dels+.5))
c xm=zh/xp
c if(xp*xpp.lt..99999)then
c uv1=psdfh4(xp*xpp,q2min,0.,iclp,1)
c dv1=psdfh4(xp*xpp,q2min,0.,iclp,2)
c xm1max=(1.-xm)**(1.+alplea(iclt))
c do i2=1,3
c do m2=1,2
c xm1=1.-(xm1max*(.5+x9(i2)*(m2-1.5)))
c * **(1./(1.+alplea(iclt)))
c
c rh=r2had(iclpro)+r2had(icltar)+slopom*log(xm1/xm)
c glu2=(1.-xm/xm1)**betpom*(1.-glusea)
c sea2=EsoftQZero(xm/xm1)*glusea
c stq=stq+a9(i1)*a9(i2)*(glu2*sgq+sea2*sqq)*(uv1+dv1)
c * *z**(rp/rh)/rh*xm1max*xm1**(dels-alppar)/sqrt(xp)
c * *((1.-xp)/(1.-xp*xpp))**(1.-alpq+alplea(iclp))
c enddo
c enddo
c endif
c enddo
c enddo
c stq=stq*(1.-xpmin)
c omi5pp=omi5pp+a9(i)*stq/zh**delh
c endif
c enddo
c enddo
c endif
c
c omi5pp=omi5pp*(1.-xmin)/(delh-dels)
c if(iqq.eq.1)then
c omi5pp=omi5pp*chad(iclp)*chad(iclt)*gamhad(iclp)
c * *gamhad(iclt)*ffrr**2*(xpp*xpm)**(1.-alppar)
c * /(1.+alplea(iclp))/(1.+alplea(iclt))*pi/8.*factk
c else
c omi5pp=omi5pp*chad(iclp)*chad(iclt)*ffrr*gamhad(iclt)
c * *xpp**(1.-alpq)*xpm**(1.-alppar)/(.5+dels)
c * /(1.+alplea(iclt))/16.*factk
c endif
c return
c end
c
c------------------------------------------------------------------------
function om52pi(sy,xpp,xpm,iqq,je1,je2) !modified om51pp
c-----------------------------------------------------------------------
c sy - energy squared for the hard interaction
c
c iqq = 0 - sea-sea,
c iqq = 1 - val-sea,
c iqq = 2 - sea-val,
c iqq = 3 - val-val,
c
c je = emission type
c 0 ... no emissions
c 1 ... emissions
c else ... all
c
c already b-averaged (\int d2b /sigine*10)
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
common /psar7/ delx,alam3p,gam3p
include 'epos.inc'
include 'epos.incsem'
if(iqq.lt.0.or.iqq.gt.3)stop'om52pi: unvalid iqq'
om52pi=0.
ef1=0
ef2=0
ef3=0
ef4=0
if( je1.ge.1 .and. je2.ge.1) ef1=1
if( je1.ge.1 .and.(je2.eq.0.or.je2.eq.2))ef2=1
if((je1.eq.0.or.je1.eq.2).and. je2.ge.1) ef3=1
if((je1.eq.0.or.je1.eq.2).and.(je2.eq.0.or.je2.eq.2))ef4=1
spmin=4.*q2min
if(sy.le.spmin)goto999
if(iqq.eq.1)then
iclv=iclpro
ctp060829 icls=icltar
elseif(iqq.eq.2)then
ctp060829 icls=iclpro
iclv=icltar
endif
delss=dels
if(iqq.eq.3)delss=-0.5
xmin=spmin/sy
xmin=xmin**(delh-delss)
alpq=(alppar+1.)/2.
c numerical integration over zh
do i=1,7
do m=1,2
zh=(.5*(1.+xmin-(2*m-3)*x1(i)*(1.-xmin)))**(1./(delh-delss))
sgg= ef1 *pijet(2,q2min,q2min,zh*sy,0,0)
* + (ef2+ef3)*pijet(1,q2min,q2min,zh*sy,0,0)
* + ef4 *pijet(0,q2min,q2min,zh*sy,0,0)
sgq= ef1 *pijet(2,q2min,q2min,zh*sy,0,1)
* + (ef2+ef3)*pijet(1,q2min,q2min,zh*sy,0,1)
* + ef4 *pijet(0,q2min,q2min,zh*sy,0,1)
sqq= ef1 *pijet(2,q2min,q2min,zh*sy,1,1)
* + (ef2+ef3)*pijet(1,q2min,q2min,zh*sy,1,1)
* + ef4 *pijet(0,q2min,q2min,zh*sy,1,1)
sqaq= ef1 *pijet(2,q2min,q2min,zh*sy,-1,1)
* + (ef2+ef3)*pijet(1,q2min,q2min,zh*sy,-1,1)
* + ef4 *pijet(0,q2min,q2min,zh*sy,-1,1)
sqqp= ef1 *pijet(2,q2min,q2min,zh*sy,1,2)
* + (ef2+ef3)*pijet(1,q2min,q2min,zh*sy,1,2)
* + ef4 *pijet(0,q2min,q2min,zh*sy,1,2)
sqqi=sqq
sqq=(sqq+sqaq+2.*(naflav-1)*sqqp)/naflav/2.
if(iqq.eq.0)then
stg=0.
do i1=1,7
do m1=1,2
xx=.5+x1(i1)*(m1-1.5)
xp=zh**xx
xm=zh/xp
glu1=EsoftGluonTil(xp)
sea1=EsoftQuarkTil(xp)
glu2=EsoftGluonTil(xm)
sea2=EsoftQuarkTil(xm)
dstg= glu1*glu2*sgg
* +(glu1*sea2+sea1*glu2)*sgq !ccccc
* +sea1*sea2*sqq !ccccc
stg=stg+a1(i1)*dstg
enddo
enddo
om52pi=om52pi-a1(i)*log(zh)*stg/zh**delh
elseif(iqq.eq.3)then
stq=0. !int^1_(sqrt(z)) dx_p / x_p / sqrt(1-x_p) =int^(tmax)_(0) dt
tmax=sqrt(1.-sqrt(zh)) !t=ln((1+sqrt(1-x_p))/(1-sqrt(1-x_p)))
tmax=log((1.+tmax)/(1.-tmax))
if(tmax.gt.1.e-20)then
do i1=1,7
do m1=1,2
t=tmax*(.5+x1(i1)*(m1-1.5))
z01=((1.d0-exp(-1.d0*t))/(1.d0+exp(-1.d0*t)))**2
xp=1.-z01
xm=zh/xp
if(xp*xpp.le..9999.and.xm*xpm.le..9999
* .or.xm*xpp.le..9999.and.xp*xpm.le..9999)then
stq=stq+a1(i1)
* *(psharg(xp*xpp,xm*xpm,sqqi,sqqp,sqaq)
* +psharg(xm*xpp,xp*xpm,sqqi,sqqp,sqaq))
* *max(1e-20,1.-xp)**(.5-alpq)
* *max(1e-20,1.-xm)**(-alpq)
* *xp**delss*xm**delss
* *xpp**alppar/gamhad(iclpro) ! Eval
* *xpm**alppar/gamhad(icltar) ! Eval
endif
enddo
enddo
stq=stq*tmax
endif
om52pi=om52pi+a1(i)*stq/zh**delh
elseif(iqq.eq.1.or.iqq.eq.2)then
stq=0.
tmax=acos(sqrt(zh))
do i1=1,7
do m1=1,2
t=tmax*(.5+x1(i1)*(m1-1.5))
xp=cos(t)**2
xm=zh/xp
if(xp*xpp.lt..99999)then
uv1=psdfh4(xp*xpp,q2min,0.,iclv,1) ! Eval
dv1=psdfh4(xp*xpp,q2min,0.,iclv,2) ! Eval
glu2=EsoftGluonTil(xm)
sea2=EsoftQuarkTil(xm)
dstq=0
if(xp.ne.1.)
* dstq=(glu2*sgq+sea2*sqq)*(uv1+dv1)
* *(1.-xp*xpp)**(-1.+alpq-alplea(iclv)) ! Eval
* *xp**(delss-.5)*(1.-xp)**(-alpq+.5) ! Eval *sqrt(1-x)/sqrt(x)
* *xpp**alppar/gamhad(iclv) ! Eval
stq=stq+a1(i1)*dstq
endif
enddo
enddo
stq=stq*tmax
om52pi=om52pi+a1(i)*stq/zh**delh
else
stop'om52pi: unvalid iqq (2). '
endif
enddo
enddo
om52pi=om52pi*(1.-xmin)/(delh-delss)
if(iqq.eq.0)then
om52pi=om52pi/4
elseif(iqq.eq.3)then
om52pi=om52pi/4
* * utgam1(2.+alplea(iclpro)-alpq) ! Eval
* /utgam1(1.+alplea(iclpro))/utgam1(1.-alpq) ! Eval
* * utgam1(2.+alplea(icltar)-alpq) ! Eval
* /utgam1(1.+alplea(icltar))/utgam1(1.-alpq) ! Eval
* /xpp**alpq/xpm**alpq ! Eval
elseif(iqq.le.2)then
om52pi=om52pi/2
* *utgam1(2.+alplea(iclv)-alpq)/utgam1(1.+alplea(iclv)) ! Eval
* /utgam1(1.-alpq) ! Eval
* /xpp**alpq ! Eval
endif
999 continue
om52pi=om52pi*factk * .0390 /sigine*10 /2.
end
c------------------------------------------------------------------------
function psharg(zh1,zh2,sqq,sqqp,sqaq)
c-----------------------------------------------------------------------
include 'epos.incsem'
include 'epos.inc'
alpq=(alppar+1.)/2.
if(zh1.le..9999.and.zh2.le..9999)then
uv1=psdfh4(zh1,q2min,0.,iclpro,1)
dv1=psdfh4(zh1,q2min,0.,iclpro,2)
uv2=psdfh4(zh2,q2min,0.,icltar,1)
dv2=psdfh4(zh2,q2min,0.,icltar,2)
if(iclpro.eq.2.and.icltar.eq.2)then !proton
fff=sqq*(uv1*uv2+dv1*dv2)+sqqp*(uv1*dv2+dv1*uv2)
elseif(iclpro.eq.1.or.icltar.eq.1)then !pion
fff=sqq*uv1*uv2+sqaq*dv1*dv2+sqqp*(uv1*dv2+dv1*uv2)
elseif(iclpro.eq.3.or.icltar.eq.3)then !kaon
fff=sqq*uv1*uv2+sqqp*(uv1*dv2+dv1*uv2+dv1*dv2)
elseif(iclpro.eq.4.or.icltar.eq.4)then !J/psi
fff=sqq*uv1*(uv2+dv2)
else
fff=0.
call utstop("Projectile not know in psharg !&")
endif
psharg=fff
* *(1.-zh1)**(-1.+alpq-alplea(iclpro))
* *(1.-zh2)**(-1.+alpq-alplea(icltar))
else
psharg=0.
endif
return
end
c------------------------------------------------------------------------
function om51pp(sy,xpp,z,iqq) !former psfsh
c-----------------------------------------------------------------------
c om51pp - semihard interaction eikonal
c sy - energy squared for the hard interaction,
c z - impact parameter factor, z=exp(-b**2/rp),
c iqq - type of the hard interaction:
c 0 - gg, 1 - qg, 2 - gq, 3 - gg(int), 4 - gg(proj), 5 - qg(proj),
c 6 - gg(int)|b=0, 7 - <b^2*gg(int)>, 8 - gg(proj)|b=0,
c 9 - <b^2*gg(proj)>, 10 - qg(proj)|b=0, 11 - <b^2*qg(proj)>
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
common /psar7/ delx,alam3p,gam3p
include 'epos.inc'
include 'epos.incsem'
om51pp=0.
if(iqq.eq.0.or.iqq.eq.3.or.iqq.eq.4
*.or.iqq.eq.6.or.iqq.eq.7.or.iqq.eq.8.or.iqq.eq.9
*.or.iclpro.ne.4.and.(iqq.eq.1.or.iqq.eq.5
*.or.iqq.eq.10.or.iqq.eq.11)
*.or.icltar.ne.4.and.iqq.eq.2)then
spmin=4.*q2min
else
spmin=4.*q2min+2.*qcmass**2
endif
if(sy.le.spmin)goto999
icls=iclpro
if(iqq.eq.1.or.iqq.eq.5.or.iqq.eq.10.or.iqq.eq.11)then
iclv=iclpro
icls=icltar
elseif(iqq.eq.2)then
icls=iclpro
iclv=icltar
endif
xmin=spmin/sy
xmin=xmin**(delh-dels)
rp=r2had(iclpro)+r2had(icltar)+slopom*log(max(1.,sy))
alpq=(alppar+1.)/2.
c numerical integration over zh
do i=1,7
do m=1,2
zh=(.5*(1.+xmin-(2*m-3)*x1(i)*(1.-xmin)))**(1./
* (delh-dels))
if(iqq.eq.0.or.iqq.eq.3.or.iqq.eq.4
* .or.iqq.eq.6.or.iqq.eq.7.or.iqq.eq.8.or.iqq.eq.9
* .or.iclpro.ne.4.and.(iqq.eq.1.or.iqq.eq.5
* .or.iqq.eq.10.or.iqq.eq.11)
* .or.icltar.ne.4.and.iqq.eq.2)then
call psjti0(zh*sy,sgg,sggb,0,0) !inclusive (sj) and born (sjb)
call psjti0(zh*sy,sgq,sgqb,0,1)
call psjti0(zh*sy,sqq,sqqb,1,1)
call psjti0(zh*sy,sqaq,sqaqb,-1,1)
call psjti0(zh*sy,sqqp,sqqpb,1,2)
sqq=(sqq+sqaq+2.*(naflav-1)*sqqp)/naflav/2.
c...........test.......
c tgg= psjet(q2min,q2min,q2min,zh*sy,0,0,0)
c * +2*psjet1(q2min,q2min,q2min,zh*sy,0,0,0)
c * + psborn(q2min,q2min,q2min,zh*sy,0,0,0,1)
c tgq= psjet(q2min,q2min,q2min,zh*sy,0,1,0)
c * +2*psjet1(q2min,q2min,q2min,zh*sy,0,1,0)
c * + psborn(q2min,q2min,q2min,zh*sy,0,1,0,1)
c tqq= psjet(q2min,q2min,q2min,zh*sy,1,1,0)
c * +2*psjet1(q2min,q2min,q2min,zh*sy,1,1,0)
c * + psborn(q2min,q2min,q2min,zh*sy,1,1,0,1)
c tqa= psjet(q2min,q2min,q2min,zh*sy,-1,1,0)
c * +2*psjet1(q2min,q2min,q2min,zh*sy,-1,1,0)
c * + psborn(q2min,q2min,q2min,zh*sy,-1,1,0,1)
c tqqp= psjet(q2min,q2min,q2min,zh*sy,1,2,0)
c * +2*psjet1(q2min,q2min,q2min,zh*sy,1,2,0)
c * + psborn(q2min,q2min,q2min,zh*sy,1,2,0,1)
c write(6,'(f12.2,3x,2f7.3,2(3x,2f7.3))')
c * zh*sy,tgg,sgg, tgq,sgq, tqqp,sqqp
c.......................
else
call psjti0(zh*sy,sgq,sgqb,4,0)
call psjti0(zh*sy,sqq,sqqb,4,1)
endif
if(iqq.eq.0.or.iqq.eq.3.or.iqq.eq.4
* .or.iqq.eq.6.or.iqq.eq.7.or.iqq.eq.8.or.iqq.eq.9)then
stg=0.
do i1=1,7
do m1=1,2
xx=.5+x1(i1)*(m1-1.5)
xp=zh**xx
xm=zh/xp
glu1=(1.-xp)**betpom*(1.-glusea)
sea1=EsoftQZero(xp)*glusea
glu2=(1.-xm)**betpom*(1.-glusea)
sea2=EsoftQZero(xm)*glusea
rh=0.
if(iqq.eq.0)then
rh=r2had(iclpro)+r2had(icltar)-slopom*log(zh)
elseif(iqq.eq.3.or.iqq.eq.4)then
rh=1.
elseif(iqq.eq.6.or.iqq.eq.7)then
rh=alam3p-slopom*log(zh)
elseif(iqq.eq.8.or.iqq.eq.9)then
rh=r2had(iclpro)+.5*alam3p-slopom*log(zh)
endif
dstg=(glu1*glu2*sgg+
* (glu1*sea2+sea1*glu2)*sgq+sea1*sea2*sqq)
* *z**(rp/rh)/rh
if(iqq.eq.7.or.iqq.eq.9)dstg=dstg*rh**2
stg=stg+a1(i1)*dstg
enddo
enddo
om51pp=om51pp-a1(i)*log(zh)*stg/zh**delh
else
stq=0.
tmax=acos(sqrt(zh))
do i1=1,7
do m1=1,2
t=tmax*(.5+x1(i1)*(m1-1.5))
xp=cos(t)**2
xm=zh/xp
if(xp*xpp.lt..99999)then
uv1=psdfh4(xp*xpp,q2min,0.,iclv,1)
dv1=psdfh4(xp*xpp,q2min,0.,iclv,2)
glu2=(1.-xm)**betpom*(1.-glusea)
sea2=EsoftQZero(xm)*glusea
rh=0.
if(iqq.le.2)then
rh=r2had(iclpro)+r2had(icltar)-slopom*log(xm)
elseif(iqq.eq.5)then
rh=1.
elseif(iqq.le.10.or.iqq.le.11)then
rh=r2had(iclpro)+.5*alam3p-slopom*log(xm)
endif
dstq=0
if(xp.ne.1.)
* dstq=(glu2*sgq+sea2*sqq)*(uv1+dv1)
* *z**(rp/rh)/rh
* *(1.-xp*xpp)**(-1.+alpq-alplea(iclv))
* *xp**(dels-.5)*(1.-xp)**(-alpq+.5)
if(iqq.eq.11)dstq=dstq*rh**2
stq=stq+a1(i1)*dstq
endif
enddo
enddo
stq=stq*tmax
om51pp=om51pp+a1(i)*stq/zh**delh
endif
enddo
enddo
om51pp=om51pp*(1.-xmin)/(delh-dels)/sy**delh/2.
if(iqq.eq.0)then
om51pp=om51pp*chad(iclpro)*chad(icltar)*gamhad(iclpro)
* *gamhad(icltar)*ffrr**2*pi
elseif(iqq.eq.3)then
om51pp=om51pp*ffrr**2*pi*4.*.0389
elseif(iqq.eq.6)then
om51pp=om51pp*ffrr**2*pi
elseif(iqq.eq.7)then
om51pp=om51pp*ffrr**2*pi*(4.*.0389)**2
elseif(iqq.eq.4.or.iqq.eq.8.or.iqq.eq.9)then
om51pp=om51pp*ffrr**2*pi*chad(iclpro)*gamhad(iclpro)
if(iqq.eq.4)om51pp=om51pp*4.*.0389
if(iqq.eq.9)om51pp=om51pp*(4.*.0389)**2
elseif(iqq.le.2)then
om51pp=om51pp*chad(iclpro)*chad(icltar)*ffrr*gamhad(icls)
* *utgam1(2.+alplea(iclv)-alpq)/utgam1(1.+alplea(iclv))
* /utgam1(1.-alpq)/2./xpp**alpq
elseif(iqq.eq.5.or.iqq.eq.10.or.iqq.eq.11)then
om51pp=om51pp*chad(iclv)*ffrr
* *utgam1(2.+alplea(iclv)-alpq)/utgam1(1.+alplea(iclv))
* /utgam1(1.-alpq)/2./xpp**alpq
if(iqq.eq.5)om51pp=om51pp*4.*.0389
if(iqq.eq.11)om51pp=om51pp*(4.*.0389)**2
endif
999 continue
end
c-------------------------------------------------------------------------------
subroutine epocrossc(niter,gtot,gprod,gabs,gcoh,gqel,gdd)
c-------------------------------------------------------------------------------
c epocrossc - nucleus-nucleus (nucleus-hydrogen) interaction cross sections
c by calculation will real nuclear profiles and eikonal (simplified simulations)
c gtot - total cross section
c gprod - production cross section (all diffraction included)
c gabs - cut Pomerons cross section (no diffraction at all)
c gdd - proj (ionudi=2) or proj or targ (ionudi=0/3) excited diffraction
c cross section
c gcoh - coherent (elastic with respect to the projectile) cross section
c (non excited diff proj if ionudi=2, non excited proj+targ if ionudi=0/3)
c
c Be careful : this function is not symmetric for gdd and gqel (only projectile
c diffraction) in case of ionudi=2.
c (target diffraction is not treated explicitely and contributes to
c gprod, gdd, gcoh and gtot).
c
c WARNING : results are sure only in case of ionudi=1 (no substraction from
c diffractive part) in particular for AA with A > 10 (nuclear diff
c not well described). For pA seems to be OK with ionudi 2 and 3.
c
c code from QGSJET programs by S.Ostapchenko
c-------------------------------------------------------------------------------
include 'epos.inc'
include 'epos.incems'
common /cncl/xproj(mamx),yproj(mamx),zproj(mamx)
* ,xtarg(mamx),ytarg(mamx),ztarg(mamx)
common/geom/rmproj,rmtarg,bmax,bkmx
dimension wabs(28),wdd(28),wcoh(28),wprod(28),wqel(28)
& ,b0(28),ai(28)
common /ar3/ x1(7),a1(7)
double precision xgabs,xgdd,xgprod,xgcoh,xgqel
call utpri('epocrs',ish,ishini,2)
if(ish.ge.2)write(ifch,201)niter,bmax
kollini=koll !koll modified
do i=1,7
b0(15-i)=bmax*sqrt((1.+x1(i))/2.)
b0(i)=bmax*sqrt((1.-x1(i))/2.)
ai(i)=a1(i)*bmax**2*pi*5.05 !factor change cs
ai(15-i)=ai(i)
enddo
if(maproj.gt.1.or.matarg.gt.1)then
difn=max(difnuc(maproj),difnuc(matarg))
else
difn=1.
endif
do i=1,7
tp=(1.+x1(i))/2.
tm=(1.-x1(i))/2.
b0(14+i)=bmax-log(tp)*difn
b0(29-i)=bmax-log(tm)*difn
ai(14+i)=a1(i)*b0(14+i)/tp*10.*difn*pi
ai(29-i)=a1(i)*b0(29-i)/tm*10.*difn*pi
enddo
do i=1,28
wabs(i)=0.
wdd(i)=0.
wprod(i)=0.
wcoh(i)=0.
wqel(i)=0.
enddo
do nc=1,niter
if(maproj.eq.1)then
xproj(1)=0.
yproj(1)=0.
zproj(1)=0.
else
call conxyz('p',mamx,xproj,yproj,zproj,ypjtl-yhaha)
endif
if(matarg.eq.1)then
xtarg(1)=0.
ytarg(1)=0.
ztarg(1)=0.
else
call conxyz('t',mamx,xtarg,ytarg,ztarg,yhaha)
endif
do i=1,28
call epogcr(b0(i),xgabs,xgdd,xgprod,xgcoh,xgqel)
wabs(i)=wabs(i)+sngl(xgabs)
wdd(i)=wdd(i)+sngl(xgdd)
wprod(i)=wprod(i)+sngl(xgprod)
wcoh(i)=wcoh(i)+sngl(xgcoh)
wqel(i)=wqel(i)+sngl(xgqel)
enddo
enddo
gabs=0.
gdd=0.
gcoh=0.
gprod=0.
gqel=0.
do i=1,28
wabs(i)=wabs(i)/niter
wdd(i)=wdd(i)/niter
wcoh(i)=wcoh(i)/niter
wprod(i)=wprod(i)/niter
wqel(i)=wqel(i)/niter
gabs=gabs+ai(i)*wabs(i)
gdd=gdd+ai(i)*wdd(i)
gcoh=gcoh+ai(i)*wcoh(i)
gqel=gqel+ai(i)*wqel(i)
gprod=gprod+ai(i)*wprod(i)
enddo
gtot=gprod+gcoh !total=all cut (with diff) + all uncut
if(ish.ge.2)write (ifch,202)gtot,gprod,gabs,gdd,gcoh,gqel
201 format(2x,'epocrossc - A-B interaction cross sections,'
*,' N of iter.:',i5,' bmax:',f5.2)
202 format(2x,'epocrossc: gtot=',e10.3,2x,'gprod=',e10.3,2x
*,'gabs=',e10.3/4x,'gdd=',e10.3,2x,'gcoh=',e10.3,'gqel=',e10.3)
koll=kollini
call utprix('epocrs',ish,ishini,2)
return
end
c-------------------------------------------------------------------------------
subroutine epogcr(b,gabs,gdd,gprod,gcoh,gqel)
c-------------------------------------------------------------------------------
c epogcr - integrands (b-profiles) for nucleus-nucleus cross sections
c b - impact parameter
c code from QGSJET programs by S.Ostapchenko
c-------------------------------------------------------------------------------
include 'epos.inc'
include 'epos.incems'
include 'epos.incpar'
common /cncl/xproj(mamx),yproj(mamx),zproj(mamx)
* ,xtarg(mamx),ytarg(mamx),ztarg(mamx)
common/geom/rmproj,rmtarg,bmax,bkmx
common/scrangle/ phik3(kollmx),thetak3(kollmx)
double precision vin,gabs,gdd,gprod,gcoh,fdd,gqel,fdt,vdt,vcu
if(ish.ge.9)write (ifch,201)b
gprod=1d0
gabs=1d0
gdd=1d0
fdd=1d0
fdt=1d0
bx=0
by=0
if(maproj.eq.1.and.matarg.eq.1)then
if(b.gt.bkmx)then
koll=0
else
koll=1
bk(1)=b
iproj(1)=1
itarg(1)=1
lproj(1)=1
ltarg(1)=1
lproj3(1)=1
ltarg3(1)=1
kproj3(1,1)=1
ktarg3(1,1)=1
kproj(1,1)=1
ktarg(1,1)=1
endif
else
bx=b
by=0.
koll=0
do i=1,maproj
lproj(i)=0
lproj3(i)=0
enddo
do j=1,matarg
ltarg(j)=0
ltarg3(j)=0
enddo
do 12 i=1,maproj
do 11 j=1,matarg
bij=sqrt((xproj(i)+bx-xtarg(j))**2+(yproj(i)+by-ytarg(j))**2)
if(bij.gt.bkmx)goto 11
koll=koll+1
if(koll.gt.kollmx)call utstop('epogcr: kollmx too small&')
bk(koll)=bij
bkx(koll)=xproj(i)+bx-xtarg(j)
bky(koll)=yproj(i)+by-ytarg(j)
iproj(koll)=i
itarg(koll)=j
lproj(i)=lproj(i)+1
ltarg(j)=ltarg(j)+1
kproj(i,lproj(i))=koll
ktarg(j,ltarg(j))=koll
if(iscreen.ne.0.and.bij.le.bkmxndif)then
if(zbrmax.gt.0..and.bij.gt.zbcut+zbrmax*rangen())goto 11
lproj3(i)=lproj3(i)+1
ltarg3(j)=ltarg3(j)+1
kproj3(i,lproj3(i))=koll
ktarg3(j,ltarg3(j))=koll
c define angle for anti-shadowing
if(abs(bky(koll)).gt.1.e-6)then
if(abs(bkx(koll)).gt.1.e-6)then
phik3(koll)=atan(bky(koll)/bkx(koll))
else
phik3(koll)=sign(0.5*pi,bky(koll))
endif
elseif(bkx(koll).lt.0.)then
phik3(koll)=pi
endif
if(bk(koll).gt.0.)then
thetak3(koll)=atan(bglaubx/bk(koll))
else
thetak3(koll)=0.5*pi
endif
endif
11 continue
12 continue
endif
if(koll.eq.0)then
gabs=0d0
gdd=0d0
gprod=0d0
gcoh=0d0
gqel=0d0
goto 1000
endif
if(iscreen.ne.0)call CalcScrPair(b)
irea=-1
call GfunParK(irea)
if(ionudi.eq.0
& .and.(maproj.ne.1.or.matarg.ne.1).and.nglevt.eq.0)then
gabs=0d0
gdd=0d0
gprod=0d0
gcoh=0d0
gqel=0d0
goto 1000
endif
call integom1(irea)
do n=1,maproj
call epov(n,vin,vcu,vdt)
gprod=gprod*vin
gabs=gabs*vcu
fdd=fdd*(1.-rexdif(iclpro))
& **(1.+rexres(iclpro)*float(lproj(n)-1))
fdt=fdt*vdt
enddo
gprod=min(gprod,1.d0)
gcoh=1d0-2d0*sqrt(gprod)+gprod
gprod=1d0-gprod
gabs=max(0d0,1d0-gabs) !cut (no diffraction)
gdd=max(0d0,gprod-gabs) !diffractive part
gqel=0d0
if(ionudi.eq.2.and.maproj+matarg.gt.2)then
gqel=fdd*gdd !quasielastic = diffractive without excited proj.
if(iLHC.eq.1)gqel=gqel-fdd*fdt*gdd !DPE counted as inelastic
gdd=gdd-gqel !only excited projectile diffraction
elseif(iLHC.ne.1)then
gqel=fdd*fdt*gdd !quasielastic = diffractive without excited proj. or targ
gdd=gdd-gqel !inelastic part due to excited diffraction
endif
1000 continue
if(ish.ge.9)write (ifch,202)gabs,gdd,gprod,gcoh,gqel,fdd,fdt
201 format(2x,'epogcr-integrands for nucleus-nucleus cross sections,'
*,' b=',e10.3)
202 format(2x,'epogcr: gabs=',e10.3,2x,'gdd=',e10.3,2x,'gprod=',e10.3
*,2x,'gcoh=',e10.3,2x,'gqel=',e10.3,2x,'fdd=',e10.3,' fdt=',e10.3)
return
end
c=============================================================================
subroutine epov(n,vin,vcu,vdt)
c epov - eikonal factors for nucleus-nucleus interaction
c (used for cross-section calculation)
c n - projectile nucleon indice
c vin - all uncut pomerons
c vcu - all uncut non diff pomerons
c vdt - non diffractive excitation factor for target
c code from QGSJET programs by S.Ostapchenko
c----------------------------------------------------------------------------
include 'epos.inc'
include 'epos.incems'
common /cncl/xproj(mamx),yproj(mamx),zproj(mamx)
* ,xtarg(mamx),ytarg(mamx),ztarg(mamx)
double precision vvv2,vvv1,dv,vin,vcu,vdt,PhiExpoK,PhiExpoK2
if(ish.ge.9)write (ifch,201)xproj(n),yproj(n)
vin=0.d0
vcu=0.d0
vvv1=1.d0
vvv2=1.d0
dv=1.d0
do m=1,lproj(n)
k=kproj(n,m)
vvv2=vvv2*max(0.d0,PhiExpoK2(k,1.d0,1.d0))
vvv1=vvv1*max(0.d0,PhiExpoK(k,1.d0,1.d0))
dv=dv*(1.-rexdif(icltar))
& **(1.+rexres(icltar)*float(ltarg(m)-1))
enddo
vcu=vvv2
vin=vvv1 !exp(-2 * chi)
vdt=dv
if(ish.ge.9)write (ifch,202)vin,vcu,vdt
if(ish.ge.9)write (ifch,203)
201 format(2x,'epov - eikonal factor: nucleon coordinates x=',
*e10.3,2x,'y=',e10.3)
202 format(2x,'vin=',e10.3,2x,'vcu=',e10.3,2x,'vdt=',e10.3)
203 format(2x,'epov - end')
return
end
c------------------------------------------------------------------------
subroutine psfz(iqq,gz2,b)
c-----------------------------------------------------------------------
c hadron-nucleus cross sections calculation
c b - impact parameter squared
C iqq - 1 = elastic cross section
C 2 = inelastic cross section
c-----------------------------------------------------------------------
double precision PhiExpo
include 'epos.inc'
include 'epos.incems'
include 'epos.incpar'
common /ar3/ x1(7),a1(7)
external pttcs,pprcs
gz2=0.
e1=exp(-1.)
if(iomega.eq.2)then !no dif
rs=r2had(iclpro)+r2had(icltar)+slopom*log(engy**2)
else
rs=r2had(iclpro)+r2had(icltar)+max(slopom,slopoms)*log(engy**2)
& +gwidth*(r2had(iclpro)+r2had(icltar))
& +bmxdif(iclpro,icltar)/4./0.0389
endif
rpom=4.*.0389*rs
kollini=koll !koll modified in zzfz
koll=1
if(iscreen.ne.0.and.(maproj.gt.1.or.matarg.gt.1))then
call zzfz(zzp,zzt,kollth,b)
koll=kollth
else
zzp=0.
zzt=0.
endif
do i1=1,7
do m=1,2
z=.5+x1(i1)*(m-1.5)
zv1=exp(-z)
zv2=(e1*z)
b1=sqrt(-rpom*log(zv1))
b2=sqrt(-rpom*log(zv2))
if(maproj.eq.1.and.matarg.eq.1)then
cg1=1.
cg2=1.
elseif(matarg.eq.1)then
cg1=ptrot(pprcs,b,b1)
cg2=ptrot(pprcs,b,b2)
else
cg1=ptrot(pttcs,b,b1)
cg2=ptrot(pttcs,b,b2)
endif
vv21=sngl(Phiexpo(zzp,zzt,1.,1.d0,1.d0,engy**2,b1))
vv22=sngl(Phiexpo(zzp,zzt,1.,1.d0,1.d0,engy**2,b2))
if(iqq.ne.1)then
gz2=gz2+a1(i1)*(cg1*(1.-vv21)+cg2*(1.-vv22)/z)
else
vv11=sngl(Phiexpo(zzp,zzt,0.5,1.d0,1.d0,engy**2,b1))
vv12=sngl(Phiexpo(zzp,zzt,0.5,1.d0,1.d0,engy**2,b2))
gz2=gz2+a1(i1)*(cg1*(vv21-2.*vv11+1.)
& +cg2*(vv22-2.*vv12+1.)/z)
endif
enddo
enddo
gz2=gz2*rpom*0.5
koll=kollini
return
end
c------------------------------------------------------------------------
subroutine zzfz(zzp,zzt,kollth,b)
c-----------------------------------------------------------------------
c hadron-nucleus cross sections calculation
c b - impact parameter squared
C xsfct - 0.5 = total cross section
C 1.0 = inelastic cross section
c-----------------------------------------------------------------------
common /psar50/ zznuc,b2xnuc
include 'epos.inc'
include 'epos.incems'
include 'epos.incpar'
common /ar3/ x1(7),a1(7)
external pttcs,pprcs,pttzz,pprzz
zzp=0.
zzt=0.
kollth=1
if(iscreen.eq.0.or.(maproj.eq.1.and.matarg.eq.1))return
rs=r2had(iclpro)+r2had(icltar)+slopom*log(engy**2)
rpom=4.*.0389*rs
bgl2=2.*rpom*epscrp
zzpp=epscrw*fscra(engy/egyscr)
c caculate the radius where Z is saturated at epscrx to define the bases
c of nuclear shadowing
satrad=0.
if(zzpp.gt.0.)satrad=-bgl2*log(epscrx/zzpp)
bglx=zbrads*sqrt(max(0.1,satrad))
fzbrmax=1.
if(zbrmax.gt.0)fzbrmax=zbrmax
fzbcut=1.
if(zbcut.gt.0)fzbcut=zbcut*bglx
fzbrads=1.
if(bglx.gt.0)fzbrads=bglx
fnuc=1.2*fzbcut/fzbrads
b2xnuc=bgl2+4.*fzbrmax*sqrt(float(maproj*matarg))*fnuc
e1=exp(-1.)
colp=0.
colt=0.
do i1=1,7
do m=1,2
z=.5+x1(i1)*(m-1.5)
zv1=exp(-z)
zv2=(e1*z)
b1=sqrt(-rpom*log(zv1))
b2=sqrt(-rpom*log(zv2))
if(maproj.gt.1)then
cg1=ptrot(pprcs,b,b1)
cg2=ptrot(pprcs,b,b2)
colnuc=a1(i1)*(cg1+cg2/z)
colp=colp+colnuc
rho=0.05
zznuc=epscrw*fscro(engy/egyscr,rho)
zp1=ptrot(pprzz,b,b1)
zp2=ptrot(pprzz,b,b2)
zzp=zzp+a1(i1)*(zp1+zp2/z)
endif
if(matarg.gt.1)then
cg1=ptrot(pttcs,b,b1)
cg2=ptrot(pttcs,b,b2)
colnuc=a1(i1)*(cg1+cg2/z)
colt=colt+colnuc
rho=0.05
zznuc=epscrw*fscro(engy/egyscr,rho)
zt1=ptrot(pttzz,b,b1)
zt2=ptrot(pttzz,b,b2)
zzt=zzt+a1(i1)*(zt1+zt2/z)
endif
enddo
enddo
colp=sqrt(colp)
colt=sqrt(colt)
if(colp.gt.1.)then
kollth=nint(max(1.,colp))
colp=fnuc*log(colp)
zzp=sqrt(zzp)
zzp=0.01*zzp*colp*bgl2
c saturation
zzp=min(zzp,colp*epscrx)
else
zzp=0.
endif
if(colt.gt.1.)then
kollth=nint(max(1.,kollth+colt))
colt=fnuc*log(colt)
zzt=sqrt(zzt)
zzt=0.01*zzt*colt*bgl2
c saturation
zzt=min(zzt,colt*epscrx)
else
zzt=0.
endif
c zzp=zzp*2. !correction to have formula=MC
c zzt=zzt*2.
c print *,'ici',b,zzp,zzt,kollth,b2xnuc
return
end
c------------------------------------------------------------------------
function ptgau(func,bm,ipt,iqq)
c-----------------------------------------------------------------------
c impact parameter integration for impact parameters <bm -
c for nucleus-nucleus and hadron-nucleus cross-sections calculation
c ipt=1 : projectile, ipt=2 : target
c iqq=1 : elastic xsection, iqq=2 : inelastic cross section
c-----------------------------------------------------------------------
include 'epos.inc'
common /ar3/ x1(7),a1(7)
external func
ptgau=0.
do i=1,7
do m=1,2
b=bm*sqrt(.5+x1(i)*(m-1.5))
ptgau=ptgau+func(b,ipt,iqq)*a1(i)
enddo
enddo
ptgau=ptgau*bm**2*pi*.5
return
end
c------------------------------------------------------------------------
function ptgau1(bm,ipt,iqq)
c-----------------------------------------------------------------------
c impact parameter integration for impact parameters >bm -
c for hadron-nucleus cross-sections calculation
c ipt=1 : projectile, ipt=2 : target
c iqq=1 : elastic xsection, iqq=2 : inelastic cross section
c-----------------------------------------------------------------------
include 'epos.inc'
common /ar5/ x5(2),a5(2)
ptgau1=0.
if(ipt.eq.1)then
difn=difnuc(maproj)
else
difn=difnuc(matarg)
endif
do i=1,2
b=bm+x5(i)*difn
ptgau1=ptgau1+ptfau(b,ipt,iqq)*a5(i)*exp(x5(i))*b*2.*pi*difn
enddo
return
end
c------------------------------------------------------------------------
function ptgau2(bm,iqq)
c-----------------------------------------------------------------------
c impact parameter integration for impact parameters >bm -
c for nucleus-nucleus cross-sections calculation
c iqq=1 : elastic xsection, iqq=2 : inelastic cross section
c-----------------------------------------------------------------------
include 'epos.inc'
common /ar5/ x5(2),a5(2)
ptgau2=0.
difn=difnuc(maproj)+difnuc(matarg)
do i=1,2
b=bm+x5(i)*difn
ptgau2=ptgau2+ptfauAA(b,iqq)*a5(i)*exp(x5(i))*b*2.*pi*difn
enddo
return
end
c------------------------------------------------------------------------
function ptfau(b,ipt,iqq)
c-----------------------------------------------------------------------
c ptfau - integrands for hadron-nucleus cross-sections calculation
c ipt=1 : projectile, ipt=2 : target
c iqq=1 : elastic xsection, iqq=2 : inelastic cross section
c-----------------------------------------------------------------------
include 'epos.inc'
common /psar35/ anorm,anormp
call psfz(iqq,gz2,b)
if(ipt.eq.1)then
ptfau=1.-max(0.,(1.-anormp*gz2))**maproj
else
ptfau=1.-max(0.,(1.-anorm*gz2))**matarg
endif
return
end
c------------------------------------------------------------------------
function ptfauAA(b,iqq)
c-----------------------------------------------------------------------
c ptfau - integrands for hadron-nucleus cross-sections calculation
c iqq=1 : elastic xsection, iqq=2 : inelastic cross section
c-----------------------------------------------------------------------
include 'epos.inc'
common /ar3/ x1(7),a1(7)
common /psar35/ anorm,anormp
external pprcs
ptfauAA=0.
e1=exp(-1.)
rs=r2had(iclpro)+r2had(icltar)+max(slopom,slopoms)*log(engy**2)
& +gwidth*(r2had(iclpro)+r2had(icltar))
& +bmxdif(iclpro,icltar)/4./0.0389
rpom=4.*.0389*rs
do i1=1,7
do m=1,2
z=.5+x1(i1)*(m-1.5)
zv1=exp(-z)
zv2=(e1*z)
b1=sqrt(-rpom*log(zv1))
b2=sqrt(-rpom*log(zv2))
call psfz(iqq,gz21,b1)
call psfz(iqq,gz22,b2)
ptfau1=max(0.,(1.-anorm*gz21))**matarg
ptfau2=max(0.,(1.-anorm*gz22))**matarg
cg1=ptrot(pprcs,b,b1)
cg2=ptrot(pprcs,b,b2)
ptfauAA=ptfauAA+a1(i1)*(cg1*(1.-ptfau1)+cg2*(1.-ptfau2)/z)
enddo
enddo
ptfauAA=ptfauAA*rpom/2.
ptfauAA=1.-max(0.,(1.-anormp*ptfauAA))**maproj
return
end
c------------------------------------------------------------------------
function ptrot(func,s,b)
c-----------------------------------------------------------------------
c convolution of nuclear profile functions (axial angle integration)
c-----------------------------------------------------------------------
common /ar8/ x2(4),a2
external func
ptrot=0.
do i=1,4
sb1=b**2+s**2-2.*b*s*(2.*x2(i)-1.)
sb2=b**2+s**2-2.*b*s*(1.-2.*x2(i))
ptrot=ptrot+(func(sb1)+func(sb2))
enddo
ptrot=ptrot*a2
return
end
c------------------------------------------------------------------------
function pttcs(b0)
c-----------------------------------------------------------------------
c ptt - nuclear profile function value at imp param squared b*difnuc**2
c-----------------------------------------------------------------------
include 'epos.inc'
common /psar34/ rrr,rrrm
common /ar5/ x5(2),a5(2)
common /ar9/ x9(3),a9(3)
b=b0/difnuc(matarg)**2
pttcs=0.
zm=rrrm**2-b
if(zm.gt.4.*b)then
zm=sqrt(zm)
else
zm=2.*sqrt(b)
endif
do i=1,3
z1=zm*(1.+x9(i))*0.5
z2=zm*(1.-x9(i))*0.5
quq=sqrt(b+z1**2)-rrr
if (quq.lt.85.)pttcs=pttcs+a9(i)/(1.+exp(quq))
quq=sqrt(b+z2**2)-rrr
if (quq.lt.85.)pttcs=pttcs+a9(i)/(1.+exp(quq))
enddo
pttcs=pttcs*zm*0.5
dt=0.
do i=1,2
z1=x5(i)+zm
quq=sqrt(b+z1**2)-rrr-x5(i)
if (quq.lt.85.)dt=dt+a5(i)/(exp(-x5(i))+exp(quq))
enddo
pttcs=pttcs+dt
return
end
c------------------------------------------------------------------------
function pttzz(b0)
c-----------------------------------------------------------------------
c ptt - nuclear Z function value at imp param squared b*difnuc**2
c-----------------------------------------------------------------------
include 'epos.inc'
include 'epos.incpar'
common /psar34/ rrr,rrrm
common /psar50/ zznuc,b2xnuc
common /ar5/ x5(2),a5(2)
common /ar9/ x9(3),a9(3)
pttzz=0.
b=b0/difnuc(matarg)**2
c absb=max(1.e-9,sqrt(b0)-zbcut)
absb=max(1.e-9,sqrt(b0))
bsq=absb*absb
zm=rrrm**2-b
if(zm.gt.4.*b)then
zm=sqrt(zm)
else
zm=2.*sqrt(b)
endif
do i=1,3
z1=zm*(1.+x9(i))*0.5
z2=zm*(1.-x9(i))*0.5
quq=sqrt(b+z1**2)-rrr
if (quq.lt.85.)pttzz=pttzz+a9(i)/(1.+exp(quq))
quq=sqrt(b+z2**2)-rrr
if (quq.lt.85.)pttzz=pttzz+a9(i)/(1.+exp(quq))
enddo
pttzz=pttzz*zm*0.5
dt=0.
do i=1,2
z1=x5(i)+zm
quq=sqrt(b+z1**2)-rrr-x5(i)
if (quq.lt.85.)dt=dt+a5(i)/(exp(-x5(i))+exp(quq))
enddo
pttzz=max(0.,(pttzz+dt)-1.)*zznuc*exp(-bsq/2./b2xnuc)
return
end
c------------------------------------------------------------------------
function pprcs(b0)
c-----------------------------------------------------------------------
c ppr - nuclear profile function value at imp param squared b*difnuc**2
c-----------------------------------------------------------------------
include 'epos.inc'
common /psar41/ rrrp,rrrmp
common /ar5/ x5(2),a5(2)
common /ar9/ x9(3),a9(3)
b=b0/difnuc(maproj)**2
pprcs=0.
zm=rrrmp**2-b
if(zm.gt.4.*b)then
zm=sqrt(zm)
else
zm=2.*sqrt(b)
endif
do i=1,3
z1=zm*(1.+x9(i))*0.5
z2=zm*(1.-x9(i))*0.5
quq=sqrt(b+z1**2)-rrrp
if (quq.lt.85.)pprcs=pprcs+a9(i)/(1.+exp(quq))
quq=sqrt(b+z2**2)-rrrp
if (quq.lt.85.)pprcs=pprcs+a9(i)/(1.+exp(quq))
enddo
pprcs=pprcs*zm*0.5
dt=0.
do i=1,2
z1=x5(i)+zm
quq=sqrt(b+z1**2)-rrrp-x5(i)
if (quq.lt.85.)dt=dt+a5(i)/(exp(-x5(i))+exp(quq))
enddo
pprcs=pprcs+dt
return
end
c------------------------------------------------------------------------
function pprzz(b0)
c-----------------------------------------------------------------------
c ppr - Z nuclear function value at imp param squared b*difnuc**2
c-----------------------------------------------------------------------
include 'epos.inc'
include 'epos.incpar'
common /psar41/ rrrp,rrrmp
common /psar50/ zznuc,b2xnuc
common /ar5/ x5(2),a5(2)
common /ar9/ x9(3),a9(3)
pprzz=0.
b=b0/difnuc(maproj)**2
c absb=max(1.e-9,sqrt(b0)-zbcut)
absb=max(1.e-9,sqrt(b0))
bsq=absb*absb
zm=rrrmp**2-b
if(zm.gt.4.*b)then
zm=sqrt(zm)
else
zm=2.*sqrt(b)
endif
do i=1,3
z1=zm*(1.+x9(i))*0.5
z2=zm*(1.-x9(i))*0.5
quq=sqrt(b+z1**2)-rrrp
if (quq.lt.85.)pprzz=pprzz+a9(i)/(1.+exp(quq))
quq=sqrt(b+z2**2)-rrrp
if (quq.lt.85.)pprzz=pprzz+a9(i)/(1.+exp(quq))
enddo
pprzz=pprzz*zm*0.5
dt=0.
do i=1,2
z1=x5(i)+zm
quq=sqrt(b+z1**2)-rrrp-x5(i)
if (quq.lt.85.)dt=dt+a5(i)/(exp(-x5(i))+exp(quq))
enddo
pprzz=max(0.,(pprzz+dt)-1.)*zznuc*exp(-bsq/2./b2xnuc)
return
end
c------------------------------------------------------------------------------
function pscrse(ek,mapr,matg,iqq)
c------------------------------------------------------------------------------
c hadron-nucleus (hadron-proton) and nucl-nucl particle production cross section
c ek - lab kinetic energy for the interaction
c maproj - projec mass number
c matarg - target mass number
c iqq=1 - ela cross section
c >2 - ine cross section (2 used for cut (changing iomega), 3 uses table,
c 4 used for ine without table)
c------------------------------------------------------------------------------
dimension wk(3),wa(3),wb(3)
include 'epos.inc'
common /psar33/ asect(7,4,7),asectn(7,7,7)
common /psar34/ rrr,rrrm
common /psar35/ anorm,anormp
common /psar41/ rrrp,rrrmp
external ptfau,ptfauAA
pscrse=0.
call idmass(1120,amt1)
call idmass(1220,amt2)
amtar=0.5*(amt1+amt2)
if(matg.eq.1)amtar=amt1
if(mapr.eq.1)then
call idmass(idproj,ampro)
else
ampro=amtar
endif
egy=ek+ampro
c p=sqrt(max(0.,egy**2-ampro**2))
egy=sqrt( 2*egy*amtar+amtar**2+ampro**2 )
if(isetcs.le.1.or.iqq.ne.3)then
maprojsave=maproj
matargsave=matarg
engysave=engy
maproj=mapr
matarg=matg
engy=egy
if(matg.eq.1.and.mapr.eq.1)then
if(iqq.eq.1)then !sig ela
call psfz(1,gz2,0.)
else !sig ine
call psfz(2,gz2,0.)
endif
gin=gz2*pi*10.
elseif(mapr.eq.1)then
rad=radnuc(matg)
bm=rad+2.
rrr=rad/difnuc(matg)
rrrm=rrr+log(9.)
anorm=1.5/pi/rrr**3/(1.+(pi/rrr)**2)/difnuc(matg)**2
if(iqq.ne.1)then
gin=(ptgau(ptfau,bm,2,2)+ptgau1(bm,2,2))*10. !sig ine
else
gin=(ptgau(ptfau,bm,2,1)+ptgau1(bm,2,1))*10. !sig ela
endif
elseif(matg.eq.1)then
rad=radnuc(mapr)
bm=rad+2.
rrrp=rad/difnuc(mapr)
rrrmp=rrrp+log(9.)
anormp=1.5/pi/rrrp**3/(1.+(pi/rrrp)**2)/difnuc(mapr)**2
if(iqq.ne.1)then
gin=(ptgau(ptfau,bm,1,2)+ptgau1(bm,1,2))*10. !sig ine
else
gin=(ptgau(ptfau,bm,1,1)+ptgau1(bm,1,1))*10. !sig ela
endif
else
rad=radnuc(matg)+1.
radp=radnuc(mapr)+1.
bm=rad+radp+2.
rrr=rad/difnuc(matg)
rrrm=rrr+log(9.)
rrrp=radp/difnuc(mapr)
rrrmp=rrrp+log(9.)
anorm=1.5/pi/rrr**3/(1.+(pi/rrr)**2)/difnuc(matg)**2
anormp=1.5/pi/rrrp**3/(1.+(pi/rrrp)**2)/difnuc(mapr)**2
if(iqq.ne.1)then
gin=(ptgau(ptfauAA,bm,2,2)+ptgau2(bm,2))*10. !sig ine
else
gin=(ptgau(ptfauAA,bm,2,1)+ptgau2(bm,1))*10. !sig ela
endif
endif
pscrse=gin
maproj=maprojsave
matarg=matargsave
engy=engysave
else
ye=log10(max(1.,egy/1.5))+1.
je=min(5,int(ye))
wk(2)=ye-je
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
ya=matg
ya=log(ya)/.69315+1.
ja=min(int(ya),4)
wa(2)=ya-ja
wa(3)=wa(2)*(wa(2)-1.)*.5
wa(1)=1.-wa(2)+wa(3)
wa(2)=wa(2)-2.*wa(3)
if(mapr.eq.1)then
do i=1,3
do m=1,3
pscrse=pscrse+asect(je+i-1,iclpro,ja+m-1)*wk(i)*wa(m)
enddo
enddo
else
yb=mapr
yb=log(yb)/.69315+1.
jb=min(int(yb),4)
wb(2)=yb-jb
wb(3)=wb(2)*(wb(2)-1.)*.5
wb(1)=1.-wb(2)+wb(3)
wb(2)=wb(2)-2.*wb(3)
do i=1,3
do m=1,3
do n=1,3
pscrse=pscrse+asectn(je+i-1,jb+n-1,ja+m-1)*wk(i)*wa(m)*wb(n)
enddo
enddo
enddo
endif
pscrse=exp(pscrse)
endif
return
end
c------------------------------------------------------------------------------
function eposcrse(ek,mapro,matar,id)
c------------------------------------------------------------------------------
c inelastic cross section of epos
c (id=0 corresponds to air)
c ek - kinetic energy for the interaction
c maproj - projec mass number (1<maproj<64)
c matarg - target mass number (1<matarg<64)
c------------------------------------------------------------------------------
include 'epos.inc'
eposcrse=0.
if(id.eq.0)then
do k=1,3
mt=int(airanxs(k))
eposcrse=eposcrse+airwnxs(k)*pscrse(ek,mapro,mt,3)
enddo
else
eposcrse=pscrse(ek,mapro,matar,3)
endif
return
end
c------------------------------------------------------------------------------
function eposinecrse(ek,mapro,matar,id)
c------------------------------------------------------------------------------
c inelastic cross section of epos not using tabulated xs
c (id=0 corresponds to air)
c ek - kinetic energy for the interaction
c maproj - projec mass number (1<maproj<64)
c matarg - target mass number (1<matarg<64)
c------------------------------------------------------------------------------
include 'epos.inc'
eposinecrse=0.
if(id.eq.0)then
do k=1,3
mt=int(airanxs(k))
eposinecrse=eposinecrse+airwnxs(k)*pscrse(ek,mapro,mt,4)
enddo
else
eposinecrse=pscrse(ek,mapro,matar,4)
endif
return
end
c------------------------------------------------------------------------------
function eposelacrse(ek,mapro,matar,id)
c------------------------------------------------------------------------------
c elastic cross section of epos
c (id=0 corresponds to air)
c ek - kinetic energy for the interaction
c maproj - projec mass number (1<maproj<64)
c matarg - target mass number (1<matarg<64)
c------------------------------------------------------------------------------
include 'epos.inc'
eposelacrse=0.
if(id.eq.0)then
do k=1,3
mt=int(airanxs(k))
eposelacrse=eposelacrse+airwnxs(k)*pscrse(ek,mapro,mt,1)
enddo
else
eposelacrse=pscrse(ek,mapro,matar,1)
endif
return
end
c------------------------------------------------------------------------------
function eposcutcrse(ek,mapro,matar,id)
c------------------------------------------------------------------------------
c total cross section of epos
c (id=0 corresponds to air)
c ek - kinetic energy for the interaction
c maproj - projec mass number (1<maproj<64)
c matarg - target mass number (1<matarg<64)
c------------------------------------------------------------------------------
include 'epos.inc'
eposcutcrse=0.
iomegasave=iomega
iomega=2
if(id.eq.0)then
do k=1,3
mt=int(airanxs(k))
eposcutcrse=eposcutcrse+airwnxs(k)*pscrse(ek,mapro,mt,2)
enddo
else
eposcutcrse=pscrse(ek,mapro,matar,2)
endif
iomega=iomegasave
return
end
c------------------------------------------------------------------------------
subroutine crseaaEpos(sigt,sigi,sigc,sige)
c------------------------------------------------------------------------------
c nucleus-nucleus (hadron) cross section of epos from simplified (realistic)
c simulations
c (id=0 corresponds to air)
c sigt = sig tot
c sigi = sig inelastic (cut + projectile diffraction)
c sigc = sig cut
c sige = sig elastic (includes target diffraction)
c------------------------------------------------------------------------------
include 'epos.inc'
niter=20000
if(idtarg.eq.0)then
sigt=0.
sigc=0.
sigi=0.
sige=0.
sigd=0.
sigql=0.
do k=1,3
matarg=int(airanxs(k))
call epocrossc(niter,xsigt,xsigi,xsigc,xsige,xsigql,xsigd)
sigt=sigt+airwnxs(k)*xsigt
sigi=sigi+airwnxs(k)*xsigi
sigc=sigc+airwnxs(k)*xsigc
sige=sige+airwnxs(k)*xsige
sigd=sigd+airwnxs(k)*xsigd
sigql=sigql+airwnxs(k)*xsigql
enddo
else
call epocrossc(niter,sigt,sigi,sigc,sige,sigql,sigd)
endif
if(ionudi.ne.1)then
sige=sige+sigql !add non-excited diffractive projectile to elastic
sigi=sigi-sigql !do not count non-excited diffractive projectile in inelastic
if(maproj+matarg.gt.2)then
sigc=sigc+sigd*0.95 !for absorbtion cross section remove 5% of the
!excited projectile diffractive cross section
!which "looks like" non excited (approximation)
endif
endif
end
cc------------------------------------------------------------------------
c function pshard1(sy,xpp,xpm,z)
cc-----------------------------------------------------------------------
cc pshard - qq-pomeron eikonal
cc sy - energy squared for the pomeron,
cc xpp - lc+ for the pomeron,
cc xpm - lc- for the pomeron
cc-----------------------------------------------------------------------
c common /ar3/ x1(7),a1(7)
c common /ar9/ x9(3),a9(3)
c include 'epos.inc'
c include 'epos.incsem'
c
c pshard1=0.
c if(iclpro.ne.4.and.icltar.ne.4)then
c spmin=4.*q2min
c else
c spmin=4.*q2min+2.*qcmass**2
c endif
c if(sy.le.spmin)return
c
c rp=r2had(iclpro)+r2had(icltar)+slopom*log(max(1.,sy))
c alpq=(alppar+1.)/2.
c xmin=spmin/sy !min hard pomeron mass share
c xminl=xmin**(delh+.5)
c
c do i=1,3
c do m=1,2
c zh=(.5*(1.+xminl-(2*m-3)*x9(i)*(1.-xminl)))**(1./(delh+.5))
c if(iclpro.ne.4.and.icltar.ne.4)then
c call psjti0(zh*sy,sqq,sqqb,1,1)
c call psjti0(zh*sy,sqqp,sqqpb,1,2)
c call psjti0(zh*sy,sqaq,sqaqb,-1,1)
c else
c call psjti0(zh*sy,sqq,sqqb,4,1)
c sqq=0.
c sqaq=0.
c endif
c
c stq=0.
c do i1=1,3
c do m1=1,2
c xx=.5+x9(i1)*(m1-1.5)
c xp=zh**xx
c xm=zh/xp
c if(xp*xpp.le..9999.and.xm*xpm.le..9999.or.
c * xm*xpp.le..9999.and.xp*xpm.le..9999)then
c stq=stq+a9(i1)*psharf(xp*xpp,xm*xpm,sqq,sqqp,sqaq)
c * *(1.-xp)**(1.+alplea(iclpro)-alpq)
c * *(1.-xm)**(1.+alplea(icltar)-alpq)
c endif
c enddo
c enddo
c pshard1=pshard1-a9(i)*stq/zh**(delh+0.5)*log(zh)
c enddo
c enddo
c pshard1=pshard1*(1.-xminl)/(delh+.5)/4.*factk
c **chad(iclpro)*chad(icltar)*(xpp*xpm)**(1.-alpq)
c **z**(rp/(r2had(iclpro)+r2had(icltar)))
c */(8.*pi*(r2had(iclpro)+r2had(icltar)))
c return
c end
c
c------------------------------------------------------------------------
function pshard(sy,xpp,xpm)
c-----------------------------------------------------------------------
c pshard - qq-pomeron eikonal
c sy - energy squared for the pomeron,
c xpp - lc+ for the pomeron,
c xpm - lc- for the pomeron
c-----------------------------------------------------------------------
double precision z01
common /ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
pshard=0.
if(iclpro.ne.4.and.icltar.ne.4)then
spmin=4.*q2min
else
spmin=4.*q2min+2.*qcmass**2
endif
if(sy.le.spmin)return
alpq=(alppar+1.)/2.
xmin=spmin/sy !min hard pomeron mass share
xminl=xmin**(delh+.5)
do i=1,7
do m=1,2
zh=(.5*(1.+xminl-(2*m-3)*x1(i)*(1.-xminl)))**(1./(delh+.5))
if(iclpro.ne.4.and.icltar.ne.4)then
call psjti0(zh*sy,sqq,sqqb,1,1)
call psjti0(zh*sy,sqqp,sqqpb,1,2)
call psjti0(zh*sy,sqaq,sqaqb,-1,1)
else
call psjti0(zh*sy,sqq,sqqb,4,1)
sqqp=0.
sqaq=0.
endif
stq=0. !int^1_(sqrt(z)) dx_p / x_p / sqrt(1-x_p) =int^(tmax)_(0) dt
tmax=sqrt(1.-sqrt(zh)) !t=ln((1+sqrt(1-x_p))/(1-sqrt(1-x_p)))
tmax=log((1.+tmax)/(1.-tmax))
if(tmax.gt.1.e-20)then
do i1=1,7
do m1=1,2
t=tmax*(.5+x1(i1)*(m1-1.5))
z01=((1.d0-exp(-1.d0*t))/(1.d0+exp(-1.d0*t)))**2
xp=1.-z01
xm=zh/xp
if(xp*xpp.le..9999.and.xm*xpm.le..9999.or.
* xm*xpp.le..9999.and.xp*xpm.le..9999)then
stq=stq+a1(i1)*(psharf(xp*xpp,xm*xpm,sqq,sqqp,sqaq)+
* psharf(xm*xpp,xp*xpm,sqq,sqqp,sqaq))
* *z01**(.5-alpq)/(1.-xm)**alpq
endif
enddo
enddo
stq=stq*tmax
endif
pshard=pshard+a1(i)*stq/zh**(delh+0.5)
enddo
enddo
pshard=pshard*(1.-xminl)/(delh+.5)/4.*
*utgam1(2.+alplea(iclpro)-alpq)/utgam1(1.+alplea(iclpro))/
*utgam1(1.-alpq)*
*utgam1(2.+alplea(icltar)-alpq)/utgam1(1.+alplea(icltar))/
*utgam1(1.-alpq)*
*chad(iclpro)*chad(icltar)/(8.*pi*(r2had(iclpro)+r2had(icltar)))*
*(xpp*xpm)**(-alpq)/sy**delh
return
end
c------------------------------------------------------------------------
function psharf(zh1,zh2,sqq,sqqp,sqaq)
c-----------------------------------------------------------------------
include 'epos.incsem'
include 'epos.inc'
alpq=(alppar+1.)/2.
if(zh1.le..9999.and.zh2.le..9999)then
uv1=psdfh4(zh1,q2min,0.,iclpro,1)
dv1=psdfh4(zh1,q2min,0.,iclpro,2)
uv2=psdfh4(zh2,q2min,0.,icltar,1)
dv2=psdfh4(zh2,q2min,0.,icltar,2)
if(iclpro.eq.2.and.icltar.eq.2)then !proton
fff=sqq*(uv1*uv2+dv1*dv2)+sqqp*(uv1*dv2+dv1*uv2)
elseif(iclpro.eq.1.or.icltar.eq.1)then !pion
fff=sqq*uv1*uv2+sqaq*dv1*dv2+sqqp*(uv1*dv2+dv1*uv2)
elseif(iclpro.eq.3.or.icltar.eq.3)then !kaon
fff=sqq*uv1*uv2+sqqp*(uv1*dv2+dv1*uv2+dv1*dv2)
elseif(iclpro.eq.4.or.icltar.eq.4)then !J/psi
fff=sqq*uv1*(uv2+dv2)
else
fff=0.
call utstop("Projectile not know in psharg !&")
endif
psharf=fff*(1.-zh1)**(-1.+alpq-alplea(iclpro))*
* (1.-zh2)**(-1.+alpq-alplea(icltar))
else
psharf=0.
endif
return
end
c------------------------------------------------------------------------
function psvin(sy,xpp,xpm,z,iqq)
c-----------------------------------------------------------------------
c psvin - contributions to the interaction eikonal
c sy - energy squared for the hard interaction,
c xpp - lc+ for the sh pomeron,
c xpm - lc- for the sh pomeron,
c z - impact parameter factor, z=exp(-b**2/4*rp),
c iqq = 1 - gg,
c iqq = 2 - qg,
c iqq = 3 - gq,
c iqq = 4 - qq,
c iqq = 5 - gg(int),
c iqq = 6 - gg(proj),
c iqq = 7 - qg(proj),
c iqq = 9 - total uncut-integrated,
c iqq = 10 - total cut,
c iqq = 14 - gg(int)|b=0,
c iqq = 15 - <b^2*gg(int)>,
c iqq = 16 - gg(proj)|b=0,
c iqq = 17 - <b^2*gg(proj)>,
c iqq = 18 - qg(proj)|b=0,
c iqq = 19 - <b^2*qg(proj)>
c-----------------------------------------------------------------------
dimension wk(3),wi(3),wj(3),wz(3),fa(3)
common /psar2/ edmax,epmax
common /psar4/ fhgg(11,10,8),fhqg(11,10,80)
*,fhgq(11,10,80),fhqq(11,10,80),fhgg0(11,10),fhgg1(11,10,4)
*,fhqg1(11,10,40),fhgg01(11),fhgg02(11),fhgg11(11,4)
*,fhgg12(11,4),fhqg11(11,10,4),fhqg12(11,10,4)
*,ftoint(11,14,2,2,3)
common /psar7/ delx,alam3p,gam3p
include 'epos.inc'
include 'epos.incsem'
if(iqq.eq.3)then
xp=xpm
xm=xpp
iclp=icltar
iclt=iclpro
else
xp=xpp
xm=xpm
iclp=iclpro
iclt=icltar
endif
rp=r2had(iclpro)+r2had(icltar)+slopom*log(max(1.,sy))
psvin=0.
if(iqq.eq.1.or.iqq.eq.5.or.iqq.eq.6.or.iqq.eq.14
*.or.iqq.eq.15.or.iqq.eq.16.or.iqq.eq.17
*.or.iclpro.ne.4.and.(iqq.eq.2.or.iqq.eq.7
*.or.iqq.eq.18.or.iqq.eq.19)
*.or.icltar.ne.4.and.iqq.eq.3
*.or.iclpro.ne.4.and.icltar.ne.4)then
spmin=4.*q2min
else
spmin=4.*q2min+2.*qcmass**2
endif
if(sy.le.spmin.and.(iqq.le.7.or.iqq.gt.13))return
if(iqq.le.7.or.iqq.gt.13)then
yl=log(sy/spmin)/log(epmax/2./spmin)*10.+1
k=int(yl)
if(k.gt.9)k=9
wk(2)=yl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
if(iqq.ne.4)then !---------------- not 4 ------------------
if(iqq.eq.5)then
if(k.eq.1)then
psvin=max(0.,exp(fhgg01(k+1))*wk(2)
* +exp(fhgg01(k+2))*wk(3))
else
psvin=exp(fhgg01(k)*wk(1)+fhgg01(k+1)*wk(2)
* +fhgg01(k+2)*wk(3))
endif
psvin=psvin*factk*sy**delh
return
elseif(iqq.eq.15)then
if(k.eq.1)then
psvin=max(0.,exp(fhgg02(k+1))*wk(2)
* +exp(fhgg02(k+2))*wk(3))
else
psvin=exp(fhgg02(k)*wk(1)+fhgg02(k+1)*wk(2)
* +fhgg02(k+2)*wk(3))
endif
psvin=psvin*factk*sy**delh
return
elseif(iqq.eq.6)then
if(k.eq.1)then
psvin=max(0.,exp(fhgg11(k+1,iclpro))*wk(2)
* +exp(fhgg11(k+2,iclpro))*wk(3))
else
psvin=exp(fhgg11(k,iclpro)*wk(1)+fhgg11(k+1,iclpro)*wk(2)
* +fhgg11(k+2,iclpro)*wk(3))
endif
psvin=psvin*factk*sy**delh*xp**(-alppar)
return
elseif(iqq.eq.17)then
if(k.eq.1)then
psvin=max(0.,exp(fhgg12(k+1,iclpro))*wk(2)
* +exp(fhgg12(k+2,iclpro))*wk(3))
else
psvin=exp(fhgg12(k,iclpro)*wk(1)+fhgg12(k+1,iclpro)*wk(2)
* +fhgg12(k+2,iclpro)*wk(3))
endif
psvin=psvin*factk*sy**delh*xp**(-alppar)
return
elseif(iqq.eq.7.or.iqq.eq.19)then
if(xp.lt..2)then
xl=log(10.*xp)/log(2.)+5.
else
xl=5.*xp+5.
endif
i=int(xl)
if(i.lt.1)i=1
if(i.eq.5)i=4
if(i.gt.8)i=8
wi(2)=xl-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
do k1=1,3
fa(k1)=0.
do i1=1,3
k2=k+k1-1
fhhh=0.
if(iqq.eq.7)then
fhhh=fhqg11(k2,i+i1-1,iclpro)
elseif(iqq.eq.19)then
fhhh=fhqg12(k2,i+i1-1,iclpro)
endif
fa(k1)=fa(k1)+fhhh*wi(i1)
enddo
enddo
if(k.eq.1)then
psvin=max(0.,exp(fa(2))*wk(2)+exp(fa(3))*wk(3))
else
psvin=exp(fa(1)*wk(1)+fa(2)*wk(2)+fa(3)*wk(3))
endif
psvin=psvin*factk*sy**delh
return
endif
jz=int(10.*z)
if(jz.gt.8)jz=8
if(jz.lt.1)jz=1
wz(2)=10.*z-jz
wz(3)=wz(2)*(wz(2)-1.)*.5
wz(1)=1.-wz(2)+wz(3)
wz(2)=wz(2)-2.*wz(3)
if(iqq.eq.14)then
do k1=1,3
k2=k+k1-1
fa(k1)=fhgg0(k2,jz)*wz(1)+fhgg0(k2,jz+1)
* *wz(2)+fhgg0(k2,jz+2)*wz(3)
enddo
if(k.eq.1)then
psvin=max(0.,exp(fa(2))*wk(2)+exp(fa(3))*wk(3))
else
psvin=exp(fa(1)*wk(1)+fa(2)*wk(2)+fa(3)*wk(3))
endif
psvin=psvin*z*factk*sy**delh
elseif(iqq.eq.16)then
do k1=1,3
k2=k+k1-1
fa(k1)=fhgg1(k2,jz,iclpro)*wz(1)+fhgg1(k2,jz+1,iclpro)
* *wz(2)+fhgg1(k2,jz+2,iclpro)*wz(3)
enddo
if(k.eq.1)then
psvin=max(0.,exp(fa(2))*wk(2)+exp(fa(3))*wk(3))
else
psvin=exp(fa(1)*wk(1)+fa(2)*wk(2)+fa(3)*wk(3))
endif
psvin=psvin*z*factk*sy**delh*xp**(-alppar)
elseif(iqq.eq.18)then
if(xp.lt..2)then
xl=log(10.*xp)/log(2.)+5.
else
xl=5.*xp+5.
endif
i=int(xl)
if(i.lt.1)i=1
if(i.eq.5)i=4
if(i.gt.8)i=8
wi(2)=xl-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
do k1=1,3
fa(k1)=0.
do i1=1,3
do l1=1,3
k2=k+k1-1
l2=jz+l1-1+10*(iclpro-1)
fhhh=fhqg1(k2,i+i1-1,l2)
fa(k1)=fa(k1)+fhhh*wi(i1)*wz(l1)
enddo
enddo
enddo
if(k.eq.1)then
psvin=max(0.,exp(fa(2))*wk(2)+exp(fa(3))*wk(3))
else
psvin=exp(fa(1)*wk(1)+fa(2)*wk(2)+fa(3)*wk(3))
endif
psvin=psvin*z*factk*sy**delh
elseif(iqq.eq.1)then !1111111111111111111111111111111111
do k1=1,3
k2=k+k1-1
iclpt=iclpro+4*(icltar-1)
fa(k1)=fhgg(k2,jz,iclpt)*wz(1)+fhgg(k2,jz+1,iclpt)
* *wz(2)+fhgg(k2,jz+2,iclpt)*wz(3)
enddo
if(k.eq.1)then
psvin=max(0.,exp(fa(2))*wk(2)+exp(fa(3))*wk(3))
else
psvin=exp(fa(1)*wk(1)+fa(2)*wk(2)+fa(3)*wk(3))
endif
psvin=psvin*z*factk*sy**delh*(xp*xm)**(-alppar)
else ! 2222222222222222222222 3333333333333333333333 ....
if(xp.lt..2)then
xl=log(10.*xp)/log(2.)+5.
else
xl=5.*xp+5.
endif
i=int(xl)
if(i.lt.1)i=1
if(i.eq.5)i=4
if(i.gt.8)i=8
wi(2)=xl-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
do k1=1,3
fa(k1)=0.
do i1=1,3
do l1=1,3
k2=k+k1-1
fhhh=0.
if(iqq.eq.2)then
l2=jz+l1-1+10*(iclpro+4*(icltar-1)-1)
fhhh=fhqg(k2,i+i1-1,l2)
elseif(iqq.eq.3)then
l2=jz+l1-1+10*(iclpro+4*(icltar-1)-1)
fhhh=fhgq(k2,i+i1-1,l2)
endif
fa(k1)=fa(k1)+fhhh*wi(i1)*wz(l1)
enddo
enddo
enddo
if(k.eq.1)then
psvin=max(0.,exp(fa(2))*wk(2)+exp(fa(3))*wk(3))
else
psvin=exp(fa(1)*wk(1)+fa(2)*wk(2)+fa(3)*wk(3))
endif
psvin=psvin*xm**(-alppar)*z*factk*sy**delh
endif
else ! ------------- 4444444444444444444 -----------------------
if(xp.lt..2)then
xl1=log(10.*xp)/log(2.)+5.
else
xl1=5.*xp+5.
endif
i=max(1,int(xl1))
if(i.eq.5)i=4
i=min(8,i)
wi(2)=xl1-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
if(xm.lt..2)then
xl2=log(10.*xm)/log(2.)+5.
else
xl2=5.*xm+5.
endif
j=max(1,int(xl2))
if(j.eq.5)j=4
j=min(8,j)
wj(2)=xl2-j
wj(3)=wj(2)*(wj(2)-1.)*.5
wj(1)=1.-wj(2)+wj(3)
wj(2)=wj(2)-2.*wj(3)
do k1=1,3
fa(k1)=0.
do i1=1,3
do j1=1,3
k2=k+k1-1
j2=j+j1-1+10*(iclp+4*(iclt-1)-1)
fa(k1)=fa(k1)+fhqq(k2,i+i1-1,j2)*wi(i1)*wj(j1)
enddo
enddo
enddo
if(k.eq.1)then
psvin=max(0.,exp(fa(2))*wk(2)+exp(fa(3))*wk(3))
else
psvin=exp(fa(1)*wk(1)+fa(2)*wk(2)+fa(3)*wk(3))
endif
psvin=psvin*z**(rp/(r2had(iclpro)+r2had(icltar)))*
* factk*sy**delh
endif !--------------------------------------------
return
endif
yl=log(sy)/log(1.e8)*10.+1
k=max(1,int(yl))
k=min(k,9) !?????????????9
wk(2)=yl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
if(z.gt..1)then
zz=10.*z+4
else
zz=50.*z
endif
jz=min(12,int(zz))
if(jz.eq.0)jz=1
if(jz.eq.4)jz=3
wz(2)=zz-jz
wz(3)=wz(2)*(wz(2)-1.)*.5
wz(1)=1.-wz(2)+wz(3)
wz(2)=wz(2)-2.*wz(3)
if(iqq.eq.9)then
do k1=1,3
do l1=1,3
k2=k+k1-1
l2=jz+l1-1
psvin=psvin+ftoint(k2,l2,icdp,icdt,iclp)*wk(k1)*wz(l1)
enddo
enddo
psvin=exp(psvin)*z
endif
return
end
c------------------------------------------------------------------------
function psbint(q1,q2,qqcut,ss,m1,l1,jdis)
c-----------------------------------------------------------------------
c psbint - born cross-section interpolation
c q1 - virtuality cutoff at current end of the ladder;
c q2 - virtuality cutoff at opposite end of the ladder;
c qqcut - p_t cutoff for the born process;
c s - total c.m. energy squared for the scattering,
c m1 - parton type at current end of the ladder (0 - g, 1,-1,2,... - q)
c l1 - parton type at opposite end of the ladder (0 - g, 1,-1,2,... - q)
c-----------------------------------------------------------------------
dimension wi(3),wk(3)
common /psar2/ edmax,epmax
common /psar21/ csbor(20,160,2)
include 'epos.incsem'
double precision psuds
psbint=0.
if(jdis.eq.0)then
qq=max(q1,q2)
else
qq=max(q1/4.,q2)
endif
qq=max(qq,qqcut)
if(iabs(m1).ne.4)then
q2mass=0.
if(m1.ne.0.and.m1.eq.l1)then
m=2
l=2
elseif(m1.ne.0.and.m1.eq.-l1)then
m=3
l=1
elseif(m1.ne.0.and.l1.ne.0.and.m1.ne.l1)then
m=3
l=2
else
m=min(1,iabs(m1))+1
l=min(1,iabs(l1))+1
endif
else
q2mass=qcmass**2
m=4
l=min(1,iabs(l1))+1
endif
s=ss-q2mass
spmin=4.*q2min+q2mass
s2min=4.*qq+q2mass
if(s.le.s2min)return
p1=s/(1.+q2mass/s)
if(p1.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/p1))
else
tmin=2.*qq
endif
qmax=p1/4.
tmax=p1/2.
ml=20*(m-1)+80*(l-1)
qli=log(qq/q2min)/log(qmax/q2min)*19.+1.
sl=log(s/spmin)/log(epmax/2./spmin)*19.+1.
k=int(sl)
i=int(qli)
if(k.lt.1)k=1
if(i.lt.1)i=1
if(k.gt.18)k=18
if(i.gt.18)i=18
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
wk(2)=sl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
do i1=1,3
do k1=1,3
psbint=psbint+csbor(i+i1-1,k+k1+ml-1,jdis+1)
* *wi(i1)*wk(k1)
enddo
enddo
psbint=exp(psbint)*(1./tmin-1./tmax)
if(jdis.eq.0.and.qq.gt.q1)then
psbint=psbint*sngl(psuds(qq,m1)/psuds(q1,m1))
elseif(jdis.eq.1.and.4.*qq.gt.q1)then
psbint=psbint*sngl(psuds(4.*qq,m1)/psuds(q1,m1))
endif
if(qq.gt.q2)psbint=psbint*sngl(psuds(qq,l1)/psuds(q2,l1))
return
end
c-----------------------------------------------------------------------
function psborn(q1,q2,qqcut,s,j,l,jdis,md)
c-----------------------------------------------------------------------
c
c hard 2->2 parton scattering born cross-section
c including sudakov on both sides
c
c q1 - virtuality cutoff at current end of the ladder;
c q2 - virtuality cutoff at opposite end of the ladder;
c qqcut - p_t cutoff for the born process;
c s - c.m. energy squared for the scattering;
c j - parton type at current end of the ladder (0 - g, 1,2 etc. - q);
c l - parton type at opposite end of the ladder (0 - g, 1,2 etc. - q).
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
double precision sud0,psbornd,psuds
include 'epos.inc'
include 'epos.incsem'
psborn=0
if(jdis.eq.0)then
qq=max(q1,q2)
else
qq=max(q1/4.,q2)
endif
qq=max(qq,qqcut)
c if(j.ne.3)then !kkkkkkkkkk charm is 3 ???
if(j.ne.4)then
j1=j
q2mass=0.
else
j1=4
q2mass=qcmass**2
endif
p1=s/(1.+q2mass/s)
if(p1.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/p1))
else
tmin=2.*qq
! return !tmin=2.*qq !kkkkkkk !????????????? tp why not ?
endif
tmax=p1/2.
sud0=psuds(q1,j1)*psuds(q2,l)
psbornd=0.d0
do i=1,7
do m=1,2
t=2.*tmin/(1.+tmin/tmax-x1(i)*(2*m-3)
& *(1.-tmin/tmax))
qt=t*(1.-t/p1)
if(qt.lt..999*qq.and.ish.ge.1)write(ifch,*)'psborn:qt,qq,q1,q2'
& ,qq,qt,q1,q2
if(jdis.eq.0)then
scale=qt
else
scale=qt*4.
endif
if(j1.eq.0.and.l.eq.0)then
fb=ffborn(s,t, 1. , 0. , 0. , 0. , 0. ) !gg
elseif(j1*l.eq.0)then
fb=ffborn(s,t, 0. , 1. , 0. , 0. , 0.) !qg
elseif(j1.eq.l)then
fb=ffborn(s,t, 0. , 0. , 1. , 0. , 0.) !qq
elseif(j1.eq.-l)then
fb=ffborn(s,t, 0. , 0. , 0. , 1. , 0.) !qq
else
fb=ffborn(s,t, 0. , 0. , 0. , 0. , 1.) !qq
endif
fb=fb*pssalf(qt/qcdlam)**2
psbornd=psbornd+dble(a1(i)*fb)*dble(t)**2
& *psuds(scale,j1)*psuds(qt,l)
enddo
enddo
psbornd=psbornd*dble(2.*pi**3)/dble(s)**2/sud0*2
* /2 !CS for parton pair
if(md.eq.1)psbornd=psbornd*(1./tmin-1./tmax)
psborn=sngl(psbornd)
return
end
c------------------------------------------------------------------------
function psdgh(s,qq,long)
c-----------------------------------------------------------------------
c psdgh
c s - energy squared for the interaction (hadron-hadron),
c-----------------------------------------------------------------------
common/ar3/ x1(7),a1(7)
common /cnsta/ pi,pii,hquer,prom,piom,ainfin
include 'epos.incsem'
double precision psuds
xd=qq/s
if(long.eq.0)then
psdgh=(psdfh4(xd,q2min,0.,2,1)/2.25+psdfh4(xd,q2min,0.,2,2)/9.
* +psdfh4(xd,q2min,0.,2,3)/9.+
* 2.*(psdfh4(xd,q2min,0.,2,-1)+psdfh4(xd,q2min,0.,2,-2)+
* psdfh4(xd,q2min,0.,2,-3))/4.5)
* *sngl(psuds(qq,1)/psuds(q2min,1))*4.*pi**2*alfe/qq
else
psdgh=0.
endif
dgh=0.
if(long.eq.0)then
s2min=qq/(1.-q2ini/qq)
else
s2min=4.*max(q2min,qcmass**2)+qq
s2min=s2min/(1.-4.*q2ini/(s2min-qq))
endif
xmin=s2min/s
if(xmin.lt.1.)then
do i=1,7 !numerical integration over z1
do m=1,2
if(long.eq.0)then
z1=qq/s+(xmin-qq/s)*((1.-qq/s)/(xmin-qq/s))
* **(.5+(m-1.5)*x1(i))
else
z1=.5*(1.+xmin+(2*m-3)*x1(i)*(1.-xmin))
endif
call psdint(z1*s,qq,sds,sdn,sdb,sdt,sdr,1,long)
call psdint(z1*s,qq,sdsg,sdng,sdbg,sdtg,sdrg,0,long)
tu=psdfh4(z1,q2min,0.,2,1)
td=psdfh4(z1,q2min,0.,2,2)
ts=psdfh4(z1,q2min,0.,2,3)
tg=psdfh4(z1,q2min,0.,2,0)
tsea=2.*(psdfh4(z1,q2min,0.,2,-1)+psdfh4(z1,q2min,0.,2,-2)
* +psdfh4(z1,q2min,0.,2,-3))
gy=sdn*(tu/2.25+td/9.+ts/9.+tsea/4.5)+sdtg*tg/4.5
* +sdt*(tu+td+ts+tsea)/4.5
dgh=dgh+a1(i)*gy*(1.-qq/s/z1)
enddo
enddo
dgh=dgh*log((1.-qq/s)/(xmin-qq/s))*.5
endif
psdgh=psdgh+dgh
return
end
c------------------------------------------------------------------------
function psdh(s,qq,iclpro0,long)
c-----------------------------------------------------------------------
c pshard - hard quark-quark interaction cross-section
c s - energy squared for the interaction (hadron-hadron),
c iclpro0 - type of the primary hadron (nucleon)
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
include 'epos.inc'
double precision psuds
xd=qq/s
qqs=q2min
if(long.eq.0.and.(idisco.eq.0.or.idisco.eq.1))then
psdh=(psdfh4(xd,qqs,0.,iclpro0,1)/2.25+
* psdfh4(xd,qqs,0.,iclpro0,2)/9.)
* *sngl(psuds(qq,1)/psuds(qqs,1))
* *4.*pi**2*alfe/qq
else
psdh=0.
endif
dh=0.
if(long.eq.0)then
s2min=qq/(1.-q2ini/qq)
else
s2min=4.*max(q2min,qcmass**2)+qq
s2min=s2min/(1.-4.*q2ini/(s2min-qq))
endif
xmin=s2min/s
if(xmin.lt.1.)then
do i=1,7 !numerical integration over z1
do m=1,2
if(long.eq.0)then
z1=qq/s+(xmin-qq/s)*((1.-qq/s)/(xmin-qq/s))
* **(.5+(m-1.5)*x1(i))
else
z1=.5*(1.+xmin+(2*m-3)*x1(i)*(1.-xmin))
endif
call psdint(z1*s,qq,sds,sdn,sdb,sdt,sdr,1,long)
tu=psdfh4(z1,qqs,0.,iclpro0,1)
td=psdfh4(z1,qqs,0.,iclpro0,2)
gy=sdt*(tu+td)/4.5+sdn*(tu/2.25+td/9.)
if(long.eq.0)then
gy=gy*(1.-qq/s/z1)
else
gy=gy/z1
endif
dh=dh+a1(i)*gy
enddo
enddo
if(long.eq.0)then
dh=dh*log((1.-qq/s)/(xmin-qq/s))*.5
else
dh=dh*(1.-xmin)*.5
endif
endif
psdh=psdh+dh
return
end
c------------------------------------------------------------------------
function psdsh(s,qq,iclpro0,dqsh,long)
c-----------------------------------------------------------------------
c psdsh - semihard interaction eikonal
c s - energy squared for the interaction (hadron-hadron),
c iclpro0 - hadron class,
c z - impact parameter factor, z=exp(-b**2/rp),
c iqq - type of the hard interaction (0 - gg, 1 - qg, 2 - gq)
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
double precision psuds
xd=qq/s
if(long.eq.0.and.(idisco.eq.0.or.idisco.eq.1))then
dqsh=fzeroSeaZZ(xd,iclpro0)/xd**dels
* *ffrr*4.*pi*gamhad(iclpro0)/
* 4.5*sngl(psuds(qq,1)/psuds(q2min,1))
* *4.*pi**2*alfe/qq
else
dqsh=0.
endif
if(long.eq.0)then
s2min=qq/(1.-q2ini/qq)
else
s2min=qq+4.*max(q2min,qcmass**2)
endif
xmin=s2min/s
xmin=xmin**(delh-dels)
dsh=0.
if(xmin.lt.1.)then
c numerical integration over z1
do i=1,7
do m=1,2
z1=(.5*(1.+xmin-(2*m-3)*x1(i)*(1.-xmin)))**(1./
* (delh-dels))
call psdint(z1*s,qq,sdsg,sdng,sdbg,sdtg,sdrg,0,long)
call psdint(z1*s,qq,sdsq,sdnq,sdbq,sdtq,sdrq,1,long)
dsh=dsh+a1(i)/z1**delh*(sdtg*fzeroGluZZ(z1,iclpro0)
* +(sdtq+sdnq)*fzeroSeaZZ(z1,iclpro0))
enddo
enddo
dsh=dsh*(1.-xmin)/(delh-dels)/2.
endif
psdsh=dqsh+dsh*ffrr*4.*pi*gamhad(iclpro0)/4.5 !*ccorr(1,1,iclpro0)
return
end
cc------------------------------------------------------------------------
c function psdsh1(s,qq,iclpro0,dqsh,long)
cc-----------------------------------------------------------------------
cc psdsh - semihard interaction eikonal
cc s - energy squared for the interaction (hadron-hadron),
cc iclpro0 - hadron class,
cc z - impact parameter factor, z=exp(-b**2/rp),
cc iqq - type of the hard interaction (0 - gg, 1 - qg, 2 - gq)
cc-----------------------------------------------------------------------
c common /ar3/ x1(7),a1(7)
c include 'epos.inc'
c include 'epos.incsem'
cc double precision psuds
c
c psdsh1=0. !only for plotting in psaevp : not use any more
c
cc$$$ xd=qq/s
cc$$$ write(ifch,*)'Psdsh1 for xd,qq',xd,qq
cc$$$ if(long.eq.0.and.(idisco.eq.0.or.idisco.eq.1))then
cc$$$ dqsh=psftist(xd)/4.5*sngl(psuds(qq,1)/psuds(q2min,1))
cc$$$ * *4.*pi**2*alfe/qq
cc$$$ else
cc$$$ dqsh=0.
cc$$$ endif
cc$$$
cc$$$ if(long.eq.0)then
cc$$$ s2min=qq/(1.-q2ini/qq)
cc$$$ else
cc$$$ s2min=qq+4.*max(q2min,qcmass**2)
cc$$$ endif
cc$$$ xmin=s2min/s
cc$$$ xmin=xmin**(delh-dels)
cc$$$ dsh=0.
cc$$$ if(xmin.lt.1.)then
cc$$$c numerical integration over z1
cc$$$ do i=1,7
cc$$$ do m=1,2
cc$$$ z1=(.5*(1.+xmin-(2*m-3)*x1(i)*(1.-xmin)))**(1./
cc$$$ * (delh-dels))
cc$$$ call psdint(z1*s,qq,sdsg,sdng,sdbg,sdtg,sdrg,0,long)
cc$$$ call psdint(z1*s,qq,sdsq,sdnq,sdbq,sdtq,sdrq,1,long)
cc$$$ dsh=dsh+a1(i)/z1**delh*(sdtg*psftigt(z1)
cc$$$ * +(sdtq+sdnq)*psftist(z1))*z1**dels
cc$$$ enddo
cc$$$ enddo
cc$$$ dsh=dsh*(1.-xmin)/(delh-dels)/2.
cc$$$ endif
cc$$$ psdsh1=dqsh+dsh/4.5
c return
c end
c
c------------------------------------------------------------------------
function psev0(q1,qq,xx,j)
c-----------------------------------------------------------------------
double precision xx,psuds,psev00
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
psev0=0.
psev00=0.d0
do i=1,7
do m=1,2
if(j.eq.1)then !g->q
qi=2.*q1/(1.+q1/qq+(1.-q1/qq)*(2.*m-3.)*x1(i))
psev00=psev00+a1(i)*qi*psuds(qi,0)/psuds(qi,1)
* /log(qi*(1.d0-xx)/qcdlam)
else !q->g
qi=(.5*(q1+qq+(q1-qq)*(2.*m-3.)*x1(i)))
psev00=psev00+a1(i)/qi/psuds(qi,0)*psuds(qi,1)
* /log(qi*(1.d0-xx)/qcdlam)
endif
enddo
enddo
if(j.eq.1)then
psev00=psev00*(1.d0/q1-1.d0/qq)*psuds(qq,1)/psuds(qq,0)/2.d0
else
psev00=psev00*(qq-q1)*psuds(qq,0)/psuds(qq,1)/2.d0
endif
psev00=psev00/log(log(qq*(1.d0-xx)/qcdlam)
& /log(q1*(1.d0-xx)/qcdlam))
psev0=sngl(psev00)
return
end
c------------------------------------------------------------------------
function psev(q1,qq,xx,j,l,n)
c------------------------------------------------------------------------
double precision xx,zmax,zmax1,zmin,zmin1,z,psuds,fk,fq
&,fz1,fz2
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
zmax=1.d0-q2ini/qq
zmin=xx/zmax
qmax=qq
fz1=0.d0
fz2=0.d0
if(zmin.lt.zmax)then
if(zmin.lt..1d0)then
zmax1=min(.1d0,zmax)
do i=1,7
do m=1,2
if(n.eq.2)then
z=xx+(zmin-xx)*((zmax1-xx)/(zmin-xx))**(.5+(m-1.5)*x1(i))
elseif(j.eq.1)then
z=zmin*(zmax1/zmin)**(.5+(m-1.5)*x1(i))
else
z=(.5d0*(zmax1+zmin+(zmax1-zmin)*(2*m-3)*x1(i)))
endif
qmin=max(q2ini/(1.d0-xx/z),q2ini/(1.d0-z))
qmin=max(qmin,q1)
do k=1,2
fq=0.d0
do i1=1,7
do m1=1,2
if(n.eq.2)then
qi=qmin*(qmax/qmin)**(.5+x1(i1)*(m1-1.5))
else
qi=(.5*(qmax+qmin+(qmax-qmin)*(2.*m1-3.)*x1(i1)))
endif
if(j.eq.3.and.k.eq.1)then
fk=0.d0
else
if(n.eq.2)then
fk=dble(psevi0(q1,qi,xx/z,min(2,j),k))
else
fk=dble(psevi(q1,qi,xx/z,j,k)/qi)
endif
endif
qt=qi*(1.d0-z)
fq=fq+a1(i1)*fk/psuds(qi,l-1)*pssalf(qt/qcdlam)
enddo
enddo
if(n.eq.2)then
fq=fq*log(qmax/qmin)*(1.d0-xx/z)
elseif(j.eq.1)then
fq=fq*(qmax-qmin)
else
fq=fq*(qmax-qmin)/z
endif
fz1=fz1+a1(i)*fq*psfap(z,k-1,l-1)
enddo
enddo
enddo
if(n.eq.2)then
fz1=fz1*log((zmax1-xx)/(zmin-xx))/4.
elseif(j.eq.1)then
fz1=fz1*log(zmax1/zmin)/4.
else
fz1=fz1*(zmax1-zmin)/4.
endif
endif
if(zmax.gt..1d0)then
zmin1=max(.1d0,zmin)
do i=1,7
do m=1,2
z=1.d0-(1.d0-zmax)*((1.d0-zmin1)/(1.d0-zmax))**
* (.5+x1(i)*(m-1.5))
qmin=max(q2ini/(1.d0-z),q2ini/(1.d0-xx/z))
qmin=max(qmin,q1)
do k=1,2
fq=0.
do i1=1,7
do m1=1,2
if(n.eq.2)then
qi=qmin*(qmax/qmin)**(.5+x1(i1)*(m1-1.5))
else
qi=(.5*(qmax+qmin+(qmax-qmin)*(2.*m1-3.)*x1(i1)))
endif
if(j.eq.3.and.k.eq.1)then
fk=0.d0
else
if(n.eq.2)then
fk=dble(psevi0(q1,qi,xx/z,min(2,j),k))
else
fk=dble(psevi(q1,qi,xx/z,j,k)/qi)
endif
endif
qt=qi*(1.d0-z)
fq=fq+a1(i1)*fk/psuds(qi,l-1)*pssalf(qt/qcdlam)
enddo
enddo
if(n.eq.2)then
fq=fq*log(qmax/qmin)
else
fq=fq*(qmax-qmin)
endif
fz2=fz2+a1(i)*fq*psfap(z,k-1,l-1)*(1.d0/z-1.d0)
enddo
enddo
enddo
fz2=fz2*log((1.d0-zmin1)/(1.d0-zmax))/4.
endif
endif
psev=sngl((fz1+fz2)*psuds(qq,l-1))
return
end
c------------------------------------------------------------------------
function psevi0(q1,qq,xx,m,l)
c------------------------------------------------------------------------
double precision xx,xmax,psuds
dimension wi(3),wj(3),wk(3)
common /psar2/ edmax,epmax
common /psar31/ evk0(21,21,54)
include 'epos.inc'
include 'epos.incsem'
xmax=1.d0-2.d0*q2ini/epmax
qmin=max(1.d0*q2min,q2ini/(1.d0-xx))
qm1=max(q1,qmin)
if(qq.gt..5001*epmax.and.ish.ge.1)then
write(ifch,*)'0-extrap.:q1,qq,epmax,xx,m,l:',q1,qq,epmax,xx,m,l
c stop
endif
if(xx.ge.xmax.or.qq.le.1.000*qm1)then
psevi0=0.
c write (*,*)'xx,xmax,qq,qm1,qmin,q1',xx,xmax,qq,qm1,qmin,q1
return
endif
if(m.eq.l)then
psevi0=1.
else
if(xx.lt..1d0)then
yx=log(10.d0*xx)+13.
k=int(yx)
if(k.gt.11)k=11
if(k.lt.1)k=1
elseif(xx.lt..9d0)then
yx=10.*xx+12.
k=int(yx)
if(k.gt.19)k=19
else
yx=log(10.d0*(1.d0-xx))/log(10.d0*(1.d0-xmax))*6.+21
k=int(yx)
if(k.gt.25)k=25
endif
wk(2)=yx-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
qli=log(qq/qmin)/log(.5*epmax/qmin)*20.+1.
qlj=log(qm1/qmin)/log(qq/qmin)*20.+1.
i=int(qli)
if(i.gt.19)i=19
if(i.lt.1)i=1
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
j=int(qlj)
if(j.lt.1)j=1
if(j.gt.19)j=19
wj(2)=qlj-j
wj(3)=wj(2)*(wj(2)-1.)*.5
wj(1)=1.-wj(2)+wj(3)
wj(2)=wj(2)-2.*wj(3)
psevi0=0.
do i1=1,3
do j1=1,3
do k1=1,3
psevi0=psevi0+evk0(i+i1-1,j+j1-1,k+k1-1+27*(m-1))
* *wi(i1)*wj(j1)*wk(k1)
enddo
enddo
enddo
psevi0=exp(psevi0)
endif
psevi0=psevi0*psfap(xx,m-1,l-1)*log(log(qq*(1.d0-xx)/qcdlam)
*/log(qm1*(1.d0-xx)/qcdlam))*sngl(psuds(qq,m-1)/psuds(q1,m-1))/4.5
return
end
c------------------------------------------------------------------------
function psevi(q1,qq,xx,m,l)
c------------------------------------------------------------------------
c m l: 1 1 ... gluon -> gluon
c 2 1 ... quark -> gluon
c 1 2 ... gluon -> quark
c 3 2 ... quark -> quark non singlet
c 2 2 ... quark -> quark all
c singlet = all - non singlet
c-----------------------------------------------------------------------
double precision xx,xmax,psuds
dimension wi(3),wj(3),wk(3)
common /psar2/ edmax,epmax
common /psar32/ evk(21,21,135)
include 'epos.inc'
include 'epos.incsem'
psevi=0.
xmax=1.d0-2.d0*q2ini/epmax
if(qq.gt..5001*epmax.and.ish.ge.1)then
write(ifch,*)'1-extrap.:q1,qq,epmax,xx,m,l:',q1,qq,epmax,xx,m,l
c stop
endif
qmin=max(1.d0*q2min,q2ini/(1.d0-xx))
qm1=max(q1,qmin)
if(xx.ge.xmax.or.qq.le.1.0001*qm1)then
return
endif
qmin1=max(1.d0*qmin,q2ini/(1.d0-dsqrt(xx)))
if(qq.le.1.0001*qmin1)then
psevi=psevi0(q1,qq,xx,min(m,2),l)
return
endif
if(xx.lt..1d0)then
yx=log(10.d0*xx)+13.
k=int(yx)
if(k.gt.11)k=11
if(k.lt.1)k=1
elseif(xx.lt..9d0)then
yx=10.*xx+12.
k=int(yx)
if(k.gt.19)k=19
else
yx=log(10.d0*(1.d0-xx))/log(10.d0*(1.d0-xmax))*6.+21
k=int(yx)
if(k.gt.25)k=25
endif
wk(2)=yx-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
qli=log(qq/qmin)/log(.5*epmax/qmin)*20.+1.
qlj=log(qm1/qmin)/log(qq/qmin)*20.+1.
i=int(qli)
if(i.lt.1)i=1
if(i.gt.19)i=19
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
j=int(qlj)
if(j.lt.1)j=1
if(j.gt.19)j=19
wj(2)=qlj-j
wj(3)=wj(2)*(wj(2)-1.)*.5
wj(1)=1.-wj(2)+wj(3)
wj(2)=wj(2)-2.*wj(3)
do i1=1,3
do j1=1,3
do k1=1,3
if(m.eq.3)then
k2=k+k1-1+108
else
k2=k+k1-1+27*(m-1)+54*(l-1)
endif
psevi=psevi+evk(i+i1-1,j+j1-1,k2)
* *wi(i1)*wj(j1)*wk(k1)
enddo
enddo
enddo
psevi=exp(psevi)*psfap(xx,m-1,l-1)*log(log(qq*(1.d0-xx)/qcdlam)
*/log(qm1*(1.d0-xx)/qcdlam))/4.5
if(q1.lt.qm1)psevi=psevi*sngl(psuds(qm1,m-1)/psuds(q1,m-1))
return
end
c------------------------------------------------------------------------
function psjci(q1,s,l1)
c-----------------------------------------------------------------------
c psjci - inclusive ordered ladder cross-section interpolation for c-quark
c q1 - virtuality cutoff at current end of the ladder
c s - total c.m. energy squared for the ladder,
c l1 - parton type at current end of the ladder (0-g, 1,2,etc.-q)
c-----------------------------------------------------------------------
dimension wi(3),wk(3)
common /psar2/ edmax,epmax
common /psar23/ cschar(20,20,2)
include 'epos.incsem'
psjci=0.
q2mass=qcmass**2
spmin=4.*q2min+q2mass
qq=q1
s2min=4.*qq+q2mass
if(s.le.s2min)return
smins=s2min/(1.-q2ini/q1)
c if(s.le.smins)goto 1
if(s.le.smins.or.qq.le.q2min)goto 1 !??????? ctp070618
p1=s/(1.+q2mass/s)
if(p1.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/p1))
else
tmin=2.*qq
endif
tmax=p1/2.
qmax=p1/4.
l=min(1,iabs(l1))+1
qli=log(qq/q2min)/log(qmax/q2min)*19.+1.
sl=log(s/spmin)/log(epmax/2./spmin)*19.+1.
k=int(sl)
i=int(qli)
if(i.lt.1)i=1
if(k.gt.18)k=18
if(i.gt.18)i=18
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
wk(2)=sl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
do i1=1,3
do k1=1,3
psjci=psjci+cschar(i+i1-1,k+k1-1,l)*wi(i1)*wk(k1)
enddo
enddo
psjci=exp(psjci)*(1./tmin-1./tmax)
return
1 psjci=psbint(q2min,q1,0.,s,4,l1,0)
return
end
c-----------------------------------------------------------------------
function psjct(s,l)
c-----------------------------------------------------------------------
c psjct - unordered ladder cross-section for c-quark
c s - c.m. energy squared for the scattering;
c l - parton type at opposite end of the ladder (0 - g, 1,2 etc. - q).
c-----------------------------------------------------------------------
double precision xx,zmax,qmax,qmin,qi,zmin,fsj,z,s2,sj
common /ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
psjct=0.
q2mass=qcmass**2
zmax=dble(s)/(dble(s)+dble(5.*q2mass))
qmax=zmax**2*dble(q2mass)/(1.d0-zmax)
qmin=dble(q2min)
if(qmax.lt.qmin.and.ish.ge.1)write(ifch,*)'psjct:qmin,qmax'
* ,qmin,qmax
do i=1,7
do m=1,2
qi=2.d0*qmin/(1.d0+qmin/qmax+dble((2*m-3)*x1(i))
* *(1.d0-qmin/qmax))
zmax=(2.d0/(1.d0+dsqrt(1.d0+4.d0*dble(q2mass)/qi)))**delh
zmin=(5.d0*qi/dble(s))**delh
fsj=0.d0
if(zmax.lt.zmin.and.ish.ge.1)write(ifch,*)'psjct:zmin,zmax'
* ,zmin,zmax
do i1=1,7
do m1=1,2
z=(.5d0*(zmax+zmin+dble((2*m1-3)*x1(i1))
* *(zmax-zmin)))**(1./delh)
s2=z*dble(s)-qi
xx=z
sj=dble(psjti(sngl(qi),q2min,sngl(s2),0,l,0)*psfap(xx,1,0))*z
fsj=fsj+dble(a1(i1))*sj*dble(pssalf(sngl(qi)/qcdlam))/z**delh
enddo
enddo
fsj=fsj*(zmax-zmin)
psjct=psjct+a1(i)*sngl(fsj*qi)
enddo
enddo
psjct=psjct*sngl(1./qmin-1./qmax)/delh/4.
return
end
c------------------------------------------------------------------------
function psjet1(q1,q2,qqcut,s,j,l,jdis)
c-----------------------------------------------------------------------
c psjet1 - ordered parton ladder cross-section
c q1 - virtuality cutoff at current end of the ladder;
c q2 - virtuality cutoff at opposite end of the ladder;
c qqcut - p_t cutoff for the born process;
c s - c.m. energy squared for the scattering;
c j - parton type at current end of the ladder (0 - g, 1,2 etc. - q);
c l - parton type at opposite end of the ladder (0 - g, 1,2 etc. - q).
c-----------------------------------------------------------------------
double precision xx,z,qq,xmax,xmin,s2min,smin,p1,q2ms,q2inis,xmin1
*,sh,qtmin,t,xmax1,fx1,fx2,psuds
common /ar3/ x1(7),a1(7)
common /ar9/ x9(3),a9(3)
include 'epos.inc'
include 'epos.incsem'
psjet1=0.
if(jdis.eq.0)then
qq=dble(max(q1,q2))
elseif(jdis.eq.1)then
qq=dble(max(q1/4.,q2))
else
qq=dble(max(q1,q2/4.))
endif
qq=max(qq,dble(qqcut))
if(l.ne.3)then
q2mass=0.
else
q2mass=qcmass**2
endif
s2min=dble(q2mass)+4.d0*qq
if(jdis.eq.0.or.jdis.eq.2)then
smin=s2min/(1.d0-dble(q2ini)/qq)
else
smin=s2min/(1.d0-dble(q2ini)/qq/4.d0)
endif
if(dble(s).le.smin)return
q2ms=dble(q2mass)/dble(s)
q2inis=dble(q2ini)/dble(s)
p1=dble(s)/(1.d0+q2ms)
if(jdis.eq.0.or.jdis.eq.2)then
xmax=.5d0*(1.d0+q2ms)+dsqrt(.25d0*(1.d0-q2ms)**2-4.d0*q2inis)
else
xmax=.5d0*(1.+q2ms)+dsqrt(.25d0*(1.-q2ms)**2-q2inis)
endif
xmin=max(1.d0+q2ms-xmax,s2min/dble(s))
if(xmin.ge.xmax.and.ish.ge.1)then
write(ifch,*)'jti1,xmin,xmax',xmin,xmax
c return
endif
fx1=0.d0
fx2=0.d0
if(xmax.gt..8d0)then
xmin1=max(xmin,.8d0)
do i=1,3
do m=1,2
z=1.d0-(1.d0-xmax)*((1.d0-xmin1)/(1.d0-xmax))**
* (.5d0+dble(x9(i)*(m-1.5)))
sh=z*dble(s)
xx=z
p1=sh/(1.d0+dble(q2mass)/sh)
if(jdis.eq.0.or.jdis.eq.2)then
qtmin=max(qq,dble(q2ini)/(1.d0-z))
else
qtmin=max(qq,dble(q2ini)/(1.d0-z)/4.d0)
endif
tmin=2.d0*dble(qtmin)/(1.d0+dsqrt(1.d0-4.d0*dble(qtmin)/p1))
tmax=p1/2.d0
ft=0.
if(tmin.ge.tmax.and.ish.ge.1)write(ifch,*)'psjet1:tmin,tmax'
* ,tmin,tmax
do i1=1,3
do m1=1,2
t=2.d0*tmin/(1.d0+tmin/tmax-dble(x9(i1)*(2*m1-3))
& *(1.d0-tmin/tmax))
qt=sngl(t*(1.d0-t/p1))
c if(qt.lt.qtmin)write (*,*)'psjet1:qt,qq',qt,qq
if(jdis.eq.0)then
scale1=qt
scale2=qt
elseif(jdis.eq.1)then
scale1=qt*4.
scale2=qt
elseif(jdis.eq.2)then
scale1=qt
scale2=qt*4.
endif
fb=0.
do n=1,3
fb=fb+psjetj(q1,scale1,sngl(t),xx,sngl(sh),j,l,n)
enddo
ft=ft+a9(i1)*fb*pssalf(qt/qcdlam)**2*sngl(t**2
* *psuds(scale2,l))
enddo
enddo
fx1=fx1+dble(a9(i)*ft)*(1.d0/tmin-1.d0/tmax)/sh**2*(1.d0-z)
enddo
enddo
fx1=fx1*dlog((1.d0-xmin1)/(1.d0-xmax))
endif
if(xmin.lt..8d0)then
xmax1=min(xmax,.8d0)**(-delh)
xmin1=xmin**(-delh)
do i=1,3
do m=1,2
z=(.5d0*(xmax1+xmin1+(xmin1-xmax1)*dble((2*m-3)*x9(i))))
* **(-1./delh)
sh=z*dble(s)
xx=z
p1=sh/(1.d0+dble(q2mass)/sh)
if(jdis.eq.0.or.jdis.eq.2)then
qtmin=max(qq,dble(q2ini)/(1.d0-z))
else
qtmin=max(qq,dble(q2ini)/(1.d0-z)/4.d0)
endif
tmin=2.d0*dble(qtmin)/(1.d0+dsqrt(1.d0-4.d0*dble(qtmin)/p1))
tmax=p1/2.d0
ft=0.
if(tmin.ge.tmax.and.ish.ge.1)write(ifch,*)'psjet1:tmin,tmax'
& ,tmin,tmax
do i1=1,3
do m1=1,2
t=2.d0*tmin/(1.d0+tmin/tmax-dble(x9(i1)*(2*m1-3))
& *(1.d0-tmin/tmax))
qt=sngl(t*(1.d0-t/p1))
if(qt.lt.sngl(qtmin).and.ish.ge.1)write(ifch,*)'psjet1:qt,qq'
& ,qt,qq
if(jdis.eq.0)then
scale1=qt
scale2=qt
elseif(jdis.eq.1)then
scale1=qt*4.
scale2=qt
elseif(jdis.eq.2)then
scale1=qt
scale2=qt*4.
endif
fb=0.
do n=1,3
fb=fb+psjetj(q1,scale1,sngl(t),xx,sngl(sh),j,l,n)
enddo
ft=ft+a9(i1)*fb*pssalf(qt/qcdlam)**2*sngl(t**2
* *psuds(scale2,l))
enddo
enddo
fx2=fx2+dble(a9(i)*ft)*(1.d0/tmin-1.d0/tmax)/sh**2*z**(1.+delh)
enddo
enddo
fx2=fx2*(xmin1-xmax1)/dble(delh)
endif
psjet1=sngl((fx1+fx2)/psuds(q2,l))*pi**3*2
* /2 !CS for parton pair
return
end
c-----------------------------------------------------------------------
function psjet(q1,q2,qqcut,s,j,l,jdis)
c-----------------------------------------------------------------------
c parton ladder cross-section
c with at least one emission on each side
c
c q1 - virtuality cutoff at current end of the ladder;
c q2 - virtuality cutoff at opposite end of the ladder;
c qqcut - p_t cutoff for the born process;
c s - c.m. energy squared for the scattering;
c j - parton type at current end of the ladder (0 - g, 1,2 etc. - q);
c l - parton type at opposite end of the ladder (0 - g, 1,2 etc. - q).
c-----------------------------------------------------------------------
double precision xx1,xx2,qq,s2min,xmin,xmax,xmin1,xmax1,t,tmin
*,tmax,sh,z,qtmin,ft,fx1,fx2
common /ar3/ x1(7),a1(7)
common /ar9/ x9(3),a9(3)
include 'epos.inc'
include 'epos.incsem'
common/ccctest/iiitest
iiitest=0
psjet=0.
if(jdis.eq.0)then
qq=dble(max(q1,q2))
else
qq=dble(max(q1/4.,q2))
endif
qq=max(qq,dble(qqcut))
s2min=4.d0*qq
if(dble(s).le.s2min/(1.d0-dble(q2ini)/qq)**2)return !kkkkkkk
phi=acos(1.-54.*q2ini/s)/3.
zmax=(1.+2.*cos(phi))**2/9. !kkkkkkk
zmin=(1.-cos(phi)+sqrt(3.d0)*sin(phi))/3. !kkkkkkk
zmin=max(zmin**2,sngl(s2min/dble(s)))
if(zmin.gt.zmax.and.ish.ge.1)write(ifch,*)'psjet:zmin,zmax'
* ,zmin,zmax
zmin=zmin**(-delh)
zmax=zmax**(-delh)
do i=1,3
do m=1,2
z=dble(.5*(zmax+zmin+(zmin-zmax)*(2*m-3)*x9(i)))**(-1./delh)
xmin=dsqrt(z)
sh=z*dble(s)
qtmin=max(qq,dble(q2ini)/(1.d0-dsqrt(z)))
tmin=max(0.d0,1.d0-4.d0*qtmin/sh)
tmin=2.d0*qtmin/(1.d0+dsqrt(tmin)) !kkkkkkk
tmax=sh/2.d0
ft=0.d0
c if(tmin.gt.tmax)write (*,*)'psjet:tmin,tmax',tmin,tmax
do i1=1,3
do m1=1,2
t=2.d0*tmin/(1.d0+tmin/tmax-dble(x9(i1)*(2*m1-3))
& *(1.d0-tmin/tmax))
qt=t*(1.d0-t/sh)
c if(qt.lt.qtmin)write (*,*)'psjet:qt,qq',qt,qq
xmax=1.d0-q2ini/qt
xmin=max(dsqrt(z),z/xmax) !xm>xp !!!
if(xmin.gt.xmax.and.ish.ge.1)write(ifch,*)'psjet:xmin,xmax'
* ,xmin,xmax
fx1=0.d0
fx2=0.d0
if(xmax.gt..8d0)then
xmin1=max(xmin,.8d0)
do i2=1,3
do m2=1,2
xx1=1.d0-(1.d0-xmax)*((1.d0-xmin1)/(1.d0-xmax))**
* dble(.5+x9(i2)*(m2-1.5))
xx2=z/xx1
fb=0.
fb=fb+psjeti(q1,q2,qt,sngl(t),xx1,xx2,sngl(sh)
* ,j,l,jdis)
* +psjeti(q1,q2,qt,sngl(t),xx2,xx1,sngl(sh)
* ,j,l,jdis)
fx1=fx1+dble(a9(i2)*fb)*(1.d0/xx1-1.d0)
* *pssalf(qt/qcdlam)**2
enddo
enddo
fx1=fx1*dlog((1.d0-xmin1)/(1.d0-xmax))
endif
if(xmin.lt..8d0)then
xmax1=min(xmax,.8d0)
do i2=1,3
do m2=1,2
xx1=xmin*(xmax1/xmin)**dble(.5+x9(i2)*(m2-1.5))
xx2=z/xx1
fb=0.
fb=fb+psjeti(q1,q2,qt,sngl(t),xx1,xx2,sngl(sh)
* ,j,l,jdis)
* +psjeti(q1,q2,qt,sngl(t),xx2,xx1,sngl(sh)
* ,j,l,jdis)
fx2=fx2+dble(a9(i2))*fb*pssalf(qt/qcdlam)**2
enddo
enddo
fx2=fx2*dlog(xmax1/xmin)
endif
ft=ft+dble(a9(i1))*(fx1+fx2)*t**2
enddo
enddo
ft=ft*(1.d0/tmin-1.d0/tmax)
psjet=psjet+a9(i)*sngl(ft*z**(1.+delh)/sh**2)
enddo
enddo
psjet=psjet*(zmin-zmax)/delh*pi**3
* /2. !CS for parton pair
return
end
c-----------------------------------------------------------------------
function pijet(ii,qi,qq,sk,m1,l1) !polynomial interpol of jet CS
c-----------------------------------------------------------------------
c ii ..... type of CS (2 = bothside, 1 = oneside, 0 = no emission, Born)
c qi ..... virtuality cutoff at current end of the ladder
c qq ..... virtuality cutoff of Born
c sk ..... energy squared for the scattering
c m1,l1 .. parton types
c-----------------------------------------------------------------------
include 'epos.incsem'
common/psar2/edmax,epmax
common/tabcsjet/ksmax,iqmax,jqmax,csjet(0:2,2,20,20,20,3,2)
real wi(3),wj(3),wk(3)
common/cpijet/npijet
data npijet/0/
npijet=npijet+1
if(npijet.eq.1)call MakeCSTable
if(m1.ne.0.and.m1.eq.l1)then
m=2
l=2
elseif(m1.ne.0.and.m1.eq.-l1)then
m=3
l=1
elseif(m1.ne.0.and.l1.ne.0.and.m1.ne.l1)then
m=3
l=2
else
m=min(1,iabs(m1))+1
l=min(1,iabs(l1))+1
endif
qqmin=min(qi,qq)
qmax=sk/4.
spmin=4.*q2min
spmed=spmin*(epmax/2./spmin)**(1./(ksmax-1.))
if(sk.le.spmed)then
kk=2
spmax=spmed
else
kk=1
spmax=epmax/2.
endif
qli=1.+log(qi/q2min)/log(qmax/q2min)*(iqmax-1)
qlj=1.+log(qq/qqmin)/log(qmax/qqmin)*(jqmax-1)
sl= 1.+log(sk/spmin)/log(spmax/spmin)*(ksmax-1)
k=int(sl)
i=int(qli)
j=int(qlj)
if(k.lt.1)k=1
if(j.lt.1)j=1
if(i.lt.1)i=1
if(k.gt.(ksmax-2))k=ksmax-2
if(i.gt.(iqmax-2))i=iqmax-2
if(j.gt.(jqmax-2))j=jqmax-2
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
wj(2)=qlj-j
wj(3)=wj(2)*(wj(2)-1.)*.5
wj(1)=1.-wj(2)+wj(3)
wj(2)=wj(2)-2.*wj(3)
wk(2)=sl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
pijet=0
do i1=1,3
do j1=1,3
do k1=1,3
pijet=pijet+csjet(ii,kk,k+k1-1,i+i1-1,j+j1-1,m,l)
* *wi(i1)*wj(j1)*wk(k1)
enddo
enddo
enddo
! if(ii.eq.2)print*,' '
! write(*,'(i2,f6.0,i2,3x,3(2f5.2,2x),f5.2)')
!* ii,sk,k,(wk(kk1),csjet(ii,kk,k+kk1-1,1,1,m,l),kk1=1,3) ,pijet
end
c-----------------------------------------------------------------------
subroutine MakeCSTable !tabulates psjet
c-----------------------------------------------------------------------
c last two indices of table: parton types
c 1 1 ... gg
c 1 2 ... gq
c 2 1 ... qg
c 2 2 ... qq
c 3 1 ... qa
c 3 2 ... qq'
c-----------------------------------------------------------------------
include 'epos.incsem'
common/psar2/edmax,epmax
common/tabcsjet/ksmax,iqmax,jqmax,csjet(0:2,2,20,20,20,3,2)
write (*,'(a,$)')'(CS table'
ksmax=10
iqmax=3
jqmax=3
spmin=4.*q2min
do kk=1,2
if(kk.eq.1)then
spmax=epmax/2.
else !if(kk.eq.2)
spmax=spmin*(epmax/2./spmin)**(1./(ksmax-1.))
endif
do m=1,3 !parton type at upper end of the ladder
write (*,'(a,$)')'.'
do l=1,2 !parton type at lower end of the ladder
m1=m-1
l1=l-1
if(m.eq.3.and.l.eq.1)l1=-m1
do k=1,ksmax
sk=spmin*(spmax/spmin)**((k-1.)/(ksmax-1.))
qmax=sk/4.
do i=1,iqmax
qi=q2min*(qmax/q2min)**((i-1.)/(iqmax-1.))
do j=1,jqmax
qq=qi*(qmax/qi)**((j-1.)/(jqmax-1.))
!write(*,'(i3,4f8.3,2i4,$)')j, qi,q2min,qq,sk,m1,l1
csjet(2,kk,k,i,j,m,l)= psjet(qi,q2min,qq,sk,m1,l1,0)
csjet(1,kk,k,i,j,m,l)=psjet1(qi,q2min,qq,sk,m1,l1,0)
csjet(0,kk,k,i,j,m,l)=psborn(qi,q2min,qq,sk,m1,l1,0,1)
! if(i.eq.1.and.j.eq.1.and.m.eq.1.and.l.eq.1)
! *write(*,'(2f8.2,f13.2,2i3,3x,i3,3f8.3)')
! * qi,qq,sk,m1,l1,k,csjet(2,kk,k,i,j,m,l)
! * ,csjet(1,kk,k,i,j,m,l),csjet(0,kk,k,i,j,m,l)
enddo
enddo
enddo
enddo
enddo
enddo
write (*,'(a,$)')'done)'
end
c-----------------------------------------------------------------------
function psjeti(q1,q2,qt,t,xx1,xx2,s,j,l,jdis)
c-----------------------------------------------------------------------
c
c E~qcd_ji * E~qcd_lk * B_ik
c
c B_ik = psbori = contribution to Born xsection:
c dsigmaBorn/d2pt/dy
c = s/pi * delta(s+t+u) * 2*pi*alpha**2 /s**2 * B_ik
c
c E~qcd: at least one emission
c
c q1 - virtuality cutoff at current end of the ladder
c q2 - virtuality cutoff at opposite end of the ladder
c xx1 - feinman x for the first parton for the born process
c xx2 - feinman x for the second parton for the born process
c s - c.m. energy squared for the born scattering
c t - invariant variable for the scattering |(p1-p3)**2|,
c j - parton type at current end of the ladder (0 - g, 1,-1,2,... - q)
c l - parton type at opposite end of the ladder (0 - g, 1,-1,2,... - q)
c-----------------------------------------------------------------------
c reminder
c psevi: 1 1 ... gluon -> gluon
c 2 1 ... quark -> gluon
c 1 2 ... gluon -> quark
c 3 2 ... quark -> quark non singlet
c 2 2 ... quark -> quark all
c singlet = all - non singlet
c-----------------------------------------------------------------------
double precision xx1,xx2
include 'epos.incsem'
common/ccctest/iiitest
if(jdis.eq.0)then
scale=qt
else
scale=qt*4.
endif
if(j.eq.0.and.l.eq.0)then ! gluon-gluon --->
akg1=psevi(q1,scale,xx1,1,1) !gluon contribution
akg2=psevi(q2,qt,xx2,1,1) !gluon contribution
aks1=psevi(q1,scale,xx1,1,2)/naflav/2. !singlet contribution per quark
aks2=psevi(q2,qt,xx2,1,2)/naflav/2. !singlet contribution per quark
psjeti=ffborn(s,t,akg1*akg2
* ,(akg1*aks2+aks1*akg2)*naflav*2. !ccccc
* ,aks1*aks2*naflav*2.
* ,aks1*aks2*naflav*2.
* ,aks1*aks2*naflav*2.*(naflav-1)*2.
*)
elseif(j.eq.0)then ! gluon-quark --->
akg1=psevi(q1,scale,xx1,1,1) !gluon contribution
akg2=psevi(q2,qt,xx2,2,1) !gluon contribution
aks1=psevi(q1,scale,xx1,1,2)/naflav/2. !singlet contribution
akns2=psevi(q2,qt,xx2,3,2) !nonsinglet contribution
aks2=(psevi(q2,qt,xx2,2,2)-akns2)/naflav/2. !singlet contribution
psjeti=ffborn(s,t,akg1*akg2
* ,(akg1*(akns2+aks2*naflav*2.)+aks1*akg2*naflav*2.)
* ,aks1*(akns2+aks2*naflav*2.)
* ,aks1*(akns2+aks2*naflav*2.)
* ,aks1*(akns2+aks2*naflav*2.)*(naflav-1)*2.)
elseif(l.eq.0)then ! quark-gluon --->
akg1=psevi(q1,scale,xx1,2,1) !gluon contribution
akg2=psevi(q2,qt,xx2,1,1) !gluon contribution
akns1=psevi(q1,scale,xx1,3,2) !nonsinglet contribution
aks1=(psevi(q1,scale,xx1,2,2)-akns1)/naflav/2. !singlet contribution
aks2=psevi(q2,qt,xx2,1,2)/naflav/2. !singlet contribution
psjeti=ffborn(s,t,akg1*akg2
* ,(akg2*(akns1+aks1*naflav*2.)+aks2*akg1*naflav*2.)
* ,aks2*(akns1+aks1*naflav*2.)
* ,aks2*(akns1+aks1*naflav*2.)
* ,aks2*(akns1+aks1*naflav*2.)*(naflav-1)*2.)
else ! quark-quark --->
akg1=psevi(q1,scale,xx1,2,1) !gluon contribution
akg2=psevi(q2,qt,xx2,2,1) !gluon contribution
akns1=psevi(q1,scale,xx1,3,2) !nonsinglet contribution
aks1=(psevi(q1,scale,xx1,2,2)-akns1)/naflav/2.!singlet contribution
akns2=psevi(q2,qt,xx2,3,2) !nonsinglet contribution
aks2=(psevi(q2,qt,xx2,2,2)-akns2)/naflav/2.!singlet contribution
if(j.eq.l)then
psjeti=ffborn(s,t,akg1*akg2
* ,(akg2*(akns1+aks1*naflav*2.)+akg1*(akns2+aks2*naflav*2.))
* ,((akns1+aks1)*(akns2+aks2)+aks1*aks2*(2.*naflav-1.))
* ,(akns1*aks2+akns2*aks1+aks1*aks2*naflav*2.)
* ,(akns1*aks2+akns2*aks1+aks1*aks2*naflav*2.)*(naflav-1)*2.)
elseif(j.eq.-l)then
psjeti=ffborn(s,t,akg1*akg2
* ,(akg2*(akns1+aks1*naflav*2.)+akg1*(akns2+aks2*naflav*2.))
* ,(akns1*aks2+akns2*aks1+aks1*aks2*naflav*2.)
* ,((akns1+aks1)*(akns2+aks2)+aks1*aks2*(2.*naflav-1.))
* ,(akns1*aks2+akns2*aks1+aks1*aks2*naflav*2.)*(naflav-1)*2.)
else !j.ne.l,-l
psjeti=ffborn(s,t,akg1*akg2
* ,(akg2*(akns1+aks1*naflav*2.)+akg1*(akns2+aks2*naflav*2.))
* ,(akns1*aks2+akns2*aks1+aks1*aks2*naflav*2.)
* ,(akns1*aks2+akns2*aks1+aks1*aks2*naflav*2.)
* ,(akns1*akns2+akns1*aks2*(naflav-1)*2.
* +akns2*aks1*(naflav-1)*2.+aks1*aks2*naflav*2.*(naflav-1)*2.))
endif
endif
return
end
c-----------------------------------------------------------------------
function psjetj(q1,scale,t,xx,s,j,l,n)
c-----------------------------------------------------------------------
c psjetj - integrand for the ordered ladder cross-section
c q1 - virtuality cutoff at current end of the ladder,
c scale - born process scale,
c t - invariant variable for the scattering |(p1-p3)**2|,
c xx - feinman x for the first parton for the born process
c s - c.m. energy squared for the born scattering,
c j - parton type at current end of the ladder (0 - g, 1,-1,2,... - q)
c l - parton type at opposite end of the ladder (0 - g, 1,-1,2,... - q)
c n - subprocess number
c-----------------------------------------------------------------------
double precision xx
include 'epos.incsem'
m=min(1,iabs(j))+1
if(l.ne.3)then
if(l.eq.0)then
psjetj=psevi(q1,scale,xx,m,1)*(psbori(s,t,0,0,n)+ !gg
* psbori(s,s-t,0,0,n))/2.
* +psevi(q1,scale,xx,m,2)*(psbori(s,t,1,0,n)+ !qg
* psbori(s,s-t,1,0,n))
elseif(j.eq.0)then
aks=psevi(q1,scale,xx,1,2)/naflav/2. !singlet contribution per quark
psjetj=psevi(q1,scale,xx,1,1)*(psbori(s,t,0,1,n)+ !gq
* psbori(s,s-t,0,1,n))
* +aks*(psbori(s,t,1,1,n)+psbori(s,s-t,1,1,n))/2. !qq
* +aks*(psbori(s,t,-1,1,n)+psbori(s,s-t,-1,1,n)) !qq~
* +aks*(psbori(s,t,1,2,n)+psbori(s,s-t,1,2,n))*(naflav-1)*2. !qq'
else
akg=psevi(q1,scale,xx,2,1) !gluon contribution
akns=psevi(q1,scale,xx,3,2) !nonsinglet contribution
aks=(psevi(q1,scale,xx,2,2)-akns)/naflav/2. !singlet contribution
if(j.eq.l)then
psjetj=akg*(psbori(s,t,0,1,n)+psbori(s,s-t,0,1,n)) !gq
* +(akns+aks)*(psbori(s,t,1,1,n)+psbori(s,s-t,1,1,n))/2. !qq
* +aks*(psbori(s,t,-1,1,n)+psbori(s,s-t,-1,1,n)) !qq~
* +aks*(psbori(s,t,1,2,n)+psbori(s,s-t,1,2,n))*(naflav-1)*2. !qq'
elseif(j.eq.-l)then
psjetj=akg*(psbori(s,t,0,1,n)+psbori(s,s-t,0,1,n)) !gq
* +aks*(psbori(s,t,1,1,n)+psbori(s,s-t,1,1,n))/2. !qq
* +(akns+aks)*(psbori(s,t,-1,1,n)+psbori(s,s-t,-1,1,n)) !qq~
* +aks*(psbori(s,t,1,2,n)+psbori(s,s-t,1,2,n))*(naflav-1)*2.!qq'
else
psjetj=akg*(psbori(s,t,0,1,n)+psbori(s,s-t,0,1,n)) !gq
* +aks*(psbori(s,t,1,1,n)+psbori(s,s-t,1,1,n))/2. !qq
* +aks*(psbori(s,t,-1,1,n)+psbori(s,s-t,-1,1,n)) !qq~
* +(akns+aks*(naflav-1)*2.)*
* (psbori(s,t,1,2,n)+psbori(s,s-t,1,2,n)) !qq'
endif
endif
elseif(n.eq.1)then
p1=s/(1.+qcmass**2/s)
psjetj=psevi(q1,scale,xx,m,1)*(psbori(s,t,4,0,n)+ !cg
* psbori(s,p1-t,4,0,n))
* +psevi(q1,scale,xx,m,2)*(psbori(s,t,4,1,n)+ !cq
* psbori(s,p1-t,4,1,n))
else
psjetj=0.
endif
return
end
c------------------------------------------------------------------------
function psjti(q1,qqcut,s,m1,l1,jdis)
c-----------------------------------------------------------------------
c psjti - inclusive hard cross-section interpolation - for any ordering
c in the ladder
c q1 - virtuality cutoff at current end of the ladder
c qqcut - p_t cutoff for the born process;
c s - total c.m. energy squared for the ladder
c m1 - parton type at current end of the ladder (0-g, 1,2,etc.-q)
c l1 - parton type at opposite end of the ladder (0-g, 1,2,etc.-q)
c-----------------------------------------------------------------------
dimension wi(3),wj(3),wk(3)
common /psar2/ edmax,epmax
common /psar19/ cstot(20,20,240)
include 'epos.incsem'
psjti=0.
c jdis1=jdis
if(jdis.eq.0)then
qqmin=q1
qmax=s/4.
else
qqmin=max(q2min,q1/4.)
qmax=s
endif
qq=max(qqmin,qqcut)
spmin=4.*q2min
s2min=4.*qq
if(s.le.s2min)return
if(jdis.eq.0)then
smins=s2min/(1.-q2ini/qq)
else
smins=s2min/(1.-q2ini/qq/4.)
endif
if(s.le.smins)goto 1
if(s.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/s))
else
tmin=2.*qq
endif
tmax=s/2.
if(m1.ne.0.and.m1.eq.l1)then
m=2
l=2
elseif(m1.ne.0.and.m1.eq.-l1)then
m=3
l=1
elseif(m1.ne.0.and.l1.ne.0.and.m1.ne.l1)then
m=3
l=2
else
m=min(1,iabs(m1))+1
l=min(1,iabs(l1))+1
endif
ml=20*(m-1)+60*(l-1)+120*jdis
qli=log(q1/q2min)/log(qmax/q2min)*19.+1.
qlj=log(qq/qqmin)/log(s/4./qqmin)*19.+1.
sl=log(s/spmin)/log(epmax/2./spmin)*19.+1.
k=int(sl)
i=int(qli)
j=int(qlj)
if(j.lt.1)j=1
if(i.lt.1)i=1
if(k.gt.18)k=18
if(i.gt.18)i=18
if(j.gt.18)j=18
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
wj(2)=qlj-j
wj(3)=wj(2)*(wj(2)-1.)*.5
wj(1)=1.-wj(2)+wj(3)
wj(2)=wj(2)-2.*wj(3)
wk(2)=sl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
do i1=1,3
do j1=1,3
do k1=1,3
psjti=psjti+cstot(i+i1-1,j+j1-1,k+k1+ml-1)
* *wi(i1)*wj(j1)*wk(k1)
enddo
enddo
enddo
psjti=exp(psjti)*(1./tmin-1./tmax)
return
1 continue
psjti=psbint(q1,q2min,qqcut,s,m1,l1,jdis)
return
end
c------------------------------------------------------------------------
subroutine psjti0(ss,sj,sjb,m1,l1)
c-----------------------------------------------------------------------
c psjti0 - inclusive hard cross-section interpolation -
c for minimal virtuality cutoff in the ladder
c s - total c.m. energy squared for the ladder,
c sj - inclusive jet cross-section,
c sjb - born cross-section,
c m1 - parton type at current end of the ladder (0-g, 1,2,etc.-q)
c l1 - parton type at opposite end of the ladder (0-g, 1,2,etc.-q)
c-----------------------------------------------------------------------
dimension wk(3)
common /psar2/ edmax,epmax
common /psar22/ cstotzero(20,4,2),csborzer(20,4,2)
include 'epos.incsem'
sj=0.
sjb=0.
if(iabs(m1).ne.4)then
q2mass=0.
if(m1.ne.0.and.m1.eq.l1)then
m=2
l=2
elseif(m1.ne.0.and.m1.eq.-l1)then
m=3
l=1
elseif(m1.ne.0.and.l1.ne.0.and.m1.ne.l1)then
m=3
l=2
else
m=min(1,iabs(m1))+1
l=min(1,iabs(l1))+1
endif
else
q2mass=qcmass**2
m=4
l=min(1,iabs(l1))+1
endif
s=ss-q2mass
qq=q2min
spmin=4.*qq+q2mass
if(s.le.spmin)return
p1=s/(1.+q2mass/s)
if(p1.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/p1))
else
tmin=2.*qq
endif
tmax=.5*p1
sl=log(s/spmin)/log(epmax/2./spmin)*19.+1.
k=int(sl)
if(k.gt.18)k=18
wk(2)=sl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
do k1=1,3
sj=sj+cstotzero(k+k1-1,m,l)*wk(k1)
sjb=sjb+csborzer(k+k1-1,m,l)*wk(k1)
enddo
sjb=exp(sjb)*(1./tmin-1./tmax)
sj=max(sjb,exp(sj)*(1./tmin-1./tmax))
return
end
c------------------------------------------------------------------------
function psjti1(q1,q2,qqcut,s,m1,l1,jdis)
c-----------------------------------------------------------------------
c psjti1 - inclusive hard cross-section interpolation - for strict order
c in the ladder
c q1 - virtuality cutoff at current end of the ladder
c q2 - virtuality cutoff at opposite end of the ladder
c qqcut - p_t cutoff for the born process;
c s - total c.m. energy squared for the ladder,
c m1 - parton type at current end of the ladder (0-g, 1,2,etc.-q)
c l1 - parton type at opposite end of the ladder (0-g, 1,2,etc.-q)
c-----------------------------------------------------------------------
dimension wi(3),wj(3),wk(3)
common /psar2/ edmax,epmax
common /psar20/ csord(20,20,240)
include 'epos.incsem'
double precision psuds
psjti1=0.
if(jdis.eq.0)then
qqmin=max(q1,q2)
else
qqmin=max(q1,q2/4.)
endif
qq=max(qqmin,qqcut)
spmin=4.*q2min
s2min=4.*qq
if(s.le.s2min)return
smins=s2min/(1.-q2ini/qq)
if(s.le.smins)goto 1
if(s.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/s))
else
tmin=2.*qq
endif
tmax=s/2.
if(m1.ne.0.and.m1.eq.l1)then
m=2
l=2
elseif(m1.ne.0.and.m1.eq.-l1)then
m=3
l=1
elseif(m1.ne.0.and.l1.ne.0.and.m1.ne.l1)then
m=3
l=2
else
m=min(1,iabs(m1))+1
l=min(1,iabs(l1))+1
endif
ml=20*(m-1)+60*(l-1)+120*jdis
qli=log(q1/q2min)/log(s/4./q2min)*19.+1.
qlj=log(qq/qqmin)/log(s/4./qqmin)*19.+1.
sl=log(s/spmin)/log(epmax/2./spmin)*19.+1.
k=int(sl)
i=int(qli)
j=int(qlj)
if(j.lt.1)j=1
if(i.lt.1)i=1
if(k.gt.18)k=18
if(i.gt.18)i=18
if(j.gt.18)j=18
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
wj(2)=qlj-j
wj(3)=wj(2)*(wj(2)-1.)*.5
wj(1)=1.-wj(2)+wj(3)
wj(2)=wj(2)-2.*wj(3)
wk(2)=sl-k
wk(3)=wk(2)*(wk(2)-1.)*.5
wk(1)=1.-wk(2)+wk(3)
wk(2)=wk(2)-2.*wk(3)
do i1=1,3
do j1=1,3
do k1=1,3
k2=k+k1+ml-1
psjti1=psjti1+csord(i+i1-1,j+j1-1,k2)
* *wi(i1)*wj(j1)*wk(k1)
enddo
enddo
enddo
psjti1=exp(psjti1)*(1./tmin-1./tmax)
if(jdis.eq.0.and.qq.gt.q2)then
psjti1=psjti1*sngl(psuds(qq,l1)/psuds(q2,l1))
elseif(jdis.eq.1.and.4.*qq.gt.q2)then
psjti1=psjti1*sngl(psuds(4.*qq,l1)/psuds(q2,l1))
endif
return
1 continue
if(jdis.eq.0)then
psjti1=psbint(q1,q2,qqcut,s,m1,l1,0)
else
psjti1=psbint(q2,q1,qqcut,s,l1,m1,1)
endif
return
end
c------------------------------------------------------------------------
function pspdfg(xx,qqs,qq,iclpro0,j)
c-----------------------------------------------------------------------
c pspdf - parton distribution function
c qq - virtuality scale
c qqs - initial virtuality for the input distributions
c iclpro0 - hadron class
c j - parton type
c-----------------------------------------------------------------------
double precision z
common/ar3/ x1(7),a1(7)
include 'epos.incsem'
double precision psuds
pspdfg=psdfh4(xx,qqs,0.,iclpro0,j)
if(j.gt.0)pspdfg=pspdfg+psdfh4(xx,qqs,0.,iclpro0,-j) !+sea contr.
pspdfg=pspdfg*sngl(psuds(qq,j)/psuds(qqs,j))
xmin=xx/(1.-q2ini/qq)
if(xmin.ge.1.)return
dpd1=0.
dpd2=0.
xm=max(xmin,.3)
do i=1,7 !numerical integration over zx
do m=1,2
zx=1.-(1.-xm)*(.5+(m-1.5)*x1(i))**.25
z=xx/zx
if(j.eq.0)then
aks=psevi(qqs,qq,z,2,1) !quark contribution
akg=psevi(qqs,qq,z,1,1) !gluon contribution
akns=0.
else
akg=psevi(qqs,qq,z,1,2)/naflav/2. !gluon contribution
akns=psevi(qqs,qq,z,3,2) !nonsinglet contribution
aks=(psevi(qqs,qq,z,2,2)-akns)/naflav/2. !quark contribution
endif
fz=akg*psdfh4(zx,qqs,0.,iclpro0,0)
* +akns*psdfh4(zx,qqs,0.,iclpro0,j)
* +aks*(psdfh4(zx,qqs,0.,iclpro0,1)+
* 2.*psdfh4(zx,qqs,0.,iclpro0,-1)
* +psdfh4(zx,qqs,0.,iclpro0,2)+2.*psdfh4(zx,qqs,0.,iclpro0,-2)
* +2.*psdfh4(zx,qqs,0.,iclpro0,-3))
if(j.gt.0)fz=fz+akns*psdfh4(zx,qqs,0.,iclpro0,-j)
dpd1=dpd1+a1(i)*fz/zx**2/(1.-zx)**3
enddo
enddo
dpd1=dpd1*(1.-xm)**4/8.*xx
if(xm.gt.xmin)then
do i=1,7 !numerical integration
do m=1,2
zx=xx+(xm-xx)*((xmin-xx)/(xm-xx))**(.5-(m-1.5)*x1(i))
z=xx/zx
if(j.eq.0)then
aks=psevi(qqs,qq,z,2,1) !quark contribution
akg=psevi(qqs,qq,z,1,1) !gluon contribution
akns=0.
else
akg=psevi(qqs,qq,z,1,2)/naflav/2. !gluon contribution
akns=psevi(qqs,qq,z,3,2) !nonsinglet contribution
aks=(psevi(qqs,qq,z,2,2)-akns)/naflav/2. !quark contribution
endif
fz=akg*psdfh4(zx,qqs,0.,iclpro0,0)
* +akns*psdfh4(zx,qqs,0.,iclpro0,j)
* +aks*(psdfh4(zx,qqs,0.,iclpro0,1)
* +2.*psdfh4(zx,qqs,0.,iclpro0,-1)
* +psdfh4(zx,qqs,0.,iclpro0,2)+2.*psdfh4(zx,qqs,0.,iclpro0,-2)
* +2.*psdfh4(zx,qqs,0.,iclpro0,-3))
if(j.gt.0)fz=fz+akns*psdfh4(zx,qqs,0.,iclpro0,-j)
dpd2=dpd2+a1(i)*fz*(1.-xx/zx)/zx
enddo
enddo
dpd2=dpd2*log((xm-xx)/(xmin-xx))*.5*xx
endif
pspdfg=pspdfg+dpd2+dpd1
return
end
c-----------------------------------------------------------------------
subroutine psaevp
c-----------------------------------------------------------------------
include 'epos.inc'
include 'epos.incsem'
qq=xpar1
jmod=nint(xpar2)
iologb=1
if(jmod.eq.0)then !??????????????ttttttt
write(*,*)"no more triple Pomeron, xpar2=0 in psaevp not accepted"
write(*,*)"use xpar2=1 instead"
jmod=1
endif
do i=1,nrbins
if(iologb.eq.0)then
xx=xminim+(xmaxim-xminim)*(i-.5)/nrbins
else
xx=xminim*(xmaxim/xminim)**((i-.5)/nrbins)
endif
ar(i,1)=xx
ar(i,2)=0.
if(jmod.eq.0)then !evolution+matrix element +3P (ours)
ww=qq/xx
ar(i,3)=(psdh(ww,qq,2,0)+psdh(ww,qq,2,1)
c * +psdsh1(ww,qq,2,dqsh,0)+psdsh1(ww,qq,2,dqsh,1)
* )/(4.*pi**2*alfe)*qq
elseif(jmod.eq.1)then !evolution+matrix element (ours)
ww=qq/xx
ar(i,3)=(psdh(ww,qq,2,0)+psdh(ww,qq,2,1)+
* psdsh(ww,qq,2,dqsh,0)+psdsh(ww,qq,2,dqsh,1)
* )/(4.*pi**2*alfe)*qq
elseif(jmod.eq.2)then !just evolution (grv)
ar(i,3)=(pspdfg(xx,q2min,qq,2,1)/2.25+
* pspdfg(xx,q2min,qq,2,2)/9.+
* pspdfg(xx,q2min,qq,2,-1)*2./3.6+
* pspdfg(xx,q2min,qq,2,-3)*2./9.)
if(naflav.eq.4)ar(i,3)=ar(i,3)+pspdfg(xx,q2min,qq,2,-4)
* *2./2.25
elseif(jmod.eq.3)then !grv
ar(i,3)=(psdfh4(xx,qq,0.,2,1)+2.*psdfh4(xx,qq,0.,2,-1))/2.25
* +(psdfh4(xx,qq,0.,2,2)+2.*psdfh4(xx,qq,0.,2,-2))/9.
* +2.*psdfh4(xx,qq,0.,2,-3)/9. !
elseif(jmod.eq.4)then !just evolution (ours)
ar(i,3)=(fparton(xx,qq,1)/2.25+fparton(xx,qq,2)/9.+
* fparton(xx,qq,-1)*6./4.5) !uv+dv+6*sea
if(naflav.eq.4)ar(i,3)=ar(i,3)+fparton(xx,qq,-4)*2./2.25
elseif(jmod.eq.5)then !grv+res
ww=qq/xx
ar(i,3)=(psdgh(ww,qq,0)+psdgh(ww,qq,1)
* )/(4.*pi**2*alfe)*qq
endif
ar(i,4)=0.
enddo
return
end
c------------------------------------------------------------------------
subroutine pscs(c,s)
c-----------------------------------------------------------------------
c pscs - cos (c) and sin (s) generation for uniformly distributed angle
c-----------------------------------------------------------------------
1 s1=2.*rangen()-1.
s2=2.*rangen()-1.
s3=s1*s1+s2*s2
if(s3.gt.1.)goto 1
s3=sqrt(s3)
c=s1/s3
s=s2/s3
return
end
c------------------------------------------------------------------------
subroutine psdefrot(ep,s0x,c0x,s0,c0)
c-----------------------------------------------------------------------
c psdefrot - determination of the parameters the spacial rotation to the
c system for 4-vector ep
c s0, c0 - sin and cos for the zx-rotation;
c s0x, c0x - sin and cos for the xy-rotation
c-----------------------------------------------------------------------
dimension ep(4)
c transverse momentum square for the current parton (ep)
pt2=ep(3)**2+ep(4)**2
if(pt2.ne.0.)then
pt=sqrt(pt2)
c system rotation to get pt=0 - euler angles are determined (c0x = cos t
c s0x = sin theta, c0 = cos phi, s0 = sin phi)
c0x=ep(3)/pt
s0x=ep(4)/pt
c total momentum for the gluon
pl=sqrt(pt2+ep(2)**2)
s0=pt/pl
c0=ep(2)/pl
else
c0x=1.
s0x=0.
pl=abs(ep(2))
s0=0.
c0=ep(2)/pl
endif
ep(2)=pl
ep(3)=0.
ep(4)=0.
return
end
c------------------------------------------------------------------------
subroutine psdeftr(s,ep,ey)
c-----------------------------------------------------------------------
c psdeftr - determination of the parameters for the lorentz transform to
c rest frame system for 4-vector ep of mass squared s
c-----------------------------------------------------------------------
dimension ey(3)
double precision ep(4)
do i=1,3
if(ep(i+1).eq.0.d0)then
ey(i)=1.
else
wp=ep(1)+ep(i+1)
wm=ep(1)-ep(i+1)
if(wp.gt.1.e-8.and.wm/wp.lt.1.e-8)then
ww=s
do l=1,3
if(l.ne.i)ww=ww+ep(l+1)**2
enddo
wm=ww/wp
elseif(wm.gt.1.e-8.and.wp/wm.lt.1.e-8)then
ww=s
do l=1,3
if(l.ne.i)ww=ww+ep(l+1)**2
enddo
wp=ww/wm
endif
ey(i)=sqrt(wm/wp)
ep(1)=wp*ey(i)
ep(i+1)=0.
endif
enddo
ep(1)=dsqrt(dble(s))
return
end
c------------------------------------------------------------------------
function psdfh4(xxx,qqs,qq,icq,iq)
c------------------------------------------------------------------------
c psdfh4 - GRV structure functions
c------------------------------------------------------------------------
common /psar8/ stmass ,amhadr(8),qcmass
common /psar36/ alvc
psdfh4=0.
! if(x.gt..99999)return
x=min(xxx,0.99999) !warning ! but necessary for idraflx
if(icq.eq.2)then
if(qqs.le.0.232**2)return
sq=log(log(qqs/.232**2)/log(.23/.232**2))
if(sq.le.0.)return
if(iq.eq.0)then !gluon
alg=.524
betg=1.088
aag=1.742-.93*sq
bbg=-.399*sq**2
ag=7.486-2.185*sq
bg=16.69-22.74*sq+5.779*sq*sq
cg=-25.59+29.71*sq-7.296*sq*sq
dg=2.792+2.215*sq+.422*sq*sq-.104*sq*sq*sq
eg=.807+2.005*sq
eeg=3.841+.361*sq
psdfh4=(1.-x)**dg*(x**aag*(ag+bg*x+cg*x**2)*log(1./x)**bbg
* +sq**alg*exp(-eg+sqrt(eeg*sq**betg*log(1./x))))
elseif(iq.eq.1.or.iq.eq.2)then !u_v or d_v
aau=.59-.024*sq
bbu=.131+.063*sq
auu=2.284+.802*sq+.055*sq*sq
au=-.449-.138*sq-.076*sq*sq
bu=.213+2.669*sq-.728*sq*sq
cu=8.854-9.135*sq+1.979*sq*sq
du=2.997+.753*sq-.076*sq*sq
uv=auu*x**aau*(1.-x)**du*
* (1.+au*x**bbu+bu*x+cu*x**1.5)
aad=.376
bbd=.486+.062*sq
add=.371+.083*sq+.039*sq*sq
ad=-.509+3.31*sq-1.248*sq*sq
bd=12.41-10.52*sq+2.267*sq*sq
ccd=6.373-6.208*sq+1.418*sq*sq
dd=3.691+.799*sq-.071*sq*sq
dv=add*x**aad*(1.-x)**dd*
* (1.+ad*x**bbd+bd*x+ccd*x**1.5)
if(iq.eq.1)then !u_v
psdfh4=uv
elseif(iq.eq.2)then !d_v
psdfh4=dv
endif
elseif(iq.eq.-3)then !s_sea
als=.914
bets=.577
aas=1.798-.596*sq
as=-5.548+3.669*sqrt(sq)-.616*sq
bs=18.92-16.73*sqrt(sq)+5.168*sq
ds=6.379-.35*sq+.142*sq*sq
es=3.981+1.638*sq
ees=6.402
psdfh4=(1.-x)**ds*sq**als/log(1./x)**aas*(1.+as*sqrt(x)
* +bs*x)*exp(-es+sqrt(ees*sq**bets*log(1./x)))
elseif(iabs(iq).lt.3)then !u_sea or d_sea
aadel=.409-.005*sq
bbdel=.799+.071*sq
addel=.082+.014*sq+.008*sq*sq
adel=-38.07+36.13*sq-.656*sq*sq
bdel=90.31-74.15*sq+7.645*sq*sq
ccdel=0.
ddel=7.486+1.217*sq-.159*sq*sq
delv=addel*x**aadel*(1.-x)**ddel*
* (1.+adel*x**bbdel+bdel*x+ccdel*x**1.5)
alud=1.451
betud=.271
aaud=.41-.232*sq
bbud=.534-.457*sq
aud=.89-.14*sq
bud=-.981
cud=.32+.683*sq
dud=4.752+1.164*sq+.286*sq*sq
eud=4.119+1.713*sq
eeud=.682+2.978*sq
udsea=(1.-x)**dud*(x**aaud*(aud+bud*x+cud*x**2)
* *log(1./x)**bbud+sq**alud*exp(-eud+sqrt(eeud*sq**betud*
* log(1./x))))
if(iq.eq.-1)then !u_sea
psdfh4=(udsea-delv)/2.
elseif(iq.eq.-2)then !d_sea
psdfh4=(udsea+delv)/2.
endif
else
psdfh4=0.
endif
elseif(icq.eq.1.or.icq.eq.3)then
if(qqs.le.0.204**2)return
sq=log(log(qqs/.204**2)/log(.26/.204**2))
if(sq.le.0.)return
if(iq.eq.1.or.iq.eq.2)then
aapi=.517-.02*sq
api=-.037-.578*sq
bpi=.241+.251*sq
dpi=.383+.624*sq
anorm=1.212+.498*sq+.009*sq**2
psdfh4=.5*anorm*x**aapi*(1.-x)**dpi*
* (1.+api*sqrt(x)+bpi*x)
elseif(iq.eq.0)then
alfpi=.504
betpi=.226
aapi=2.251-1.339*sqrt(sq)
api=2.668-1.265*sq+.156*sq**2
bbpi=0.
bpi=-1.839+.386*sq
cpi=-1.014+.92*sq-.101*sq**2
dpi=-.077+1.466*sq
epi=1.245+1.833*sq
eppi=.51+3.844*sq
psdfh4=(1.-x)**dpi*(x**aapi*(api+bpi*sqrt(x)+cpi*x)*
* log(1./x)**bbpi+sq**alfpi*
* exp(-epi+sqrt(eppi*sq**betpi*log(1./x))))
elseif(iq.eq.-3)then
alfpi=.823
betpi=.65
aapi=1.036-.709*sq
api=-1.245+.713*sq
bpi=5.58-1.281*sq
dpi=2.746-.191*sq
epi=5.101+1.294*sq
eppi=4.854-.437*sq
psdfh4=sq**alfpi/log(1./x)**aapi*(1.-x)**dpi*
* (1.+api*sqrt(x)+bpi*x)*
* exp(-epi+sqrt(eppi*sq**betpi*log(1./x)))
elseif(iabs(iq).lt.3)then
alfpi=1.147
betpi=1.241
aapi=.309-.134*sqrt(sq)
api=.219-.054*sq
bbpi=.893-.264*sqrt(sq)
bpi=-.593+.24*sq
cpi=1.1-.452*sq
dpi=3.526+.491*sq
epi=4.521+1.583*sq
eppi=3.102
psdfh4=(1.-x)**dpi*(x**aapi*(api+bpi*sqrt(x)+cpi*x)*
* log(1./x)**bbpi+sq**alfpi*
* exp(-epi+sqrt(eppi*sq**betpi*log(1./x))))
else
psdfh4=0.
endif
elseif(icq.eq.0)then
if(qqs.le.0.204**2)return
sq=log(log(qqs/.204**2)/log(.26/.204**2))
if(sq.le.0.)return
if(iq.eq.0)then
alfpi=.504
betpi=.226
aapi=2.251-1.339*sqrt(sq)
api=2.668-1.265*sq+.156*sq**2
bbpi=0.
bpi=-1.839+.386*sq
cpi=-1.014+.92*sq-.101*sq**2
dpi=-.077+1.466*sq
epi=1.245+1.833*sq
eppi=.51+3.844*sq
psdfh4=(1.-x)**dpi*(x**aapi*(api+bpi*sqrt(x)+cpi*x)*
* log(1./x)**bbpi+sq**alfpi*
* exp(-epi+sqrt(eppi*sq**betpi*log(1./x))))
* *.543
else
alfpi=.823
betpi=.65
aapi=1.036-.709*sq
api=-1.245+.713*sq
bpi=5.58-1.281*sq
dpi=2.746-.191*sq
epi=5.101+1.294*sq
eppi=4.854-.437*sq
str=sq**alfpi/log(1./x)**aapi*(1.-x)**dpi*
* (1.+api*sqrt(x)+bpi*x)*
* exp(-epi+sqrt(eppi*sq**betpi*log(1./x)))
if(iq.eq.3)then
psdfh4=str*.543*2.
else
aapi=.517-.02*sq
api=-.037-.578*sq
bpi=.241+.251*sq
dpi=.383+.624*sq
anorm=1.212+.498*sq+.009*sq**2
val=.5*anorm*x**aapi*(1.-x)**dpi*
* (1.+api*sqrt(x)+bpi*x)
alfpi=1.147
betpi=1.241
aapi=.309-.134*sqrt(sq)
api=.219-.054*sq
bbpi=.893-.264*sqrt(sq)
bpi=-.593+.24*sq
cpi=1.1-.452*sq
dpi=3.526+.491*sq
epi=4.521+1.583*sq
eppi=3.102
sea=(1.-x)**dpi*(x**aapi*(api+bpi*sqrt(x)+cpi*x)*
* log(1./x)**bbpi+sq**alfpi*
* exp(-epi+sqrt(eppi*sq**betpi*log(1./x))))
if(iq.eq.1)then
psdfh4=(.836*(val+2.*sea)-.587*str)
elseif(iq.eq.2)then
psdfh4=(.25*(val+2.*sea)+.587*str)
else
psdfh4=0.
endif
endif
endif
psdfh4=psdfh4/(1.+qq/.59)**2
elseif(icq.eq.4)then
if(qqs.le.qcmass**2)return
sq=log(log(qqs/qcmass**2)/log(.23/qcmass**2))
if(sq.le.0.)return
if(iq.eq.2)then
psdfh4=x**3*(1.-x)**alvc*(alvc+3.)*(alvc+2.)*(alvc+1.)
else
aapi=.517-.02*sq
api=-.037-.578*sq
bpi=.241+.251*sq
dpi=.383+.624*sq
anorm=1.212+.498*sq+.009*sq**2
psdfh4=.5*anorm*x**aapi*(1.-x)**dpi*
* (1.+api*sqrt(x)+bpi*x)
endif
else
psdfh4=0.
endif
return
end
c------------------------------------------------------------------------
function psfap(x,j,l)
c-----------------------------------------------------------------------
c psfap - altarelli-parisi function (multiplied by x)
c x - light cone momentum share value,
c j - type of the parent parton (0-g;1,2,etc.-q)
c l - type of the daughter parton (0-g;1,2,etc.-q)
c-----------------------------------------------------------------------
double precision x
include 'epos.incsem'
if(j.eq.0)then
if(l.eq.0)then
psfap=((1.d0-x)/x+x/(1.d0-x)+x*(1.d0-x))*6.d0
else
psfap=(x**2+(1.d0-x)**2)*naflav
endif
else
if(l.eq.0)then
psfap=(1.d0+(1.d0-x)**2)/x/.75d0
else
psfap=(x**2+1.d0)/(1.d0-x)/.75d0
endif
endif
return
end
cc------------------------------------------------------------------------
c function psgen(a1,a2)
cc-----------------------------------------------------------------------
cc psgen - x-values generation according to distribution
cc x1^(-a1) x2^(-0.5)
cc-----------------------------------------------------------------------
c common/lept1/engy,elepti,elepto,angmue,icinpu
c
c aa=max(a1,a2)
c1 continue
c if(aa.lt.1.)then
c x1=.5*rangen()**(1./(1.-aa))
c elseif(aa.eq.1.)then
c x1=.5/engy**rangen()
c else
c x1=.5*(1.+rangen()*(engy**(aa-1.)-1.))**(1./(1.-aa))
c endif
c if(x1.lt.1.e-7.or.x1.gt..999999)then
c goto 1
c endif
c if(rangen().lt..5)then
c gb=x1**(aa-a1)*.5**aa/(1.-x1)**a2
c else
c x1=1.-x1
c gb=(1.-x1)**(aa-a2)*.5**aa/x1**a1
c endif
c if(rangen().gt.gb)goto 1
c psgen=x1
c return
c end
c
c------------------------------------------------------------------------
function psidd(icc)
c-----------------------------------------------------------------------
c psidd - kink type decoder
c-----------------------------------------------------------------------
if(icc.eq.0)then !g
psidd=9
elseif(iabs(icc).le.2)then !u,u~,d,d~
psidd=icc
elseif(iabs(icc).eq.4)then !s,s~
psidd=icc/4*3
elseif(iabs(icc).gt.10)then !c,c~ etc.
psidd=icc/10
elseif(icc.eq.3)then !ud
psidd=1200
elseif(icc.eq.-3)then !u~d~
psidd=-1200
elseif(icc.eq.6)then !uu
psidd=1100
elseif(icc.eq.-6)then !u~u~
psidd=-1100
elseif(icc.eq.7)then !dd
psidd=2200
elseif(icc.eq.-7)then !d~d~
psidd=-2200
else
psidd=0.
write (*,*)'psidd?????????',icc
endif
return
end
cc------------------------------------------------------------------------
c function pslam(s,a,b)
cc-----------------------------------------------------------------------
cc kinematical function for two particle decay - maximal pt-value
cc a - first particle mass squared,
cc b - second particle mass squared,
cc s - two particle invariant mass squared
cc-----------------------------------------------------------------------
c pslam=.25/s*(s+a-b)**2-a
c return
c end
c
c------------------------------------------------------------------------
function psjvrg1(qt,s,y0)
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
common /cnsta/ pi,pii,hquer,prom,piom,ainfin
include 'epos.incsem'
double precision xt,ymin,ymax,y,xmin,xmax,xx1,xx2
psjvrg1=0.
if(s.le.4.*qt)return
xt=2.d0*sqrt(dble(qt)/dble(s))
ymax=min(dble(y0),log(1d0/xt+sqrt((1d0/xt-1d0)*(1d0/xt+1d0))))
ymin=-ymax
do i=1,7
do m=1,2
y=.5d0*(ymax+ymin+(ymin-ymax)*dble((2*m-3)*x1(i)))
xmin=xt**2/2.d0/(2.d0-xt*exp(-y))
xmax=1.d0-xt*exp(y)/2.d0
fx=0.
do i1=1,7
do m1=1,2
xx1=xt*exp(y)/2d0+xmin*(xmax/xmin)**dble(.5+x1(i1)*(m1-1.5))
xx2=xt*exp(-y)*xx1/(2.d0*xx1-xt*exp(y))
z=sngl(xx1*xx2)
sh=z*s
t=sngl(dble(sh)/2d0*(1d0
& -sqrt(max(0d0,1d0-4d0*dble(qt)/dble(sh)))))
ft=psjvrx(t,qt,sngl(xx1),sngl(xx2),sh)
fx=fx+a1(i1)*ft/sh**2
enddo
enddo
fx=fx*sngl(log(xmax/xmin))
psjvrg1=psjvrg1+a1(i)*fx
enddo
enddo
psjvrg1=psjvrg1*sngl(ymax-ymin)*pi**3
**pssalf(qt/qcdlam)**2*sqrt(qt)
return
end
c-----------------------------------------------------------------------
function psjvrx(t,qt,xx1,xx2,s)
c-----------------------------------------------------------------------
include 'epos.incsem'
g1=psdfh4(xx1,qt,0.,2,0)
ub1=psdfh4(xx1,qt,0.,2,-1)
u1=psdfh4(xx1,qt,0.,2,1)+ub1
db1=psdfh4(xx1,qt,0.,2,-2)
d1=psdfh4(xx1,qt,0.,2,2)+db1
sb1=psdfh4(xx1,qt,0.,2,-3)
s1=sb1
g2=psdfh4(xx2,qt,0.,2,0)
ub2=psdfh4(xx2,qt,0.,2,-1)
u2=psdfh4(xx2,qt,0.,2,1)+ub2
db2=psdfh4(xx2,qt,0.,2,-2)
d2=psdfh4(xx2,qt,0.,2,2)+db2
sb2=psdfh4(xx2,qt,0.,2,-3)
s2=sb2
psjvrx=g1*g2*(psbori(s,t,0,0,1)+psbori(s,s-t,0,0,1)
*+psbori(s,t,0,0,2)+psbori(s,s-t,0,0,2))/2.
*+(psbori(s,t,0,1,1)+psbori(s,s-t,0,1,1))*
*(g2*(u1+ub1+d1+db1+s1+sb1)+g1*(u2+ub2+d2+db2+s2+sb2))
*+(psbori(s,t,1,1,1)+psbori(s,s-t,1,1,1))/2.*
*(u1*u2+ub1*ub2+d1*d2+db1*db2+s1*s2+sb1*sb2)
*+(psbori(s,t,1,-1,1)+psbori(s,s-t,1,-1,1)+psbori(s,t,1,-1,2)+
*psbori(s,s-t,1,-1,2)+psbori(s,t,1,-1,3)+psbori(s,s-t,1,-1,3))*
*(u1*ub2+ub1*u2+d1*db2+db1*d2+s1*sb2+sb1*s2)
*+(psbori(s,t,1,2,1)+psbori(s,s-t,1,2,1))*
*((u1+ub1)*(d2+db2+s2+sb2)+(u2+ub2)*(d1+db1+s1+sb1)+
*(d1+db1)*(u2+ub2+s2+sb2)+(d2+db2)*(u1+ub1+s1+sb1)+
*(s1+sb1)*(u2+ub2+d2+db2)+(s2+sb2)*(u1+ub1+d1+db1))
return
end
c------------------------------------------------------------------------
function psjwo1(qt,s,y0)
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
common /cnsta/ pi,pii,hquer,prom,piom,ainfin
double precision xt,ymax,ymin,y,xmin,xmax,xx1,xx2
include 'epos.incsem'
psjwo1=0.
if(s.le.4.*qt)return
xt=2.d0*sqrt(dble(qt)/dble(s))
ymax=min(dble(y0),log(1d0/xt+sqrt((1d0/xt-1d0)*(1d0/xt+1d0))))
ymin=-ymax
do i=1,7
do m=1,2
y=.5d0*(ymax+ymin+(ymin-ymax)*dble(2*m-3)*dble(x1(i)))
xmin=xt**2/2.d0/(2.d0-xt*exp(-y))
xmax=1.d0-xt*exp(y)/2.d0
fx=0.
do i1=1,7
do m1=1,2
xx1=xt*exp(y)/2.d0+xmin*(xmax/xmin)**dble(.5+x1(i1)*(m1-1.5))
xx2=xt*exp(-y)/(2.d0-xt*exp(y)/xx1)
z=sngl(xx1*xx2)
sh=z*s
t=sngl(dble(sh)/2d0*(1d0-sqrt(1d0-4d0*dble(qt)/dble(sh))))
ft=psjwox(t,qt,sngl(xx1),sngl(xx2),sh)
fx=fx+a1(i1)*ft/sh**2
enddo
enddo
fx=fx*log(xmax/xmin)
psjwo1=psjwo1+a1(i)*fx
enddo
enddo
psjwo1=psjwo1*sngl(ymax-ymin)*pi**3
**pssalf(qt/qcdlam)**2*sqrt(qt)
return
end
c-----------------------------------------------------------------------
function psjwox(t,qt,xx1,xx2,s)
c-----------------------------------------------------------------------
double precision x,scale,upv1,dnv1,sea1,str1,chm1,gl1,
*upv2,dnv2,sea2,str2,chm2,gl2
scale=sqrt(qt)
x=xx1
call strdo1(x,scale,upv1,dnv1,sea1,str1,chm1,gl1)
x=xx2
call strdo1(x,scale,upv2,dnv2,sea2,str2,chm2,gl2)
psjwox=gl1*gl2*(psbori(s,t,0,0,1)+psbori(s,s-t,0,0,1)
*+psbori(s,t,0,0,2)+psbori(s,s-t,0,0,2)+psbori(s,t,0,0,3)
*+psbori(s,s-t,0,0,3))/2.
*+(psbori(s,t,0,1,1)+psbori(s,s-t,0,1,1)
*+psbori(s,t,0,1,2)+psbori(s,s-t,0,1,2)+psbori(s,t,0,1,3)
*+psbori(s,s-t,0,1,3))*(gl2*(upv1+dnv1+4.*sea1+2.*str1+2.*chm1)+
*gl1*(upv2+dnv2+4.*sea2+2.*str2+2.*chm2))
*+(psbori(s,t,1,1,1)+psbori(s,s-t,1,1,1)
*+psbori(s,t,1,1,2)+psbori(s,s-t,1,1,2)+psbori(s,t,1,1,3)+
*psbori(s,s-t,1,1,3))/2.*
*((upv1+sea1)*(upv2+sea2)+(dnv1+sea1)*(dnv2+sea2)+2.*sea1*sea2
*+2.*str1*str2+2.*chm1*chm2)
*+(psbori(s,t,1,-1,1)+psbori(s,s-t,1,-1,1)+psbori(s,t,1,-1,2)+
*psbori(s,s-t,1,-1,2)+psbori(s,t,1,-1,3)+psbori(s,s-t,1,-1,3))*
*((upv1+sea1)*sea2+sea1*(upv2+sea2)+(dnv1+sea1)*sea2+
*sea1*(dnv2+sea2)+2.*str1*str2+2.*chm1*chm2)
*+(psbori(s,t,1,2,1)
*+psbori(s,s-t,1,2,1)+psbori(s,t,1,2,2)+psbori(s,s-t,1,2,2)
*+psbori(s,t,1,2,3)+psbori(s,s-t,1,2,3))*
*(upv1*dnv2+upv2*dnv1+(upv1+dnv1)*(2.*sea2+2.*str2+2.*chm2)+
*(upv2+dnv2)*(2.*sea1+2.*str1+2.*chm1)+
*4.*sea1*(2.*sea2+2.*str2+2.*chm2)+2.*str1*(4.*sea2+2.*chm2)+
*2.*chm1*(4.*sea2+2.*str2))
return
end
c------------------------------------------------------------------------
subroutine pslcsh(wp1,wm1,wp2,wm2,samqt,amqpt)
c-----------------------------------------------------------------------
c pslcsh - sh pomeron lc momentum sharing between two strings
c------------------------------------------------------------------------
double precision amqt(4),yqm(4),yqm1(4),xlp(4),xlm(4),am23,sx,y2
*,wp1,wp2,wm1,wm2,s,sq,psutz,yqmax,y,amjp,amjm,y1,s12,s34,x34,amqpt
dimension samqt(4)
include 'epos.inc'
s=wp1*wm1
sq=dsqrt(s)
do i=1,4
amqt(i)=dble(samqt(i))
yqm(i)=dlog(sq/amqt(i)*psutz(s,amqt(i)**2,(amqpt-amqt(i))**2))
enddo
yqmax=max(yqm(1),yqm(2))
1 y=yqmax*dble(rangen())
j=int(1.5+rangen())
if(y.gt.yqm(j))goto 1
amjp=amqt(j)*dexp(y)
amjm=amqt(j)*dexp(-y)
do i=3,4
am23=amqt(3-j)+amqt(7-i)
sx=(am23+amjp)*(am23+amjm)
yqm1(i)=dlog(sq/amqt(i)*psutz(s,amqt(i)**2,sx))
enddo
yqmax1=max(yqm1(3),yqm1(4))
if(dble(rangen()).gt.yqmax1/max(yqm(3),yqm(4)))goto 1
y1=yqmax1*dble(rangen())
j1=int(3.5+rangen())
if(y1.gt.yqm1(j1))goto 1
amjp1=amqt(j1)*exp(y1)
amjm1=amqt(j1)*exp(-y1)
s12=(amqt(3-j)+amjp)*(amqt(3-j)+amjm)
s34=(amqt(7-j1)+amjp1)*(amqt(7-j1)+amjm1)
y2=dlog(sq/(amqt(3-j)+amjp)*psutz(s,s12,s34))
xlp(j)=amqt(j)/sq*dexp(y+y2)
xlm(j)=amqt(j)/sq*dexp(-y-y2)
xlp(3-j)=amqt(3-j)/sq*dexp(y2)
xlm(3-j)=amqt(3-j)/sq*dexp(-y2)
x34=1.-xlm(1)-xlm(2)
xlm(7-j1)=x34/(1.+amjp1/amqt(7-j1))
xlm(j1)=x34-xlm(7-j1)
c write (*,*)'xlc',xlp(1),xlp(2),xlm(3),xlm(4)
if(dble(rangen()).gt.(xlp(1)*xlp(2)*xlm(3)*xlm(4))**(-alpqua)*
*(xlp(j)*(1.d0-xlp(j))*xlm(j1)*(1.d0-xlm(j1))))goto 1
wp2=xlp(2)*wp1
wp1=xlp(1)*wp1
wm2=xlm(4)*wm1
wm1=xlm(3)*wm1
c write (*,*)'wp1,wm1,wp2,wm2',wp1,wm1,wp2,wm2
return
end
c------------------------------------------------------------------------
function psnorm(ep)
c-----------------------------------------------------------------------
c 4-vector squared calculation
c-----------------------------------------------------------------------
double precision sm2,ep(4)
sm2=ep(1)**2
do i=1,3
sm2=sm2-ep(i+1)**2
enddo
psnorm=sm2
return
end
c------------------------------------------------------------------------
subroutine psrotat(ep,s0x,c0x,s0,c0)
c-----------------------------------------------------------------------
c psrotat - spacial rotation to the lab. system for 4-vector ep
c s0, c0 - sin and cos for the zx-rotation;
c s0x, c0x - sin and cos for the xy-rotation
c-----------------------------------------------------------------------
dimension ep(4),ep1(3)
ep1(3)=ep(4)
ep1(2)=ep(2)*s0+ep(3)*c0
ep1(1)=ep(2)*c0-ep(3)*s0
ep(2)=ep1(1)
ep(4)=ep1(2)*s0x+ep1(3)*c0x
ep(3)=ep1(2)*c0x-ep1(3)*s0x
return
end
cc------------------------------------------------------------------------
c subroutine psrotat1(ep,s0x,c0x,s0,c0)
cc-----------------------------------------------------------------------
cc psrotat - spacial rotation to the lab. system for 4-vector ep
cc s0, c0 - sin and cos for the zx-rotation;
cc s0x, c0x - sin and cos for the xy-rotation
cc-----------------------------------------------------------------------
c dimension ep(4),ep1(3)
c
c ep1(1)=ep(2)
c ep1(3)=-ep(3)*s0x+ep(4)*c0x
c ep1(2)=ep(3)*c0x+ep(4)*s0x
c
c ep(4)=ep1(3)
c ep(3)=-ep1(1)*s0+ep1(2)*c0
c ep(2)=ep1(1)*c0+ep1(2)*s0
c return
c end
c
c-----------------------------------------------------------------------
function pssalf(qq)
c-----------------------------------------------------------------------
c pssalf - effective qcd coupling (alpha_s/2/pi)
c-----------------------------------------------------------------------
include "epos.incsem"
pssalf=2./(11.-naflav/1.5)/log(qq)
return
end
c------------------------------------------------------------------------
subroutine pstrans(ep,ey,jj)
c-----------------------------------------------------------------------
c pstrans - lorentz boosts according to the parameters ey ( determining
c shift along the z,x,y-axis respectively (ey(1),ey(2),ey(3)))
c jj=1 - inverse transformation to the lab. system;
c jj=-1 - direct transformation
c-----------------------------------------------------------------------
dimension ey(3),ep(4)
if(jj.eq.1)then
c lorentz transform to lab. system according to 1/ey(i) parameters
do i=1,3
if(ey(4-i).ne.1.)then
wp=(ep(1)+ep(5-i))/ey(4-i)
wm=(ep(1)-ep(5-i))*ey(4-i)
ep(1)=.5*(wp+wm)
ep(5-i)=.5*(wp-wm)
endif
enddo
else
c lorentz transform to lab. system according to ey(i) parameters
do i=1,3
if(ey(i).ne.1.)then
wp=(ep(1)+ep(i+1))*ey(i)
wm=(ep(1)-ep(i+1))/ey(i)
ep(1)=.5*(wp+wm)
ep(i+1)=.5*(wp-wm)
endif
enddo
endif
return
end
c------------------------------------------------------------------------
double precision function psuds(q,m)
c-----------------------------------------------------------------------
c psuds - spacelike sudakov formfactor
c q - maximal value of the effective momentum,
c m - type of parton (0 - g, 1,2, etc. - q)
c-----------------------------------------------------------------------
dimension wi(3)
common /psar15/ sudx(40,2)
include 'epos.incsem'
double precision dps,qlm,ffacs,qlm0,qlmi
j=min(iabs(m),1)+1
if(q.gt.q2ini)then
qli=log(q/q2min)*2.+1.
i=int(qli)
if(i.lt.1)i=1
if(i.gt.38)i=38
wi(2)=qli-i
wi(3)=wi(2)*(wi(2)-1.)*.5
wi(1)=1.-wi(2)+wi(3)
wi(2)=wi(2)-2.*wi(3)
dps=0.d0
do i1=1,3
dps=dps+dble(sudx(i+i1-1,j)*wi(i1))
enddo
qlm0=dble(log(q2ini/qcdlam))
qlm=dble(log(q/qcdlam))
qlmi=qlm-qlm0 !=log(q/q2ini)
psuds=(qlm*log(qlm/qlm0)-qlmi)
ffacs=(11.d0-dble(naflav)/1.5d0)/12.d0
if(j.eq.1)then
psuds=(psuds-ffacs*log(qlm/qlm0)
* +dps*(1.d0-dble(q2ini/q)))/ffacs
else
psuds=(psuds-log(qlm/qlm0)*.75d0
* +dps*(1.d0-dble(q2ini/q)))*4.d0/9.d0/ffacs
endif
psuds=exp(-psuds)
else
psuds=1.d0
endif
return
end
c------------------------------------------------------------------------
function psudx(q,j)
c-----------------------------------------------------------------------
c psudx - part of the bspacelike sudakov formfactor
c q - maximal value of the effective momentum,
c j - type of parton (1 - g, 2 - q)
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
psudx=0.
do i=1,7
do m=1,2
qt=.5*(q2ini+q-x1(i)*(2.*m-3.)*(q2ini-q))
if(j.eq.1)then
zm=1.-qt/q
dps=((11.-naflav/1.5)/12.-zm**2*(1.-naflav/12.)+
* (zm**3/3.-zm**4/4.)*(1.-naflav/3.))*q/qt
else
dps=(1.-qt/q/4.)
endif
psudx=psudx+a1(i)*dps/log(qt/qcdlam)
enddo
enddo
psudx=psudx*.5
return
end
c------------------------------------------------------------------------
double precision function psutz(s,a,b)
c-----------------------------------------------------------------------
c psutz - kinematical function for two particle decay - light cone momen
c share for the particle of mass squared a,
c b - partner's mass squared,
c s - two particle invariant mass
c-----------------------------------------------------------------------
double precision a1,b1,s1,x,dx,s,a,b
a1=dsqrt(a)
b1=dsqrt(b)
s1=dsqrt(s)
x=(1.d0+(a1-b1)*(a1+b1)/s)/2.d0
dx=(x-a1/s1)*(x+a1/s1)
c x=.5*(1.+(a-b)/s)
c dx=(x*x-a/s)
if(dx.gt.0.d0)then
x=x+dsqrt(dx)
else
x=a1/s1
endif
psutz=min(0.999999999d0,x)
return
end
c------------------------------------------------------------------------
block data ptdata
c-----------------------------------------------------------------------
c constants for numerical integration (gaussian weights)
c-----------------------------------------------------------------------
common /ar3/ x1(7),a1(7)
common /ar4/ x4(2),a4(2)
common /ar5/ x5(2),a5(2)
common /ar8/ x2(4),a2
common /ar9/ x9(3),a9(3)
data x1/.9862838,.9284349,.8272013,.6872929,.5152486,
*.3191124,.1080549/
data a1/.03511946,.08015809,.1215186,.1572032,
*.1855384,.2051985,.2152639/
data x2/.00960736,.0842652,.222215,.402455/
data a2/.392699/
data x4/ 0.339981,0.861136/
data a4/ 0.652145,0.347855/
data x5/.585786,3.41421/
data a5/.853553,.146447/
data x9/.93247,.661209,.238619/
data a9/.171324,.360762,.467914/
end
c------------------------------------------------------------------------
subroutine strdo1(x,scale,upv,dnv,sea,str,chm,gl)
c------------------------------------------------------------------------
c :::::::::::: duke owens set 1 ::::::::::::::::::::::::::::
c------------------------------------------------------------------------
implicit double precision(a-h,o-z)
double precision
+ f(5),a(6,5),b1(3,6,5)
data q0,ql1/2.d0,.2d0/
data b1/3.d0,0.d0,0.d0,.419d0,.004383d0,-.007412d0,
&3.46d0,.72432d0,-.065998d0,4.4d0,-4.8644d0,1.3274d0,
&6*0.d0,1.d0,
&0.d0,0.d0,.763d0,-.23696d0,.025836d0,4.d0,.62664d0,-.019163d0,
&0.d0,-.42068d0,.032809d0,6*0.d0,1.265d0,-1.1323d0,.29268d0,
&0.d0,-.37162d0,-.028977d0,8.05d0,1.5877d0,-.15291d0,
&0.d0,6.3059d0,-.27342d0,0.d0,-10.543d0,-3.1674d0,
&0.d0,14.698d0,9.798d0,0.d0,.13479d0,-.074693d0,
&-.0355d0,-.22237d0,-.057685d0,6.3494d0,3.2649d0,-.90945d0,
&0.d0,-3.0331d0,1.5042d0,0.d0,17.431d0,-11.255d0,
&0.d0,-17.861d0,15.571d0,1.564d0,-1.7112d0,.63751d0,
&0.d0,-.94892d0,.32505d0,6.d0,1.4345d0,-1.0485d0,
&9.d0,-7.1858d0,.25494d0,0.d0,-16.457d0,10.947d0,
&0.d0,15.261d0,-10.085d0/
wn=1.d0
s= log( log( max(q0,scale)/ql1)/ log(q0/ql1))
do 10 i=1,5
do 10 j=1,6
10 a(j,i)=b1(1,j,i)+s*(b1(2,j,i)+s*b1(3,j,i))
do 40 i=1,5
40 f(i)=a(1,i)*x**a(2,i)*(wn-x)**a(3,i)*(wn+x*
& (a(4,i)+x*(a(5,i)+x*a(6,i))))
do 50 i=1,2
aa=wn+a(2,i)+a(3,i)
50 f(i)=f(i)*utgam2(aa)/((wn+a(2,i)*a(4,i)/aa)
&*utgam2(a(2,i))*utgam2(wn+a(3,i)))
upv=f(1)-f(2)
dnv=f(2)
sea=f(3)/6.d0
str=sea
chm=f(4)
gl =f(5)
return
end
c------------------------------------------------------------------------
function fzeroGluZZ(z,k) ! former psftild
c-----------------------------------------------------------------------
c
c fzeroGluZZComplete = fzeroGluZZ * z^(-1-dels) * gamsoft * gamhad
c
c A = 8*pi*s0*gampar*gamtilde
c integration over semihard pomeron light cone momentum share xp==u
c
c fzeroGluZZ = (1-glusea) * engy^epszero
c * int(du) u^(epszero-alppar+dels) (1-u)^alplea * (1-z/u)**betpom
c
c z - light cone x of the gluon,
c k - hadron class
c-----------------------------------------------------------------------
double precision xpmin,xp
include 'epos.inc'
common /ar3/ x1(7),a1(7)
include 'epos.incsem'
fzeroGluZZ=0.
xpmin=z
xpmin=xpmin**(1.-alppar+dels+epszero)
do i=1,7
do m=1,2
xp=(.5*(1.+xpmin+(2*m-3)*x1(i)*(1.-xpmin)))**(1./
* (1.-alppar+dels+epszero))
fzeroGluZZ=fzeroGluZZ+a1(i)*(1.-xp)**alplea(k)*(1.-z/xp)**betpom
enddo
enddo
fzeroGluZZ=
* fzeroGluZZ*.5*(1.-xpmin)/(1.-alppar+dels+epszero)
* *(1.-glusea) *engy**epszero
return
end
c------------------------------------------------------------------------
function fzeroSeaZZ(z,k) ! former psftile
c-----------------------------------------------------------------------
c
c fzeroSeaZZComplete = fzeroSeaZZ * z^(-1-dels) * gamsoft * gamhad
c
c gamsoft = 8*pi*s0*gampar*gamtilde
c integration over semihard pomeron light cone momentum share xp==u
c
c fzeroSeaZZ = glusea * engy^epszero
c * int(du) u^(epszero-alppar+dels) (1-u)^alplea * EsoftQZero(z/u)
c
c z - light cone x of the quark,
c k - hadron class
c-----------------------------------------------------------------------
double precision xpmin,xp
common /ar3/ x1(7),a1(7)
include 'epos.inc'
include 'epos.incsem'
fzeroSeaZZ=0.
xpmin=z
xpmin=xpmin**(1.-alppar+dels+epszero)
do i=1,7
do m=1,2
xp=(.5*(1.+xpmin+(2*m-3)*x1(i)*(1.-xpmin)))**(1./
* (1.-alppar+dels+epszero))
zz=z/xp
fzeroSeaZZ=fzeroSeaZZ+a1(i)*(1.-xp)**alplea(k)*EsoftQZero(zz)
enddo
enddo
fzeroSeaZZ=fzeroSeaZZ*.5*(1.-xpmin)/(1.-alppar+dels+epszero)
* *glusea *engy**epszero
return
end
c########################################################################
c########################################################################
subroutine psaini
c########################################################################
c########################################################################
c-----------------------------------------------------------------------
c common initialization procedure
c if isetcs = 0, alpD, betD, etc ... in inirj are not used and xkappa=1
c if isetcs = 1, alpD, betD, etc ... in inirj are not used but xkappa.ne.1
c if isetcs = 2, alpD, betD, xkappa, etc ... in inirj are used and
c cross section from calculation in inics are read.
c if epos.inics doesn't exist, it produces only the calculated part of it.
c if isetcs = 3, alpD, betD, xkappa, etc ... in inirj are used and
c cross section from simulation in inics are read.
c if epos.inics doesn't exist, it produces the calculated AND the
c simulated part of it both for ionudi=1 and 3. Only the values for
c ionudi=1 (elastic for diffraction counted in xs) are always correct.
c AA xs with ionudi=3 do not always correspond to MC simulations.
c-----------------------------------------------------------------------
include 'epos.inc'
include 'epos.incpar'
include 'epos.incsem'
include 'epos.incems'
logical lcalc!,lcalc2
c double precision om5p,xh,yh,v3pom(4),om2p
dimension gamhad0(nclha),r2had0(nclha),chad0(nclha)
*,alplea0(nclha),asect11(7,4,7),asect13(7,4,7),asect21(7,4,7)
*,asect23(7,4,7),asect31(7,7,7),asect33(7,7,7)
*,asect41(7,7,7),asect43(7,7,7)!,cgam(idxD)
common /psar2/ edmax,epmax
common /psar4/ fhgg(11,10,8),fhqg(11,10,80)
*,fhgq(11,10,80),fhqq(11,10,80),fhgg0(11,10),fhgg1(11,10,4)
*,fhqg1(11,10,40),fhgg01(11),fhgg02(11),fhgg11(11,4)
*,fhgg12(11,4),fhqg11(11,10,4),fhqg12(11,10,4)
*,ftoint(11,14,2,2,3)
common /psar7/ delx,alam3p,gam3p
common /psar9/ alpr
common /psar15/ sudx(40,2)
common /psar19/ cstot(20,20,240)
common /psar20/ csord(20,20,240)
common /psar21/ csbor(20,160,2)
common /psar22/ cstotzero(20,4,2),csborzer(20,4,2)
common /psar23/ cschar(20,20,2)
common /psar25/ csdsi(21,21,104)
common /psar27/ csds(21,26,4),csdt(21,26,2),csdr(21,26,2)
common /psar33/ asect(7,4,7),asectn(7,7,7)
common /psar34/ rrr,rrrm
common /psar35/ anorm,anormp
common /psar41/ rrrp,rrrmp
common /psar36/ alvc
common /psar37/ coefom1,coefom2
common /psar38/ vfro(11,14,3,2)
common /psar39/ vnorm(11,14,3,2,2)
c$$$ common /psar40/ coefxu1(idxD,nclha,10)
c$$$ *,coefxu2(idxD,idxD,nclha,10),coefxc2(idxD,idxD,nclha,10)
common/producetab/ producetables !used to link with CRMC
logical producetables
common /ar3/ x1(7),a1(7)
common /testj/ ajeth(4),ajete(5),ajet0(7)
parameter(nbkbin=40)
common /kfitd/ xkappafit(nclegy,nclha,nclha,nbkbin),xkappa,bkbin
common/geom/rmproj,rmtarg,bmax,bkmx
character textini*38
external ptfau,ptfauAA
call utpri('psaini',ish,ishini,4)
c for fragmentation
c -----------------
c number of flavors in fragmentation not less than active flavor in hard string
nrflav=min(max(nrflav,naflav),nflavems)
pmqu2=pmqu**2
difud=pmqd**2-pmqu2
difus=pmqs**2-pmqu2
difuuu=(pmqq+pmqu+pmqu)**2-pmqu2
difuud=(pudd*pmqq+pmqd+pmqu)**2-pmqu2
difuus=(puds*pmqq+pmqs+pmqu)**2-pmqu2
difudd=(pudd*pudd*pmqq+pmqd+pmqd)**2-pmqu2
difuds=(pudd*puds*pmqq+pmqs+pmqd)**2-pmqu2
difuss=(puds*puds*pmqq+pmqs+pmqs)**2-pmqu2
if(nrflav.gt.3)then
difuc=pmqc**2-pmqu2
difuuc=(pudc*pmqq+pmqc+pmqu)**2-pmqu2
difudc=(pudd*pudc*pmqq+pmqc+pmqd)**2-pmqu2
difusc=(puds*pudc*pmqq+pmqc+pmqs)**2-pmqu2
difucc=(pudc*pudc*pmqq+pmqc+pmqs)**2-pmqu2
else
difuc=0.
difuuc=0.
difudc=0.
difusc=0.
difucc=0.
rstrac(1)=0.
rstrac(2)=0.
rstrac(3)=0.
rstrac(4)=0.
endif
if(iappl.ne.6)then
do i=1,4
ajeth(i)=0.
enddo
do i=1,5
ajete(i)=0.
ajet0(i)=0.
enddo
ajet0(6)=0.
ajet0(7)=0.
if(isetcs.le.1)then !for Kfit
bkbin=0.3
else
bkbin=0.1
endif
xkappa=1.
edmax=edmaxi !1.e12 defined in epos-bas
epmax=epmaxi !1.e12 defined in epos-bas
c fix enhanced diagrams at minimum energy = 2.5
delx=1.5 !sqrt(egymin*egymin/exp(1.))
c arbitrary value for alam3p (not good if too small (infinite loop in rsh))
alam3p=0.5*(r2had(1)+r2had(2)+r2had(3)) !0.6
gam3p=.1
c interface to 'bas'
c ----------------
dels=alppom-1.
alpqua=(alppar+1.)/2.
if(abs(alpqua).lt.1.e-6)call utstop('alpar should not be -1 !&')
alpr=-2.+alpqua !x-exponent for remnant mass
c omega coeffs
c ----------------
coefom0=utgam1(1.+dels-alppar)*utgam1(1.+alplea(iclpro))
*/utgam1(2.+alplea(iclpro)+dels-alppar)
**utgam1(1.+dels-alppar)*utgam1(1.+alplea(icltar))
*/utgam1(2.+alplea(icltar)+dels-alppar)
coefom1=1.-utgam1(1.+dels-alppar)**2*utgam1(1.+alplea(iclpro))
*/utgam1(1.+alplea(iclpro)+2.*(1.+dels-alppar))
**utgam1(1.+dels-alppar)**2*utgam1(1.+alplea(icltar))
*/utgam1(1.+alplea(icltar)+2.*(1.+dels-alppar))/coefom0**2
coefom2=3.*coefom1-1.
*+utgam1(1.+dels-alppar)**3*utgam1(1.+alplea(iclpro))
*/utgam1(1.+alplea(iclpro)+3.*(1.+dels-alppar))
**utgam1(1.+dels-alppar)**3*utgam1(1.+alplea(icltar))
*/utgam1(1.+alplea(icltar)+3.*(1.+dels-alppar))/coefom0**3
if(ish.ge.4)write(ifch,*)'coefom',coefom0,coefom1,coefom2,delx
c soft pomeron: abbreviations
c---------------------------------------
if(iappl.eq.1.or.iappl.eq.8.or.iappl.eq.9)then
c---------------------------------------
c auxiliary constants:
c---------------------------------------
stmass=.05 !string mass cutoff
c---------------------------------------
c parton density normalization
sq=log(log(q2min/.232**2)/log(.23/.232**2))
du=2.997+.753*sq-.076*sq*sq
qnorm=0.
do i=1,7
do m=1,2
xx=.5+x1(i)*(m-1.5)
xxq=1.-xx**(1./(1.+du))
qnorm=qnorm+a1(i)*(psdfh4(xxq,q2min,0.,2,1)+
* psdfh4(xxq,q2min,0.,2,2))/(1.-xxq)**du
enddo
enddo
qnorm=qnorm*.5/(1.+du)
qnormp=qnorm
ckkkkk-----------------------------
c ffrr=(1.-qnorm)/4./pi/gamhad(2)
c * *utgam1(2.+betpom-dels)/utgam1(1.-dels)
c * /utgam1(1.+betpom)/utgam1(1.+alplea(2))/
c * utgam1(2.-alppar)*utgam1(3.+alplea(2)-alppar)
c ffrr=(1.-qnorm)/4./pi/gamhad(2)
c * *utgam1(2.+betpom-dels)/utgam1(1.-dels)
c * /utgam1(1.+betpom)
c write(6,*)'===========',ffrr
ffrr=gamtil
* /utgam1(1.+alplea(2))/
* utgam1(2.-alppar)*utgam1(3.+alplea(2)-alppar)
gamsoft=ffrr*4.*pi
ckkkkkkk-------------------------------
if(ish.ge.4)write (ifch,*)'rr,qnorm',ffrr,qnorm
sq=log(log(q2min/.232**2)/log(.25/.232**2))
dpi=.367+.563*sq
qnorm=0.
do i=1,7
do m=1,2
xx=.5+x1(i)*(m-1.5)
xxq=1.-xx**(1./(1.+dpi))
qnorm=qnorm+a1(i)*(psdfh4(xxq,q2min,0.,1,1)+
* psdfh4(xxq,q2min,0.,1,2))/(1.-xxq)**dpi
enddo
enddo
qnorm=qnorm*.5/(1.+dpi)
cftmp=1./(1.-qnormp)*(1.-qnorm)
* *utgam1(alplea(2)+1.)/utgam1(alplea(2)+3.-alppar)
* /utgam1(alplea(1)+1.)*utgam1(alplea(1)+3.-alppar)
gamhad(1)=gamhad(2)*cftmp
if(gamhadsi(1).lt.0.)then
gamhads(1)=gamhad(1)
else
gamhads(1)=gamhad(1)*gamhadsi(1)
endif
gamhad(1)=gamhads(1)
if(ish.ge.4)
* write (ifch,*)'gamhad(1),gamhads(1)',gamhad(1),gamhads(1)
if(gamhadsi(2).lt.0.)then
gamhads(2)=gamhad(2)
else
gamhads(2)=gamhad(2)*gamhadsi(2)
endif
gamhad(2)=gamhads(2)
if(ish.ge.4)
* write (ifch,*)'gamhad(2),gamhads(2)',gamhad(2),gamhads(2)
qnorm=0.
do i=1,7
do m=1,2
xx=.5+x1(i)*(m-1.5)
xxq=1.-xx**(1./(1.+dpi))
qnorm=qnorm+a1(i)*(psdfh4(xxq,q2min,0.,1,1)+
* psdfh4(xxq,q2min,0.,1,2))/(1.-xxq)**dpi
enddo
enddo
qnorm=qnorm*.5/(1.+dpi)
cftmp=1./(1.-qnormp)*(1.-qnorm)
* *utgam1(alplea(2)+1.)/utgam1(alplea(2)+3.-alppar)
* /utgam1(alplea(3)+1.)*utgam1(alplea(3)+3.-alppar)
gamhad(3)=gamhad(2)*cftmp
if(gamhadsi(3).lt.0.)then
gamhads(3)=gamhad(3)
else
gamhads(3)=gamhad(3)*gamhadsi(3)
endif
gamhad(3)=gamhads(3)
if(ish.ge.4)
* write (ifch,*)'gamhad(3),gamhads(3)',gamhad(3),gamhads(3)
quamas=.35
gamhad(4)=gamhad(1)*(quamas/qcmass)**2
if(gamhadsi(4).lt.0.)then
gamhads(4)=gamhad(4)
else
gamhads(4)=gamhad(4)*gamhadsi(4)
endif
gamhad(4)=gamhads(4)
if(ish.ge.4)
* write (ifch,*)'gamhad(4),gamhads(4)',gamhad(4),gamhads(4)
gnorm=0.
do i=1,7
do m=1,2
xx=.5+x1(i)*(m-1.5)
xxg=xx**(1./(1.-dels))
gnorm=gnorm+a1(i)*(fzeroGluZZ(xxg,4)+fzeroSeaZZ(xxg,4))
enddo
enddo
gnorm=gnorm/(1.-dels)*2.*pi*gamhad(4)*ffrr
alvc=6./(1.-gnorm)-4.
if(ish.ge.4) write (ifch,*)'rr,qnorm,gnorm,alvc',
* ffrr,qnorm,gnorm,alvc
c write (*,*)'rr-c,qnorm,gnorm,alvc',ffrr,qnorm,gnorm,alvc
endif
c-----------------------------------------------
c tabulation of inclusive jet cross sections
c--------------------------------------------------
do i=1,40
qi=q2min*exp(.5*(i-1))
sudx(i,1)=psudx(qi,1)
sudx(i,2)=psudx(qi,2)
enddo
if(ish.ge.4)write(ifch,*)'bare cross sections ...'
call psaevc
ccc call MakeCSTable
inquire(file=fnii(1:nfnii),exist=lcalc)
if(lcalc)then
if(inicnt.eq.1)then
write(ifmt,'(3a)')'read from ',fnii(1:nfnii),' ...'
open(1,file=fnii(1:nfnii),status='old')
read (1,*)qcdlam0,q2min0,q2ini0,naflav0,epmax0,pt2cut0
if(qcdlam0.ne.qcdlam)write(ifmt,'(a)')'initl: wrong qcdlam'
if(q2min0 .ne.q2min )write(ifmt,'(a)')'initl: wrong q2min'
if(q2ini0 .ne.q2ini )write(ifmt,'(a)')'initl: wrong q2ini'
if(naflav0.ne.naflav)write(ifmt,'(a)')'initl: wrong naflav'
if(epmax0 .ne.epmax )write(ifmt,'(a)')'initl: wrong epmax'
if(pt2cut0 .ne.pt2cut )write(ifmt,'(a)')'initl: wrong pt2cut'
if(qcdlam0.ne.qcdlam.or.q2min0 .ne.q2min .or.q2ini0 .ne.q2ini
* .or.naflav0.ne.naflav.or.epmax0 .ne.epmax.or. pt2cut.ne.pt2cut0)
* then
write(ifmt,'(//a//)')' initl has to be reinitialized!!!'
stop
endif
read (1,*)csbor,csord,cstot,cstotzero,csborzer
close(1)
endif
goto 1
elseif(.not.producetables)then
write(ifmt,*) "Missing epos.initl file !"
write(ifmt,*) "Please correct the defined path ",
&"or force production ..."
stop
endif
write(ifmt,'(a)')'initl does not exist -> calculate tables ...'
write (*,*)'Born xsection csbor'
spmin=4.*q2min
spminc=4.*q2min+qcmass**2
do m=1,4 !parton type at upper end of the ladder (1...4 - g,u,d,c)
do k=1,20
if(m.ne.4)then
sk=spmin*(epmax/2./spmin)**((k-1)/19.)
p1=sk
else
sk=spminc*(epmax/2./spminc)**((k-1)/19.)
p1=sk/(1.+qcmass**2/sk)
endif
qmax=p1/4.
do i=1,20
qq=q2min*(qmax/q2min)**((i-1)/19.)
do l=1,2 !parton type at lower end of the ladder
k1=k+20*(m-1)+80*(l-1)
m1=m-1
if(m.eq.3.and.l.eq.1)then !dd~
l1=-m1
else !du
l1=l-1
endif !born cr.-sect.
csbor(i,k1,1)=log(max(1.e-30,psborn(qq,qq,qq,sk,m1,l1,0,0)))
if(m.ne.4)then
csbor(i,k1,2)=log(max(1.e-30,psborn(4.*qq,qq,qq,sk,m1,l1,1,0)))
endif
enddo
enddo
enddo
enddo
write (*,*)'ordered jet xsection csord'
do m=1,4 !parton type at upper end of the ladder
do k=1,20
write (*,*)' m=',m,'/4 k=',k,'/20'
if(m.ne.4)then
sk=spmin*(epmax/2./spmin)**((k-1)/19.) !c.m. energy squared for the hard
p1=sk
else
sk=spminc*(epmax/2./spminc)**((k-1)/19.)
p1=sk/(1.+qcmass**2/sk)
endif
qmax=p1/4.
tmax=p1/2.
do i=1,20 !cross-sections initialization
qi=q2min*(qmax/q2min)**((i-1)/19.)
do j=1,20
qq=qi*(qmax/qi)**((j-1)/19.)
if(p1.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/p1))
else
tmin=2.*qq
endif
do l=1,2 !parton type at lower end of the ladder
m1=m-1
if(m.eq.3.and.l.eq.1)then
l1=-m1
else
l1=l-1
endif
if(m.ne.4)then
k1=k+20*(m-1)+60*(l-1)
if(k.eq.1.or.i.eq.20.or.j.eq.20)then
csord(i,j,k1)=log(max(1.e-30,psborn(qi,qq,qq,sk,m1,l1,0,0)))
csord(i,j,k1+120)=
* log(max(1.e-30,psborn(4.*qq,qi,qq,sk,l1,m1,1,0)))
else
csord(i,j,k1)=log(psjet1(qi,qq,qq,sk,m1,l1,0)
* /(1./tmin-1./tmax)+psborn(qi,qq,qq,sk,m1,l1,0,0))
csord(i,j,k1+120)=log(psjet1(qi,4.*qq,qq,sk,m1,l1,2)
* /(1./tmin-1./tmax)+psborn(4.*qq,qi,qq,sk,l1,m1,1,0))
endif
elseif(j.eq.1)then
if(k.eq.1.or.i.eq.20)then
cschar(i,k,l)=log(max(1.e-30,psborn(q2min,qi,qq,sk,m1,l1,0,0)))
else
cschar(i,k,l)=log(psjet1(qi,q2min,qq,sk,l1,m1,0)
* /(1./tmin-1./tmax)+psborn(q2min,qi,qq,sk,m1,l1,0,0))
endif
endif
enddo
enddo
enddo
enddo
enddo
write (ifmt,*)'tests:'
write (ifmt,'(a,a)')' n-1 sk qi qj qq '
* ,' born born-i ord ord-i '
do k=1,7
sk=spmin*(epmax/2./spmin)**((k-1)/19.)
if(k.ge.5)sk=spmin*1.5**(k-4)
do n=1,2
if(n.eq.1)then
qmax1=sk/4.
qmax2=sk/4.
else !if(n.eq.2)then
qmax1=sk/4.
qmax2=sk
endif
do i=1,3
qi=q2min*(qmax1/q2min)**((i-1)/3.)
do j=1,3
qj=q2min*(qmax2/q2min)**((j-1)/3.)
qqmax=sk/4.
if(n.eq.1)then
qqmin=max(qi,qj)
else
qqmin=max(qi,qj/4.)
endif
do lq=1,3
qq=qqmin*(qqmax/qqmin)**((lq-1)/3.)
if(sk.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/sk))
else
tmin=2.*qq
endif
tmax=sk/2.
do m=1,1 !parton type at upper end of the ladder (1
do l=1,1 !parton type at lower end of the ladder (1
m1=m-1
if(m.eq.3.and.l.eq.1)then
l1=-m1
else
l1=l-1
endif
a=psborn(qj,qi,qq,sk,l1,m1,n-1,0)*(1./tmin-1./tmax)
b=psbint(qj,qi,qq,sk,l1,m1,n-1)
c=psjet1(qi,qj,qq,sk,m1,l1,2*(n-1))
* +psborn(qj,qi,qq,sk,l1,m1,n-1,0)*(1./tmin-1./tmax)
d=psjti1(qi,qj,qq,sk,m1,l1,n-1)
write (ifmt,'(i3,4f9.1,3x,4f9.4)')n-1,sk,qi,qj,qq,a,b,c,d
enddo
enddo
enddo
enddo
enddo
enddo
enddo
write (*,*)'jet xsection cstot'
do k=1,20
write (*,*)'k=',k,'/20'
sk=spmin*(epmax/2./spmin)**((k-1)/19.) !c.m. energy squared for the hard
qmax=sk/4.
tmax=sk/2.
do i=1,20 !cross-sections initialization
do n=1,2
if(n.eq.1)then
qi=q2min*(qmax/q2min)**((i-1)/19.)
else
qi=q2min*(4.*qmax/q2min)**((i-1)/19.)
endif
do j=1,20
if(n.eq.1)then
qq=qi*(qmax/qi)**((j-1)/19.)
else
qq=max(q2min,qi/4.)*(qmax/max(q2min,qi/4.))**
* ((j-1)/19.)
endif
if(sk.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/sk))
else
tmin=2.*qq
endif
do m=1,3 !parton type at upper end of the ladder (1
do l=1,2 !parton type at lower end of the ladder (1
m1=m-1
if(m.eq.3.and.l.eq.1)then
l1=-m1
else
l1=l-1
endif
k1=k+20*(m-1)+60*(l-1)+120*(n-1)
if(k.eq.1.or.i.eq.20.or.j.eq.20)then
cstot(i,j,k1)=log(max(1.e-30,psborn(qi,q2min,qq,sk,m1,l1,n-1,0)))
else
if(n.eq.1)then
cstot(i,j,k1)=log((psjet(qi,q2min,qq,sk,m1,l1,0)+
* psjti1(qi,q2min,qq,sk,m1,l1,0)+
* psjti1(q2min,qi,qq,sk,l1,m1,0)
* -psbint(qi,q2min,qq,sk,m1,l1,0))/(1./tmin-1./tmax))
else
cstot(i,j,k1)=log((psjet(qi,q2min,qq,sk,m1,l1,1)+
* psjet1(qi,q2min,qq,sk,m1,l1,1)+
* psjti1(q2min,qi,qq,sk,l1,m1,1))/(1./tmin-1./tmax))
endif
endif
enddo
enddo
enddo
enddo
enddo
enddo
c total and born hard cross-sections logarithms for minimal cutoff
c (q2min), interpolated in the psjti0 procedure
spmin=4.*q2min
spminc=4.*q2min+qcmass**2
do m=1,4
do l=1,2
m1=m-1
if(m.eq.3.and.l.eq.1)then
l1=-m1
else
l1=l-1
endif
do k=1,20
if(m.ne.4)then
sk=spmin*(epmax/2./spmin)**((k-1)/19.) !c.m. energy squared for the hard
p1=sk
qq=q2min
else
sk=spminc*(epmax/2./spminc)**((k-1)/19.)
p1=sk/(1.+qcmass**2/sk)
qq=q2min
endif
if(p1.gt.4.*qq)then
tmin=2.*qq/(1.+sqrt(1.-4.*qq/p1))
else
tmin=2.*qq
endif
tmax=p1/2.
k1=k+20*(m-1)+80*(l-1)
csborzer(k,m,l)
* =log(max(1.e-30,psborn(q2min,q2min,qq,sk,m1,l1,0,0)))
if(k.eq.1)then
cstotzero(k,m,l)=csborzer(k,m,l)
elseif(m.ne.4)then
cstotzero(k,m,l)=log(psjti(q2min,qq,sk,m1,l1,0)/
* (1./tmin-1./tmax))
else
smins=2.5*q2min*(1.+sqrt(1.+4.*qcmass**2/q2min))
if(sk.le.smins)then
cstotzero(k,m,l)=log(psjci(q2min,sk,l1)/(1./tmin-1./tmax))
else
cstotzero(k,m,l)=log((psjci(q2min,sk,l1)+psjct(sk,l1))
* /(1./tmin-1./tmax))
endif
endif
enddo
enddo
enddo
write(ifmt,'(a)')'write to initl ...'
open(1,file=fnii(1:nfnii),status='unknown')
write (1,*)qcdlam,q2min,q2ini,naflav,epmax,pt2cut
write (1,*)csbor,csord,cstot,cstotzero,csborzer,cschar
close(1)
1 continue
if(iappl.ne.8)goto 3
if(ish.ge.3)write(ifch,*)'dis cross sections ...'
inquire(file=fnid(1:nfnid),exist=lcalc)
if(lcalc)then
if(inicnt.eq.1)then
write(ifmt,'(3a)')'read from ',fnid(1:nfnid),' ...'
open(1,file=fnid(1:nfnid),status='old')
read (1,*)qcdlam0,q2min0,q2ini0,naflav0,epmax0,edmax0
if(qcdlam0.ne.qcdlam)write(ifmt,'(a)')'inidi: wrong qcdlam'
if(q2min0 .ne.q2min )write(ifmt,'(a)')'inidi: wrong q2min'
if(q2ini0 .ne.q2ini )write(ifmt,'(a)')'inidi: wrong q2ini'
if(naflav0.ne.naflav)write(ifmt,'(a)')'inidi: wrong naflav'
if(epmax0 .ne.epmax )write(ifmt,'(a)')'inidi: wrong epmax'
if(edmax0 .ne.edmax )write(ifmt,'(a)')'inidi: wrong edmax'
if(qcdlam0.ne.qcdlam.or.q2min0 .ne.q2min.or.q2ini0 .ne.q2ini
* .or.naflav0.ne.naflav.or.epmax0 .ne.epmax
* .or.edmax0 .ne.edmax)then
write(ifmt,'(//a//)')' inidi has to be reinitialized!!!'
stop
endif
read (1,*)csdsi,csds,csdt,csdr
close(1)
endif
goto 3
elseif(.not.producetables)then
write(ifmt,*) "Missing epos.inidi file !"
write(ifmt,*) "Please correct the defined path ",
&"or force production ..."
stop
endif
write(ifmt,'(a)')'inidi does not exist -> calculate tables ...'
do j=1,21
qq=q2min*exp(.5*(j-1)) !photon virtuality
do m=1,2 !parton type at the end of the ladder
q2mass=qcmass**2
s2min=4.*max(q2mass,q2min)+qq
if(m.eq.2)s2min=s2min/(1.-4.*q2ini/(s2min-qq))
do k=1,26
write (*,*)'sin,j,m,k',j,m,k
sk=s2min*(edmax/s2min)**(.04*(k-1)) !c.m. energy squared
if(k.eq.26)sk=1.01*sk
qmin=q2min
if(m.eq.1)then
qmax=(sk-qq)/4.
else
qmax=(sk-qq+sqrt((sk-qq)**2-16.*sk*q2ini))/8.
endif
do i=1,21 !cross-sections calculation
qi=qmin*(qmax/qmin)**((i-1)/20.)
tmax=.5*sk
qtq=4.*max(q2mass,qi)/(sk-qq)
if(qtq.lt.1.)then
tmin=.5*sk*qtq/(1.+sqrt(1.-qtq))
else
tmin=.5*sk
endif
do ilong=1,2
k1=k+26*(m-1)+52*(ilong-1)
if(m.eq.1)then
if(tmax.gt.1.01*tmin)then
sij=psds(qi,qq,sk,m-1,ilong-1)
if(sij.lt.0.)write (*,*)'qi,qq,sk,m,long,sij',
* qi,qq,sk,m,ilong,sij
csdsi(i,j,k1)=log(max(0.,sij)/(1./tmin-1./tmax)
* +psdbor(qi,qq,sk,ilong-1))
else
csdsi(i,j,k1)=
* log(max(1.e-25,psdbor(qi,qq,sk,ilong-1)))
endif
else
csdsi(i,j,k1)=psds(qi,qq,sk,m-1,ilong-1)
endif
enddo
enddo
enddo
enddo
enddo
do j=1,21
qq=q2min*exp(.5*(j-1)) !photon virtuality
s2min=max(4.*qq,16.*q2min) !pt2dis=qq
do m=1,2
do k=1,26
do ilong=1,2
k1=k+26*(m-1)+52*(ilong-1)
csds(j,k,m+2*(ilong-1))=csdsi(1,j,k1)
enddo
sk=(s2min+qq)*(edmax/(s2min+qq))**(.04*(k-1))
csdt(j,k,m)=psdres(qq,sk,s2min,m-1)
csdr(j,k,m)=psdrga(qq,sk-qq,s2min,m-1)
enddo
enddo
enddo
write(ifmt,'(a)')'write to inidi ...'
write(ifmt,'(a)')'write to inidi ...'
open(1,file=fnid(1:nfnid),status='unknown')
write (1,*)qcdlam,q2min,q2ini,naflav,epmax,edmax
write (1,*)csdsi,csds,csdt,csdr
close(1)
3 continue
c---------------------------------------
c tabulation of semihard eikonals
c---------------------------------------
!!!!!!!!! if(iappl.eq.1)then
if(ish.ge.4)write(ifch,*)'semihard eikonals ...'
5 continue
inquire(file=fnrj,exist=lcalc)
if(lcalc)then
if(inicnt.eq.1)then
write(ifmt,'(3a)')'read from ',fnrj(1:nfnrj),' ...'
open(1,file=fnrj(1:nfnrj),status='old')
read (1,*)alpqua0,alplea0,alppom0,slopom0,
* gamhad0,r2had0,chad0,
* qcdlam0,q2min0,q2ini0,betpom0,glusea0,naflav0,
* factk0,pt2cut0,gamtil0
if(alpqua0.ne.alpqua)write(ifmt,'(a,2f8.4)')
* 'inirj: wrong alpqua',alpqua0,alpqua
if(alppom0.ne.alppom)write(ifmt,'(a,2f8.4)')
* 'inirj: wrong alppom',alppom0,alppom
if(slopom0.ne.slopom)write(ifmt,'(a,2f8.4)')
* 'inirj: wrong slopom',slopom0,slopom
iii=2
if(gamhad0(iii).ne.gamhad(iii))write(ifmt,'(a,i1,a,2f8.4)')
* 'inirj: wrong gamhad(',iii,')',gamhad0(iii),gamhad(iii)
do iii=1,3
if(r2had0(iii) .ne.r2had(iii) )write(ifmt,'(a,i1,a,2f8.4)')
* 'inirj: wrong r2had(',iii,')',r2had0(iii),r2had(iii)
if(chad0(iii) .ne.chad(iii) )write(ifmt,'(a,i1,a,2f8.4)')
* 'inirj: wrong chad(',iii,')',chad0(iii),chad(iii)
if(alplea0(iii).ne.alplea0(iii))write(ifmt,'(a,i1,a,2f8.4)')
* 'inirj: wrong alplea(',iii,')',alplea0(iii),alplea(iii)
enddo
if(qcdlam0.ne.qcdlam)write(ifmt,'(a,2f8.4)')
* 'inirj: wrong qcdlam',qcdlam0,qcdlam
if(q2min0 .ne.q2min )write(ifmt,'(a,2f8.4)')
* 'inirj: wrong q2min',q2min0,q2min
if(q2ini0 .ne.q2ini )write(ifmt,'(a,2f8.4)')
* 'inirj: wrong q2ini',q2ini0,q2ini
if(betpom0.ne.betpom)write(ifmt,'(a,2f8.4)')
* 'inirj: wrong betpom',betpom0,betpom
if(glusea0.ne.glusea)write(ifmt,'(a,2f8.4)')
* 'inirj: wrong glusea',glusea0,glusea
if(naflav0.ne.naflav)write(ifmt,'(a,2f8.4)')
* 'inirj: wrong naflav',naflav0,naflav
if(factk0 .ne.factk )write(ifmt,'(a,2f8.4)')
* 'inirj: wrong factk', factk0,factk
if(pt2cut0 .ne.pt2cut )write(ifmt,'(a,2f8.4)')
* 'inirj: wrong pt2cut', pt2cut0,pt2cut
if(gamtil0 .ne.gamtil )write(ifmt,'(a,2f8.4)')
* 'inirj: wrong gamtil', gamtil0,gamtil
if(alpqua0.ne.alpqua.or.alppom0.ne.alppom
* .or.slopom0.ne.slopom.or.gamhad0(2).ne.gamhad(2)
* .or.r2had0(1).ne.r2had(1).or.r2had0(2).ne.r2had(2)
* .or.r2had0(3).ne.r2had(3)
* .or.chad0(1).ne.chad(1).or.chad0(2).ne.chad(2)
* .or.chad0(3).ne.chad(3)
* .or.alplea0(1).ne.alplea(1).or.alplea0(2).ne.alplea(2)
* .or.alplea0(3).ne.alplea(3)
* .or.qcdlam0.ne.qcdlam.or.q2min0 .ne.q2min
* .or.q2ini0 .ne.q2ini.or.gamtil0.ne.gamtil
* .or.betpom0.ne.betpom.or.glusea0.ne.glusea.or.naflav0.ne.naflav
* .or.factk0 .ne.factk .or.pt2cut0.ne.pt2cut)then
write(ifmt,'(//a//)')' inirj has to be reinitialized!!!!'
stop
endif
read(1,*)fhgg,fhqg,fhgq,fhqq,fhgg0,fhgg1,fhqg1
* ,fhgg01,fhgg02,fhgg11,fhgg12,fhqg11,fhqg12
* ,ftoint,vfro,vnorm,coefxu1,coefxu2,coefxc2
read(1,*)bkbin0,iclpro10,iclpro20,icltar10,icltar20,iclegy10
* ,iclegy20,egylow0,egymax0,iomega0,egyscr0,epscrw0,epscrp0
if(isetcs.gt.1)then
textini=' '
if(iclpro10.ne.iclpro1)write(textini,'(a,2i8)')
* 'inirj: wrong iclpro1 ',iclpro10,iclpro1
if(iclpro20.ne.iclpro2)write(textini,'(a,2i8)')
* 'inirj: wrong iclpro2 ',iclpro20,iclpro2
if(icltar10.ne.icltar1)write(textini,'(a,2i8)')
* 'inirj: wrong icltar1 ',icltar10,icltar1
if(icltar20.ne.icltar2)write(textini,'(a,2i8)')
* 'inirj: wrong icltar2 ',icltar20,icltar2
if(iclegy10.ne.iclegy1)write(textini,'(a,2i8)')
* 'inirj: wrong iclegy1 ',iclegy10,iclegy1
if(iclegy20.ne.iclegy2)write(textini,'(a,2i8)')
* 'inirj: wrong iclegy2 ',iclegy20,iclegy2
if(iomega0.ne.iomega)write(textini,'(a,2i8)')
* 'inirj: wrong iomega ',iomega0,iomega
if(egylow0.ne.egylow)write(textini,'(a,2f8.4)')
* 'inirj: wrong egylow ',egylow0,egylow
if(egymax0.ne.egymax)write(textini,'(a,2f8.4)')
* 'inirj: wrong egymax ',egymax0,egymax
if(epscrw0.ne.epscrw)write(textini,'(a,2f8.4)')
* 'inirj: wrong epscrw ',epscrw0,epscrw
if(epscrp0.ne.epscrp)write(textini,'(a,2f8.4)')
* 'inirj: wrong epscrp ',epscrp0,epscrp
if(bkbin0.ne.bkbin)write(textini,'(a,2f8.4)')
* 'inirj: wrong bkbin',bkbin0,bkbin
if(textini.ne.' ')then
write(ifmt,'(//10x,a//10x,a//)')textini,
* 'inirj has to be reinitialized!!!!'
stop
endif
do iiipro=iclpro1,iclpro2
do iiitar=icltar1,icltar2
do iiiegy=iclegy1,iclegy2
do iiib=1,nbkbin
read(1,*)xkappafit(iiiegy,iiipro,iiitar,iiib)
enddo
xkappafit(iiiegy,iiipro,iiitar,nbkbin)=1.
do iiib=2,nbkbin-1
if(xkappafit(iiiegy,iiipro,iiitar,iiib).lt.1.)then
xkappafit(iiiegy,iiipro,iiitar,iiib)=max(1.,0.5*
* (xkappafit(iiiegy,iiipro,iiitar,iiib-1)
* +xkappafit(iiiegy,iiipro,iiitar,iiib+1)))
endif
enddo
do iiidf=idxD0,idxD
read(1,*)alpDs(iiidf,iiiegy,iiipro,iiitar),
* alpDps(iiidf,iiiegy,iiipro,iiitar),
* alpDpps(iiidf,iiiegy,iiipro,iiitar),
* betDs(iiidf,iiiegy,iiipro,iiitar),
* betDps(iiidf,iiiegy,iiipro,iiitar),
* betDpps(iiidf,iiiegy,iiipro,iiitar),
* gamDs(iiidf,iiiegy,iiipro,iiitar),
* delDs(iiidf,iiiegy,iiipro,iiitar)
enddo
enddo
enddo
enddo
endif
close(1)
endif
goto 4
elseif(.not.producetables)then
write(ifmt,*) "Missing epos.inirj file !"
write(ifmt,*) "Please correct the defined path ",
&"or force production ..."
stop
endif
write(ifmt,'(a)')'inirj does not exist -> calculate tables ...'
engysave=engy
maprojsave=maproj
matargsave=matarg
iclpros=iclpro
icltars=icltar
spmin=4.*q2min
spminc=4.*q2min+2.*qcmass**2
icltar=2
write(ifmt,'(a)')' tabulate om5 ...'
do iy=1,11
sy=spmin*(epmax/2./spmin)**((iy-1)/10.)
syc=spminc*(epmax/2./spminc)**((iy-1)/10.)
iclpro=2
icltar=2
if(iy.eq.1)then
fhgg01(iy)=-80.
fhgg02(iy)=-80.
else
fhgg01(iy)=log(om51pp(sy,1.,1.,3))
fhgg02(iy)=log(om51pp(sy,1.,1.,7))
endif
do iclpro=iclpro1,iclpro2
if(iy.eq.1)then
fhgg11(iy,iclpro)=-80.
fhgg12(iy,iclpro)=-80.
else
fhgg11(iy,iclpro)=log(om51pp(sy,1.,1.,4))
fhgg12(iy,iclpro)=log(om51pp(sy,1.,1.,9))
endif
do ix=1,10
if(ix.le.5)then
xp=.1*2.**(ix-5)
else
xp=.2*(ix-5)
endif
if(iy.eq.1)then
fhqg11(iy,ix,iclpro)=-80.
fhqg12(iy,ix,iclpro)=-80.
elseif(iclpro.eq.4)then
fhqg11(iy,ix,iclpro)=log(om51pp(syc,1.,1.,5))
fhqg12(iy,ix,iclpro)=log(om51pp(syc,1.,1.,11))
else
fhqg11(iy,ix,iclpro)=log(om51pp(sy,xp,1.,5))
fhqg12(iy,ix,iclpro)=log(om51pp(sy,xp,1.,11))
endif
enddo
enddo
do iz=1,10
z=.1*iz
iclpro=2
icltar=2
if(iy.eq.1)then
fhgg0(iy,iz)=-80.
else
fhgg0(iy,iz)=log(om51pp(sy,1.,z,6)/z)
endif
do iclpro=iclpro1,iclpro2
if(iy.eq.1)then
fhgg1(iy,iz,iclpro)=-80.
else
fhgg1(iy,iz,iclpro)=log(om51pp(sy,1.,z,8)/z)
endif
do ix=1,10
if(ix.le.5)then
xp=.1*2.**(ix-5)
else
xp=.2*(ix-5)
endif
if(iy.eq.1)then
fhqg1(iy,ix,iz+10*(iclpro-1))=-80.
elseif(iclpro.eq.4)then
fhqg1(iy,ix,iz+10*(iclpro-1))=log(om51pp(syc,xp,z,10)/z)
else
fhqg1(iy,ix,iz+10*(iclpro-1))=log(om51pp(sy,xp,z,10)/z)
endif
enddo
enddo
enddo
enddo
do iclpro=iclpro1,iclpro2 !hadron type (1 - pion, 2 - nucleon, 3 - kaon, 4 - charm)
do icltar=icltar1,icltar2 !hadron type (2 - nucleon)
do iy=1,11
sy=spmin*(epmax/2./spmin)**((iy-1)/10.)
syc=spminc*(epmax/2./spminc)**((iy-1)/10.)
do iz=1,10
z=.1*iz
if(iy.eq.1)then
fhgg(iy,iz,iclpro+4*(icltar-1))=-80.
else
fhgg(iy,iz,iclpro+4*(icltar-1))=log(om51pp(sy,1.,z,0)/z)
endif
do ix=1,10
if(ix.le.5)then
xp=.1*2.**(ix-5)
else
xp=.2*(ix-5)
endif
if(iy.eq.1)then
fhqg(iy,ix,iz+10*(iclpro+4*(icltar-1)-1))=-80.
fhgq(iy,ix,iz+10*(iclpro+4*(icltar-1)-1))=-80.
else
if(iclpro.ne.4)then
syx=sy
else
syx=syc
endif
fhqg(iy,ix,iz+10*(iclpro+4*(icltar-1)-1))=
* log(om51pp(syx,xp,z,1)/z)
if(icltar.ne.4)then
syx=sy
else
syx=syc
endif
fhgq(iy,ix,iz+10*(iclpro+4*(icltar-1)-1))=
* log(om51pp(syx,xp,z,2)/z)
endif
enddo
enddo
do ix1=1,10
if(ix1.le.5)then
xpph=.1*2.**(ix1-5)
else
xpph=.2*(ix1-5)
endif
do ix2=1,10
if(ix2.le.5)then
xmm=.1*2.**(ix2-5)
else
xmm=.2*(ix2-5)
endif
if(iy.eq.1)then
fhqq(iy,ix1,ix2+10*(iclpro+4*(icltar-1)-1))=-80.
else
if(iclpro.ne.4.and.icltar.ne.4)then
syx=sy
else
syx=syc
endif
fhqq(iy,ix1,ix2+10*(iclpro+4*(icltar-1)-1))=
* log(pshard(syx,xpph,xmm))
endif
enddo
enddo
enddo
enddo
enddo
if(isetcs.gt.1)then
write(ifmt,'(a)')' tabulate fit parameters ...'
engysave=engy
do iclpro=iclpro1,iclpro2 !hadron type (1 - pion, 2 - nucleon, 3 - kaon, 4 - charm)
do icltar=icltar1,icltar2 !hadron type (2 - nucleon)
do iclegy=iclegy2,iclegy1,-1
call param
enddo
do iiclegy=iclegy2,iclegy1,-1
engy=egyfac**(iiclegy-1)*egylow
call paramini(0)
call Kfit(iiclegy)
enddo
enddo
enddo
engy=engysave
endif
write(ifmt,'(a)')' write to inirj ...'
open(1,file=fnrj,status='unknown')
write (1,*)alpqua,alplea,alppom,slopom,gamhad,r2had,chad,
*qcdlam,q2min,q2ini,betpom,glusea,naflav,factk,pt2cut,gamtil
write (1,*)fhgg,fhqg,fhgq,fhqq,fhgg0,fhgg1,fhqg1
*,fhgg01,fhgg02,fhgg11,fhgg12,fhqg11,fhqg12
*,ftoint,vfro,vnorm,coefxu1,coefxu2,coefxc2
write(1,*)bkbin,iclpro1,iclpro2,icltar1,icltar2,iclegy1,iclegy2
*,egylow,egymax,iomega,egyscr,epscrw,epscrp
do iiipro=iclpro1,iclpro2
do iiitar=icltar1,icltar2
do iiiegy=iclegy1,iclegy2
do iiib=1,nbkbin
write(1,*)xkappafit(iiiegy,iiipro,iiitar,iiib)
enddo
do iiidf=idxD0,idxD
write(1,*)alpDs(iiidf,iiiegy,iiipro,iiitar),
* alpDps(iiidf,iiiegy,iiipro,iiitar),
* alpDpps(iiidf,iiiegy,iiipro,iiitar),
* betDs(iiidf,iiiegy,iiipro,iiitar),
* betDps(iiidf,iiiegy,iiipro,iiitar),
* betDpps(iiidf,iiiegy,iiipro,iiitar),
* gamDs(iiidf,iiiegy,iiipro,iiitar),
* delDs(iiidf,iiiegy,iiipro,iiitar)
enddo
enddo
enddo
enddo
close(1)
engy=engysave
maproj=maprojsave
matarg=matargsave
iclpro=iclpros
icltar=icltars
inicnt=1
goto 5
4 continue
c--------------------------------------
c inelastic cross sections
c---------------------------------------
if(isetcs.ge.2)then !--------------------
if(ish.ge.4)write(ifch,*)'cross sections ...'
6 continue
inquire(file=fncs,exist=lcalc)
if(lcalc)then
if(inicnt.eq.1)then
write(ifmt,'(3a)')'read from ',fncs(1:nfncs),' ...'
open(1,file=fncs(1:nfncs),status='old')
read (1,*)alpqua0,alplea0,alppom0,slopom0,
* gamhad0,r2had0,chad0,
* qcdlam0,q2min0,q2ini0,betpom0,glusea0,naflav0,
* factk0,pt2cut0
if(alpqua0.ne.alpqua)write(ifmt,'(a,2f8.4)')
* 'inics: wrong alpqua',alpqua0,alpqua
if(alppom0.ne.alppom)write(ifmt,'(a,2f8.4)')
* 'inics: wrong alppom',alppom0,alppom
if(slopom0.ne.slopom)write(ifmt,'(a,2f8.4)')
* 'inics: wrong slopom',slopom0,slopom
iii=2
if(gamhad0(iii).ne.gamhad(iii))write(ifmt,'(a,i1,a,2f8.4)')
* 'inics: wrong gamhad(',iii,')',gamhad0(iii),gamhad(iii)
do iii=1,3
if(r2had0(iii) .ne.r2had(iii) )write(ifmt,'(a,i1,a,2f8.4)')
* 'inics: wrong r2had(',iii,')',r2had0(iii),r2had(iii)
if(chad0(iii) .ne.chad(iii) )write(ifmt,'(a,i1,a,2f8.4)')
* 'inics: wrong chad(',iii,')',chad0(iii),chad(iii)
if(alplea0(iii).ne.alplea0(iii))write(ifmt,'(a,i1,a,2f8.4)')
* 'inics: wrong alplea(',iii,')',alplea0(iii),alplea(iii)
enddo
if(qcdlam0.ne.qcdlam)write(ifmt,'(a,2f8.4)')
* 'inics: wrong qcdlam',qcdlam0,qcdlam
if(q2min0 .ne.q2min )write(ifmt,'(a,2f8.4)')
* 'inics: wrong q2min',q2min0,q2min
if(q2ini0 .ne.q2ini )write(ifmt,'(a,2f8.4)')
* 'inics: wrong q2ini',q2ini0,q2ini
if(betpom0.ne.betpom)write(ifmt,'(a,2f8.4)')
* 'inics: wrong betpom',betpom0,betpom
if(glusea0.ne.glusea)write(ifmt,'(a,2f8.4)')
* 'inics: wrong glusea',glusea0,glusea
if(naflav0.ne.naflav)write(ifmt,'(a,2f8.4)')
* 'inics: wrong naflav',naflav0,naflav
if(factk0 .ne.factk )write(ifmt,'(a,2f8.4)')
* 'inics: wrong factk', factk0,factk
if(pt2cut0 .ne.pt2cut )write(ifmt,'(a,2f8.4)')
* 'inics: wrong pt2cut', pt2cut0,pt2cut
if(alpqua0.ne.alpqua.or.alppom0.ne.alppom
* .or.slopom0.ne.slopom.or.gamhad0(2).ne.gamhad(2)
* .or.r2had0(1).ne.r2had(1).or.r2had0(2).ne.r2had(2)
* .or.r2had0(3).ne.r2had(3)
* .or.chad0(1).ne.chad(1).or.chad0(2).ne.chad(2)
* .or.chad0(3).ne.chad(3)
* .or.alplea0(1).ne.alplea(1).or.alplea0(2).ne.alplea(2)
* .or.alplea0(3).ne.alplea(3)
* .or.qcdlam0.ne.qcdlam.or.q2min0 .ne.q2min
* .or.q2ini0 .ne.q2ini
* .or.betpom0.ne.betpom.or.glusea0.ne.glusea.or.naflav0.ne.naflav
* .or.factk0 .ne.factk .or.pt2cut0.ne.pt2cut)then
write(ifmt,'(//a//)')' inics has to be reinitialized!!!!'
stop
endif
read(1,*)isetcs0,iclpro10,iclpro20,icltar10,icltar20,iclegy10
* ,iclegy20,egylow0,egymax0,iomega0,egyscr0,epscrw0,epscrp0
if(iclpro10.ne.iclpro1)write(ifmt,'(a,2i2)')
* 'inics: wrong iclpro1',iclpro10,iclpro1
if(iclpro20.ne.iclpro2)write(ifmt,'(a,2i2)')
* 'inics: wrong iclpro2',iclpro20,iclpro2
if(icltar10.ne.icltar1)write(ifmt,'(a,2i2)')
* 'inics: wrong icltar1',icltar10,icltar1
if(icltar20.ne.icltar2)write(ifmt,'(a,2i2)')
* 'inics: wrong icltar2',icltar20,icltar2
if(iclegy10.ne.iclegy1)write(ifmt,'(a,2i4)')
* 'inics: wrong iclegy1',iclegy10,iclegy1
if(iclegy20.ne.iclegy2)write(ifmt,'(a,2i4)')
* 'inics: wrong iclegy2',iclegy20,iclegy2
if(iomega0.ne.iomega)write(textini,'(a,2i8)')
* 'inics: wrong iomega ',iomega0,iomega
if(egylow0.ne.egylow)write(ifmt,'(a,2f8.4)')
* 'inics: wrong egylow',egylow0,egylow
if(egymax0.ne.egymax)write(ifmt,'(a,2f12.4)')
* 'inics: wrong egymax',egymax0,egymax
if(egyscr0.ne.egyscr)write(ifmt,'(a,2f8.4)')
* 'inics: wrong egyscr ',egyscr0,egyscr
if(epscrw0.ne.epscrw)write(ifmt,'(a,2f8.4)')
* 'inics: wrong epscrw',epscrw0,epscrw
if(epscrp0.ne.epscrp)write(ifmt,'(a,2f8.4)')
* 'inics: wrong epscrp',epscrp0,epscrp
if(isetcs0.lt.isetcs)write(ifmt,'(a,2f8.4)')
* 'inics: wrong isetcs',isetcs0,isetcs
if(iclpro10.ne.iclpro1.or.iclpro20.ne.iclpro2
* .or.icltar10.ne.icltar1.or.icltar20.ne.icltar2
* .or.iclegy10.ne.iclegy1.or.iclegy20.ne.iclegy2
* .or.egylow0.ne.egylow.or.egymax0.ne.egymax
* .or.egyscr0.ne.egyscr.or.epscrw0.ne.epscrw.or.isetcs0.lt.isetcs
* .or.epscrp0.ne.epscrp)then
write(ifmt,'(//a//)')' inics has to be reinitialized!!!!'
stop
endif
if(isetcs.eq.2)then
if(ionudi.eq.1)then
read (1,*)asect,asect13,asect21,asect23,asectn
* ,asect33,asect41,asect43
else !ionudi=3
read (1,*)asect11,asect,asect21,asect23,asect31
* ,asectn,asect41,asect43
endif
elseif(isetcs.eq.3)then
if(ionudi.eq.1)then
read (1,*)asect11,asect13,asect,asect23,asect31
* ,asect33,asectn,asect43
else !ionudi=3
read (1,*)asect11,asect13,asect21,asect,asect31
* ,asect33,asect41,asectn
endif
else
write(ifmt,'(//a//)')' Wrong isetcs in psaini !!!!'
endif
close(1)
endif
goto 7
elseif(.not.producetables)then
write(ifmt,*) "Missing epos.inics file !"
write(ifmt,*) "Please correct the defined path ",
&"or force production ..."
stop
endif
ifradesave=ifrade
iremnsave=iremn
idprojsave=idproj
idprojinsave=idprojin
idtargsave=idtarg
idtarginsave=idtargin
laprojsave=laproj
latargsave=latarg
maprojsave=maproj
matargsave=matarg
icltarsave=icltar
iclprosave=iclpro
engysave=engy
pnllsave=pnll
elabsave=elab
ecmssave=ecms
iclegysave=iclegy
nrevtsave=nrevt
neventsave=nevent
ntevtsave=ntevt
isetcssave=isetcs
noebinsave=noebin
isigmasave=isigma
bminimsave=bminim
bmaximsave=bmaxim
bimevtsave=bimevt
bkmxndifsave=bkmxndif
c fctrmxsave=fctrmx
ionudisave=ionudi
isetcs=2
isigma=1
noebin=1
idtarg=1120
idtargin=1120
bminim=0.
bmaxim=10000.
ifrade=0 !to save time, no fragmentation
iremn=0 !to save time, simple remnants
ionudi=3 !to have both ionudi=1 and 3 in tables
write(ifmt,'(a)')'inics does not exist -> calculate tables ...'
c initialize random numbers
if(seedj.ne.0d0)then
call ranfini(seedj,iseqsim,2)
else
stop 'seedi = 0 ... Please define it !'
endif
call aseed(2)
laproj=-1
maproj=1
icltar=2
do iclpro=1,4
if(iclpro.lt.iclpro1.or.iclpro.gt.iclpro2)then
do ie=1,7
do iia=1,7
asect11(ie,iclpro,iia)=0.
asect21(ie,iclpro,iia)=0.
asect13(ie,iclpro,iia)=0.
asect23(ie,iclpro,iia)=0.
enddo
enddo
else
do ie=1,7
engy=1.5*10.**(ie-1)
call paramini(0)
bkmxndif=conbmxndif()
if(ish.ge.1)
& write(ifch,*)' calcul. ',ie,' (',iclpro,')',engy
write(ifmt,*)' calcul. ',ie,' (',iclpro,')',engy
sigine=0.
do iia=1,7
matarg=2**(iia-1)
if(matarg.eq.1)then !hadron-proton interaction
c ine=cut+diff
call psfz(2,gz2,0.)
gin=gz2*pi*10.
c cut
iomegasave=iomega
iomega=2
call psfz(2,gz2,0.)
iomega=iomegasave
gcut=gz2*pi*10.
c diff
difpart=gin-gcut
c non excited projectile and target
gqela=(1.-rexdif(iclpro))*(1.-rexdif(icltar))*difpart
gin3=max(1.,gin-gqela)
else
call conini
rad=radnuc(matarg)
bm=rad+2.
rrr=rad/difnuc(matarg)
rrrm=rrr+log(9.)
anorm=1.5/pi/rrr**3/(1.+(pi/rrr)**2)/difnuc(matarg)**2
c gela=(ptgau(ptfau,bm,2,1)+ptgau1(bm,2,1))*10. !sig_ela
c in=cut+diff
gcut=(ptgau(ptfau,bm,2,2)+ptgau1(bm,2,2))*10. !sig_in
gin=gcut
c cut
iomegasave=iomega
iomega=2
gcut=(ptgau(ptfau,bm,2,2)+ptgau1(bm,2,2))*10. !sig_cut
iomega=iomegasave
c diff
difpart=gin-gcut
c non excited projectile
gqela=(1.-rexdif(iclpro))
& **(1.+rexres(iclpro)*float(matarg-1)**0.3)
c non excited target
gqela=gqela*(1.-rexdif(icltar))
gqela=gqela*difpart
gin3=max(1.,gin-gqela)
endif
if(ish.ge.1)write (ifch,226)matarg,gin,gin3
226 format(2x,'psaini: hadron-nucleus (',i3,') cross sections:'/
* 4x,'gin,gin3=',2e10.3)
write(ifmt,*)' matarg,gin,gin3:',matarg,gin,gin3
asect11(ie,iclpro,iia)=log(gin)
asect13(ie,iclpro,iia)=log(gin3)
enddo
enddo
if(isetcssave.ge.3)then
if(iclpro.eq.1)then
idprojin=120
elseif(iclpro.eq.2)then
idprojin=1120
elseif(iclpro.eq.3)then
idprojin=130
endif
do ie=1,7
engy=1.5*10.**(ie-1)
if(engy.le.egymin)engy=egymin
if(engy.ge.egymax)engy=egymax
write(ifmt,*)' simul. ',ie,' (',iclpro,')',engy
if(ish.ge.1)
& write(ifch,*)' simul. ',ie,' (',iclpro,')',engy
do iia=1,7
matarg=2**(iia-1)
latarg=min(1,matarg/2)
c fctrmx=max(ftcrmxsave,float(matarg)) !to get stable pA and AA cross section, this number has to be large for large A
ntevt=0
nrevt=0
pnll=-1.
elab=-1.
ecms=-1.
ekin=-1.
call conini
call ainit
nevent=50000
if(matarg.eq.1)nevent=1
call epocrossc(nevent,sigt,sigi,sigc,sige,sigql,sigd)
c do not count non-excited diffractive projectile in inelastic
sigi3=sigi-sigql
if(ish.ge.1)write (ifch,228)matarg,sigi,sigi3
228 format(2x,'simul.: hadron-nucleus (',i3,') cross sections:'/
* 4x,'gin,gin3=',2e10.3)
write(ifmt,*)' matarg,sigi,sigi3 :',matarg,sigi,sigi3
asect21(ie,iclpro,iia)=log(sigi)
asect23(ie,iclpro,iia)=log(sigi3)
c do n=1,nevent
c ntry=0
c 222 ntevt=ntevt+1
c iret=0
c ntry=ntry+1
c bimevt=-1.
c if(ntry.lt.10000)then
cc if random sign for projectile, set it here
c idproj=idprojin*(1-2*int(rangen()+0.5d0))
c call emsaaa(iret)
c if(iret.gt.0)goto 222
c else
c ntevt=ntry
c endif
c enddo
c a=pi*bmax**2
c if(a.gt.0..and.ntevt.gt.0.)then
c xs=anintine/float(ntevt)*a*10.
c write(ifmt,*)' matarg,nevent,ntevt,bmax,xs :'
c . ,matarg,anintine,ntevt,bmax,xs
c write(ifch,*)' matarg,nevent,ntevt,bmax,xs :'
c . ,matarg,anintine,ntevt,bmax,xs
c asect2(ie,iclpro,iia)=log(xs)
c else
c write(ifmt,*)' Problem ? ',iclpro,matarg,bmax,ntevt
c asect2(ie,iclpro,iia)=0.
c endif
enddo
enddo
else
do ie=1,7
do iia=1,7
asect21(ie,iclpro,iia)=0.
asect23(ie,iclpro,iia)=0.
enddo
enddo
endif
endif
enddo
idprojin=1120
iclpro=2
icltar=2
do ie=1,7
engy=1.5*10.**(ie-1)
call paramini(0)
bkmxndif=conbmxndif()
if(ish.ge.1)
& write(ifch,*)' calcul. AB ',ie,engy
write(ifmt,*)' calcul. AB ',ie,engy
do iia=1,7
maproj=2**(iia-1)
laproj=max(1,maproj/2)
do iib=1,7
matarg=2**(iib-1)
latarg=max(1,matarg/2)
sigine=0.
if(matarg.eq.1.and.maproj.eq.1)then !proton-proton interaction
c ine=cut+diff
call psfz(2,gz2,0.)
gin=gz2*pi*10.
c cut
iomegasave=iomega
iomega=2
call psfz(2,gz2,0.)
iomega=iomegasave
gcut=gz2*pi*10.
c diff
difpart=gin-gcut
c non excited projectile and target
gqela=(1.-rexdif(iclpro))*(1.-rexdif(icltar))*difpart
gin3=max(1.,gin-gqela)
else
call conini
if(maproj.eq.1)then
rad=radnuc(matarg)
bm=rad+2.
rrr=rad/difnuc(matarg)
rrrm=rrr+log(9.)
anorm=1.5/pi/rrr**3/(1.+(pi/rrr)**2)/difnuc(matarg)**2
c gela=(ptgau(ptfau,bm,2,1)+ptgau1(bm,2,1))*10. !sig_ela
c in=cut+diff
gcut=(ptgau(ptfau,bm,2,2)+ptgau1(bm,2,2))*10. !sig_in
gin=gcut
c cut
iomegasave=iomega
iomega=2
gcut=(ptgau(ptfau,bm,2,2)+ptgau1(bm,2,2))*10. !sig_cut
iomega=iomegasave
c diff
difpart=gin-gcut
c non excited projectile
gqela=(1.-rexdif(iclpro))
& **(1.+rexres(iclpro)*float(matarg-1)**0.3)
c non excited target
gqela=gqela*(1.-rexdif(icltar))**(1.+float(matarg)**0.3)
gqela=gqela*difpart
gin3=max(1.,gin-gqela)
elseif(matarg.eq.1)then
radp=radnuc(maproj)
bm=radp+2.
rrrp=radp/difnuc(maproj)
rrrmp=rrrp+log(9.)
anormp=1.5/pi/rrrp**3/(1.+(pi/rrrp)**2)/difnuc(maproj)**2
c gtot=(ptgau(ptfau,bm,1,1)+ptgau1(bm,1,1))*10. !sig_in
c in=cut+diff
gcut=(ptgau(ptfau,bm,1,2)+ptgau1(bm,1,2))*10. !sig_in
gin=gcut !in=cut+diff
c cut
iomegasave=iomega
iomega=2
gcut=(ptgau(ptfau,bm,1,2)+ptgau1(bm,1,2))*10. !sig_cut
iomega=iomegasave
c diff
difpart=gin-gcut
c non excited projectile
gqela=(1.-rexdif(iclpro))**(1.+float(maproj)**0.3)
c non excited target
gqela=gqela*(1.-rexdif(icltar))
& **(1.+rexres(icltar)*float(maproj-1)**0.3)
gqela=gqela*difpart
gin3=max(1.,gin-gqela)
else
rad=radnuc(matarg)+1.
radp=radnuc(maproj)+1.
bm=rad+radp+2.
rrr=rad/difnuc(matarg)
rrrm=rrr+log(9.)
rrrp=radp/difnuc(maproj)
rrrmp=rrrp+log(9.)
anorm=1.5/pi/rrr**3/(1.+(pi/rrr)**2)/difnuc(matarg)**2
anormp=1.5/pi/rrrp**3/(1.+(pi/rrrp)**2)/difnuc(maproj)**2
c ine=cut+diff
c gtot=(ptgau(ptfauAA,bm,2,1)+ptgau2(bm,1))*10.
gcut=(ptgau(ptfauAA,bm,2,2)+ptgau2(bm,2))*10.
c gin=gtot
gin=gcut
c cut
iomegasave=iomega
iomega=2
gcut=(ptgau(ptfauAA,bm,2,2)+ptgau2(bm,2))*10. !sig_cut
iomega=iomegasave
c diff
difpart=gin-gcut
c non excited projectile
gqelap=(1.-rexdif(iclpro))
& **(1.+rexres(iclpro)*float(matarg-1)**0.3)
gqelap=gqelap**(1.+float(maproj)**0.3)
c non excited target
gqelat=(1.-rexdif(icltar))
& **(1.+rexres(icltar)*float(maproj-1)**0.3)
gqelat=gqelat**(1.+float(maproj)**0.3)
gqela=gqelap*gqelat*difpart
gin3=gin-gqela
endif
endif
if(ish.ge.1)write (ifch,227)maproj,matarg,gin,gin3
227 format(2x,'psaini: nucleus-nucleus (',i3,'-',i3
* ,') cross sections:',/,4x,'gin,gin3=',2e10.3)
write(ifmt,*)' maproj,matarg,gin,gin3 :'
* ,maproj,matarg,gin,gin3
asect31(ie,iia,iib)=log(gin)
asect33(ie,iia,iib)=log(gin3)
enddo
enddo
enddo
if(isetcssave.ge.3)then
do ie=1,7
engy=1.5*10.**(ie-1)
if(engy.le.egymin)engy=egymin
if(engy.ge.egymax)engy=egymax
write(ifmt,*)' AB xs ',ie,engy
if(ish.ge.1)
& write(ifch,*)' AB xs ',ie,engy
do iia=1,7
maproj=2**(iia-1)
laproj=max(1,maproj/2)
do iib=1,7
matarg=2**(iib-1)
latarg=max(1,matarg/2)
c fctrmx=max(ftcrmxsave,float(max(maproj,matarg))) !to get stable pA and AA cross section, this number has to be large for large A
ntevt=0
nrevt=0
pnll=-1.
elab=-1.
ecms=-1.
ekin=-1.
call conini
call ainit
nevent=10000
if(maproj+matarg.eq.2)nevent=1
call epocrossc(nevent,sigt,sigi,sigc,sige,sigql,sigd)
c do not count non-excited diffractive projectile in inelastic
sigi3=sigi-sigql
if(ish.ge.1)write (ifch,229)maproj,matarg,sigi,sigi3
229 format(2x,'simul.: nucleus-nucleus (',i3,'-',i3
* ,') cross sections:',/,4x,'gin,gin3=',2e10.3)
write(ifmt,*)' maproj,matarg,sigi,sigi3 :',maproj,matarg
& ,sigi,sigi3
asect41(ie,iia,iib)=log(sigi)
asect43(ie,iia,iib)=log(sigi3)
c do n=1,nevent
c ntry=0
c 223 ntevt=ntevt+1
c iret=0
c ntry=ntry+1
c bimevt=-1.
c if(ntry.lt.10000)then
c call emsaaa(iret)
c if(iret.gt.0)goto 223
c else
c ntevt=ntry
c endif
c enddo
c a=pi*bmax**2
c if(a.gt.0..and.ntevt.gt.0.)then
c xs=anintine/float(ntevt)*a*10.
c write(ifmt,*)' maproj,matarg,nevent,ntevt,bmax,xs :'
c & ,maproj,matarg,anintine,ntevt,bmax,xs
c write(ifch,*)' maproj,matarg,nevent,ntevt,bmax,xs :'
c & ,maproj,matarg,anintine,ntevt,bmax,xs
c asect4(ie,iia,iib)=log(xs)
c else
c write(ifmt,*)' Problem ? ',maproj,matarg,bmax,ntevt
c asect4(ie,iia,iib)=0.
c endif
enddo
enddo
enddo
else
do ie=1,7
do iia=1,7
do iib=1,7
asect41(ie,iia,iib)=0.
asect43(ie,iia,iib)=0.
enddo
enddo
enddo
endif
ifrade=ifradesave
iremn=iremnsave
idproj=idprojsave
idprojin=idprojinsave
idtarg=idtargsave
idtargin=idtarginsave
laproj=laprojsave
latarg=latargsave
maproj=maprojsave
matarg=matargsave
icltar=icltarsave
iclpro=iclprosave
engy=engysave
pnll=pnllsave
elab=elabsave
ecms=ecmssave
iclegy=iclegysave
nrevt=nrevtsave
nevent=neventsave
ntevt=ntevtsave
isetcs=isetcssave
noebin=noebinsave
isigma=isigmasave
bminim=bminimsave
bmaxim=bmaximsave
bimevt=bimevtsave
bkmxndif=bkmxndifsave
ionudi=ionudisave
c fctrmx=fctrmxsave
inicnt=1
write(ifmt,'(a)')'write to inics ...'
open(1,file=fncs,status='unknown')
write (1,*)alpqua,alplea,alppom,slopom,gamhad,r2had,chad,
*qcdlam,q2min,q2ini,betpom,glusea,naflav,factk,pt2cut
write(1,*)isetcs,iclpro1,iclpro2,icltar1,icltar2,iclegy1,iclegy2
*,egylow,egymax,iomega,egyscr,epscrw,epscrp
write (1,*)asect11,asect13,asect21,asect23
* ,asect31,asect33,asect41,asect43
close(1)
goto 6
7 continue
endif !----------isetcs.ge.2-----------
endif
call utprix('psaini',ish,ishini,4)
return
end
cc-----------------------------------------------------------------------
c function fjetxx(jpp,je1,je2)
cc-----------------------------------------------------------------------
cc almost exactly psjet, just with Eqcd replaced by fparton
cc for testing
cc gives indeed the same result as jetx
cc so the integration seems correct
cc-----------------------------------------------------------------------
c double precision xx1,xx2,s2min,xmin,xmax,xmin1,xmax1,t,tmin
c *,tmax,sh,z,qtmin,ft,fx1,fx2
c common /ar3/ x1(7),a1(7)
c common /ar9/ x9(3),a9(3)
c include 'epos.inc'
c include 'epos.incsem'
c
c fjetxx=0.
c s=engy*engy
c s2min=4.d0*q2min
c
c zmin=s2min/dble(s)
c zmax=1
c
c zmin=zmin**(-delh)
c zmax=zmax**(-delh)
c do i=1,3
c do m=1,2
c z=dble(.5*(zmax+zmin+(zmin-zmax)*(2*m-3)*x9(i)))**(-1./delh)
c xmin=dsqrt(z)
c sh=z*dble(s)
c qtmin=max(dble(q2min),dble(q2ini)/(1.d0-dsqrt(z)))
c tmin=max(0.d0,1.d0-4.d0*qtmin/sh)
c tmin=2.d0*qtmin/(1.d0+dsqrt(tmin))
c tmax=sh/2.d0
c ft=0.d0
c do i1=1,3
c do m1=1,2
c t=2.d0*tmin/(1.d0+tmin/tmax-dble(x9(i1)*(2*m1-3))
c & *(1.d0-tmin/tmax))
c qt=t*(1.d0-t/sh)
c xmax=1.d0-q2ini/qt
c xmin=max(dsqrt(z),z/xmax) !xm<xp !!!
c if(xmin.gt.xmax.and.ish.ge.1)write(ifmt,*)'fjetxx:xmin,xmax'
c * ,xmin,xmax
c fx1=0.d0
c fx2=0.d0
c if(xmax.gt..8d0)then
c xmin1=max(xmin,.8d0)
c do i2=1,3
c do m2=1,2
c xx1=1.d0-(1.d0-xmax)*((1.d0-xmin1)/(1.d0-xmax))**
c * dble(.5+x9(i2)*(m2-1.5))
c xx2=z/xx1
c fb=ffsigj(sngl(t),qt,sngl(xx1),sngl(xx2),jpp,je1,je2)
c * +ffsigj(sngl(t),qt,sngl(xx2),sngl(xx1),jpp,je1,je2)
c fx1=fx1+dble(a9(i2)*fb)*(1.d0/xx1-1.d0)
c * *pssalf(qt/qcdlam)**2
c enddo
c enddo
c fx1=fx1*dlog((1.d0-xmin1)/(1.d0-xmax))
c endif
c if(xmin.lt..8d0)then
c xmax1=min(xmax,.8d0)
c do i2=1,3
c do m2=1,2
c xx1=xmin*(xmax1/xmin)**dble(.5+x9(i2)*(m2-1.5))
c xx2=z/xx1
c
c fb=0.
c fb=fb
c * +ffsigj(sngl(t),qt,sngl(xx1),sngl(xx2),jpp,je1,je2)
c * +ffsigj(sngl(t),qt,sngl(xx2),sngl(xx1),jpp,je1,je2)
c fx2=fx2+dble(a9(i2))*fb*pssalf(qt/qcdlam)**2
c enddo
c enddo
c fx2=fx2*dlog(xmax1/xmin)
c endif
c ft=ft+dble(a9(i1))*(fx1+fx2)*t**2
c enddo
c enddo
c ft=ft*(1.d0/tmin-1.d0/tmax)
c fjetxx=fjetxx+a9(i)*sngl(ft*z**(1.+delh)/sh**2)
c * /z ! ffsig = xp f xm f sigma
c enddo
c enddo
c fjetxx=fjetxx*(zmin-zmax)/delh*pi**3
c ! * /2. !??????????????? kkkkkkkkk
c return
c end
c
c
|
# This file is generated. Do not modify it by hand.
## @type x : raw|complex|logical
"!" <- function (x) .Primitive("!")
"&" <- function (e1, e2) .Primitive("&")
"*" <- function (e1, e2) .Primitive("*")
"+" <- function (e1, e2) .Primitive("+")
"-" <- function (e1, e2) .Primitive("-")
"<" <- function (e1, e2) .Primitive("<")
">" <- function (e1, e2) .Primitive(">")
"^" <- function (e1, e2) .Primitive("^")
## @type recursive : logical
c <- function (..., recursive = FALSE) .Primitive("c")
I <- function (x)
{
structure(x, class = unique(c("AsIs", oldClass(x))))
}
## @type save : character
q <- function (save = "default", status = 0, runLast = TRUE)
.Internal(quit(save, status, runLast))
t <- function (x)
UseMethod("t")
"|" <- function (e1, e2) .Primitive("|")
"!=" <- function (e1, e2) .Primitive("!=")
"%%" <- function (e1, e2) .Primitive("%%")
## @type pkg : character
## @type name : character
"::" <- function (pkg, name)
{
pkg <- as.character(substitute(pkg))
name <- as.character(substitute(name))
getExportedValue(pkg, name)
}
"<=" <- function (e1, e2) .Primitive("<=")
"==" <- function (e1, e2) .Primitive("==")
">=" <- function (e1, e2) .Primitive(">=")
## @type simplify : logical
by <- function (data, INDICES, FUN, ..., simplify = TRUE)
UseMethod("by")
## @type reset : logical
## @type verbose : logical
gc <- function (verbose = getOption("verbose"), reset = FALSE)
{
res <- .Internal(gc(verbose, reset))
res <- matrix(res, 2L, 7L, dimnames = list(c("Ncells", "Vcells"),
c("used", "(Mb)", "gc trigger", "(Mb)", "limit (Mb)",
"max used", "(Mb)")))
if (all(is.na(res[, 5L])))
res[, -5L]
else res
}
gl <- function (n, k, length = n * k, labels = seq_len(n), ordered = FALSE)
{
f <- rep_len(rep.int(seq_len(n), rep.int(k, n)), length)
levels(f) <- as.character(labels)
class(f) <- c(if (ordered) "ordered", "factor")
f
}
## @type z : complex
Im <- function (z) .Primitive("Im")
ls <- function (name, pos = -1L, envir = as.environment(pos), all.names = FALSE,
pattern)
{
if (!missing(name)) {
pos <- tryCatch(name, error = function(e) e)
if (inherits(pos, "error")) {
name <- substitute(name)
if (!is.character(name))
name <- deparse(name)
warning(gettextf("%s converted to character string",
sQuote(name)), domain = NA)
pos <- name
}
}
all.names <- .Internal(ls(envir, all.names))
if (!missing(pattern)) {
if ((ll <- length(grep("[", pattern, fixed = TRUE))) &&
ll != length(grep("]", pattern, fixed = TRUE))) {
if (pattern == "[") {
pattern <- "\\["
warning("replaced regular expression pattern '[' by '\\\\['")
}
else if (length(grep("[^\\\\]\\[<-", pattern))) {
pattern <- sub("\\[<-", "\\\\\\[<-", pattern)
warning("replaced '[<-' by '\\\\[<-' in regular expression pattern")
}
}
grep(pattern, all.names, value = TRUE)
}
else all.names
}
## @type x : complex
qr <- function (x, ...)
UseMethod("qr")
## @type z : complex
Re <- function (z) .Primitive("Re")
## @type list : character
rm <- function (..., list = character(), pos = -1, envir = as.environment(pos),
inherits = FALSE)
{
dots <- match.call(expand.dots = FALSE)$...
if (length(dots) && !all(sapply(dots, function(x) is.symbol(x) ||
is.character(x))))
stop("... must contain names or character strings")
names <- sapply(dots, as.character)
if (length(names) == 0L)
names <- character()
list <- .Primitive("c")(list, names)
.Internal(remove(list, envir, inherits))
}
## @type y : complex
## @type x : complex
"%*%" <- function (x, y) .Primitive("%*%")
"%o%" <- function (X, Y)
outer(X, Y)
"%x%" <- function (X, Y)
kronecker(X, Y)
## @type name : character
## @type pkg : character
":::" <- function (pkg, name)
{
pkg <- as.character(substitute(pkg))
name <- as.character(substitute(name))
get(name, envir = asNamespace(pkg), inherits = FALSE)
}
## @type x : complex
abs <- function (x) .Primitive("abs")
## @type na.rm : logical
## @return logical
all <- function (..., na.rm = FALSE) .Primitive("all")
## @type na.rm : logical
## @return logical
any <- function (..., na.rm = FALSE) .Primitive("any")
## @type z : complex
Arg <- function (z) .Primitive("Arg")
## @type file : character
## @type labels : character
## @type sep : character
## @type append : logical|character
## @type fill : numeric|logical
cat <- function (..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE)
{
if (is.character(file))
if (file == "")
file <- stdout()
else if (substring(file, 1L, 1L) == "|") {
file <- pipe(substring(file, 2L), "w")
on.exit(close(file))
}
else {
file <- file(file, ifelse(append, "a", "w"))
on.exit(close(file))
}
.Internal(cat(list(...), file, sep, fill, labels, append))
}
## @type as.factor : logical
col <- function (x, as.factor = FALSE)
{
if (as.factor) {
labs <- colnames(x, do.NULL = FALSE, prefix = "")
res <- factor(.Internal(col(dim(x))), labels = labs)
dim(res) <- dim(x)
res
}
else .Internal(col(dim(x)))
}
## @type x : complex
cos <- function (x) .Primitive("cos")
## @type x : numeric
cut <- function (x, ...)
UseMethod("cut")
## @type x : logical|numeric
## @return numeric
det <- function (x, ...)
{
z <- determinant(x, logarithm = TRUE, ...)
c(z$sign * exp(z$modulus))
}
dim <- function (x) .Primitive("dim")
## @type no.. : logical
## @type full.names : logical
## @type include.dirs : logical
## @type ignore.case : logical
## @type recursive : logical
## @type path : character
## @type all.files : logical
## @return character
dir <- function (path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE,
recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE,
no.. = FALSE)
.Internal(list.files(path, pattern, all.files, full.names, recursive,
ignore.case, include.dirs, no..))
## @type x : complex
exp <- function (x) .Primitive("exp")
## @type envir : character
## @type pos : character
## @type x : character
get <- function (x, pos = -1L, envir = as.environment(pos), mode = "any",
inherits = TRUE)
.Internal(get(x, envir, mode, inherits))
## @type x : complex
## @type base : complex
log <- function (x, base = exp(1)) .Primitive("log")
Map <- function (f, ...)
{
f <- match.fun(f)
mapply(FUN = f, ..., SIMPLIFY = FALSE)
}
## @type na.rm : logical
max <- function (..., na.rm = FALSE) .Primitive("max")
## @return numeric|character
min <- function (..., na.rm = FALSE) .Primitive("min")
## @type z : complex
Mod <- function (z) .Primitive("Mod")
raw <- function (length = 0L)
.Internal(vector("raw", length))
rep <- function (x, ...) .Primitive("rep")
rev <- function (x)
UseMethod("rev")
rle <- function (x)
{
if (!is.vector(x) && !is.list(x))
stop("'x' must be a vector of an atomic type")
n <- length(x)
if (n == 0L)
return(structure(list(lengths = integer(), values = x),
class = "rle"))
y <- x[-1L] != x[-n]
i <- c(which(y | is.na(y)), n)
structure(list(lengths = diff(c(0L, i)), values = x[i]),
class = "rle")
}
## @type as.factor : logical
row <- function (x, as.factor = FALSE)
{
if (as.factor) {
labs <- rownames(x, do.NULL = FALSE, prefix = "")
res <- factor(.Internal(row(dim(x))), labels = labs)
dim(res) <- dim(x)
res
}
else .Internal(row(dim(x)))
}
seq <- function (...)
UseMethod("seq")
## @type x : complex
sin <- function (x) .Primitive("sin")
## @type na.rm : logical
sum <- function (..., na.rm = FALSE) .Primitive("sum")
## @type LINPACK : logical
## @type nu : complex
## @type x : complex
## @type nv : complex
svd <- function (x, nu = min(n, p), nv = min(n, p), LINPACK = FALSE)
{
x <- as.matrix(x)
if (any(!is.finite(x)))
stop("infinite or missing values in 'x'")
dx <- dim(x)
n <- dx[1L]
p <- dx[2L]
if (!n || !p)
stop("a dimension is zero")
La.res <- La.svd(x, nu, nv)
res <- list(d = La.res$d)
if (nu)
res$u <- La.res$u
if (nv) {
if (is.complex(x))
res$v <- Conj(t(La.res$vt))
else res$v <- t(La.res$vt)
}
res
}
## @type x : complex
tan <- function (x) .Primitive("tan")
## @type silent : logical
try <- function (expr, silent = FALSE)
{
tryCatch(expr, error = function(e) {
call <- conditionCall(e)
if (!is.null(call)) {
if (identical(call[[1L]], quote(doTryCatch)))
call <- sys.call(-4L)
dcall <- deparse(call)[1L]
prefix <- paste("Error in", dcall, ": ")
LONG <- 75L
msg <- conditionMessage(e)
sm <- strsplit(msg, "\n")[[1L]]
w <- 14L + nchar(dcall, type = "w") + nchar(sm[1L],
type = "w")
if (is.na(w))
w <- 14L + nchar(dcall, type = "b") + nchar(sm[1L],
type = "b")
if (w > LONG)
prefix <- paste0(prefix, "\n ")
}
else prefix <- "Error : "
msg <- paste0(prefix, conditionMessage(e), "\n")
.Internal(seterrmessage(msg[1L]))
if (!silent && identical(getOption("show.error.messages"),
TRUE)) {
cat(msg, file = stderr())
.Internal(printDeferredWarnings())
}
invisible(structure(msg, class = "try-error", condition = e))
})
}
## @type open : character
## @type description : character
## @type encoding : character
unz <- function (description, filename, open = "", encoding = getOption("encoding"))
.Internal(unz(paste(description, filename, sep = ":"), open,
encoding))
## @type description : character
## @type open : character
## @type encoding : character
## @type blocking : logical
url <- function (description, open = "", blocking = TRUE, encoding = getOption("encoding"))
.Internal(url(description, open, blocking, encoding))
## @type x : raw|complex|logical
## @type y : raw|complex|logical
xor <- function (x, y)
{
(x | y) & !(x & y)
}
"%in%" <- function (x, table)
match(x, table, nomatch = 0L) > 0L
## @type x : complex
acos <- function (x) .Primitive("acos")
## @type x : complex
asin <- function (x) .Primitive("asin")
## @type complete : logical
## @type flag : logical
asS3 <- function (object, flag = TRUE, complete = TRUE)
.Internal(setS4Object(object, !as.logical(flag), complete))
## @type flag : logical
## @type complete : logical
asS4 <- function (object, flag = TRUE, complete = TRUE)
.Internal(setS4Object(object, flag, complete))
## @type x : complex
atan <- function (x) .Primitive("atan")
attr <- function (x, which, exact = FALSE) .Primitive("attr")
## @type b : numeric
## @type a : numeric
beta <- function (a, b)
.Internal(beta(a, b))
body <- function (fun = sys.function(sys.parent()))
{
if (is.character(fun))
fun <- get(fun, mode = "function", envir = parent.frame())
.Internal(body(fun))
}
## @type name : character
call <- function (name, ...) .Primitive("call")
## @type x : logical|numeric
chol <- function (x, ...)
UseMethod("chol")
## @type z : complex
Conj <- function (z) .Primitive("Conj")
## @type x : complex
cosh <- function (x) .Primitive("cosh")
date <- function ()
.Internal(date())
dget <- function (file)
eval(parse(file = file))
diag <- function (x = 1, nrow, ncol)
{
if (is.matrix(x)) {
if (nargs() > 1L)
stop("'nrow' or 'ncol' cannot be specified when 'x' is a matrix")
if ((m <- min(dim(x))) == 0L)
return(vector(typeof(x), 0L))
y <- c(x)[1 + 0L:(m - 1L) * (dim(x)[1L] + 1)]
nms <- dimnames(x)
if (is.list(nms) && !any(sapply(nms, is.null)) && identical((nm <- nms[[1L]][seq_len(m)]),
nms[[2L]][seq_len(m)]))
names(y) <- nm
return(y)
}
if (is.array(x) && length(dim(x)) != 1L)
stop("'x' is an array, but not one-dimensional.")
if (missing(x))
n <- nrow
else if (length(x) == 1L && nargs() == 1L) {
n <- as.integer(x)
x <- 1
}
else n <- length(x)
if (!missing(nrow))
n <- nrow
if (missing(ncol))
ncol <- n
.Internal(diag(x, n, ncol))
}
## @type x : numeric
diff <- function (x, ...)
UseMethod("diff")
## @type file : character
## @type control : character
dput <- function (x, file = "", control = c("keepNA", "keepInteger",
"showAttributes"))
{
if (is.character(file))
if (nzchar(file)) {
file <- file(file, "wt")
on.exit(close(file))
}
else file <- stdout()
opts <- .deparseOpts(control)
if (isS4(x)) {
clx <- class(x)
cat("new(\"", clx, "\"\n", file = file, sep = "")
for (n in .slotNames(clx)) {
cat(" ,", n, "= ", file = file)
dput(slot(x, n), file = file, control = control)
}
cat(")\n", file = file)
invisible()
}
else .Internal(dput(x, file, opts))
}
drop <- function (x)
.Internal(drop(x))
## @return character
dump <- function (list, file = "dumpdata.R", append = FALSE, control = "all",
envir = parent.frame(), evaluate = TRUE)
{
if (is.character(file)) {
ex <- sapply(list, exists, envir = envir)
if (!any(ex))
return(invisible(character()))
if (nzchar(file)) {
file <- file(file, ifelse(append, "a", "w"))
on.exit(close(file), add = TRUE)
}
else file <- stdout()
}
opts <- .deparseOpts(control)
.Internal(dump(list, file, envir, opts, evaluate))
}
eval <- function (expr, envir = parent.frame(), enclos = if (is.list(envir) ||
is.pairlist(envir)) parent.frame() else baseenv())
.Internal(eval(expr, envir, enclos))
## @type description : character
## @type encoding : character
## @type open : character
## @type blocking : logical
fifo <- function (description, open = "", blocking = FALSE, encoding = getOption("encoding"))
.Internal(fifo(description, open, blocking, encoding))
## @type description : character
## @type encoding : character
## @type raw : raw|logical|character
## @type open : character
## @type blocking : logical
file <- function (description = "", open = "", blocking = TRUE, encoding = getOption("encoding"),
raw = FALSE)
.Internal(file(description, open, blocking, encoding, raw))
## @type right : logical
Find <- function (f, x, right = FALSE, nomatch = NULL)
{
f <- match.fun(f)
if ((pos <- Position(f, x, right, nomatch = 0L)) > 0L)
x[[pos]]
else nomatch
}
## @type invert : logical
## @type value : integer
## @type pattern : character
## @type fixed : logical|character
## @type useBytes : logical
## @type x : character
## @type perl : logical
## @return logical|integer|character
grep <- function (pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE,
fixed = FALSE, useBytes = FALSE, invert = FALSE)
{
if (!is.character(x))
x <- structure(as.character(x), names = names(x))
.Internal(grep(as.character(pattern), x, ignore.case, value,
perl, fixed, useBytes, invert))
}
## @type replacement : character
## @type x : character
## @type fixed : logical|character
## @type pattern : character
## @type perl : logical
## @type useBytes : logical
gsub <- function (pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)
{
if (!is.character(x))
x <- as.character(x)
.Internal(gsub(as.character(pattern), as.character(replacement),
x, ignore.case, perl, fixed, useBytes))
}
is.R <- function ()
exists("version") && !is.null(vl <- version$language) && vl ==
"R"
isS4 <- function (object) .Primitive("isS4")
list <- function (...) .Primitive("list")
load <- function (file, envir = parent.frame(), verbose = FALSE)
{
if (is.character(file)) {
con <- gzfile(file)
on.exit(close(con))
magic <- readChar(con, 5L, useBytes = TRUE)
if (!length(magic))
stop("empty (zero-byte) input file")
if (!grepl("RD[AX]2\n", magic)) {
if (grepl("RD[ABX][12]\r", magic))
stop("input has been corrupted, with LF replaced by CR")
warning(sprintf("file %s has magic number '%s'\n",
sQuote(basename(file)), gsub("[\n\r]*", "", magic)),
" ", "Use of save versions prior to 2 is deprecated",
domain = NA, call. = FALSE)
return(.Internal(load(file, envir)))
}
}
else if (inherits(file, "connection")) {
con <- if (inherits(file, "gzfile") || inherits(file,
"gzcon"))
file
else gzcon(file)
}
else stop("bad 'file' argument")
if (verbose)
cat("Loading objects:\n")
.Internal(loadFromConn2(con, envir, verbose))
}
## @type x : complex
log2 <- function (x) .Primitive("log2")
## @type base : complex
## @type x : complex
logb <- function (x, base = exp(1))
if (missing(base)) log(x) else log(x, base)
mean <- function (x, ...)
UseMethod("mean")
## @type x : character
## @type envir : character
mget <- function (x, envir = as.environment(-1L), mode = "any", ifnotfound,
inherits = FALSE)
.Internal(mget(x, envir, mode, if (missing(ifnotfound)) list(function(x) stop(gettextf("value for %s not found",
sQuote(x)), call. = FALSE)) else ifnotfound, inherits))
mode <- function (x)
{
if (is.expression(x))
return("expression")
if (is.call(x))
return(switch(deparse(x[[1L]])[1L], `(` = "(", "call"))
if (is.name(x))
"name"
else switch(tx <- typeof(x), double = , integer = "numeric",
closure = , builtin = , special = "function", tx)
}
NCOL <- function (x)
if (length(d <- dim(x)) > 1L) d[2L] else 1L
## @type type : character
## @type x : numeric
norm <- function (x, type = c("O", "I", "F", "M", "2"))
{
if (identical("2", type)) {
svd(x, nu = 0L, nv = 0L)$d[1L]
}
else .Internal(La_dlange(x, type))
}
NROW <- function (x)
if (length(d <- dim(x))) d[1L] else length(x)
open <- function (con, ...)
UseMethod("open")
## @type encoding : character
## @type description : character
## @type open : character
pipe <- function (description, open = "", encoding = getOption("encoding"))
.Internal(pipe(description, open, encoding))
## @return numeric|character
pmax <- function (..., na.rm = FALSE)
{
elts <- list(...)
if (length(elts) == 0L)
stop("no arguments")
if (all(vapply(elts, function(x) is.atomic(x) && !is.object(x),
NA))) {
mmm <- .Internal(pmax(na.rm, ...))
}
else {
mmm <- elts[[1L]]
attr(mmm, "dim") <- NULL
has.na <- FALSE
for (each in elts[-1L]) {
attr(each, "dim") <- NULL
l1 <- length(each)
l2 <- length(mmm)
if (l2 < l1) {
if (l2 && l1%%l2)
warning("an argument will be fractionally recycled")
mmm <- rep(mmm, length.out = l1)
}
else if (l1 && l1 < l2) {
if (l2%%l1)
warning("an argument will be fractionally recycled")
each <- rep(each, length.out = l2)
}
nas <- cbind(is.na(mmm), is.na(each))
if (has.na || (has.na <- any(nas))) {
mmm[nas[, 1L]] <- each[nas[, 1L]]
each[nas[, 2L]] <- mmm[nas[, 2L]]
}
change <- mmm < each
change <- change & !is.na(change)
mmm[change] <- each[change]
if (has.na && !na.rm)
mmm[nas[, 1L] | nas[, 2L]] <- NA
}
}
mostattributes(mmm) <- attributes(elts[[1L]])
mmm
}
## @return numeric|character
pmin <- function (..., na.rm = FALSE)
{
elts <- list(...)
if (length(elts) == 0L)
stop("no arguments")
if (all(vapply(elts, function(x) is.atomic(x) && !is.object(x),
NA))) {
mmm <- .Internal(pmin(na.rm, ...))
}
else {
mmm <- elts[[1L]]
attr(mmm, "dim") <- NULL
has.na <- FALSE
for (each in elts[-1L]) {
attr(each, "dim") <- NULL
l1 <- length(each)
l2 <- length(mmm)
if (l2 < l1) {
if (l2 && l1%%l2)
warning("an argument will be fractionally recycled")
mmm <- rep(mmm, length.out = l1)
}
else if (l1 && l1 < l2) {
if (l2%%l1)
warning("an argument will be fractionally recycled")
each <- rep(each, length.out = l2)
}
nas <- cbind(is.na(mmm), is.na(each))
if (has.na || (has.na <- any(nas))) {
mmm[nas[, 1L]] <- each[nas[, 1L]]
each[nas[, 2L]] <- mmm[nas[, 2L]]
}
change <- mmm > each
change <- change & !is.na(change)
mmm[change] <- each[change]
if (has.na && !na.rm)
mmm[nas[, 1L] | nas[, 2L]] <- NA
}
}
mostattributes(mmm) <- attributes(elts[[1L]])
mmm
}
## @type na.rm : logical
prod <- function (..., na.rm = FALSE) .Primitive("prod")
## @type complete : logical
qr.Q <- function (qr, complete = FALSE, Dvec)
{
if (!is.qr(qr))
stop("argument is not a QR decomposition")
dqr <- dim(qr$qr)
n <- dqr[1L]
cmplx <- mode(qr$qr) == "complex"
if (missing(Dvec))
Dvec <- rep.int(if (cmplx)
1 + (0+0i)
else 1, if (complete)
n
else min(dqr))
D <- if (complete)
diag(Dvec, n)
else {
ncols <- min(dqr)
diag(Dvec[seq_len(ncols)], nrow = n, ncol = ncols)
}
qr.qy(qr, D)
}
## @type complete : logical
qr.R <- function (qr, complete = FALSE, ...)
{
if (!is.qr(qr))
stop("argument is not a QR decomposition")
if (!missing(...))
warning(sprintf(ngettext(length(list(...)), "extra argument %s will be disregarded",
"extra arguments %s will be disregarded"), paste(sQuote(names(list(...))),
collapse = ", ")), domain = NA)
R <- qr$qr
if (!complete)
R <- R[seq.int(min(dim(R))), , drop = FALSE]
R[row(R) > col(R)] <- 0
R
}
## @type ncol : complex
## @type complete : logical
qr.X <- function (qr, complete = FALSE, ncol = if (complete) nrow(R) else min(dim(R)))
{
if (!is.qr(qr))
stop("argument is not a QR decomposition")
pivoted <- !identical(qr$pivot, ip <- seq_along(qr$pivot))
R <- qr.R(qr, complete = TRUE)
if (pivoted && ncol < length(qr$pivot))
stop("need larger value of 'ncol' as pivoting occurred")
cmplx <- mode(R) == "complex"
p <- as.integer(dim(R)[2L])
if (is.na(p))
stop("invalid NCOL(R)")
if (ncol < p)
R <- R[, seq_len(ncol), drop = FALSE]
else if (ncol > p) {
tmp <- diag(if (!cmplx)
1
else 1 + (0+0i), nrow(R), ncol)
tmp[, seq_len(p)] <- R
R <- tmp
}
res <- qr.qy(qr, R)
cn <- colnames(res)
if (pivoted) {
res[, qr$pivot] <- res[, ip]
if (!is.null(cn))
colnames(res)[qr$pivot] <- cn[ip]
}
res
}
## @type save : character
quit <- function (save = "default", status = 0, runLast = TRUE)
.Internal(quit(save, status, runLast))
## @type ties.method : character
## @type x : complex|logical|character
rank <- function (x, na.last = TRUE, ties.method = c("average", "first",
"random", "max", "min"))
{
nas <- is.na(x)
nm <- names(x)
ties.method <- match.arg(ties.method)
if (is.factor(x))
x <- as.integer(x)
xx <- x[!nas]
y <- switch(ties.method, average = , min = , max = .Internal(rank(xx,
length(xx), ties.method)), first = sort.list(sort.list(xx)),
random = sort.list(order(xx, stats::runif(sum(!nas)))))
if (!is.na(na.last) && any(nas)) {
yy <- integer(length(x))
storage.mode(yy) <- storage.mode(y)
yy <- NA
NAkeep <- (na.last == "keep")
if (NAkeep || na.last) {
yy[!nas] <- y
if (!NAkeep)
yy[nas] <- (length(y) + 1L):length(yy)
}
else {
len <- sum(nas)
yy[!nas] <- y + len
yy[nas] <- 1L:len
}
y <- yy
names(y) <- nm
}
else names(y) <- nm[!nas]
y
}
save <- function (..., list = character(), file = stop("'file' must be specified"),
ascii = FALSE, version = NULL, envir = parent.frame(), compress = !ascii,
compression_level, eval.promises = TRUE, precheck = TRUE)
{
opts <- getOption("save.defaults")
if (missing(compress) && !is.null(opts$compress))
compress <- opts$compress
if (missing(compression_level) && !is.null(opts$compression_level))
compression_level <- opts$compression_level
if (missing(ascii) && !is.null(opts$ascii))
ascii <- opts$ascii
if (missing(version))
version <- opts$version
if (!is.null(version) && version < 2)
warning("Use of save versions prior to 2 is deprecated",
domain = NA)
names <- as.character(substitute(list(...)))[-1L]
if (missing(list) && !length(names))
warning("nothing specified to be save()d")
list <- c(list, names)
if (!is.null(version) && version == 1)
.Internal(save(list, file, ascii, version, envir, eval.promises))
else {
if (precheck) {
ok <- unlist(lapply(list, exists, envir = envir))
if (!all(ok)) {
n <- sum(!ok)
stop(sprintf(ngettext(n, "object %s not found",
"objects %s not found"), paste(sQuote(list[!ok]),
collapse = ", ")), domain = NA)
}
}
if (is.character(file)) {
if (!nzchar(file))
stop("'file' must be non-empty string")
if (!is.character(compress)) {
if (!is.logical(compress))
stop("'compress' must be logical or character")
compress <- if (compress)
"gzip"
else "no compression"
}
con <- switch(compress, bzip2 = {
if (!missing(compression_level)) bzfile(file,
"wb", compression = compression_level) else bzfile(file,
"wb")
}, xz = {
if (!missing(compression_level)) xzfile(file,
"wb", compression = compression_level) else xzfile(file,
"wb", compression = 9)
}, gzip = {
if (!missing(compression_level)) gzfile(file,
"wb", compression = compression_level) else gzfile(file,
"wb")
}, `no compression` = file(file, "wb"), stop(gettextf("'compress = \"%s\"' is invalid",
compress)))
on.exit(close(con))
}
else if (inherits(file, "connection"))
con <- file
else stop("bad file argument")
if (isOpen(con) && summary(con)$text != "binary")
stop("can only save to a binary connection")
.Internal(saveToConn(list, con, ascii, version, envir,
eval.promises))
}
}
scan <- function (file = "", what = double(), nmax = -1L, n = -1L, sep = "",
quote = if (identical(sep, "\n")) "" else "'\"", dec = ".",
skip = 0L, nlines = 0L, na.strings = "NA", flush = FALSE,
fill = FALSE, strip.white = FALSE, quiet = FALSE, blank.lines.skip = TRUE,
multi.line = TRUE, comment.char = "", allowEscapes = FALSE,
fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)
{
na.strings <- as.character(na.strings)
if (!missing(n)) {
if (missing(nmax))
nmax <- n/pmax(length(what), 1L)
else stop("either specify 'nmax' or 'n', but not both.")
}
if (missing(file) && !missing(text)) {
file <- textConnection(text, encoding = "UTF-8")
encoding <- "UTF-8"
on.exit(close(file))
}
if (is.character(file))
if (file == "")
file <- stdin()
else {
file <- if (nzchar(fileEncoding))
file(file, "r", encoding = fileEncoding)
else file(file, "r")
on.exit(close(file))
}
if (!inherits(file, "connection"))
stop("'file' must be a character string or connection")
.Internal(scan(file, what, nmax, sep, dec, quote, skip, nlines,
na.strings, flush, fill, strip.white, quiet, blank.lines.skip,
multi.line, comment.char, allowEscapes, encoding, skipNul))
}
seek <- function (con, ...)
UseMethod("seek")
## @type x : numeric
sign <- function (x) .Primitive("sign")
## @type x : complex
sinh <- function (x) .Primitive("sinh")
## @type type : character
## @type file : character
## @type split : logical
## @type append : logical
sink <- function (file = NULL, append = FALSE, type = c("output", "message"),
split = FALSE)
{
type <- match.arg(type)
if (type == "message") {
if (is.null(file))
file <- stderr()
else if (!inherits(file, "connection") || !isOpen(file))
stop("'file' must be NULL or an already open connection")
if (split)
stop("cannot split the message connection")
.Internal(sink(file, FALSE, TRUE, FALSE))
}
else {
closeOnExit <- FALSE
if (is.null(file))
file <- -1L
else if (is.character(file)) {
file <- file(file, ifelse(append, "a", "w"))
closeOnExit <- TRUE
}
else if (!inherits(file, "connection"))
stop("'file' must be NULL, a connection or a character string")
.Internal(sink(file, closeOnExit, FALSE, split))
}
}
## @optional x
sort <- function (x, decreasing = FALSE, ...)
{
if (!is.logical(decreasing) || length(decreasing) != 1L)
stop("'decreasing' must be a length-1 logical vector.\nDid you intend to set 'partial'?")
UseMethod("sort")
}
## @type x : complex
sqrt <- function (x) .Primitive("sqrt")
## @type call. : logical
stop <- function (..., call. = TRUE, domain = NULL)
{
args <- list(...)
if (length(args) == 1L && inherits(args[[1L]], "condition")) {
cond <- args[[1L]]
if (nargs() > 1L)
warning("additional arguments ignored in stop()")
message <- conditionMessage(cond)
call <- conditionCall(cond)
.Internal(.signalCondition(cond, message, call))
.Internal(.dfltStop(message, call))
}
else .Internal(stop(call., .makeMessage(..., domain = domain)))
}
## @type x : complex
tanh <- function (x) .Primitive("tanh")
with <- function (data, expr, ...)
UseMethod("with")
## @type x : complex
acosh <- function (x) .Primitive("acosh")
addNA <- function (x, ifany = FALSE)
{
if (!is.factor(x))
x <- factor(x)
if (ifany & !anyNA(x))
return(x)
ll <- levels(x)
if (!anyNA(ll))
ll <- c(ll, NA)
factor(x, levels = ll, exclude = NULL)
}
## @type x : character
## @type pattern : character
## @type costs : numeric
## @type value : integer
## @type max.distance : integer
## @type useBytes : logical
## @type fixed : logical
agrep <- function (pattern, x, max.distance = 0.1, costs = NULL, ignore.case = FALSE,
value = FALSE, fixed = TRUE, useBytes = FALSE)
{
pattern <- as.character(pattern)
if (!is.character(x))
x <- as.character(x)
costs <- as.integer(.amatch_costs(costs))
bounds <- .amatch_bounds(max.distance)
.Internal(agrep(pattern, x, ignore.case, value, costs, bounds,
useBytes, fixed))
}
alist <- function (...)
as.list(sys.call())[-1L]
anyNA <- function (x) .Primitive("anyNA")
## @type perm : complex|character
aperm <- function (a, perm, ...)
UseMethod("aperm")
apply <- function (X, MARGIN, FUN, ...)
{
FUN <- match.fun(FUN)
dl <- length(dim(X))
if (!dl)
stop("dim(X) must have a positive length")
if (is.object(X))
X <- if (dl == 2L)
as.matrix(X)
else as.array(X)
d <- dim(X)
dn <- dimnames(X)
ds <- seq_len(dl)
if (is.character(MARGIN)) {
if (is.null(dnn <- names(dn)))
stop("'X' must have named dimnames")
MARGIN <- match(MARGIN, dnn)
if (anyNA(MARGIN))
stop("not all elements of 'MARGIN' are names of dimensions")
}
s.call <- ds[-MARGIN]
s.ans <- ds[MARGIN]
d.call <- d[-MARGIN]
d.ans <- d[MARGIN]
dn.call <- dn[-MARGIN]
dn.ans <- dn[MARGIN]
d2 <- prod(d.ans)
if (d2 == 0L) {
newX <- array(vector(typeof(X), 1L), dim = c(prod(d.call),
1L))
ans <- FUN(if (length(d.call) < 2L)
newX[, 1]
else array(newX[, 1L], d.call, dn.call), ...)
return(if (is.null(ans)) ans else if (length(d.ans) <
2L) ans[1L][-1L] else array(ans, d.ans, dn.ans))
}
newX <- aperm(X, c(s.call, s.ans))
dim(newX) <- c(prod(d.call), d2)
ans <- vector("list", d2)
if (length(d.call) < 2L) {
if (length(dn.call))
dimnames(newX) <- c(dn.call, list(NULL))
for (i in 1L:d2) {
tmp <- FUN(newX[, i], ...)
if (!is.null(tmp))
ans[[i]] <- tmp
}
}
else for (i in 1L:d2) {
tmp <- FUN(array(newX[, i], d.call, dn.call), ...)
if (!is.null(tmp))
ans[[i]] <- tmp
}
ans.list <- is.recursive(ans[[1L]])
l.ans <- length(ans[[1L]])
ans.names <- names(ans[[1L]])
if (!ans.list)
ans.list <- any(unlist(lapply(ans, length)) != l.ans)
if (!ans.list && length(ans.names)) {
all.same <- vapply(ans, function(x) identical(names(x),
ans.names), NA)
if (!all(all.same))
ans.names <- NULL
}
len.a <- if (ans.list)
d2
else length(ans <- unlist(ans, recursive = FALSE))
if (length(MARGIN) == 1L && len.a == d2) {
names(ans) <- if (length(dn.ans[[1L]]))
dn.ans[[1L]]
return(ans)
}
if (len.a == d2)
return(array(ans, d.ans, dn.ans))
if (len.a && len.a%%d2 == 0L) {
if (is.null(dn.ans))
dn.ans <- vector(mode = "list", length(d.ans))
dn.ans <- c(list(ans.names), dn.ans)
return(array(ans, c(len.a%/%d2, d.ans), if (!all(vapply(dn.ans,
is.null, NA))) dn.ans))
}
return(ans)
}
## @type dimnames : complex|character
## @type dim : integer
array <- function (data = NA, dim = length(data), dimnames = NULL)
{
if (is.atomic(data) && !is.object(data))
return(.Internal(array(data, dim, dimnames)))
data <- as.vector(data)
if (is.object(data)) {
dim <- as.integer(dim)
if (!length(dim))
stop("'dims' cannot be of length 0")
vl <- prod(dim)
if (length(data) != vl) {
if (vl > .Machine$integer.max)
stop("'dim' specifies too large an array")
data <- rep_len(data, vl)
}
if (length(dim))
dim(data) <- dim
if (is.list(dimnames) && length(dimnames))
dimnames(data) <- dimnames
data
}
else .Internal(array(data, dim, dimnames))
}
## @type x : complex
as.qr <- function (x)
stop("you cannot be serious", domain = NA)
## @type x : complex
asinh <- function (x) .Primitive("asinh")
## @type x : complex
## @type y : complex
atan2 <- function (y, x)
.Internal(atan2(y, x))
## @type x : complex
atanh <- function (x) .Primitive("atanh")
## @type deparse.level : integer
cbind <- function (..., deparse.level = 1)
.Internal(cbind(deparse.level, ...))
class <- function (x) .Primitive("class")
close <- function (con, ...)
UseMethod("close")
## @type x : complex
cospi <- function (x) .Primitive("cospi")
## @type text : character
debug <- function (fun, text = "", condition = NULL)
.Internal(debug(fun, text, condition))
## @type value : numeric
"dim<-" <- function (x, value) .Primitive("dim<-")
eigen <- function (x, symmetric, only.values = FALSE, EISPACK = FALSE)
{
x <- as.matrix(x)
n <- nrow(x)
if (!n)
stop("0 x 0 matrix")
if (n != ncol(x))
stop("non-square matrix in 'eigen'")
n <- as.integer(n)
if (is.na(n))
stop("invalid nrow(x)")
complex.x <- is.complex(x)
if (!all(is.finite(x)))
stop("infinite or missing values in 'x'")
if (missing(symmetric))
symmetric <- isSymmetric.matrix(x)
if (symmetric) {
z <- if (!complex.x)
.Internal(La_rs(x, only.values))
else .Internal(La_rs_cmplx(x, only.values))
ord <- rev(seq_along(z$values))
}
else {
z <- if (!complex.x)
.Internal(La_rg(x, only.values))
else .Internal(La_rg_cmplx(x, only.values))
ord <- sort.list(Mod(z$values), decreasing = TRUE)
}
return(list(values = z$values[ord], vectors = if (!only.values) z$vectors[,
ord, drop = FALSE]))
}
evalq <- function (expr, envir = parent.frame(), enclos = if (is.list(envir) ||
is.pairlist(envir)) parent.frame() else baseenv())
.Internal(eval(substitute(expr), envir, enclos))
## @type x : complex
expm1 <- function (x) .Primitive("expm1")
## @type x : complex
floor <- function (x) .Primitive("floor")
flush <- function (con)
UseMethod("flush")
force <- function (x)
x
## @type x : numeric
gamma <- function (x) .Primitive("gamma")
getwd <- function ()
.Internal(getwd())
## @type x : character
## @type fixed : logical|character
## @type perl : logical
## @type pattern : character
## @type useBytes : logical
grepl <- function (pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE,
useBytes = FALSE)
{
if (!is.character(x))
x <- as.character(x)
.Internal(grepl(as.character(pattern), x, ignore.case, FALSE,
perl, fixed, useBytes, FALSE))
}
## @type allowNonCompressed : logical
## @type level : integer
gzcon <- function (con, level = 6, allowNonCompressed = TRUE)
.Internal(gzcon(con, level, allowNonCompressed))
## @type toRaw : raw|logical|character
## @type x : raw|character
## @type mark : logical
## @type from : character
## @type sub : character
## @type to : character
iconv <- function (x, from = "", to = "", sub = NA, mark = TRUE, toRaw = FALSE)
{
if (!(is.character(x) || (is.list(x) && is.null(oldClass(x)))))
x <- as.character(x)
.Internal(iconv(x, from, to, as.character(sub), mark, toRaw))
}
is.na <- function (x) .Primitive("is.na")
## @type x : complex
is.qr <- function (x)
inherits(x, "qr")
kappa <- function (z, ...)
UseMethod("kappa")
## @type a : numeric
## @type b : numeric
lbeta <- function (a, b)
.Internal(lbeta(a, b))
local <- function (expr, envir = new.env())
eval.parent(substitute(eval(quote(expr), envir)))
log10 <- function (x) .Primitive("log10")
## @type x : complex
log1p <- function (x) .Primitive("log1p")
## @type nomatch : integer
match <- function (x, table, nomatch = NA_integer_, incomparables = NULL)
.Internal(match(x, table, nomatch, incomparables))
merge <- function (x, y, ...)
UseMethod("merge")
names <- function (x) .Primitive("names")
nargs <- function () .Primitive("nargs")
## @type type : character
## @type allowNA : logical
## @type x : character
nchar <- function (x, type = "chars", allowNA = FALSE)
.Internal(nchar(x, type, allowNA))
## @type decreasing : logical
order <- function (..., na.last = TRUE, decreasing = FALSE)
{
z <- list(...)
if (any(unlist(lapply(z, is.object)))) {
z <- lapply(z, function(x) if (is.object(x))
xtfrm(x)
else x)
if (!is.na(na.last))
return(do.call("order", c(z, na.last = na.last, decreasing = decreasing)))
}
else if (!is.na(na.last)) {
if (length(z) == 1L && is.factor(zz <- z[[1L]]) && nlevels(zz) <
1e+05)
return(.Internal(radixsort(zz, na.last, decreasing)))
else return(.Internal(order(na.last, decreasing, ...)))
}
if (any(diff(l.z <- vapply(z, length, 1L)) != 0L))
stop("argument lengths differ")
ans <- vapply(z, is.na, rep.int(NA, l.z[1L]))
ok <- if (is.matrix(ans))
!apply(ans, 1, any)
else !any(ans)
if (all(!ok))
return(integer())
z[[1L]][!ok] <- NA
ans <- do.call("order", c(z, decreasing = decreasing))
keep <- seq_along(ok)[ok]
ans[ans %in% keep]
}
outer <- function (X, Y, FUN = "*", ...)
{
if (is.array(X)) {
dX <- dim(X)
nx <- dimnames(X)
no.nx <- is.null(nx)
}
else {
dX <- length(X)
no.nx <- is.null(names(X))
if (!no.nx)
nx <- list(names(X))
}
if (is.array(Y)) {
dY <- dim(Y)
ny <- dimnames(Y)
no.ny <- is.null(ny)
}
else {
dY <- length(Y)
no.ny <- is.null(names(Y))
if (!no.ny)
ny <- list(names(Y))
}
if (is.character(FUN) && FUN == "*") {
if (!missing(...))
stop("using ... with FUN = \"*\" is an error")
robj <- as.vector(X) %*% t(as.vector(Y))
dim(robj) <- c(dX, dY)
}
else {
FUN <- match.fun(FUN)
Y <- rep(Y, rep.int(length(X), length(Y)))
if (length(X))
X <- rep(X, times = ceiling(length(Y)/length(X)))
robj <- FUN(X, Y, ...)
dim(robj) <- c(dX, dY)
}
if (!(no.nx && no.ny)) {
if (no.nx)
nx <- vector("list", length(dX))
else if (no.ny)
ny <- vector("list", length(dY))
dimnames(robj) <- c(nx, ny)
}
robj
}
parse <- function (file = "", n = NULL, text = NULL, prompt = "?", keep.source = getOption("keep.source"),
srcfile = NULL, encoding = "unknown")
{
keep.source <- isTRUE(keep.source)
if (!is.null(text)) {
if (length(text) == 0L)
return(expression())
if (missing(srcfile)) {
srcfile <- "<text>"
if (keep.source)
srcfile <- srcfilecopy(srcfile, text)
}
file <- stdin()
}
else {
if (is.character(file)) {
if (file == "") {
file <- stdin()
if (missing(srcfile))
srcfile <- "<stdin>"
}
else {
filename <- file
file <- file(filename, "r")
if (missing(srcfile))
srcfile <- filename
if (keep.source) {
text <- readLines(file, warn = FALSE)
if (!length(text))
text <- ""
close(file)
file <- stdin()
srcfile <- srcfilecopy(filename, text, file.info(filename)[1,
"mtime"], isFile = TRUE)
}
else on.exit(close(file))
}
}
}
.Internal(parse(file, n, text, prompt, srcfile, encoding))
}
## @type sep : character
## @type collapse : character
## @return character
paste <- function (..., sep = " ", collapse = NULL)
.Internal(paste(list(...), sep, collapse))
print <- function (x, ...)
UseMethod("print")
qr.qy <- function (qr, y)
{
if (!is.qr(qr))
stop("argument is not a QR decomposition")
if (is.complex(qr$qr))
return(.Internal(qr_qy_cmplx(qr, as.matrix(y), FALSE)))
if (isTRUE(attr(qr, "useLAPACK")))
return(.Internal(qr_qy_real(qr, as.matrix(y), FALSE)))
n <- as.integer(nrow(qr$qr))
if (is.na(n))
stop("invalid nrow(qr$qr)")
k <- as.integer(qr$rank)
ny <- as.integer(NCOL(y))
if (is.na(ny))
stop("invalid NCOL(y)")
storage.mode(y) <- "double"
if (NROW(y) != n)
stop("'qr' and 'y' must have the same number of rows")
.Fortran(.F_dqrqy, as.double(qr$qr), n, k, as.double(qr$qraux),
y, ny, qy = y)$qy
}
quote <- function (expr) .Primitive("quote")
## @type na.rm : logical
range <- function (..., na.rm = FALSE) .Primitive("range")
## @type deparse.level : integer
rbind <- function (..., deparse.level = 1)
.Internal(rbind(deparse.level, ...))
## @type triangular : logical
## @type norm : complex|character
rcond <- function (x, norm = c("O", "I", "1"), triangular = FALSE, ...)
{
norm <- match.arg(norm)
stopifnot(is.matrix(x))
if ({
d <- dim(x)
d[1L] != d[2L]
})
return(rcond(qr.R(qr(if (d[1L] < d[2L]) t(x) else x)),
norm = norm, ...))
if (is.complex(x)) {
if (triangular)
.Internal(La_ztrcon(x, norm))
else .Internal(La_zgecon(x, norm))
}
else {
if (triangular)
.Internal(La_dtrcon(x, norm))
else .Internal(La_dgecon(x, norm))
}
}
round <- function (x, digits = 0) .Primitive("round")
## @type x : numeric
## @type center : complex|logical
## @type scale : complex|logical
scale <- function (x, center = TRUE, scale = TRUE)
UseMethod("scale")
## @return character
setwd <- function (dir)
.Internal(setwd(dir))
## @type x : complex
sinpi <- function (x) .Primitive("sinpi")
"/" <- function (e1, e2) .Primitive("/")
## @type a : complex
## @type b : complex
solve <- function (a, b, ...)
UseMethod("solve")
## @type drop : logical
split <- function (x, f, drop = FALSE, ...)
UseMethod("split")
stdin <- function ()
.Internal(stdin())
## @type check.margin : logical
sweep <- function (x, MARGIN, STATS, FUN = "-", check.margin = TRUE, ...)
{
FUN <- match.fun(FUN)
dims <- dim(x)
if (check.margin) {
dimmargin <- dims[MARGIN]
dimstats <- dim(STATS)
lstats <- length(STATS)
if (lstats > prod(dimmargin)) {
warning("STATS is longer than the extent of 'dim(x)[MARGIN]'")
}
else if (is.null(dimstats)) {
cumDim <- c(1L, cumprod(dimmargin))
upper <- min(cumDim[cumDim >= lstats])
lower <- max(cumDim[cumDim <= lstats])
if (lstats && (upper%%lstats != 0L || lstats%%lower !=
0L))
warning("STATS does not recycle exactly across MARGIN")
}
else {
dimmargin <- dimmargin[dimmargin > 1L]
dimstats <- dimstats[dimstats > 1L]
if (length(dimstats) != length(dimmargin) || any(dimstats !=
dimmargin))
warning("length(STATS) or dim(STATS) do not match dim(x)[MARGIN]")
}
}
perm <- c(MARGIN, seq_along(dims)[-MARGIN])
FUN(x, aperm(array(STATS, dims[perm]), order(perm)), ...)
}
table <- function (..., exclude = if (useNA == "no") c(NA, NaN), useNA = c("no",
"ifany", "always"), dnn = list.names(...), deparse.level = 1)
{
list.names <- function(...) {
l <- as.list(substitute(list(...)))[-1L]
nm <- names(l)
fixup <- if (is.null(nm))
seq_along(l)
else nm == ""
dep <- vapply(l[fixup], function(x) switch(deparse.level +
1, "", if (is.symbol(x)) as.character(x) else "",
deparse(x, nlines = 1)[1L]), "")
if (is.null(nm))
dep
else {
nm[fixup] <- dep
nm
}
}
if (!missing(exclude) && is.null(exclude))
useNA <- "always"
useNA <- match.arg(useNA)
args <- list(...)
if (!length(args))
stop("nothing to tabulate")
if (length(args) == 1L && is.list(args[[1L]])) {
args <- args[[1L]]
if (length(dnn) != length(args))
dnn <- if (!is.null(argn <- names(args)))
argn
else paste(dnn[1L], seq_along(args), sep = ".")
}
bin <- 0L
lens <- NULL
dims <- integer()
pd <- 1L
dn <- NULL
for (a in args) {
if (is.null(lens))
lens <- length(a)
else if (length(a) != lens)
stop("all arguments must have the same length")
cat <- if (is.factor(a)) {
if (any(is.na(levels(a))))
a
else {
if (is.null(exclude) && useNA != "no")
addNA(a, ifany = (useNA == "ifany"))
else {
if (useNA != "no")
a <- addNA(a, ifany = (useNA == "ifany"))
ll <- levels(a)
a <- factor(a, levels = ll[!(ll %in% exclude)],
exclude = if (useNA == "no")
NA)
}
}
}
else {
a <- factor(a, exclude = exclude)
if (useNA != "no")
addNA(a, ifany = (useNA == "ifany"))
else a
}
nl <- length(ll <- levels(cat))
dims <- c(dims, nl)
if (prod(dims) > .Machine$integer.max)
stop("attempt to make a table with >= 2^31 elements")
dn <- c(dn, list(ll))
bin <- bin + pd * (as.integer(cat) - 1L)
pd <- pd * nl
}
names(dn) <- dnn
bin <- bin[!is.na(bin)]
if (length(bin))
bin <- bin + 1L
y <- array(tabulate(bin, pd), dims, dimnames = dn)
class(y) <- "table"
y
}
## @type x : complex
tanpi <- function (x) .Primitive("tanpi")
## @optional tracer, at, signature, print, exit
trace <- function (what, tracer, exit, at, print, signature, where = topenv(parent.frame()),
edit = FALSE)
{
needsAttach <- nargs() > 1L && !.isMethodsDispatchOn()
if (needsAttach) {
ns <- try(loadNamespace("methods"))
if (isNamespace(ns))
message("(loaded the methods namespace)", domain = NA)
else stop("tracing functions requires the 'methods' package, but unable to load the 'methods' namespace")
}
else if (nargs() == 1L)
return(.primTrace(what))
tState <- tracingState(FALSE)
on.exit(tracingState(tState))
call <- sys.call()
call[[1L]] <- quote(methods::.TraceWithMethods)
call$where <- where
value <- eval.parent(call)
on.exit()
tracingState(tState)
value
}
## @type x : complex
trunc <- function (x, ...) .Primitive("trunc")
union <- function (x, y)
unique(c(as.vector(x), as.vector(y)))
units <- function (x)
UseMethod("units")
## @type useNames : logical
## @type arr.ind : logical
## @type x : logical
which <- function (x, arr.ind = FALSE, useNames = TRUE)
{
wh <- .Internal(which(x))
if (arr.ind && !is.null(d <- dim(x)))
arrayInd(wh, d, dimnames(x), useNames = useNames)
else wh
}
write <- function (x, file = "data", ncolumns = if (is.character(x)) 1 else 5,
append = FALSE, sep = " ")
cat(x, file = file, sep = c(rep.int(sep, ncolumns - 1), "\n"),
append = append)
xtfrm <- function (x) .Primitive("xtfrm")
"+.Date" <- function (e1, e2)
{
coerceTimeUnit <- function(x) as.vector(round(switch(attr(x,
"units"), secs = x/86400, mins = x/1440, hours = x/24,
days = x, weeks = 7 * x)))
if (nargs() == 1)
return(e1)
if (inherits(e1, "Date") && inherits(e2, "Date"))
stop("binary + is not defined for \"Date\" objects")
if (inherits(e1, "difftime"))
e1 <- coerceTimeUnit(e1)
if (inherits(e2, "difftime"))
e2 <- coerceTimeUnit(e2)
structure(unclass(e1) + unclass(e2), class = "Date")
}
"-.Date" <- function (e1, e2)
{
coerceTimeUnit <- function(x) as.vector(round(switch(attr(x,
"units"), secs = x/86400, mins = x/1440, hours = x/24,
days = x, weeks = 7 * x)))
if (!inherits(e1, "Date"))
stop("can only subtract from \"Date\" objects")
if (nargs() == 1)
stop("unary - is not defined for \"Date\" objects")
if (inherits(e2, "Date"))
return(difftime(e1, e2, units = "days"))
if (inherits(e2, "difftime"))
e2 <- coerceTimeUnit(e2)
if (!is.null(attr(e2, "class")))
stop("can only subtract numbers from \"Date\" objects")
structure(unclass(as.Date(e1)) - e2, class = "Date")
}
"[.AsIs" <- function (x, i, ...)
I(NextMethod("["))
"[.Date" <- function (x, ..., drop = TRUE)
{
cl <- oldClass(x)
class(x) <- NULL
val <- NextMethod("[")
class(val) <- cl
val
}
## @type costs : numeric
## @type x : character
## @type fixed : logical
## @type useBytes : logical
## @type pattern : character
## @type max.distance : integer
agrepl <- function (pattern, x, max.distance = 0.1, costs = NULL, ignore.case = FALSE,
fixed = TRUE, useBytes = FALSE)
{
pattern <- as.character(pattern)
if (!is.character(x))
x <- as.character(x)
costs <- as.integer(.amatch_costs(costs))
bounds <- .amatch_bounds(max.distance)
.Internal(agrepl(pattern, x, ignore.case, FALSE, costs, bounds,
useBytes, fixed))
}
append <- function (x, values, after = length(x))
{
lengx <- length(x)
if (!after)
c(values, x)
else if (after >= lengx)
c(x, values)
else c(x[1L:after], values, x[(after + 1L):lengx])
}
as.raw <- function (x) .Primitive("as.raw")
assign <- function (x, value, pos = -1, envir = as.environment(pos), inherits = FALSE,
immediate = TRUE)
.Internal(assign(x, value, envir, inherits))
## @type warn.conflicts : logical
## @type pos : integer
## @type name : character
attach <- function (what, pos = 2L, name = deparse(substitute(what)), warn.conflicts = TRUE)
{
checkConflicts <- function(env) {
dont.mind <- c("last.dump", "last.warning", ".Last.value",
".Random.seed", ".Last.lib", ".onDetach", ".packageName",
".noGenerics", ".required", ".no_S3_generics", ".requireCachedGenerics")
sp <- search()
for (i in seq_along(sp)) {
if (identical(env, as.environment(i))) {
db.pos <- i
break
}
}
ob <- objects(db.pos, all.names = TRUE)
if (.isMethodsDispatchOn()) {
these <- ob[substr(ob, 1L, 6L) == ".__T__"]
gen <- gsub(".__T__(.*):([^:]+)", "\\1", these)
from <- gsub(".__T__(.*):([^:]+)", "\\2", these)
gen <- gen[from != ".GlobalEnv"]
ob <- ob[!(ob %in% gen)]
}
ipos <- seq_along(sp)[-c(db.pos, match(c("Autoloads",
"CheckExEnv"), sp, 0L))]
for (i in ipos) {
obj.same <- match(objects(i, all.names = TRUE), ob,
nomatch = 0L)
if (any(obj.same > 0L)) {
same <- ob[obj.same]
same <- same[!(same %in% dont.mind)]
Classobjs <- grep("^\\.__", same)
if (length(Classobjs))
same <- same[-Classobjs]
same.isFn <- function(where) vapply(same, exists,
NA, where = where, mode = "function", inherits = FALSE)
same <- same[same.isFn(i) == same.isFn(db.pos)]
if (length(same)) {
pkg <- if (sum(sp == sp[i]) > 1L)
sprintf("%s (pos = %d)", sp[i], i)
else sp[i]
message(.maskedMsg(same, pkg, by = i < db.pos),
domain = NA)
}
}
}
}
if (pos == 1L) {
warning("*** 'pos=1' is not possible; setting 'pos=2' for now.\n",
"*** Note that 'pos=1' will give an error in the future")
pos <- 2L
}
if (is.character(what) && (length(what) == 1L)) {
if (!file.exists(what))
stop(gettextf("file '%s' not found", what), domain = NA)
if (missing(name))
name <- paste0("file:", what)
value <- .Internal(attach(NULL, pos, name))
load(what, envir = as.environment(pos))
}
else value <- .Internal(attach(what, pos, name))
if (warn.conflicts && !exists(".conflicts.OK", envir = value,
inherits = FALSE)) {
checkConflicts(value)
}
if (length(ls(envir = value, all.names = TRUE)) && .isMethodsDispatchOn())
methods:::cacheMetaData(value, TRUE)
invisible(value)
}
## @type which : character
"attr<-" <- function (x, which, value) .Primitive("attr<-")
## @return integer
bitwOr <- function (a, b)
.Internal(bitwiseOr(a, b))
bquote <- function (expr, where = parent.frame())
{
unquote <- function(e) if (is.pairlist(e))
as.pairlist(lapply(e, unquote))
else if (length(e) <= 1L)
e
else if (e[[1L]] == as.name("."))
eval(e[[2L]], where)
else as.call(lapply(e, unquote))
unquote(substitute(expr))
}
## @type compression : integer
## @type description : character
## @type open : character
## @type encoding : character
bzfile <- function (description, open = "", encoding = getOption("encoding"),
compression = 9)
.Internal(bzfile(description, open, encoding, compression))
c.Date <- function (..., recursive = FALSE)
structure(c(unlist(lapply(list(...), unclass))), class = "Date")
## @optional fun
callCC <- function (fun)
{
value <- NULL
delayedAssign("throw", return(value))
fun(function(v) {
value <<- v
throw
})
}
chartr <- function (old, new, x)
{
if (!is.character(x))
x <- as.character(x)
.Internal(chartr(old, new, x))
}
## @type n : numeric
## @type k : integer
choose <- function (n, k)
.Internal(choose(n, k))
## @type x : complex
cummax <- function (x) .Primitive("cummax")
## @type x : complex
cummin <- function (x) .Primitive("cummin")
## @type x : complex
cumsum <- function (x) .Primitive("cumsum")
detach <- function (name, pos = 2L, unload = FALSE, character.only = FALSE,
force = FALSE)
{
if (!missing(name)) {
if (!character.only)
name <- substitute(name)
pos <- if (is.numeric(name))
name
else {
if (!is.character(name))
name <- deparse(name)
match(name, search())
}
if (is.na(pos))
stop("invalid 'name' argument")
}
packageName <- search()[[pos]]
if (!grepl("^package:", packageName))
return(invisible(.Internal(detach(pos))))
pkgname <- sub("^package:", "", packageName)
for (pkg in search()[-1L]) {
if (grepl("^package:", pkg) && exists(".Depends", pkg,
inherits = FALSE) && pkgname %in% get(".Depends",
pkg, inherits = FALSE))
if (force)
warning(gettextf("package %s is required by %s, which may no longer work correctly",
sQuote(pkgname), sQuote(sub("^package:", "",
pkg))), call. = FALSE, domain = NA)
else stop(gettextf("package %s is required by %s so will not be detached",
sQuote(pkgname), sQuote(sub("^package:", "",
pkg))), call. = FALSE, domain = NA)
}
env <- as.environment(pos)
libpath <- attr(env, "path")
hook <- getHook(packageEvent(pkgname, "detach"))
for (fun in rev(hook)) try(fun(pkgname, libpath))
ns <- .getNamespace(pkgname)
if (!is.null(ns) && exists(".onDetach", mode = "function",
where = ns, inherits = FALSE)) {
.onDetach <- get(".onDetach", mode = "function", pos = ns,
inherits = FALSE)
if (!is.null(libpath)) {
res <- tryCatch(.onDetach(libpath), error = identity)
if (inherits(res, "error")) {
warning(gettextf("%s failed in %s() for '%s', details:\n call: %s\n error: %s",
".onDetach", "detach", pkgname, deparse(conditionCall(res))[1L],
conditionMessage(res)), call. = FALSE, domain = NA)
}
}
}
else if (exists(".Last.lib", mode = "function", where = pos,
inherits = FALSE)) {
.Last.lib <- get(".Last.lib", mode = "function", pos = pos,
inherits = FALSE)
if (!is.null(libpath)) {
res <- tryCatch(.Last.lib(libpath), error = identity)
if (inherits(res, "error")) {
warning(gettextf("%s failed in %s() for '%s', details:\n call: %s\n error: %s",
".Last.lib", "detach", pkgname, deparse(conditionCall(res))[1L],
conditionMessage(res)), call. = FALSE, domain = NA)
}
}
}
.Internal(detach(pos))
if (pkgname %in% loadedNamespaces()) {
if (unload) {
tryCatch(unloadNamespace(pkgname), error = function(e) warning(gettextf("%s namespace cannot be unloaded:\n ",
sQuote(pkgname)), conditionMessage(e), call. = FALSE,
domain = NA))
}
}
else {
if (.isMethodsDispatchOn() && methods:::.hasS4MetaData(env))
methods:::cacheMetaData(env, FALSE)
.Internal(lazyLoadDBflush(paste0(libpath, "/R/", pkgname,
".rdb")))
}
invisible()
}
"diag<-" <- function (x, value)
{
dx <- dim(x)
if (length(dx) != 2L)
stop("only matrix diagonals can be replaced")
len.i <- min(dx)
len.v <- length(value)
if (len.v != 1L && len.v != len.i)
stop("replacement diagonal has wrong length")
if (len.i) {
i <- seq_len(len.i)
x[cbind(i, i)] <- value
}
x
}
## @type length : integer
double <- function (length = 0L)
.Internal(vector("double", length))
## @type x : character
dQuote <- function (x)
{
if (!length(x))
return(character())
before <- after <- "\""
q <- getOption("useFancyQuotes")
if (!is.null(q)) {
if (identical(q, TRUE)) {
li <- l10n_info()
if (li$"UTF-8")
q <- "UTF-8"
if (!is.null(li$codepage) && li$codepage > 0L) {
if (li$codepage >= 1250L && li$codepage <= 1258L ||
li$codepage == 874L) {
before <- "\x93"
after <- "\x94"
}
else {
z <- iconv(c("“", "”"), "UTF-8", "")
before <- z[1L]
after <- z[2L]
}
}
}
if (identical(q, "TeX")) {
before <- "``"
after <- "''"
}
if (identical(q, "UTF-8")) {
before <- "“"
after <- "”"
}
if (is.character(q) && length(q) >= 4L) {
before <- q[3L]
after <- q[4L]
}
Encoding(before) <- Encoding(after) <- "unknown"
}
paste0(before, x, after)
}
eapply <- function (env, FUN, ..., all.names = FALSE, USE.NAMES = TRUE)
{
FUN <- match.fun(FUN)
.Internal(eapply(env, FUN, all.names, USE.NAMES))
}
exists <- function (x, where = -1, envir = if (missing(frame)) as.environment(where) else sys.frame(frame),
frame, mode = "any", inherits = TRUE)
.Internal(exists(x, envir, mode, inherits))
factor <- function (x = character(), levels, labels = levels, exclude = NA,
ordered = is.ordered(x), nmax = NA)
{
if (is.null(x))
x <- character()
nx <- names(x)
if (missing(levels)) {
y <- unique(x, nmax = nmax)
ind <- sort.list(y)
y <- as.character(y)
levels <- unique(y[ind])
}
force(ordered)
exclude <- as.vector(exclude, typeof(x))
x <- as.character(x)
levels <- levels[is.na(match(levels, exclude))]
f <- match(x, levels)
if (!is.null(nx))
names(f) <- nx
nl <- length(labels)
nL <- length(levels)
if (!any(nl == c(1L, nL)))
stop(gettextf("invalid 'labels'; length %d should be 1 or %d",
nl, nL), domain = NA)
levels(f) <- if (nl == nL)
as.character(labels)
else paste0(labels, seq_along(levels))
class(f) <- c(if (ordered) "ordered", "factor")
f
}
Filter <- function (f, x)
{
ind <- as.logical(unlist(lapply(x, f)))
x[!is.na(ind) & ind]
}
## @type x : numeric
format <- function (x, ...)
UseMethod("format")
gcinfo <- function (verbose)
.Internal(gcinfo(verbose))
## @type description : character
## @type open : character
## @type encoding : character
## @type compression : integer
gzfile <- function (description, open = "", encoding = getOption("encoding"),
compression = 6)
.Internal(gzfile(description, open, encoding, compression))
## @type test : logical
ifelse <- function (test, yes, no)
{
if (is.atomic(test)) {
if (typeof(test) != "logical")
storage.mode(test) <- "logical"
if (length(test) == 1 && is.null(attributes(test))) {
if (is.na(test))
return(NA)
else if (test) {
if (length(yes) == 1 && is.null(attributes(yes)))
return(yes)
}
else if (length(no) == 1 && is.null(attributes(no)))
return(no)
}
}
else test <- if (isS4(test))
as(test, "logical")
else as.logical(test)
ans <- test
ok <- !(nas <- is.na(test))
if (any(test[ok]))
ans[test & ok] <- rep(yes, length.out = length(ans))[test &
ok]
if (any(!test[ok]))
ans[!test & ok] <- rep(no, length.out = length(ans))[!test &
ok]
ans[nas] <- NA
ans
}
is.nan <- function (x) .Primitive("is.nan")
is.raw <- function (x) .Primitive("is.raw")
isatty <- function (con)
{
if (!inherits(con, "terminal"))
FALSE
else .Internal(isatty(con))
}
## @type rw : character
isOpen <- function (con, rw = "")
{
rw <- pmatch(rw, c("read", "write"), 0L)
.Internal(isOpen(con, rw))
}
## @type x : raw|complex|logical
isTRUE <- function (x)
identical(TRUE, x)
## @type factor : numeric
## @type x : numeric
## @type amount : numeric
## @return numeric
jitter <- function (x, factor = 1, amount = NULL)
{
if (length(x) == 0L)
return(x)
if (!is.numeric(x))
stop("'x' must be numeric")
z <- diff(r <- range(x[is.finite(x)]))
if (z == 0)
z <- abs(r[1L])
if (z == 0)
z <- 1
if (is.null(amount)) {
d <- diff(xx <- unique(sort.int(round(x, 3 - floor(log10(z))))))
d <- if (length(d))
min(d)
else if (xx != 0)
xx/10
else z/10
amount <- factor/5 * abs(d)
}
else if (amount == 0)
amount <- factor * (z/50)
x + stats::runif(length(x), -amount, amount)
}
julian <- function (x, ...)
UseMethod("julian")
## @type nu : complex
## @type nv : complex
## @type x : complex
La.svd <- function (x, nu = min(n, p), nv = min(n, p))
{
if (!is.logical(x) && !is.numeric(x) && !is.complex(x))
stop("argument to 'La.svd' must be numeric or complex")
if (any(!is.finite(x)))
stop("infinite or missing values in 'x'")
x <- as.matrix(x)
n <- nrow(x)
p <- ncol(x)
if (!n || !p)
stop("a dimension is zero")
zero <- if (is.complex(x))
0 + (0+0i)
else 0
if (nu || nv) {
np <- min(n, p)
if (nu <= np && nv <= np) {
jobu <- "S"
u <- matrix(zero, n, np)
vt <- matrix(zero, np, p)
nu0 <- nv0 <- np
}
else {
jobu <- "A"
u <- matrix(zero, n, n)
vt <- matrix(zero, p, p)
nu0 <- n
nv0 <- p
}
}
else {
jobu <- "N"
u <- matrix(zero, 1L, 1L)
vt <- matrix(zero, 1L, 1L)
}
res <- if (is.complex(x))
.Internal(La_svd_cmplx(jobu, x, double(min(n, p)), u,
vt))
else .Internal(La_svd(jobu, x, double(min(n, p)), u, vt))
res <- res[c("d", if (nu) "u", if (nv) "vt")]
if (nu && nu < nu0)
res$u <- res$u[, seq_len(min(n, nu)), drop = FALSE]
if (nv && nv < nv0)
res$vt <- res$vt[seq_len(min(p, nv)), , drop = FALSE]
res
}
labels <- function (object, ...)
UseMethod("labels")
lapply <- function (X, FUN, ...)
{
FUN <- match.fun(FUN)
if (!is.vector(X) || is.object(X))
X <- as.list(X)
.Internal(lapply(X, FUN))
}
length <- function (x) .Primitive("length")
levels <- function (x)
UseMethod("levels")
## @type x : numeric
lgamma <- function (x) .Primitive("lgamma")
## @type SIMPLIFY : logical|character
## @type USE.NAMES : logical|character
mapply <- function (FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
{
FUN <- match.fun(FUN)
dots <- list(...)
answer <- .Internal(mapply(FUN, dots, MoreArgs))
if (USE.NAMES && length(dots)) {
if (is.null(names1 <- names(dots[[1L]])) && is.character(dots[[1L]]))
names(answer) <- dots[[1L]]
else if (!is.null(names1))
names(answer) <- names1
}
if (!identical(SIMPLIFY, FALSE) && length(answer))
simplify2array(answer, higher = (SIMPLIFY == "array"))
else answer
}
matrix <- function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
{
if (is.object(data) || !is.atomic(data))
data <- as.vector(data)
.Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow),
missing(ncol)))
}
## @type value : character
"mode<-" <- function (x, value)
{
if (storage.mode(x) == value)
return(x)
if (is.factor(x))
stop("invalid to change the storage mode of a factor")
mde <- paste0("as.", value)
atr <- attributes(x)
isSingle <- !is.null(attr(x, "Csingle"))
setSingle <- value == "single"
x <- eval(call(mde, x), parent.frame())
attributes(x) <- atr
if (setSingle != isSingle)
attr(x, "Csingle") <- if (setSingle)
TRUE
x
}
## @return complex|character
months <- function (x, abbreviate)
UseMethod("months")
Negate <- function (f)
{
f <- match.fun(f)
function(...) !f(...)
}
## @type x : character
nzchar <- function (x) .Primitive("nzchar")
## @type collapse : character
paste0 <- function (..., collapse = NULL)
.Internal(paste0(list(...), collapse))
## @return integer
pmatch <- function (x, table, nomatch = NA_integer_, duplicates.ok = FALSE)
.Internal(pmatch(as.character(x), as.character(table), nomatch,
duplicates.ok))
## @type x : numeric
pretty <- function (x, ...)
UseMethod("pretty")
qr.qty <- function (qr, y)
{
if (!is.qr(qr))
stop("argument is not a QR decomposition")
if (is.complex(qr$qr))
return(.Internal(qr_qy_cmplx(qr, as.matrix(y), TRUE)))
if (isTRUE(attr(qr, "useLAPACK")))
return(.Internal(qr_qy_real(qr, as.matrix(y), TRUE)))
n <- as.integer(nrow(qr$qr))
if (is.na(n))
stop("invalid nrow(qr$qr)")
k <- as.integer(qr$rank)
ny <- as.integer(NCOL(y))
if (is.na(ny))
stop("invalid NCOL(y)")
if (NROW(y) != n)
stop("'qr' and 'y' must have the same number of rows")
storage.mode(y) <- "double"
.Fortran(.F_dqrqty, as.double(qr$qr), n, k, as.double(qr$qraux),
y, ny, qty = y)$qty
}
R.home <- function (component = "home")
{
rh <- .Internal(R.home())
switch(component, home = rh, bin = if (.Platform$OS.type ==
"windows" && nzchar(p <- .Platform$r_arch)) file.path(rh,
component, p) else file.path(rh, component), share = if (nzchar(p <- Sys.getenv("R_SHARE_DIR"))) p else file.path(rh,
component), doc = if (nzchar(p <- Sys.getenv("R_DOC_DIR"))) p else file.path(rh,
component), include = if (nzchar(p <- Sys.getenv("R_INCLUDE_DIR"))) p else file.path(rh,
component), modules = if (nzchar(p <- .Platform$r_arch)) file.path(rh,
component, p) else file.path(rh, component), file.path(rh,
component))
}
## @type how : character
## @type classes : character
rapply <- function (object, f, classes = "ANY", deflt = NULL, how = c("unlist",
"replace", "list"), ...)
{
if (typeof(object) != "list")
stop("'object' must be a list")
how <- match.arg(how)
res <- .Internal(rapply(object, f, classes, deflt, how))
if (how == "unlist")
unlist(res, recursive = TRUE)
else res
}
Recall <- function (...)
.Internal(Recall(...))
## @type accumulate : logical
## @type right : logical
Reduce <- function (f, x, init, right = FALSE, accumulate = FALSE)
{
mis <- missing(init)
len <- length(x)
if (len == 0L)
return(if (mis) NULL else init)
f <- match.fun(f)
if (!is.vector(x) || is.object(x))
x <- as.list(x)
ind <- seq_len(len)
if (mis) {
if (right) {
init <- x[[len]]
ind <- ind[-len]
}
else {
init <- x[[1L]]
ind <- ind[-1L]
}
}
if (!accumulate) {
if (right) {
for (i in rev(ind)) init <- f(x[[i]], init)
}
else {
for (i in ind) init <- f(init, x[[i]])
}
init
}
else {
len <- length(ind) + 1L
out <- vector("list", len)
if (mis) {
if (right) {
out[[len]] <- init
for (i in rev(ind)) {
init <- f(x[[i]], init)
out[[i]] <- init
}
}
else {
out[[1L]] <- init
for (i in ind) {
init <- f(init, x[[i]])
out[[i]] <- init
}
}
}
else {
if (right) {
out[[len]] <- init
for (i in rev(ind)) {
init <- f(x[[i]], init)
out[[i]] <- init
}
}
else {
for (i in ind) {
out[[i]] <- init
init <- f(init, x[[i]])
}
out[[len]] <- init
}
}
if (all(vapply(out, length, 1) == 1L))
out <- unlist(out, recursive = FALSE)
out
}
}
## @type list : character
remove <- function (..., list = character(), pos = -1, envir = as.environment(pos),
inherits = FALSE)
{
dots <- match.call(expand.dots = FALSE)$...
if (length(dots) && !all(sapply(dots, function(x) is.symbol(x) ||
is.character(x))))
stop("... must contain names or character strings")
names <- sapply(dots, as.character)
if (length(names) == 0L)
names <- character()
list <- .Primitive("c")(list, names)
.Internal(remove(list, envir, inherits))
}
## @type x : numeric
rowsum <- function (x, group, reorder = TRUE, ...)
UseMethod("rowsum")
## @return integer
sample <- function (x, size, replace = FALSE, prob = NULL)
{
if (length(x) == 1L && is.numeric(x) && x >= 1) {
if (missing(size))
size <- x
sample.int(x, size, replace, prob)
}
else {
if (missing(size))
size <- length(x)
x[sample.int(length(x), size, replace, prob)]
}
}
sapply <- function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
{
FUN <- match.fun(FUN)
answer <- lapply(X = X, FUN = FUN, ...)
if (USE.NAMES && is.character(X) && is.null(names(answer)))
names(answer) <- X
if (!identical(simplify, FALSE) && length(answer))
simplify2array(answer, higher = (simplify == "array"))
else answer
}
search <- function ()
.Internal(search())
signif <- function (x, digits = 6) .Primitive("signif")
## @type length : integer
single <- function (length = 0L)
structure(vector("double", length), Csingle = TRUE)
source <- function (file, local = FALSE, echo = verbose, print.eval = echo,
verbose = getOption("verbose"), prompt.echo = getOption("prompt"),
max.deparse.length = 150, chdir = FALSE, encoding = getOption("encoding"),
continue.echo = getOption("continue"), skip.echo = 0, keep.source = getOption("keep.source"))
{
envir <- if (isTRUE(local)) {
parent.frame()
}
else if (identical(local, FALSE)) {
.GlobalEnv
}
else if (is.environment(local)) {
local
}
else stop("'local' must be TRUE, FALSE or an environment")
have_encoding <- !missing(encoding) && encoding != "unknown"
if (!missing(echo)) {
if (!is.logical(echo))
stop("'echo' must be logical")
if (!echo && verbose) {
warning("'verbose' is TRUE, 'echo' not; ... coercing 'echo <- TRUE'")
echo <- TRUE
}
}
if (verbose) {
cat("'envir' chosen:")
print(envir)
}
ofile <- file
from_file <- FALSE
srcfile <- NULL
if (is.character(file)) {
if (identical(encoding, "unknown")) {
enc <- utils::localeToCharset()
encoding <- enc[length(enc)]
}
else enc <- encoding
if (length(enc) > 1L) {
encoding <- NA
owarn <- options("warn")
options(warn = 2)
for (e in enc) {
if (is.na(e))
next
zz <- file(file, encoding = e)
res <- tryCatch(readLines(zz, warn = FALSE),
error = identity)
close(zz)
if (!inherits(res, "error")) {
encoding <- e
break
}
}
options(owarn)
}
if (is.na(encoding))
stop("unable to find a plausible encoding")
if (verbose)
cat(gettextf("encoding = \"%s\" chosen", encoding),
"\n", sep = "")
if (file == "") {
file <- stdin()
srcfile <- "<stdin>"
}
else {
filename <- file
file <- file(filename, "r", encoding = encoding)
on.exit(close(file))
if (isTRUE(keep.source)) {
lines <- readLines(file, warn = FALSE)
on.exit()
close(file)
srcfile <- srcfilecopy(filename, lines, file.info(filename)[1,
"mtime"], isFile = TRUE)
}
else {
from_file <- TRUE
srcfile <- filename
}
loc <- utils::localeToCharset()[1L]
encoding <- if (have_encoding)
switch(loc, `UTF-8` = "UTF-8", `ISO8859-1` = "latin1",
"unknown")
else "unknown"
}
}
else {
lines <- readLines(file, warn = FALSE)
if (isTRUE(keep.source))
srcfile <- srcfilecopy(deparse(substitute(file)),
lines)
else srcfile <- deparse(substitute(file))
}
exprs <- if (!from_file) {
if (length(lines))
.Internal(parse(stdin(), n = -1, lines, "?", srcfile,
encoding))
else expression()
}
else .Internal(parse(file, n = -1, NULL, "?", srcfile, encoding))
on.exit()
if (from_file)
close(file)
Ne <- length(exprs)
if (verbose)
cat("--> parsed", Ne, "expressions; now eval(.)ing them:\n")
if (chdir) {
if (is.character(ofile)) {
isURL <- length(grep("^(ftp|http|file)://", ofile)) >
0L
if (isURL)
warning("'chdir = TRUE' makes no sense for a URL")
if (!isURL && (path <- dirname(ofile)) != ".") {
owd <- getwd()
if (is.null(owd))
stop("cannot 'chdir' as current directory is unknown")
on.exit(setwd(owd), add = TRUE)
setwd(path)
}
}
else {
warning("'chdir = TRUE' makes no sense for a connection")
}
}
if (echo) {
sd <- "\""
nos <- "[^\"]*"
oddsd <- paste0("^", nos, sd, "(", nos, sd, nos, sd,
")*", nos, "$")
trySrcLines <- function(srcfile, showfrom, showto) {
lines <- tryCatch(suppressWarnings(getSrcLines(srcfile,
showfrom, showto)), error = function(e) e)
if (inherits(lines, "error"))
character()
else lines
}
}
yy <- NULL
lastshown <- 0
srcrefs <- attr(exprs, "srcref")
for (i in seq_len(Ne + echo)) {
tail <- i > Ne
if (!tail) {
if (verbose)
cat("\n>>>> eval(expression_nr.", i, ")\n\t\t =================\n")
ei <- exprs[i]
}
if (echo) {
nd <- 0
srcref <- if (tail)
attr(exprs, "wholeSrcref")
else if (i <= length(srcrefs))
srcrefs[[i]]
if (!is.null(srcref)) {
if (i == 1)
lastshown <- min(skip.echo, srcref[3L] - 1)
if (lastshown < srcref[3L]) {
srcfile <- attr(srcref, "srcfile")
dep <- trySrcLines(srcfile, lastshown + 1,
srcref[3L])
if (length(dep)) {
leading <- if (tail)
length(dep)
else srcref[1L] - lastshown
lastshown <- srcref[3L]
while (length(dep) && length(grep("^[[:blank:]]*$",
dep[1L]))) {
dep <- dep[-1L]
leading <- leading - 1L
}
dep <- paste0(rep.int(c(prompt.echo, continue.echo),
c(leading, length(dep) - leading)), dep,
collapse = "\n")
nd <- nchar(dep, "c")
}
else srcref <- NULL
}
}
if (is.null(srcref)) {
if (!tail) {
dep <- substr(paste(deparse(ei, control = "showAttributes"),
collapse = "\n"), 12L, 1000000L)
dep <- paste0(prompt.echo, gsub("\n", paste0("\n",
continue.echo), dep))
nd <- nchar(dep, "c") - 1L
}
}
if (nd) {
do.trunc <- nd > max.deparse.length
dep <- substr(dep, 1L, if (do.trunc)
max.deparse.length
else nd)
cat("\n", dep, if (do.trunc)
paste(if (length(grep(sd, dep)) && length(grep(oddsd,
dep)))
" ...\" ..."
else " ....", "[TRUNCATED] "), "\n", sep = "")
}
}
if (!tail) {
yy <- withVisible(eval(ei, envir))
i.symbol <- mode(ei[[1L]]) == "name"
if (!i.symbol) {
curr.fun <- ei[[1L]][[1L]]
if (verbose) {
cat("curr.fun:")
utils::str(curr.fun)
}
}
if (verbose >= 2) {
cat(".... mode(ei[[1L]])=", mode(ei[[1L]]), "; paste(curr.fun)=")
utils::str(paste(curr.fun))
}
if (print.eval && yy$visible) {
if (isS4(yy$value))
methods::show(yy$value)
else print(yy$value)
}
if (verbose)
cat(" .. after ", sQuote(deparse(ei, control = c("showAttributes",
"useSource"))), "\n", sep = "")
}
}
invisible(yy)
}
## @type x : character
sQuote <- function (x)
{
if (!length(x))
return(character())
before <- after <- "'"
q <- getOption("useFancyQuotes")
if (!is.null(q)) {
if (identical(q, TRUE)) {
li <- l10n_info()
if (li$"UTF-8")
q <- "UTF-8"
if (!is.null(li$codepage) && li$codepage > 0L) {
if (li$codepage >= 1250L && li$codepage <= 1258L ||
li$codepage == 874L) {
before <- "\x91"
after <- "\x92"
}
else {
z <- iconv(c("‘", "’"), "UTF-8", "")
before <- z[1L]
after <- z[2L]
}
}
}
if (identical(q, "TeX")) {
before <- "`"
after <- "'"
}
if (identical(q, "UTF-8")) {
before <- "‘"
after <- "’"
}
if (is.character(q) && length(q) >= 4L) {
before <- q[1L]
after <- q[2L]
}
Encoding(before) <- Encoding(after) <- "unknown"
}
paste0(before, x, after)
}
srcref <- function (srcfile, lloc)
{
stopifnot(inherits(srcfile, "srcfile"), length(lloc) %in%
c(4L, 6L, 8L))
if (length(lloc) == 4)
lloc <- c(lloc, lloc[c(2, 4)])
if (length(lloc) == 6)
lloc <- c(lloc, lloc[c(1, 3)])
structure(as.integer(lloc), srcfile = srcfile, class = "srcref")
}
stderr <- function ()
.Internal(stderr())
stdout <- function ()
.Internal(stdout())
## @type base : integer
## @type x : character
## @return integer
strtoi <- function (x, base = 0L)
.Internal(strtoi(as.character(x), as.integer(base)))
subset <- function (x, ...)
UseMethod("subset")
## @type stop : integer
## @type start : integer
## @type x : character
## @return character
substr <- function (x, start, stop)
{
if (!is.character(x))
x <- as.character(x)
.Internal(substr(x, as.integer(start), as.integer(stop)))
}
switch <- function (EXPR, ...) .Primitive("switch")
## @type intern : logical|character
## @type ignore.stderr : logical
## @type wait : logical
## @type input : character
## @type command : character
## @type ignore.stdout : logical
system <- function (command, intern = FALSE, ignore.stdout = FALSE, ignore.stderr = FALSE,
wait = TRUE, input = NULL, show.output.on.console = TRUE,
minimized = FALSE, invisible = TRUE)
{
if (!missing(show.output.on.console) || !missing(minimized) ||
!missing(invisible))
message("arguments 'show.output.on.console', 'minimized' and 'invisible' are for Windows only")
if (!is.logical(intern) || is.na(intern))
stop("'intern' must be TRUE or FALSE")
if (!is.logical(ignore.stdout) || is.na(ignore.stdout))
stop("'ignore.stdout' must be TRUE or FALSE")
if (!is.logical(ignore.stderr) || is.na(ignore.stderr))
stop("'ignore.stderr' must be TRUE or FALSE")
if (!is.logical(wait) || is.na(wait))
stop("'wait' must be TRUE or FALSE")
if (ignore.stdout)
command <- paste(command, ">/dev/null")
if (ignore.stderr)
command <- paste(command, "2>/dev/null")
if (!is.null(input)) {
if (!is.character(input))
stop("'input' must be a character vector or 'NULL'")
f <- tempfile()
on.exit(unlink(f))
writeLines(input, f)
command <- paste(command, "<", shQuote(f))
}
if (!wait && !intern)
command <- paste(command, "&")
.Internal(system(command, intern))
}
tapply <- function (X, INDEX, FUN = NULL, ..., simplify = TRUE)
{
FUN <- if (!is.null(FUN))
match.fun(FUN)
if (!is.list(INDEX))
INDEX <- list(INDEX)
nI <- length(INDEX)
if (!nI)
stop("'INDEX' is of length zero")
namelist <- vector("list", nI)
names(namelist) <- names(INDEX)
extent <- integer(nI)
nx <- length(X)
one <- 1L
group <- rep.int(one, nx)
ngroup <- one
for (i in seq_along(INDEX)) {
index <- as.factor(INDEX[[i]])
if (length(index) != nx)
stop("arguments must have same length")
namelist[[i]] <- levels(index)
extent[i] <- nlevels(index)
group <- group + ngroup * (as.integer(index) - one)
ngroup <- ngroup * nlevels(index)
}
if (is.null(FUN))
return(group)
ans <- lapply(X = split(X, group), FUN = FUN, ...)
index <- as.integer(names(ans))
if (simplify && all(unlist(lapply(ans, length)) == 1L)) {
ansmat <- array(dim = extent, dimnames = namelist)
ans <- unlist(ans, recursive = FALSE)
}
else {
ansmat <- array(vector("list", prod(extent)), dim = extent,
dimnames = namelist)
}
if (length(index)) {
names(ans) <- NULL
ansmat[index] <- ans
}
ansmat
}
topenv <- function (envir = parent.frame(), matchThisEnv = getOption("topLevelEnvironment"))
{
while (!identical(envir, emptyenv())) {
nm <- attributes(envir)[["names", exact = TRUE]]
if ((is.character(nm) && length(grep("^package:", nm))) ||
identical(envir, matchThisEnv) || identical(envir,
.GlobalEnv) || identical(envir, baseenv()) || .Internal(isNamespaceEnv(envir)) ||
exists(".packageName", envir = envir, inherits = FALSE))
return(envir)
else envir <- parent.env(envir)
}
return(.GlobalEnv)
}
typeof <- function (x)
.Internal(typeof(x))
unique <- function (x, incomparables = FALSE, ...)
UseMethod("unique")
## @type force : logical
## @type recursive : logical
## @type x : character
unlink <- function (x, recursive = FALSE, force = FALSE)
.Internal(unlink(as.character(x), recursive, force))
## @type recursive : logical
## @type use.names : logical
unlist <- function (x, recursive = TRUE, use.names = TRUE)
{
if (.Internal(islistfactor(x, recursive))) {
lv <- unique(.Internal(unlist(lapply(x, levels), recursive,
FALSE)))
nm <- if (use.names)
names(.Internal(unlist(x, recursive, use.names)))
res <- .Internal(unlist(lapply(x, as.character), recursive,
FALSE))
res <- match(res, lv)
structure(res, levels = lv, names = nm, class = "factor")
}
else .Internal(unlist(x, recursive, use.names))
}
## @type force : logical
unname <- function (obj, force = FALSE)
{
if (!is.null(names(obj)))
names(obj) <- NULL
if (!is.null(dimnames(obj)) && (force || !is.data.frame(obj)))
dimnames(obj) <- NULL
obj
}
vapply <- function (X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)
{
FUN <- match.fun(FUN)
if (!is.vector(X) || is.object(X))
X <- as.list(X)
.Internal(vapply(X, FUN, FUN.VALUE, USE.NAMES))
}
## @type length : integer
## @type mode : character
vector <- function (mode = "logical", length = 0L)
.Internal(vector(mode, length))
within <- function (data, expr, ...)
UseMethod("within")
## @type description : character
## @type encoding : character
## @type open : character
## @type compression : integer
xzfile <- function (description, open = "", encoding = getOption("encoding"),
compression = 6)
.Internal(xzfile(description, open, encoding, compression))
"%/%" <- function (e1, e2) .Primitive("%/%")
"[[.Date" <- function (x, ..., drop = TRUE)
{
cl <- oldClass(x)
class(x) <- NULL
val <- NextMethod("[[")
class(val) <- cl
val
}
as.call <- function (x) .Primitive("as.call")
as.Date <- function (x, ...)
UseMethod("as.Date")
as.list <- function (x, ...)
UseMethod("as.list")
as.name <- function (x)
.Internal(as.vector(x, "symbol"))
as.null <- function (x, ...)
UseMethod("as.null")
baseenv <- function () .Primitive("baseenv")
besselI <- function (x, nu, expon.scaled = FALSE)
{
.Internal(besselI(x, nu, 1 + as.logical(expon.scaled)))
}
besselJ <- function (x, nu)
.Internal(besselJ(x, nu))
besselK <- function (x, nu, expon.scaled = FALSE)
{
.Internal(besselK(x, nu, 1 + as.logical(expon.scaled)))
}
besselY <- function (x, nu)
.Internal(besselY(x, nu))
## @return integer
bitwAnd <- function (a, b)
.Internal(bitwiseAnd(a, b))
## @type a : numeric
bitwNot <- function (a)
.Internal(bitwiseNot(a))
## @return integer
bitwXor <- function (a, b)
.Internal(bitwiseXor(a, b))
## @type text : character
browser <- function (text = "", condition = NULL, expr = TRUE, skipCalls = 0L) .Primitive("browser")
## @type x : complex
ceiling <- function (x) .Primitive("ceiling")
## @type value : character
"class<-" <- function (x, value) .Primitive("class<-")
## @type dims : integer
## @type x : complex|logical
## @type na.rm : logical
colSums <- function (x, na.rm = FALSE, dims = 1L)
{
if (is.data.frame(x))
x <- as.matrix(x)
if (!is.array(x) || length(dn <- dim(x)) < 2L)
stop("'x' must be an array of at least two dimensions")
if (dims < 1L || dims > length(dn) - 1L)
stop("invalid 'dims'")
n <- prod(dn[1L:dims])
dn <- dn[-(1L:dims)]
z <- if (is.complex(x))
.Internal(colSums(Re(x), n, prod(dn), na.rm)) + (0+1i) *
.Internal(colSums(Im(x), n, prod(dn), na.rm))
else .Internal(colSums(x, n, prod(dn), na.rm))
if (length(dn) > 1L) {
dim(z) <- dn
dimnames(z) <- dimnames(x)[-(1L:dims)]
}
else names(z) <- dimnames(x)[[dims + 1]]
z
}
comment <- function (x)
.Internal(comment(x))
## @type imaginary : numeric
## @type length.out : numeric
## @type modulus : numeric
## @type argument : numeric
## @type real : numeric
complex <- function (length.out = 0L, real = numeric(), imaginary = numeric(),
modulus = 1, argument = 0)
{
if (missing(modulus) && missing(argument)) {
.Internal(complex(length.out, real, imaginary))
}
else {
n <- max(length.out, length(argument), length(modulus))
rep_len(modulus, n) * exp((0+1i) * rep_len(argument,
n))
}
}
## @type x : complex
## @return numeric
cumprod <- function (x) .Primitive("cumprod")
## @type width.cutoff : integer
## @type nlines : complex
## @type backtick : logical
## @type control : character
deparse <- function (expr, width.cutoff = 60L, backtick = mode(expr) %in%
c("call", "expression", "(", "function"), control = c("keepInteger",
"showAttributes", "keepNA"), nlines = -1L)
.Internal(deparse(expr, width.cutoff, backtick, .deparseOpts(control),
nlines))
## @type x : numeric
digamma <- function (x) .Primitive("digamma")
## @type path : character
## @return character
dirname <- function (path)
.Internal(dirname(path))
do.call <- function (what, args, quote = FALSE, envir = parent.frame())
{
if (!is.list(args))
stop("second argument must be a list")
if (quote)
args <- lapply(args, enquote)
.Internal(do.call(what, args, envir))
}
enquote <- function (cl)
as.call(list(as.name("quote"), cl))
formals <- function (fun = sys.function(sys.parent()))
{
if (is.character(fun))
fun <- get(fun, mode = "function", envir = parent.frame())
.Internal(formals(fun))
}
## @return character
formatC <- function (x, digits = NULL, width = NULL, format = NULL, flag = "",
mode = NULL, big.mark = "", big.interval = 3L, small.mark = "",
small.interval = 5L, decimal.mark = ".", preserve.width = "individual",
zero.print = NULL, drop0trailing = FALSE)
{
if (is.object(x)) {
x <- unclass(x)
warning("class of 'x' was discarded")
}
format.char <- function(x, width, flag) {
if (is.null(width))
width <- 0L
else if (width < 0L) {
flag <- "-"
width <- -width
}
format.default(x, width = width, justify = if (flag ==
"-")
"left"
else "right")
}
blank.chars <- function(no) vapply(no + 1L, function(n) paste(character(n),
collapse = " "), "")
if (!(n <- length(x)))
return("")
if (is.null(mode))
mode <- storage.mode(x)
else if (any(mode == c("double", "real", "integer"))) {
if (mode == "real")
mode <- "double"
storage.mode(x) <- mode
}
else if (mode != "character")
stop("'mode' must be \"double\" (\"real\"), \"integer\" or \"character\"")
if (mode == "character" || (!is.null(format) && format ==
"s")) {
if (mode != "character") {
warning("coercing argument to \"character\" for format=\"s\"")
x <- as.character(x)
}
return(format.char(x, width = width, flag = flag))
}
if (missing(format) || is.null(format))
format <- if (mode == "integer")
"d"
else "g"
else {
if (any(format == c("f", "e", "E", "g", "G", "fg"))) {
if (mode == "integer")
mode <- storage.mode(x) <- "double"
}
else if (format == "d") {
if (mode != "integer")
mode <- storage.mode(x) <- "integer"
}
else stop("'format' must be one of {\"f\",\"e\",\"E\",\"g\",\"G\", \"fg\", \"s\"}")
}
some.special <- !all(Ok <- is.finite(x))
if (some.special) {
rQ <- as.character(x[!Ok])
rQ[is.na(rQ)] <- "NA"
x[!Ok] <- as.vector(0, mode = mode)
}
if (is.null(width) && is.null(digits))
width <- 1L
if (is.null(digits))
digits <- if (mode == "integer")
2L
else 4L
else if (digits < 0L)
digits <- 6L
else {
maxDigits <- if (format != "f")
50L
else ceiling(-(.Machine$double.neg.ulp.digits + .Machine$double.min.exp)/log2(10))
if (digits > maxDigits) {
warning(gettextf("'digits' reduced to %d", maxDigits),
domain = NA)
digits <- maxDigits
}
}
if (is.null(width))
width <- digits + 1L
else if (width == 0L)
width <- digits
i.strlen <- pmax(abs(as.integer(width)), if (format == "fg" ||
format == "f") {
xEx <- as.integer(floor(log10(abs(x + ifelse(x == 0,
1, 0)))))
as.integer(x < 0 | flag != "") + digits + if (format ==
"f") {
2L + pmax(xEx, 0L)
}
else {
pmax(xEx, digits, digits + (-xEx) + 1L) + ifelse(flag !=
"", nchar(flag, "b"), 0L) + 1L
}
}
else rep.int(digits + 8L, n))
flag <- as.character(flag)
nf <- strsplit(flag, "")[[1L]]
if (!all(nf %in% c("0", "+", "-", " ", "#")))
stop("'flag' can contain only '0+- #'")
if (digits > 0 && any(nf == "#"))
digits <- -digits
attr(x, "Csingle") <- NULL
r <- .Internal(formatC(x, as.character(mode), width, digits,
as.character(format), as.character(flag), i.strlen))
if (some.special)
r[!Ok] <- format.char(rQ, width = width, flag = flag)
if (big.mark != "" || small.mark != "" || decimal.mark !=
"." || !is.null(zero.print) || drop0trailing)
r <- prettyNum(r, big.mark = big.mark, big.interval = big.interval,
small.mark = small.mark, small.interval = small.interval,
decimal.mark = decimal.mark, preserve.width = preserve.width,
zero.print = zero.print, drop0trailing = drop0trailing,
is.cmplx = FALSE)
if (!is.null(x.atr <- attributes(x)))
attributes(r) <- x.atr
r
}
## @type on : logical
gc.time <- function (on = TRUE) .Primitive("gc.time")
## @type hookName : character
getHook <- function (hookName)
{
if (exists(hookName, envir = .userHooksEnv, inherits = FALSE))
get(hookName, envir = .userHooksEnv, inherits = FALSE)
else list()
}
gettext <- function (..., domain = NULL)
{
args <- lapply(list(...), as.character)
.Internal(gettext(domain, unlist(args)))
}
## @type pattern : raw|character
## @type all : logical
## @type offset : integer
## @type invert : logical
## @type x : raw
## @type fixed : logical
## @type value : logical
grepRaw <- function (pattern, x, offset = 1L, ignore.case = FALSE, value = FALSE,
fixed = FALSE, all = FALSE, invert = FALSE)
{
if (!is.raw(pattern))
pattern <- charToRaw(as.character(pattern))
if (!is.raw(x))
x <- charToRaw(as.character(x))
.Internal(grepRaw(pattern, x, offset, ignore.case, fixed,
value, all, invert))
}
## @type length : integer
integer <- function (length = 0L)
.Internal(vector("integer", length))
is.call <- function (x) .Primitive("is.call")
is.list <- function (x) .Primitive("is.list")
"is.na<-" <- function (x, value)
UseMethod("is.na<-")
is.name <- function (x) .Primitive("is.symbol")
is.null <- function (x) .Primitive("is.null")
ISOdate <- function (year, month, day, hour = 12, min = 0, sec = 0, tz = "GMT")
ISOdatetime(year, month, day, hour, min, sec, tz)
## @type n : numeric
## @type k : integer
lchoose <- function (n, k)
.Internal(lchoose(n, k))
## @return logical
library <- function (package, help, pos = 2, lib.loc = NULL, character.only = FALSE,
logical.return = FALSE, warn.conflicts = TRUE, quietly = FALSE,
verbose = getOption("verbose"))
{
testRversion <- function(pkgInfo, pkgname, pkgpath) {
if (is.null(built <- pkgInfo$Built))
stop(gettextf("package %s has not been installed properly\n",
sQuote(pkgname)), call. = FALSE, domain = NA)
R_version_built_under <- as.numeric_version(built$R)
if (R_version_built_under < "3.0.0")
stop(gettextf("package %s was built before R 3.0.0: please re-install it",
sQuote(pkgname)), call. = FALSE, domain = NA)
current <- getRversion()
if (length(Rdeps <- pkgInfo$Rdepends2)) {
for (dep in Rdeps) if (length(dep) > 1L) {
target <- dep$version
res <- if (is.character(target)) {
do.call(dep$op, list(as.numeric(R.version[["svn rev"]]),
as.numeric(sub("^r", "", dep$version))))
}
else {
do.call(dep$op, list(current, as.numeric_version(target)))
}
if (!res)
stop(gettextf("This is R %s, package %s needs %s %s",
current, sQuote(pkgname), dep$op, target),
call. = FALSE, domain = NA)
}
}
if (R_version_built_under > current)
warning(gettextf("package %s was built under R version %s",
sQuote(pkgname), as.character(built$R)), call. = FALSE,
domain = NA)
platform <- built$Platform
r_arch <- .Platform$r_arch
if (.Platform$OS.type == "unix") {
if (!nzchar(r_arch) && length(grep("\\w", platform)) &&
!testPlatformEquivalence(platform, R.version$platform))
stop(gettextf("package %s was built for %s",
sQuote(pkgname), platform), call. = FALSE,
domain = NA)
}
else {
if (nzchar(platform) && !grepl("mingw", platform))
stop(gettextf("package %s was built for %s",
sQuote(pkgname), platform), call. = FALSE,
domain = NA)
}
if (nzchar(r_arch) && file.exists(file.path(pkgpath,
"libs")) && !file.exists(file.path(pkgpath, "libs",
r_arch)))
stop(gettextf("package %s is not installed for 'arch = %s'",
sQuote(pkgname), r_arch), call. = FALSE, domain = NA)
}
checkLicense <- function(pkg, pkgInfo, pkgPath) {
L <- tools:::analyze_license(pkgInfo$DESCRIPTION["License"])
if (!L$is_empty && !L$is_verified) {
site_file <- path.expand(file.path(R.home("etc"),
"licensed.site"))
if (file.exists(site_file) && pkg %in% readLines(site_file))
return()
personal_file <- path.expand("~/.R/licensed")
if (file.exists(personal_file)) {
agreed <- readLines(personal_file)
if (pkg %in% agreed)
return()
}
else agreed <- character()
if (!interactive())
stop(gettextf("package %s has a license that you need to accept in an interactive session",
sQuote(pkg)), domain = NA)
lfiles <- file.path(pkgpath, c("LICENSE", "LICENCE"))
lfiles <- lfiles[file.exists(lfiles)]
if (length(lfiles)) {
message(gettextf("package %s has a license that you need to accept after viewing",
sQuote(pkg)), domain = NA)
readline("press RETURN to view license")
encoding <- pkgInfo$DESCRIPTION["Encoding"]
if (is.na(encoding))
encoding <- ""
if (encoding == "latin1")
encoding <- "cp1252"
file.show(lfiles[1L], encoding = encoding)
}
else {
message(gettextf("package %s has a license that you need to accept:\naccording to the DESCRIPTION file it is",
sQuote(pkg)), domain = NA)
message(pkgInfo$DESCRIPTION["License"], domain = NA)
}
choice <- menu(c("accept", "decline"), title = paste("License for",
sQuote(pkg)))
if (choice != 1)
stop(gettextf("license for package %s not accepted",
sQuote(package)), domain = NA, call. = FALSE)
dir.create(dirname(personal_file), showWarnings = FALSE)
writeLines(c(agreed, pkg), personal_file)
}
}
checkNoGenerics <- function(env, pkg) {
nenv <- env
ns <- .getNamespace(as.name(pkg))
if (!is.null(ns))
nenv <- asNamespace(ns)
if (exists(".noGenerics", envir = nenv, inherits = FALSE))
TRUE
else {
length(objects(env, pattern = "^\\.__T", all.names = TRUE)) ==
0L
}
}
checkConflicts <- function(package, pkgname, pkgpath, nogenerics,
env) {
dont.mind <- c("last.dump", "last.warning", ".Last.value",
".Random.seed", ".Last.lib", ".onDetach", ".packageName",
".noGenerics", ".required", ".no_S3_generics", ".Depends",
".requireCachedGenerics")
sp <- search()
lib.pos <- match(pkgname, sp)
ob <- objects(lib.pos, all.names = TRUE)
if (!nogenerics) {
these <- ob[substr(ob, 1L, 6L) == ".__T__"]
gen <- gsub(".__T__(.*):([^:]+)", "\\1", these)
from <- gsub(".__T__(.*):([^:]+)", "\\2", these)
gen <- gen[from != package]
ob <- ob[!(ob %in% gen)]
}
fst <- TRUE
ipos <- seq_along(sp)[-c(lib.pos, match(c("Autoloads",
"CheckExEnv"), sp, 0L))]
for (i in ipos) {
obj.same <- match(objects(i, all.names = TRUE), ob,
nomatch = 0L)
if (any(obj.same > 0)) {
same <- ob[obj.same]
same <- same[!(same %in% dont.mind)]
Classobjs <- grep("^\\.__", same)
if (length(Classobjs))
same <- same[-Classobjs]
same.isFn <- function(where) vapply(same, exists,
NA, where = where, mode = "function", inherits = FALSE)
same <- same[same.isFn(i) == same.isFn(lib.pos)]
not.Ident <- function(ch, TRAFO = identity, ...) vapply(ch,
function(.) !identical(TRAFO(get(., i)), TRAFO(get(.,
lib.pos)), ...), NA)
if (length(same))
same <- same[not.Ident(same)]
if (length(same) && identical(sp[i], "package:base"))
same <- same[not.Ident(same, ignore.environment = TRUE)]
if (length(same)) {
if (fst) {
fst <- FALSE
packageStartupMessage(gettextf("\nAttaching package: %s\n",
sQuote(package)), domain = NA)
}
msg <- .maskedMsg(same, pkg = sQuote(sp[i]),
by = i < lib.pos)
packageStartupMessage(msg, domain = NA)
}
}
}
}
if (verbose && quietly)
message("'verbose' and 'quietly' are both true; being verbose then ..")
if (!missing(package)) {
if (is.null(lib.loc))
lib.loc <- .libPaths()
lib.loc <- lib.loc[file.info(lib.loc)$isdir %in% TRUE]
if (!character.only)
package <- as.character(substitute(package))
if (length(package) != 1L)
stop("'package' must be of length 1")
if (is.na(package) || (package == ""))
stop("invalid package name")
pkgname <- paste("package", package, sep = ":")
newpackage <- is.na(match(pkgname, search()))
if (newpackage) {
pkgpath <- find.package(package, lib.loc, quiet = TRUE,
verbose = verbose)
if (length(pkgpath) == 0L) {
txt <- if (length(lib.loc))
gettextf("there is no package called %s", sQuote(package))
else gettext("no library trees found in 'lib.loc'")
if (logical.return) {
warning(txt, domain = NA)
return(FALSE)
}
else stop(txt, domain = NA)
}
which.lib.loc <- normalizePath(dirname(pkgpath),
"/", TRUE)
pfile <- system.file("Meta", "package.rds", package = package,
lib.loc = which.lib.loc)
if (!nzchar(pfile))
stop(gettextf("%s is not a valid installed package",
sQuote(package)), domain = NA)
pkgInfo <- readRDS(pfile)
testRversion(pkgInfo, package, pkgpath)
if (!package %in% c("datasets", "grDevices", "graphics",
"methods", "splines", "stats", "stats4", "tcltk",
"tools", "utils") && isTRUE(getOption("checkPackageLicense",
FALSE)))
checkLicense(package, pkgInfo, pkgpath)
if (is.character(pos)) {
npos <- match(pos, search())
if (is.na(npos)) {
warning(gettextf("%s not found on search path, using pos = 2",
sQuote(pos)), domain = NA)
pos <- 2
}
else pos <- npos
}
.getRequiredPackages2(pkgInfo, quietly = quietly)
deps <- unique(names(pkgInfo$Depends))
if (packageHasNamespace(package, which.lib.loc)) {
tt <- try({
ns <- loadNamespace(package, c(which.lib.loc,
lib.loc))
env <- attachNamespace(ns, pos = pos, deps)
})
if (inherits(tt, "try-error"))
if (logical.return)
return(FALSE)
else stop(gettextf("package or namespace load failed for %s",
sQuote(package)), call. = FALSE, domain = NA)
else {
on.exit(detach(pos = pos))
nogenerics <- !.isMethodsDispatchOn() || checkNoGenerics(env,
package)
if (warn.conflicts && !exists(".conflicts.OK",
envir = env, inherits = FALSE))
checkConflicts(package, pkgname, pkgpath,
nogenerics, ns)
on.exit()
if (logical.return)
return(TRUE)
else return(invisible(.packages()))
}
}
else stop(gettextf("package %s does not have a namespace and should be re-installed",
sQuote(package)), domain = NA)
}
if (verbose && !newpackage)
warning(gettextf("package %s already present in search()",
sQuote(package)), domain = NA)
}
else if (!missing(help)) {
if (!character.only)
help <- as.character(substitute(help))
pkgName <- help[1L]
pkgPath <- find.package(pkgName, lib.loc, verbose = verbose)
docFiles <- c(file.path(pkgPath, "Meta", "package.rds"),
file.path(pkgPath, "INDEX"))
if (file.exists(vignetteIndexRDS <- file.path(pkgPath,
"Meta", "vignette.rds")))
docFiles <- c(docFiles, vignetteIndexRDS)
pkgInfo <- vector("list", 3L)
readDocFile <- function(f) {
if (basename(f) %in% "package.rds") {
txt <- readRDS(f)$DESCRIPTION
if ("Encoding" %in% names(txt)) {
to <- if (Sys.getlocale("LC_CTYPE") == "C")
"ASCII//TRANSLIT"
else ""
tmp <- try(iconv(txt, from = txt["Encoding"],
to = to))
if (!inherits(tmp, "try-error"))
txt <- tmp
else warning("'DESCRIPTION' has an 'Encoding' field and re-encoding is not possible",
call. = FALSE)
}
nm <- paste0(names(txt), ":")
formatDL(nm, txt, indent = max(nchar(nm, "w")) +
3)
}
else if (basename(f) %in% "vignette.rds") {
txt <- readRDS(f)
if (is.data.frame(txt) && nrow(txt))
cbind(basename(gsub("\\.[[:alpha:]]+$", "",
txt$File)), paste(txt$Title, paste0(rep.int("(source",
NROW(txt)), ifelse(txt$PDF != "", ", pdf",
""), ")")))
else NULL
}
else readLines(f)
}
for (i in which(file.exists(docFiles))) pkgInfo[[i]] <- readDocFile(docFiles[i])
y <- list(name = pkgName, path = pkgPath, info = pkgInfo)
class(y) <- "packageInfo"
return(y)
}
else {
if (is.null(lib.loc))
lib.loc <- .libPaths()
db <- matrix(character(), nrow = 0L, ncol = 3L)
nopkgs <- character()
for (lib in lib.loc) {
a <- .packages(all.available = TRUE, lib.loc = lib)
for (i in sort(a)) {
file <- system.file("Meta", "package.rds", package = i,
lib.loc = lib)
title <- if (file != "") {
txt <- readRDS(file)
if (is.list(txt))
txt <- txt$DESCRIPTION
if ("Encoding" %in% names(txt)) {
to <- if (Sys.getlocale("LC_CTYPE") == "C")
"ASCII//TRANSLIT"
else ""
tmp <- try(iconv(txt, txt["Encoding"], to,
"?"))
if (!inherits(tmp, "try-error"))
txt <- tmp
else warning("'DESCRIPTION' has an 'Encoding' field and re-encoding is not possible",
call. = FALSE)
}
txt["Title"]
}
else NA
if (is.na(title))
title <- " ** No title available ** "
db <- rbind(db, cbind(i, lib, title))
}
if (length(a) == 0L)
nopkgs <- c(nopkgs, lib)
}
dimnames(db) <- list(NULL, c("Package", "LibPath", "Title"))
if (length(nopkgs) && !missing(lib.loc)) {
pkglist <- paste(sQuote(nopkgs), collapse = ", ")
msg <- sprintf(ngettext(length(nopkgs), "library %s contains no packages",
"libraries %s contain no packages"), pkglist)
warning(msg, domain = NA)
}
y <- list(header = NULL, results = db, footer = NULL)
class(y) <- "libraryIQR"
return(y)
}
if (logical.return)
TRUE
else invisible(.packages())
}
licence <- function ()
{
cat("\nThis software is distributed under the terms of the GNU General\n")
cat("Public License, either Version 2, June 1991 or Version 3, June 2007.\n")
cat("The terms of version 2 of the license are in a file called COPYING\nwhich you should have received with\n")
cat("this software and which can be displayed by RShowDoc(\"COPYING\").\n")
cat("Version 3 of the license can be displayed by RShowDoc(\"GPL-3\").\n")
cat("\n")
cat("Copies of both versions 2 and 3 of the license can be found\n")
cat("at http://www.R-project.org/Licenses/.\n")
cat("\n")
cat("A small number of files (the API header files listed in\n")
cat("R_DOC_DIR/COPYRIGHTS) are distributed under the\n")
cat("LESSER GNU GENERAL PUBLIC LICENSE, version 2.1 or later.\n")
cat("This can be displayed by RShowDoc(\"LGPL-2.1\"),\n")
cat("or obtained at the URI given.\n")
cat("Version 3 of the license can be displayed by RShowDoc(\"LGPL-3\").\n")
cat("\n")
cat("'Share and Enjoy.'\n\n")
}
license <- function ()
{
cat("\nThis software is distributed under the terms of the GNU General\n")
cat("Public License, either Version 2, June 1991 or Version 3, June 2007.\n")
cat("The terms of version 2 of the license are in a file called COPYING\nwhich you should have received with\n")
cat("this software and which can be displayed by RShowDoc(\"COPYING\").\n")
cat("Version 3 of the license can be displayed by RShowDoc(\"GPL-3\").\n")
cat("\n")
cat("Copies of both versions 2 and 3 of the license can be found\n")
cat("at http://www.R-project.org/Licenses/.\n")
cat("\n")
cat("A small number of files (the API header files listed in\n")
cat("R_DOC_DIR/COPYRIGHTS) are distributed under the\n")
cat("LESSER GNU GENERAL PUBLIC LICENSE, version 2.1 or later.\n")
cat("This can be displayed by RShowDoc(\"LGPL-2.1\"),\n")
cat("or obtained at the URI given.\n")
cat("Version 3 of the license can be displayed by RShowDoc(\"LGPL-3\").\n")
cat("\n")
cat("'Share and Enjoy.'\n\n")
}
## @type length : integer
logical <- function (length = 0L)
.Internal(vector("logical", length))
## @type ties.method : character
max.col <- function (m, ties.method = c("random", "first", "last"))
{
ties.method <- match.arg(ties.method)
tieM <- which(ties.method == eval(formals()[["ties.method"]]))
.Internal(max.col(as.matrix(m), tieM))
}
## @type appendLF : logical|character
message <- function (..., domain = NULL, appendLF = TRUE)
{
args <- list(...)
cond <- if (length(args) == 1L && inherits(args[[1L]], "condition")) {
if (nargs() > 1L)
warning("additional arguments ignored in message()")
args[[1L]]
}
else {
msg <- .makeMessage(..., domain = domain, appendLF = appendLF)
call <- sys.call()
simpleMessage(msg, call)
}
defaultHandler <- function(c) {
cat(conditionMessage(c), file = stderr(), sep = "")
}
withRestarts({
signalCondition(cond)
defaultHandler(cond)
}, muffleMessage = function() NULL)
invisible()
}
missing <- function (x) .Primitive("missing")
## @type value : character
"names<-" <- function (x, value) .Primitive("names<-")
new.env <- function (hash = TRUE, parent = parent.frame(), size = 29L)
.Internal(new.env(hash, parent, size))
nlevels <- function (x)
length(levels(x))
## @type obj : character
noquote <- function (obj)
{
if (!inherits(obj, "noquote"))
class(obj) <- c(attr(obj, "class"), "noquote")
obj
}
## @type length : integer
numeric <- function (length = 0L)
.Internal(vector("double", length))
objects <- function (name, pos = -1L, envir = as.environment(pos), all.names = FALSE,
pattern)
{
if (!missing(name)) {
pos <- tryCatch(name, error = function(e) e)
if (inherits(pos, "error")) {
name <- substitute(name)
if (!is.character(name))
name <- deparse(name)
warning(gettextf("%s converted to character string",
sQuote(name)), domain = NA)
pos <- name
}
}
all.names <- .Internal(ls(envir, all.names))
if (!missing(pattern)) {
if ((ll <- length(grep("[", pattern, fixed = TRUE))) &&
ll != length(grep("]", pattern, fixed = TRUE))) {
if (pattern == "[") {
pattern <- "\\["
warning("replaced regular expression pattern '[' by '\\\\['")
}
else if (length(grep("[^\\\\]\\[<-", pattern))) {
pattern <- sub("\\[<-", "\\\\\\[<-", pattern)
warning("replaced '[<-' by '\\\\[<-' in regular expression pattern")
}
}
grep(pattern, all.names, value = TRUE)
}
else all.names
}
on.exit <- function (expr = NULL, add = FALSE) .Primitive("on.exit")
options <- function (...)
.Internal(options(...))
ordered <- function (x, ...)
factor(x, ..., ordered = TRUE)
qr.coef <- function (qr, y)
{
if (!is.qr(qr))
stop("first argument must be a QR decomposition")
n <- as.integer(nrow(qr$qr))
if (is.na(n))
stop("invalid nrow(qr$qr)")
p <- as.integer(ncol(qr$qr))
if (is.na(p))
stop("invalid ncol(qr$qr)")
k <- as.integer(qr$rank)
if (is.na(k))
stop("invalid ncol(qr$rank)")
im <- is.matrix(y)
if (!im)
y <- as.matrix(y)
ny <- as.integer(ncol(y))
if (is.na(ny))
stop("invalid ncol(y)")
if (p == 0L)
return(if (im) matrix(0, p, ny) else numeric())
ix <- if (p > n)
c(seq_len(n), rep(NA, p - n))
else seq_len(p)
if (is.complex(qr$qr)) {
coef <- matrix(NA_complex_, nrow = p, ncol = ny)
coef[qr$pivot, ] <- .Internal(qr_coef_cmplx(qr, y))[ix,
]
return(if (im) coef else c(coef))
}
if (isTRUE(attr(qr, "useLAPACK"))) {
coef <- matrix(NA_real_, nrow = p, ncol = ny)
coef[qr$pivot, ] <- .Internal(qr_coef_real(qr, y))[ix,
]
return(if (im) coef else c(coef))
}
if (k == 0L)
return(if (im) matrix(NA, p, ny) else rep.int(NA, p))
storage.mode(y) <- "double"
if (nrow(y) != n)
stop("'qr' and 'y' must have the same number of rows")
z <- .Fortran(.F_dqrcf, as.double(qr$qr), n, k, as.double(qr$qraux),
y, ny, coef = matrix(0, nrow = k, ncol = ny), info = integer(1L),
NAOK = TRUE)[c("coef", "info")]
if (z$info)
stop("exact singularity in 'qr.coef'")
if (k < p) {
coef <- matrix(NA_real_, nrow = p, ncol = ny)
coef[qr$pivot[seq_len(k)], ] <- z$coef
}
else coef <- z$coef
if (!is.null(nam <- colnames(qr$qr)))
if (k < p)
rownames(coef)[qr$pivot] <- nam
else rownames(coef) <- nam
if (im && !is.null(nam <- colnames(y)))
colnames(coef) <- nam
if (im)
coef
else drop(coef)
}
readBin <- function (con, what, n = 1L, size = NA_integer_, signed = TRUE,
endian = .Platform$endian)
{
if (is.character(con)) {
con <- file(con, "rb")
on.exit(close(con))
}
swap <- endian != .Platform$endian
if (!is.character(what) || is.na(what) || length(what) !=
1L || !any(what == c("numeric", "double", "integer",
"int", "logical", "complex", "character", "raw")))
what <- typeof(what)
.Internal(readBin(con, what, n, size, signed, swap))
}
readRDS <- function (file, refhook = NULL)
{
if (is.character(file)) {
con <- gzfile(file, "rb")
on.exit(close(con))
}
else if (inherits(file, "connection"))
con <- file
else stop("bad 'file' argument")
.Internal(unserializeFromConn(con, refhook))
}
regexec <- function (pattern, text, ignore.case = FALSE, fixed = FALSE,
useBytes = FALSE)
.Internal(regexec(pattern, text, ignore.case, fixed, useBytes))
## @return logical|integer|character
regexpr <- function (pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE,
useBytes = FALSE)
{
if (!is.character(text))
text <- as.character(text)
.Internal(regexpr(as.character(pattern), text, ignore.case,
perl, fixed, useBytes))
}
rep.int <- function (x, times)
.Internal(rep.int(x, times))
## @type length.out : integer
rep_len <- function (x, length.out)
.Internal(rep_len(x, length.out))
## @optional list
replace <- function (x, list, values)
{
x[list] <- values
x
}
require <- function (package, lib.loc = NULL, quietly = FALSE, warn.conflicts = TRUE,
character.only = FALSE)
{
if (!character.only)
package <- as.character(substitute(package))
loaded <- paste("package", package, sep = ":") %in% search()
if (!loaded) {
if (!quietly)
packageStartupMessage(gettextf("Loading required package: %s",
package), domain = NA)
value <- tryCatch(library(package, lib.loc = lib.loc,
character.only = TRUE, logical.return = TRUE, warn.conflicts = warn.conflicts,
quietly = quietly), error = function(e) e)
if (inherits(value, "error")) {
if (!quietly) {
msg <- conditionMessage(value)
cat("Failed with error: ", sQuote(msg), "\n",
file = stderr(), sep = "")
.Internal(printDeferredWarnings())
}
return(invisible(FALSE))
}
if (!value)
return(invisible(FALSE))
}
else value <- TRUE
invisible(value)
}
## @type normal.kind : character
## @type kind : character
## @return complex|character
RNGkind <- function (kind = NULL, normal.kind = NULL)
{
kinds <- c("Wichmann-Hill", "Marsaglia-Multicarry", "Super-Duper",
"Mersenne-Twister", "Knuth-TAOCP", "user-supplied", "Knuth-TAOCP-2002",
"L'Ecuyer-CMRG", "default")
n.kinds <- c("Buggy Kinderman-Ramage", "Ahrens-Dieter", "Box-Muller",
"user-supplied", "Inversion", "Kinderman-Ramage", "default")
do.set <- length(kind) > 0L
if (do.set) {
if (!is.character(kind) || length(kind) > 1L)
stop("'kind' must be a character string of length 1 (RNG to be used).")
if (is.na(i.knd <- pmatch(kind, kinds) - 1L))
stop(gettextf("'%s' is not a valid abbreviation of an RNG",
kind), domain = NA)
if (i.knd == length(kinds) - 1L)
i.knd <- -1L
}
else i.knd <- NULL
if (!is.null(normal.kind)) {
if (!is.character(normal.kind) || length(normal.kind) !=
1L)
stop("'normal.kind' must be a character string of length 1")
normal.kind <- pmatch(normal.kind, n.kinds) - 1L
if (is.na(normal.kind))
stop(gettextf("'%s' is not a valid choice", normal.kind),
domain = NA)
if (normal.kind == 0L)
warning("buggy version of Kinderman-Ramage generator used",
domain = NA)
if (normal.kind == length(n.kinds) - 1L)
normal.kind <- -1L
}
r <- 1L + .Internal(RNGkind(i.knd, normal.kind))
r <- c(kinds[r[1L]], n.kinds[r[2L]])
if (do.set || !is.null(normal.kind))
invisible(r)
else r
}
## @type na.rm : logical
## @type x : complex|logical
## @type dims : integer
rowSums <- function (x, na.rm = FALSE, dims = 1L)
{
if (is.data.frame(x))
x <- as.matrix(x)
if (!is.array(x) || length(dn <- dim(x)) < 2L)
stop("'x' must be an array of at least two dimensions")
if (dims < 1L || dims > length(dn) - 1L)
stop("invalid 'dims'")
p <- prod(dn[-(1L:dims)])
dn <- dn[1L:dims]
z <- if (is.complex(x))
.Internal(rowSums(Re(x), prod(dn), p, na.rm)) + (0+1i) *
.Internal(rowSums(Im(x), prod(dn), p, na.rm))
else .Internal(rowSums(x, prod(dn), p, na.rm))
if (length(dn) > 1L) {
dim(z) <- dn
dimnames(z) <- dimnames(x)[1L:dims]
}
else names(z) <- dimnames(x)[[1L]]
z
}
## @type file : character
## @type ascii : logical
## @type compress : logical
saveRDS <- function (object, file = "", ascii = FALSE, version = NULL, compress = TRUE,
refhook = NULL)
{
if (is.character(file)) {
if (file == "")
stop("'file' must be non-empty string")
mode <- if (ascii)
"w"
else "wb"
con <- if (identical(compress, "bzip2"))
bzfile(file, mode)
else if (identical(compress, "xz"))
xzfile(file, mode)
else if (compress)
gzfile(file, mode)
else file(file, mode)
on.exit(close(con))
}
else if (inherits(file, "connection")) {
if (!missing(compress))
warning("'compress' is ignored unless 'file' is a file name")
con <- file
}
else stop("bad 'file' argument")
.Internal(serializeToConn(object, con, ascii, version, refhook))
}
seq.int <- function (from, to, by, length.out, along.with, ...) .Primitive("seq.int")
## @type length.out : complex
seq_len <- function (length.out) .Primitive("seq_len")
setdiff <- function (x, y)
{
x <- as.vector(x)
y <- as.vector(y)
unique(if (length(x) || length(y))
x[match(x, y, 0L) == 0L]
else x)
}
## @type hookName : character
setHook <- function (hookName, value, action = c("append", "prepend", "replace"))
{
action <- match.arg(action)
old <- getHook(hookName)
new <- switch(action, append = c(old, value), prepend = c(value,
old), replace = if (is.null(value) || is.list(value)) value else list(value))
if (length(new))
assign(hookName, new, envir = .userHooksEnv, inherits = FALSE)
else if (exists(hookName, envir = .userHooksEnv, inherits = FALSE))
remove(list = hookName, envir = .userHooksEnv, inherits = FALSE)
invisible()
}
## @type string : character
## @type type : character
## @return character
shQuote <- function (string, type = c("sh", "csh", "cmd"))
{
cshquote <- function(x) {
xx <- strsplit(x, "'", fixed = TRUE)[[1L]]
paste(paste0("'", xx, "'"), collapse = "\"'\"")
}
if (missing(type) && .Platform$OS.type == "windows")
type <- "cmd"
type <- match.arg(type)
if (type == "cmd") {
paste0("\"", gsub("\"", "\\\\\"", string), "\"")
}
else {
if (!length(string))
return("")
has_single_quote <- grep("'", string)
if (!length(has_single_quote))
return(paste0("'", string, "'"))
if (type == "sh")
paste0("\"", gsub("([\"$`\\])", "\\\\\\1", string),
"\"")
else {
if (!length(grep("([$`])", string))) {
paste0("\"", gsub("([\"!\\])", "\\\\\\1", string),
"\"")
}
else vapply(string, cshquote, "")
}
}
}
## @type drop : logical
"split<-" <- function (x, f, drop = FALSE, ..., value)
UseMethod("split<-")
## @type fmt : character
sprintf <- function (fmt, ...)
.Internal(sprintf(fmt, ...))
## @type encoding : character
## @type filename : character
srcfile <- function (filename, encoding = getOption("encoding"), Enc = "unknown")
{
stopifnot(is.character(filename), length(filename) == 1L)
e <- new.env(hash = FALSE, parent = emptyenv())
e$wd <- getwd()
e$filename <- filename
e$timestamp <- file.info(filename)[1, "mtime"]
if (identical(encoding, "unknown"))
encoding <- "native.enc"
e$encoding <- encoding
e$Enc <- Enc
class(e) <- "srcfile"
return(e)
}
## @type x : character
## @type width : integer
## @return character
strtrim <- function (x, width)
{
if (!is.character(x))
x <- as.character(x)
.Internal(strtrim(x, width))
}
## @type prefix : character
## @type width : integer
## @type indent : integer
## @type x : character
## @type exdent : integer
## @type initial : character
## @type simplify : logical|character
strwrap <- function (x, width = 0.9 * getOption("width"), indent = 0, exdent = 0,
prefix = "", simplify = TRUE, initial = prefix)
{
if (!is.character(x))
x <- as.character(x)
indentString <- paste(rep.int(" ", indent), collapse = "")
exdentString <- paste(rep.int(" ", exdent), collapse = "")
y <- list()
UB <- TRUE
if (all(Encoding(x) == "UTF-8"))
UB <- FALSE
else {
enc <- Encoding(x) %in% c("latin1", "UTF-8")
if (length(enc))
x[enc] <- enc2native(x[enc])
}
z <- lapply(strsplit(x, "\n[ \t\n]*\n", perl = TRUE, useBytes = UB),
strsplit, "[ \t\n]", perl = TRUE, useBytes = UB)
for (i in seq_along(z)) {
yi <- character()
for (j in seq_along(z[[i]])) {
words <- z[[i]][[j]]
nc <- nchar(words, type = "w")
if (anyNA(nc)) {
nc0 <- nchar(words, type = "b")
nc[is.na(nc)] <- nc0[is.na(nc)]
}
if (any(nc == 0L)) {
zLenInd <- which(nc == 0L)
zLenInd <- zLenInd[!(zLenInd %in% (grep("[.?!][)\"']{0,1}$",
words, perl = TRUE, useBytes = TRUE) + 1L))]
if (length(zLenInd)) {
words <- words[-zLenInd]
nc <- nc[-zLenInd]
}
}
if (!length(words)) {
yi <- c(yi, "", initial)
next
}
currentIndex <- 0L
lowerBlockIndex <- 1L
upperBlockIndex <- integer()
lens <- cumsum(nc + 1L)
first <- TRUE
maxLength <- width - nchar(initial, type = "w") -
indent
while (length(lens)) {
k <- max(sum(lens <= maxLength), 1L)
if (first) {
first <- FALSE
maxLength <- width - nchar(prefix, type = "w") -
exdent
}
currentIndex <- currentIndex + k
if (nc[currentIndex] == 0L)
upperBlockIndex <- c(upperBlockIndex, currentIndex -
1L)
else upperBlockIndex <- c(upperBlockIndex, currentIndex)
if (length(lens) > k) {
if (nc[currentIndex + 1L] == 0L) {
currentIndex <- currentIndex + 1L
k <- k + 1L
}
lowerBlockIndex <- c(lowerBlockIndex, currentIndex +
1L)
}
if (length(lens) > k)
lens <- lens[-seq_len(k)] - lens[k]
else lens <- NULL
}
nBlocks <- length(upperBlockIndex)
s <- paste0(c(initial, rep.int(prefix, nBlocks -
1L)), c(indentString, rep.int(exdentString, nBlocks -
1L)))
initial <- prefix
for (k in seq_len(nBlocks)) s[k] <- paste0(s[k],
paste(words[lowerBlockIndex[k]:upperBlockIndex[k]],
collapse = " "))
yi <- c(yi, s, prefix)
}
y <- if (length(yi))
c(y, list(yi[-length(yi)]))
else c(y, "")
}
if (simplify)
y <- as.character(unlist(y))
y
}
summary <- function (object, ...)
UseMethod("summary")
## @type command : character
## @type stdout : character
## @type wait : logical
## @type args : character
## @type input : character
## @type stderr : character
## @type env : character
## @type stdin : character
system2 <- function (command, args = character(), stdout = "", stderr = "",
stdin = "", input = NULL, env = character(), wait = TRUE,
minimized = FALSE, invisible = TRUE)
{
if (!missing(minimized) || !missing(invisible))
message("arguments 'minimized' and 'invisible' are for Windows only")
if (!is.logical(wait) || is.na(wait))
stop("'wait' must be TRUE or FALSE")
intern <- FALSE
command <- paste(c(env, shQuote(command), args), collapse = " ")
if (is.null(stdout))
stdout <- FALSE
if (is.null(stderr))
stderr <- FALSE
if (isTRUE(stderr)) {
if (!isTRUE(stdout))
warning("setting stdout = TRUE")
stdout <- TRUE
}
if (identical(stdout, FALSE))
command <- paste(command, ">/dev/null")
else if (isTRUE(stdout))
intern <- TRUE
else if (is.character(stdout)) {
if (length(stdout) != 1L)
stop("'stdout' must be of length 1")
if (nzchar(stdout)) {
command <- if (identical(stdout, stderr))
paste(command, ">", shQuote(stdout), "2>&1")
else command <- paste(command, ">", shQuote(stdout))
}
}
if (identical(stderr, FALSE))
command <- paste(command, "2>/dev/null")
else if (isTRUE(stderr)) {
command <- paste(command, "2>&1")
}
else if (is.character(stderr)) {
if (length(stderr) != 1L)
stop("'stderr' must be of length 1")
if (nzchar(stderr) && !identical(stdout, stderr))
command <- paste(command, "2>", shQuote(stderr))
}
if (!is.null(input)) {
if (!is.character(input))
stop("'input' must be a character vector or 'NULL'")
f <- tempfile()
on.exit(unlink(f))
writeLines(input, f)
command <- paste(command, "<", shQuote(f))
}
else if (nzchar(stdin))
command <- paste(command, "<", stdin)
if (!wait && !intern)
command <- paste(command, "&")
.Internal(system(command, intern))
}
tempdir <- function ()
.Internal(tempdir())
## @type x : character
## @return character
tolower <- function (x)
{
if (!is.character(x))
x <- as.character(x)
.Internal(tolower(x))
}
## @type x : character
## @return character
toupper <- function (x)
{
if (!is.character(x))
x <- as.character(x)
.Internal(toupper(x))
}
unclass <- function (x) .Primitive("unclass")
undebug <- function (fun)
.Internal(undebug(fun))
## @type value : character
"units<-" <- function (x, value)
UseMethod("units<-")
## @type drop : logical
unsplit <- function (value, f, drop = FALSE)
{
len <- length(if (is.list(f)) f[[1L]] else f)
if (is.data.frame(value[[1L]])) {
x <- value[[1L]][rep(NA, len), , drop = FALSE]
rownames(x) <- unsplit(lapply(value, rownames), f, drop = drop)
}
else x <- value[[1L]][rep(NA, len)]
split(x, f, drop = drop) <- value
x
}
untrace <- function (what, signature = NULL, where = topenv(parent.frame()))
{
MethodsDispatchOn <- .isMethodsDispatchOn()
if (MethodsDispatchOn) {
tState <- tracingState(FALSE)
on.exit(tracingState(tState))
}
if (!MethodsDispatchOn)
return(.primUntrace(what))
call <- sys.call()
call[[1L]] <- quote(methods::.TraceWithMethods)
call$where <- where
call$untrace <- TRUE
value <- eval.parent(call)
on.exit()
tracingState(tState)
invisible(value)
}
## @type noBreaks. : logical
## @type call. : logical
## @type immediate. : logical
## @return character
warning <- function (..., call. = TRUE, immediate. = FALSE, noBreaks. = FALSE,
domain = NULL)
{
args <- list(...)
if (length(args) == 1L && inherits(args[[1L]], "condition")) {
cond <- args[[1L]]
if (nargs() > 1L)
cat(gettext("additional arguments ignored in warning()"),
"\n", sep = "", file = stderr())
message <- conditionMessage(cond)
call <- conditionCall(cond)
withRestarts({
.Internal(.signalCondition(cond, message, call))
.Internal(.dfltWarn(message, call))
}, muffleWarning = function() NULL)
invisible(message)
}
else .Internal(warning(call., immediate., noBreaks., .makeMessage(...,
domain = domain)))
}
"+.POSIXt" <- function (e1, e2)
{
coerceTimeUnit <- function(x) as.vector(switch(attr(x, "units"),
secs = x, mins = 60 * x, hours = 60 * 60 * x, days = 60 *
60 * 24 * x, weeks = 60 * 60 * 24 * 7 * x))
if (nargs() == 1)
return(e1)
if (inherits(e1, "POSIXt") && inherits(e2, "POSIXt"))
stop("binary '+' is not defined for \"POSIXt\" objects")
if (inherits(e1, "POSIXlt"))
e1 <- as.POSIXct(e1)
if (inherits(e2, "POSIXlt"))
e2 <- as.POSIXct(e2)
if (inherits(e1, "difftime"))
e1 <- coerceTimeUnit(e1)
if (inherits(e2, "difftime"))
e2 <- coerceTimeUnit(e2)
.POSIXct(unclass(e1) + unclass(e2), check_tzones(e1, e2))
}
"-.POSIXt" <- function (e1, e2)
{
coerceTimeUnit <- function(x) as.vector(switch(attr(x, "units"),
secs = x, mins = 60 * x, hours = 60 * 60 * x, days = 60 *
60 * 24 * x, weeks = 60 * 60 * 24 * 7 * x))
if (!inherits(e1, "POSIXt"))
stop("can only subtract from \"POSIXt\" objects")
if (nargs() == 1)
stop("unary '-' is not defined for \"POSIXt\" objects")
if (inherits(e2, "POSIXt"))
return(difftime(e1, e2))
if (inherits(e2, "difftime"))
e2 <- coerceTimeUnit(e2)
if (!is.null(attr(e2, "class")))
stop("can only subtract numbers from \"POSIXt\" objects")
e1 <- as.POSIXct(e1)
.POSIXct(unclass(e1) - e2, attr(e1, "tzone"))
}
## @type drop : logical
"[.factor" <- function (x, ..., drop = FALSE)
{
y <- NextMethod("[")
attr(y, "contrasts") <- attr(x, "contrasts")
attr(y, "levels") <- attr(x, "levels")
class(y) <- oldClass(x)
lev <- levels(x)
if (drop)
factor(y, exclude = if (anyNA(levels(x)))
NULL
else NA)
else y
}
"[.listof" <- function (x, i, ...)
structure(NextMethod("["), class = class(x))
"[<-.Date" <- function (x, ..., value)
{
if (!length(value))
return(x)
value <- unclass(as.Date(value))
cl <- oldClass(x)
class(x) <- NULL
x <- NextMethod(.Generic)
class(x) <- cl
x
}
## @type unique : logical
## @type functions : logical
## @type max.names : complex
## @return character
all.vars <- function (expr, functions = FALSE, max.names = -1L, unique = TRUE)
.Internal(all.names(expr, functions, max.names, unique))
## @type .dimnames : character
## @type .dim : integer
## @type useNames : logical
arrayInd <- function (ind, .dim, .dimnames = NULL, useNames = FALSE)
{
m <- length(ind)
rank <- length(.dim)
wh1 <- ind - 1L
ind <- 1L + wh1%%.dim[1L]
dnms <- if (useNames) {
list(.dimnames[[1L]][ind], if (any(nzchar(nd <- names(.dimnames)))) nd else if (rank ==
2L) c("row", "col") else paste0("dim", seq_len(rank)))
}
ind <- matrix(ind, nrow = m, ncol = rank, dimnames = dnms)
if (rank >= 2L) {
denom <- 1L
for (i in 2L:rank) {
denom <- denom * .dim[i - 1L]
nextd1 <- wh1%/%denom
ind[, i] <- 1L + nextd1%%.dim[i]
}
}
storage.mode(ind) <- "integer"
ind
}
as.array <- function (x, ...)
UseMethod("as.array")
as.table <- function (x, ...)
UseMethod("as.table")
autoload <- function (name, package, reset = FALSE, ...)
{
if (!reset && exists(name, envir = .GlobalEnv, inherits = FALSE))
stop("an object with that name already exists")
m <- match.call()
m[[1L]] <- as.name("list")
newcall <- eval(m, parent.frame())
newcall <- as.call(c(as.name("autoloader"), newcall))
newcall$reset <- NULL
if (is.na(match(package, .Autoloaded)))
assign(".Autoloaded", c(package, .Autoloaded), envir = .AutoloadEnv)
do.call("delayedAssign", list(name, newcall, .GlobalEnv,
.AutoloadEnv))
invisible()
}
## @type path : character
## @return character
basename <- function (path)
.Internal(basename(path))
## @type internal : logical
builtins <- function (internal = FALSE)
.Internal(builtins(internal))
## @type upper : logical
## @type x : character
casefold <- function (x, upper = FALSE)
if (upper) toupper(x) else tolower(x)
## @type size : complex
## @type LINPACK : logical
chol2inv <- function (x, size = NCOL(x), LINPACK = FALSE)
.Internal(La_chol2inv(x, size))
## @type na.rm : logical
## @type x : complex|logical
## @type dims : integer
## @return complex
colMeans <- function (x, na.rm = FALSE, dims = 1L)
{
if (is.data.frame(x))
x <- as.matrix(x)
if (!is.array(x) || length(dn <- dim(x)) < 2L)
stop("'x' must be an array of at least two dimensions")
if (dims < 1L || dims > length(dn) - 1L)
stop("invalid 'dims'")
n <- prod(dn[1L:dims])
dn <- dn[-(1L:dims)]
z <- if (is.complex(x))
.Internal(colMeans(Re(x), n, prod(dn), na.rm)) + (0+1i) *
.Internal(colMeans(Im(x), n, prod(dn), na.rm))
else .Internal(colMeans(x, n, prod(dn), na.rm))
if (length(dn) > 1L) {
dim(z) <- dn
dimnames(z) <- dimnames(x)[-(1L:dims)]
}
else names(z) <- dimnames(x)[[dims + 1]]
z
}
## @type do.NULL : logical
colnames <- function (x, do.NULL = TRUE, prefix = "col")
{
if (is.data.frame(x) && do.NULL)
return(names(x))
dn <- dimnames(x)
if (!is.null(dn[[2L]]))
dn[[2L]]
else {
nc <- NCOL(x)
if (do.NULL)
NULL
else if (nc > 0L)
paste0(prefix, seq_len(nc))
else character()
}
}
## @type breaks : complex
## @type start.on.monday : logical
## @type labels : integer
cut.Date <- function (x, breaks, labels = NULL, start.on.monday = TRUE, right = FALSE,
...)
{
if (!inherits(x, "Date"))
stop("'x' must be a date-time object")
x <- as.Date(x)
if (inherits(breaks, "Date")) {
breaks <- sort(as.Date(breaks))
}
else if (is.numeric(breaks) && length(breaks) == 1L) {
}
else if (is.character(breaks) && length(breaks) == 1L) {
by2 <- strsplit(breaks, " ", fixed = TRUE)[[1L]]
if (length(by2) > 2L || length(by2) < 1L)
stop("invalid specification of 'breaks'")
valid <- pmatch(by2[length(by2)], c("days", "weeks",
"months", "years", "quarters"))
if (is.na(valid))
stop("invalid specification of 'breaks'")
start <- as.POSIXlt(min(x, na.rm = TRUE))
if (valid == 1L)
incr <- 1L
if (valid == 2L) {
start$mday <- start$mday - start$wday
if (start.on.monday)
start$mday <- start$mday + ifelse(start$wday >
0L, 1L, -6L)
start$isdst <- -1L
incr <- 7L
}
if (valid == 3L) {
start$mday <- 1L
start$isdst <- -1L
end <- as.POSIXlt(max(x, na.rm = TRUE))
step <- ifelse(length(by2) == 2L, as.integer(by2[1L]),
1L)
end <- as.POSIXlt(end + (31 * step * 86400))
end$mday <- 1L
end$isdst <- -1L
breaks <- as.Date(seq(start, end, breaks))
}
else if (valid == 4L) {
start$mon <- 0L
start$mday <- 1L
start$isdst <- -1L
end <- as.POSIXlt(max(x, na.rm = TRUE))
step <- ifelse(length(by2) == 2L, as.integer(by2[1L]),
1L)
end <- as.POSIXlt(end + (366 * step * 86400))
end$mon <- 0L
end$mday <- 1L
end$isdst <- -1L
breaks <- as.Date(seq(start, end, breaks))
}
else if (valid == 5L) {
qtr <- rep(c(0L, 3L, 6L, 9L), each = 3L)
start$mon <- qtr[start$mon + 1L]
start$mday <- 1L
start$isdst <- -1L
maxx <- max(x, na.rm = TRUE)
end <- as.POSIXlt(maxx)
step <- ifelse(length(by2) == 2L, as.integer(by2[1L]),
1L)
end <- as.POSIXlt(end + (93 * step * 86400))
end$mon <- qtr[end$mon + 1L]
end$mday <- 1L
end$isdst <- -1L
breaks <- as.Date(seq(start, end, paste(step * 3L,
"months")))
lb <- length(breaks)
if (maxx < breaks[lb - 1])
breaks <- breaks[-lb]
}
else {
start <- as.Date(start)
if (length(by2) == 2L)
incr <- incr * as.integer(by2[1L])
maxx <- max(x, na.rm = TRUE)
breaks <- seq(start, maxx + incr, breaks)
breaks <- breaks[seq_len(1L + max(which(breaks <=
maxx)))]
}
}
else stop("invalid specification of 'breaks'")
res <- cut(unclass(x), unclass(breaks), labels = labels,
right = right, ...)
if (is.null(labels)) {
levels(res) <- as.character(if (is.numeric(breaks)) x[!duplicated(res)] else breaks[-length(breaks)])
}
res
}
## @type units : character
difftime <- function (time1, time2, tz, units = c("auto", "secs", "mins",
"hours", "days", "weeks"))
{
if (missing(tz)) {
time1 <- as.POSIXct(time1)
time2 <- as.POSIXct(time2)
}
else {
time1 <- as.POSIXct(time1, tz = tz)
time2 <- as.POSIXct(time2, tz = tz)
}
z <- unclass(time1) - unclass(time2)
attr(z, "tzone") <- NULL
units <- match.arg(units)
if (units == "auto") {
if (all(is.na(z)))
units <- "secs"
else {
zz <- min(abs(z), na.rm = TRUE)
if (is.na(zz) || zz < 60)
units <- "secs"
else if (zz < 3600)
units <- "mins"
else if (zz < 86400)
units <- "hours"
else units <- "days"
}
}
switch(units, secs = .difftime(z, units = "secs"), mins = .difftime(z/60,
units = "mins"), hours = .difftime(z/3600, units = "hours"),
days = .difftime(z/86400, units = "days"), weeks = .difftime(z/(7 *
86400), units = "weeks"))
}
dimnames <- function (x) .Primitive("dimnames")
## @type local : logical
## @type x : character
## @type now : logical
dyn.load <- function (x, local = TRUE, now = TRUE, ...)
.Internal(dyn.load(x, as.logical(local), as.logical(now), ""))
emptyenv <- function () .Primitive("emptyenv")
## @type x : character
enc2utf8 <- function (x) .Primitive("enc2utf8")
## @type x : character
## @return character
Encoding <- function (x)
.Internal(Encoding(x))
## @type indent : integer
## @type style : character
## @type width : integer
## @optional y
formatDL <- function (x, y, style = c("table", "list"), width = 0.9 * getOption("width"),
indent = NULL)
{
if (is.list(x)) {
if (length(x) == 2L && diff(vapply(x, length, 1L)) ==
0L) {
y <- x[[2L]]
x <- x[[1L]]
}
else stop("incorrect value for 'x'")
}
else if (is.matrix(x)) {
if (NCOL(x) == 2L) {
y <- x[, 2L]
x <- x[, 1L]
}
else stop("incorrect value for 'x'")
}
else if (missing(y) && !is.null(nms <- names(x))) {
y <- x
x <- nms
}
else if (length(x) != length(y))
stop("'x' and 'y' must have the same length")
x <- as.character(x)
if (!length(x))
return(x)
y <- as.character(y)
style <- match.arg(style)
if (is.null(indent))
indent <- switch(style, table = width/3, list = width/9)
if (indent > 0.5 * width)
stop("incorrect values of 'indent' and 'width'")
indentString <- paste(rep.int(" ", indent), collapse = "")
if (style == "table") {
i <- (nchar(x, type = "w") > indent - 3L)
if (any(i))
x[i] <- paste0(x[i], "\n", indentString)
i <- !i
if (any(i))
x[i] <- formatC(x[i], width = indent, flag = "-")
y <- lapply(strwrap(y, width = width - indent, simplify = FALSE),
paste, collapse = paste0("\n", indentString))
r <- paste0(x, unlist(y))
}
else if (style == "list") {
y <- strwrap(paste0(x, ": ", y), exdent = indent, width = width,
simplify = FALSE)
r <- unlist(lapply(y, paste, collapse = "\n"))
}
r
}
## @type fmt : character
gettextf <- function (fmt, ..., domain = NULL)
sprintf(gettext(fmt, domain = domain), ...)
gregexpr <- function (pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE,
useBytes = FALSE)
{
if (!is.character(text))
text <- as.character(text)
.Internal(gregexpr(as.character(pattern), text, ignore.case,
perl, fixed, useBytes))
}
identity <- function (x)
x
## @type what : character
## @type which : logical
inherits <- function (x, what, which = FALSE)
.Internal(inherits(x, what, which))
is.array <- function (x) .Primitive("is.array")
is.table <- function (x)
inherits(x, "table")
kappa.lm <- function (z, ...)
kappa.qr(z$qr, ...)
## @optional z
kappa.qr <- function (z, ...)
{
qr <- z$qr
R <- qr[1L:min(dim(qr)), , drop = FALSE]
R[lower.tri(R)] <- 0
.kappa_tri(R, ...)
}
lazyLoad <- function (filebase, envir = parent.frame(), filter)
{
fun <- function(db) {
vals <- db$vals
vars <- db$vars
expr <- quote(lazyLoadDBfetch(key, datafile, compressed,
envhook))
.Internal(makeLazy(vars, vals, expr, db, envir))
}
lazyLoadDBexec(filebase, fun, filter)
}
## @type value : integer
"length<-" <- function (x, value) .Primitive("length<-")
## @type value : complex|character
"levels<-" <- function (x, value) .Primitive("levels<-")
list2env <- function (x, envir = NULL, parent = parent.frame(), hash = (length(x) >
100), size = max(29L, length(x)))
{
if (is.null(envir))
envir <- new.env(hash = hash, parent = parent, size = size)
.Internal(list2env(x, envir))
}
## @type n : integer
ngettext <- function (n, msg1, msg2, domain = NULL)
.Internal(ngettext(n, msg1, msg2, domain))
oldClass <- function (x) .Primitive("oldClass")
Ops.Date <- function (e1, e2)
{
if (nargs() == 1)
stop(gettextf("unary %s not defined for \"Date\" objects",
.Generic), domain = NA)
boolean <- switch(.Generic, `<` = , `>` = , `==` = , `!=` = ,
`<=` = , `>=` = TRUE, FALSE)
if (!boolean)
stop(gettextf("%s not defined for \"Date\" objects",
.Generic), domain = NA)
if (is.character(e1))
e1 <- as.Date(e1)
if (is.character(e2))
e2 <- as.Date(e2)
NextMethod(.Generic)
}
packBits <- function (x, type = c("raw", "integer"))
{
type <- match.arg(type)
.Internal(packBits(x, type))
}
pairlist <- function (...)
as.pairlist(list(...))
pmax.int <- function (..., na.rm = FALSE)
.Internal(pmax(na.rm, ...))
pmin.int <- function (..., na.rm = FALSE)
.Internal(pmin(na.rm, ...))
polyroot <- function (z)
.Internal(polyroot(z))
## @type right : logical
## @optional f
Position <- function (f, x, right = FALSE, nomatch = NA_integer_)
{
ind <- if (right)
rev(seq_along(x))
else seq_along(x)
for (i in ind) if (f(x[[i]]))
return(i)
nomatch
}
print.by <- function (x, ..., vsep)
{
d <- dim(x)
dn <- dimnames(x)
dnn <- names(dn)
if (missing(vsep))
vsep <- paste(rep.int("-", 0.75 * getOption("width")),
collapse = "")
lapply(X = seq_along(x), FUN = function(i, x, vsep, ...) {
if (i != 1L && !is.null(vsep))
cat(vsep, "\n")
ii <- i - 1L
for (j in seq_along(dn)) {
iii <- ii%%d[j] + 1L
ii <- ii%/%d[j]
cat(dnn[j], ": ", dn[[j]][iii], "\n", sep = "")
}
print(x[[i]], ...)
}, x, vsep, ...)
invisible(x)
}
prmatrix <- function (x, rowlab = dn[[1]], collab = dn[[2]], quote = TRUE,
right = FALSE, na.print = NULL, ...)
{
x <- as.matrix(x)
dn <- dimnames(x)
.Internal(prmatrix(x, rowlab, collab, quote, right, na.print))
}
## @type x : numeric
## @type deriv : integer
psigamma <- function (x, deriv = 0L)
.Internal(psigamma(x, deriv))
pushBack <- function (data, connection, newLine = TRUE, encoding = c("",
"bytes", "UTF-8"))
{
if (length(encoding) > 1)
encoding <- encoding[1]
if (nchar(encoding))
encoding <- match.arg(encoding)
type <- match(encoding, c("", "bytes", "UTF-8"))
.Internal(pushBack(data, connection, newLine, type))
}
qr.resid <- function (qr, y)
{
if (!is.qr(qr))
stop("argument is not a QR decomposition")
if (is.complex(qr$qr))
stop("not implemented for complex 'qr'")
if (isTRUE(attr(qr, "useLAPACK")))
stop("not supported for LAPACK QR")
k <- as.integer(qr$rank)
if (k == 0)
return(y)
n <- as.integer(nrow(qr$qr))
if (is.na(n))
stop("invalid nrow(qr$qr)")
ny <- as.integer(NCOL(y))
if (is.na(ny))
stop("invalid NCOL(y)")
if (NROW(y) != n)
stop("'qr' and 'y' must have the same number of rows")
storage.mode(y) <- "double"
.Fortran(.F_dqrrsd, as.double(qr$qr), n, k, as.double(qr$qraux),
y, ny, rsd = y)$rsd
}
qr.solve <- function (a, b, tol = 1e-07)
{
if (!is.qr(a))
a <- qr(a, tol = tol)
nc <- ncol(a$qr)
nr <- nrow(a$qr)
if (a$rank != min(nc, nr))
stop("singular matrix 'a' in solve")
if (missing(b)) {
if (nc != nr)
stop("only square matrices can be inverted")
b <- diag(1, nc)
}
res <- qr.coef(a, b)
res[is.na(res)] <- 0
res
}
## @return complex|character
quarters <- function (x, abbreviate)
UseMethod("quarters")
## @return raw|numeric|character
rawShift <- function (x, n)
.Internal(rawShift(x, n))
read.dcf <- function (file, fields = NULL, all = FALSE, keep.white = NULL)
{
if (is.character(file)) {
file <- gzfile(file)
on.exit(close(file))
}
if (!inherits(file, "connection"))
stop("'file' must be a character string or connection")
if (!all)
return(.Internal(readDCF(file, fields, keep.white)))
.assemble_things_into_a_data_frame <- function(tags, vals,
nums) {
tf <- factor(tags, levels = unique(tags))
cnts <- table(nums, tf)
out <- array(NA_character_, dim = dim(cnts), dimnames = list(NULL,
levels(tf)))
if (all(cnts <= 1L)) {
out[cbind(nums, tf)] <- vals
out <- as.data.frame(out, stringsAsFactors = FALSE)
}
else {
levs <- colSums(cnts > 1L) == 0L
if (any(levs)) {
inds <- tf %in% levels(tf)[levs]
out[cbind(nums[inds], tf[inds])] <- vals[inds]
}
out <- as.data.frame(out, stringsAsFactors = FALSE)
for (l in levels(tf)[!levs]) {
out[[l]] <- rep.int(list(NA_character_), nrow(cnts))
i <- tf == l
out[[l]][unique(nums[i])] <- split(vals[i], nums[i])
}
}
out
}
ctype <- Sys.getlocale("LC_CTYPE")
on.exit(Sys.setlocale("LC_CTYPE", ctype), add = TRUE)
Sys.setlocale("LC_CTYPE", "C")
lines <- readLines(file)
ind <- grep("^[^[:blank:]][^:]*$", lines)
if (length(ind)) {
lines <- strtrim(lines[ind], 0.7 * getOption("width"))
stop(gettextf("Invalid DCF format.\nRegular lines must have a tag.\nOffending lines start with:\n%s",
paste0(" ", lines, collapse = "\n")), domain = NA)
}
line_is_not_empty <- !grepl("^[[:space:]]*$", lines)
nums <- cumsum(diff(c(FALSE, line_is_not_empty) > 0L) > 0L)
nums <- nums[line_is_not_empty]
lines <- lines[line_is_not_empty]
line_is_escaped_blank <- grepl("^[[:space:]]+\\.[[:space:]]*$",
lines)
if (any(line_is_escaped_blank))
lines[line_is_escaped_blank] <- ""
line_has_tag <- grepl("^[^[:blank:]][^:]*:", lines)
ind <- which(!line_has_tag[which(diff(nums) > 0L) + 1L])
if (length(ind)) {
lines <- strtrim(lines[ind], 0.7 * getOption("width"))
stop(gettextf("Invalid DCF format.\nContinuation lines must not start a record.\nOffending lines start with:\n%s",
paste0(" ", lines, collapse = "\n")), domain = NA)
}
lengths <- rle(cumsum(line_has_tag))$lengths
pos <- cumsum(lengths)
tags <- sub(":.*", "", lines[line_has_tag])
lines[line_has_tag] <- sub("[^:]*:[[:space:]]*", "", lines[line_has_tag])
foldable <- rep.int(is.na(match(tags, keep.white)), lengths)
lines[foldable] <- sub("^[[:space:]]*", "", lines[foldable])
lines[foldable] <- sub("[[:space:]]*$", "", lines[foldable])
vals <- mapply(function(from, to) paste(lines[from:to], collapse = "\n"),
c(1L, pos[-length(pos)] + 1L), pos)
out <- .assemble_things_into_a_data_frame(tags, vals, nums[pos])
if (!is.null(fields))
out <- out[fields]
out
}
## @type con : raw|character
## @type useBytes : complex|logical
## @type nchars : integer|character
readChar <- function (con, nchars, useBytes = FALSE)
{
if (is.character(con)) {
con <- file(con, "rb")
on.exit(close(con))
}
.Internal(readChar(con, as.integer(nchars), useBytes))
}
## @type prompt : character
## @return character
readline <- function (prompt = "")
.Internal(readline(prompt))
## @optional x
rep.Date <- function (x, ...)
{
y <- NextMethod()
structure(y, class = "Date")
}
## @type na.rm : logical
## @type dims : integer
## @type x : complex|logical
## @return complex
rowMeans <- function (x, na.rm = FALSE, dims = 1L)
{
if (is.data.frame(x))
x <- as.matrix(x)
if (!is.array(x) || length(dn <- dim(x)) < 2L)
stop("'x' must be an array of at least two dimensions")
if (dims < 1L || dims > length(dn) - 1L)
stop("invalid 'dims'")
p <- prod(dn[-(1L:dims)])
dn <- dn[1L:dims]
z <- if (is.complex(x))
.Internal(rowMeans(Re(x), prod(dn), p, na.rm)) + (0+1i) *
.Internal(rowMeans(Im(x), prod(dn), p, na.rm))
else .Internal(rowMeans(x, prod(dn), p, na.rm))
if (length(dn) > 1L) {
dim(z) <- dn
dimnames(z) <- dimnames(x)[1L:dims]
}
else names(z) <- dimnames(x)[[1L]]
z
}
## @type do.NULL : logical
rownames <- function (x, do.NULL = TRUE, prefix = "row")
{
dn <- dimnames(x)
if (!is.null(dn[[1L]]))
dn[[1L]]
else {
nr <- NROW(x)
if (do.NULL)
NULL
else if (nr > 0L)
paste0(prefix, seq_len(nr))
else character()
}
}
## @type length.out : integer
seq.Date <- function (from, to, by, length.out = NULL, along.with = NULL,
...)
{
if (missing(from))
stop("'from' must be specified")
if (!inherits(from, "Date"))
stop("'from' must be a \"Date\" object")
if (length(as.Date(from)) != 1L)
stop("'from' must be of length 1")
if (!missing(to)) {
if (!inherits(to, "Date"))
stop("'to' must be a \"Date\" object")
if (length(as.Date(to)) != 1L)
stop("'to' must be of length 1")
}
if (!missing(along.with)) {
length.out <- length(along.with)
}
else if (!is.null(length.out)) {
if (length(length.out) != 1L)
stop("'length.out' must be of length 1")
length.out <- ceiling(length.out)
}
status <- c(!missing(to), !missing(by), !is.null(length.out))
if (sum(status) != 2L)
stop("exactly two of 'to', 'by' and 'length.out' / 'along.with' must be specified")
if (missing(by)) {
from <- unclass(as.Date(from))
to <- unclass(as.Date(to))
res <- seq.int(from, to, length.out = length.out)
return(structure(res, class = "Date"))
}
if (length(by) != 1L)
stop("'by' must be of length 1")
valid <- 0L
if (inherits(by, "difftime")) {
by <- switch(attr(by, "units"), secs = 1/86400, mins = 1/1440,
hours = 1/24, days = 1, weeks = 7) * unclass(by)
}
else if (is.character(by)) {
by2 <- strsplit(by, " ", fixed = TRUE)[[1L]]
if (length(by2) > 2L || length(by2) < 1L)
stop("invalid 'by' string")
valid <- pmatch(by2[length(by2)], c("days", "weeks",
"months", "quarters", "years"))
if (is.na(valid))
stop("invalid string for 'by'")
if (valid <= 2L) {
by <- c(1, 7)[valid]
if (length(by2) == 2L)
by <- by * as.integer(by2[1L])
}
else by <- if (length(by2) == 2L)
as.integer(by2[1L])
else 1
}
else if (!is.numeric(by))
stop("invalid mode for 'by'")
if (is.na(by))
stop("'by' is NA")
if (valid <= 2L) {
from <- unclass(as.Date(from))
if (!is.null(length.out))
res <- seq.int(from, by = by, length.out = length.out)
else {
to0 <- unclass(as.Date(to))
res <- seq.int(0, to0 - from, by) + from
}
res <- structure(res, class = "Date")
}
else {
r1 <- as.POSIXlt(from)
if (valid == 5L) {
if (missing(to)) {
yr <- seq.int(r1$year, by = by, length.out = length.out)
}
else {
to0 <- as.POSIXlt(to)
yr <- seq.int(r1$year, to0$year, by)
}
r1$year <- yr
res <- as.Date(r1)
}
else {
if (valid == 4L)
by <- by * 3
if (missing(to)) {
mon <- seq.int(r1$mon, by = by, length.out = length.out)
}
else {
to0 <- as.POSIXlt(to)
mon <- seq.int(r1$mon, 12 * (to0$year - r1$year) +
to0$mon, by)
}
r1$mon <- mon
res <- as.Date(r1)
}
}
if (!missing(to)) {
to <- as.Date(to)
res <- if (by > 0)
res[res <= to]
else res[res >= to]
}
res
}
## @type nvec : integer
sequence <- function (nvec)
unlist(lapply(nvec, seq_len))
## @type seed : integer
## @type normal.kind : character
## @type kind : character
set.seed <- function (seed, kind = NULL, normal.kind = NULL)
{
kinds <- c("Wichmann-Hill", "Marsaglia-Multicarry", "Super-Duper",
"Mersenne-Twister", "Knuth-TAOCP", "user-supplied", "Knuth-TAOCP-2002",
"L'Ecuyer-CMRG", "default")
n.kinds <- c("Buggy Kinderman-Ramage", "Ahrens-Dieter", "Box-Muller",
"user-supplied", "Inversion", "Kinderman-Ramage", "default")
if (length(kind)) {
if (!is.character(kind) || length(kind) > 1L)
stop("'kind' must be a character string of length 1 (RNG to be used).")
if (is.na(i.knd <- pmatch(kind, kinds) - 1L))
stop(gettextf("'%s' is not a valid abbreviation of an RNG",
kind), domain = NA)
if (i.knd == length(kinds) - 1L)
i.knd <- -1L
}
else i.knd <- NULL
if (!is.null(normal.kind)) {
if (!is.character(normal.kind) || length(normal.kind) !=
1L)
stop("'normal.kind' must be a character string of length 1")
normal.kind <- pmatch(normal.kind, n.kinds) - 1L
if (is.na(normal.kind))
stop(gettextf("'%s' is not a valid choice", normal.kind),
domain = NA)
if (normal.kind == 0L)
stop("buggy version of Kinderman-Ramage generator is not allowed",
domain = NA)
if (normal.kind == length(n.kinds) - 1L)
normal.kind <- -1L
}
.Internal(set.seed(seed, i.knd, normal.kind))
}
setequal <- function (x, y)
{
x <- as.vector(x)
y <- as.vector(y)
all(c(match(x, y, 0L) > 0L, match(y, x, 0L) > 0L))
}
solve.qr <- function (a, b, ...)
{
if (!is.qr(a))
stop("this is the \"qr\" method for the generic function solve()")
nc <- ncol(a$qr)
nr <- nrow(a$qr)
if (a$rank != min(nc, nr))
if (a$rank != nc)
stop("singular matrix 'a' in 'solve'")
if (missing(b)) {
if (nc != nr)
stop("only square matrices can be inverted")
b <- diag(1, nc)
}
res <- qr.coef(a, b)
res[is.na(res)] <- 0
res
}
## @type method : character
## @type index.return : logical
## @type x : complex|logical|character
## @type decreasing : logical
sort.int <- function (x, partial = NULL, na.last = NA, decreasing = FALSE,
method = c("shell", "quick"), index.return = FALSE)
{
if (isfact <- is.factor(x)) {
if (index.return)
stop("'index.return' only for non-factors")
lev <- levels(x)
nlev <- nlevels(x)
isord <- is.ordered(x)
x <- c(x)
}
else if (!is.atomic(x))
stop("'x' must be atomic")
if (has.na <- any(ina <- is.na(x))) {
nas <- x[ina]
x <- x[!ina]
}
if (index.return && !is.na(na.last))
stop("'index.return' only for 'na.last = NA'")
if (!is.null(partial)) {
if (index.return || decreasing || isfact || !missing(method))
stop("unsupported options for partial sorting")
if (!all(is.finite(partial)))
stop("non-finite 'partial'")
y <- if (length(partial) <= 10L) {
partial <- .Internal(qsort(partial, FALSE))
.Internal(psort(x, partial))
}
else if (is.double(x))
.Internal(qsort(x, FALSE))
else .Internal(sort(x, FALSE))
}
else if (isfact && missing(method) && nlev < 1e+05) {
o <- sort.list(x, decreasing = decreasing, method = "radix")
y <- x[o]
}
else {
nms <- names(x)
method <- if (is.numeric(x))
match.arg(method)
else "shell"
switch(method, quick = {
if (!is.null(nms)) {
if (decreasing) x <- -x
y <- .Internal(qsort(x, TRUE))
if (decreasing) y$x <- -y$x
names(y$x) <- nms[y$ix]
if (!index.return) y <- y$x
} else {
if (decreasing) x <- -x
y <- .Internal(qsort(x, index.return))
if (decreasing) if (index.return) y$x <- -y$x else y <- -y
}
}, shell = {
if (index.return || !is.null(nms)) {
o <- sort.list(x, decreasing = decreasing)
y <- if (index.return) list(x = x[o], ix = o) else x[o]
} else y <- .Internal(sort(x, decreasing))
})
}
if (!is.na(na.last) && has.na)
y <- if (!na.last)
c(nas, y)
else c(y, nas)
if (isfact)
y <- (if (isord)
ordered
else factor)(y, levels = seq_len(nlev), labels = lev)
y
}
## @type usetz : logical
## @type tz : character
## @type format : complex|character
## @type x : character
strftime <- function (x, format = "", tz = "", usetz = FALSE, ...)
format(as.POSIXlt(x, tz = tz), format = format, usetz = usetz,
...)
strptime <- function (x, format, tz = "")
{
y <- .Internal(strptime(as.character(x), format, tz))
names(y$year) <- names(x)
y
}
strsplit <- function (x, split, fixed = FALSE, perl = FALSE, useBytes = FALSE)
.Internal(strsplit(x, as.character(split), fixed, perl, useBytes))
## @type stop : integer
## @type x : character
## @type value : character
## @type start : integer
"substr<-" <- function (x, start, stop, value)
.Internal(`substr<-`(x, as.integer(start), as.integer(stop),
value))
sys.call <- function (which = 0L)
.Internal(sys.call(which))
Sys.Date <- function ()
as.Date(as.POSIXlt(Sys.time()))
## @type paths : character
## @type dirmark : logical
## @return character
Sys.glob <- function (paths, dirmark = FALSE)
.Internal(Sys.glob(path.expand(paths), dirmark))
Sys.info <- function ()
.Internal(Sys.info())
Sys.time <- function ()
.POSIXct(.Internal(Sys.time()))
## @return integer
tabulate <- function (bin, nbins = max(1L, bin, na.rm = TRUE))
{
if (!is.numeric(bin) && !is.factor(bin))
stop("'bin' must be numeric or a factor")
if (typeof(bin) != "integer")
bin <- as.integer(bin)
if (nbins > .Machine$integer.max)
stop("attempt to make a table with >= 2^31 elements")
nbins <- as.integer(nbins)
if (is.na(nbins))
stop("invalid value of 'nbins'")
.Internal(tabulate(bin, nbins))
}
## @type tmpdir : character
## @type fileext : character
## @type pattern : character
## @return character
tempfile <- function (pattern = "file", tmpdir = tempdir(), fileext = "")
.Internal(tempfile(pattern, tmpdir, fileext))
toString <- function (x, ...)
UseMethod("toString")
tracemem <- function (x) .Primitive("tracemem")
## @type x : numeric
trigamma <- function (x) .Primitive("trigamma")
truncate <- function (con, ...)
UseMethod("truncate")
tryCatch <- function (expr, ..., finally)
{
tryCatchList <- function(expr, names, parentenv, handlers) {
nh <- length(names)
if (nh > 1L)
tryCatchOne(tryCatchList(expr, names[-nh], parentenv,
handlers[-nh]), names[nh], parentenv, handlers[[nh]])
else if (nh == 1L)
tryCatchOne(expr, names, parentenv, handlers[[1L]])
else expr
}
tryCatchOne <- function(expr, name, parentenv, handler) {
doTryCatch <- function(expr, name, parentenv, handler) {
.Internal(.addCondHands(name, list(handler), parentenv,
environment(), FALSE))
expr
}
value <- doTryCatch(return(expr), name, parentenv, handler)
if (is.null(value[[1L]])) {
msg <- .Internal(geterrmessage())
call <- value[[2L]]
cond <- simpleError(msg, call)
}
else cond <- value[[1L]]
value[[3L]](cond)
}
if (!missing(finally))
on.exit(finally)
handlers <- list(...)
classes <- names(handlers)
parentenv <- parent.frame()
if (length(classes) != length(handlers))
stop("bad handler specification")
tryCatchList(expr, classes, parentenv, handlers)
}
warnings <- function (...)
{
if (!exists("last.warning", envir = baseenv()))
return()
last.warning <- get("last.warning", envir = baseenv())
if (!(n <- length(last.warning)))
return()
structure(last.warning, dots = list(...), class = "warnings")
}
## @return complex|character
weekdays <- function (x, abbreviate)
UseMethod("weekdays")
writeBin <- function (object, con, size = NA_integer_, endian = .Platform$endian,
useBytes = FALSE)
{
swap <- endian != .Platform$endian
if (!is.vector(object) || mode(object) == "list")
stop("can only write vector objects")
if (is.character(con)) {
con <- file(con, "wb")
on.exit(close(con))
}
.Internal(writeBin(object, con, size, swap, useBytes))
}
## @type digits : integer
## @type x : complex
zapsmall <- function (x, digits = getOption("digits"))
{
if (length(digits) == 0L)
stop("invalid 'digits'")
if (all(ina <- is.na(x)))
return(x)
mx <- max(abs(x[!ina]))
round(x, digits = if (mx > 0) max(0L, digits - log10(mx)) else digits)
}
"!.hexmode" <- function (a)
as.hexmode(bitwNot(as.hexmode(a)))
"!.octmode" <- function (a)
as.octmode(bitwNot(as.octmode(a)))
"$.DLLInfo" <- function (x, name)
getNativeSymbolInfo(as.character(name), PACKAGE = x)
"&.hexmode" <- function (a, b)
as.hexmode(bitwAnd(as.hexmode(a), as.hexmode(b)))
"&.octmode" <- function (a, b)
as.octmode(bitwAnd(as.octmode(a), as.octmode(b)))
## @optional i
"[.hexmode" <- function (x, i)
{
cl <- oldClass(x)
y <- NextMethod("[")
oldClass(y) <- cl
y
}
"[.noquote" <- function (x, ...)
{
attr <- attributes(x)
r <- unclass(x)[...]
attributes(r) <- c(attributes(r), attr[is.na(match(names(attr),
c("dim", "dimnames", "names")))])
r
}
## @optional i
"[.octmode" <- function (x, i)
{
cl <- oldClass(x)
y <- NextMethod("[")
oldClass(y) <- cl
y
}
"[.POSIXct" <- function (x, ..., drop = TRUE)
{
cl <- oldClass(x)
class(x) <- NULL
val <- NextMethod("[")
class(val) <- cl
attr(val, "tzone") <- attr(x, "tzone")
val
}
"[.POSIXlt" <- function (x, ..., drop = TRUE)
{
val <- lapply(X = x, FUN = "[", ..., drop = drop)
attributes(val) <- attributes(x)
val
}
"[[.factor" <- function (x, ...)
{
y <- NextMethod("[[")
attr(y, "contrasts") <- attr(x, "contrasts")
attr(y, "levels") <- attr(x, "levels")
class(y) <- oldClass(x)
y
}
all.equal <- function (target, current, ...)
UseMethod("all.equal")
## @type max.names : complex
## @type functions : logical
## @type unique : logical
## @return character
all.names <- function (expr, functions = TRUE, max.names = -1L, unique = FALSE)
.Internal(all.names(expr, functions, max.names, unique))
as.double <- function (x, ...) .Primitive("as.double")
as.factor <- function (x)
{
if (is.factor(x))
x
else if (!is.object(x) && is.integer(x)) {
levels <- sort(unique.default(x))
f <- match(x, levels)
levels(f) <- as.character(levels)
class(f) <- "factor"
f
}
else factor(x)
}
as.matrix <- function (x, ...)
UseMethod("as.matrix")
as.single <- function (x, ...)
UseMethod("as.single")
as.symbol <- function (x)
.Internal(as.vector(x, "symbol"))
## @type mode : character
## @return raw|numeric|character
as.vector <- function (x, mode = "any")
.Internal(as.vector(x, mode))
## @type upper.tri : logical
## @type transpose : logical
## @type k : complex
backsolve <- function (r, x, k = ncol(r), upper.tri = TRUE, transpose = FALSE)
{
r <- as.matrix(r)
x.mat <- is.matrix(x)
if (!x.mat)
x <- as.matrix(x)
z <- .Internal(backsolve(r, x, k, upper.tri, transpose))
if (x.mat)
z
else drop(z)
}
c.noquote <- function (..., recursive = FALSE)
structure(NextMethod("c"), class = "noquote")
c.POSIXct <- function (..., recursive = FALSE)
.POSIXct(c(unlist(lapply(list(...), unclass))))
c.POSIXlt <- function (..., recursive = FALSE)
as.POSIXlt(do.call("c", lapply(list(...), as.POSIXct)))
## @type length : integer
character <- function (length = 0L)
.Internal(vector("character", length))
## @return integer
charmatch <- function (x, table, nomatch = NA_integer_)
.Internal(charmatch(as.character(x), as.character(table), nomatch))
charToRaw <- function (x)
.Internal(charToRaw(x))
## @type value : character
"comment<-" <- function (x, value)
.Internal(`comment<-`(x, value))
conflicts <- function (where = search(), detail = FALSE)
{
if (length(where) < 1L)
stop("argument 'where' of length 0")
z <- vector(length(where), mode = "list")
names(z) <- where
for (i in seq_along(where)) z[[i]] <- objects(pos = where[i])
all <- unlist(z, use.names = FALSE)
dups <- duplicated(all)
dups <- all[dups]
if (detail) {
for (i in where) z[[i]] <- z[[i]][match(dups, z[[i]],
0L)]
z[vapply(z, function(x) length(x) == 0L, NA)] <- NULL
z
}
else dups
}
## @type y : complex
## @type x : complex
crossprod <- function (x, y = NULL)
.Internal(crossprod(x, y))
## @type text : character
debugonce <- function (fun, text = "", condition = NULL)
.Internal(debugonce(fun, text, condition))
## @type lag : integer
## @type x : numeric
## @type differences : integer
diff.Date <- function (x, lag = 1L, differences = 1L, ...)
{
ismat <- is.matrix(x)
xlen <- if (ismat)
dim(x)[1L]
else length(x)
if (length(lag) != 1L || length(differences) > 1L || lag <
1L || differences < 1L)
stop("'lag' and 'differences' must be integers >= 1")
if (lag * differences >= xlen)
return(structure(numeric(), class = "difftime", units = "days"))
r <- x
i1 <- -seq_len(lag)
if (ismat)
for (i in seq_len(differences)) r <- r[i1, , drop = FALSE] -
r[-nrow(r):-(nrow(r) - lag + 1L), , drop = FALSE]
else for (i in seq_len(differences)) r <- r[i1] - r[-length(r):-(length(r) -
lag + 1L)]
r
}
dontCheck <- function (x)
x
## @type x : numeric
factorial <- function (x)
gamma(x + 1)
## @type copy.mode : logical
## @type overwrite : logical
## @type from : character
## @type to : character
## @type recursive : logical
## @type copy.date : logical
file.copy <- function (from, to, overwrite = recursive, recursive = FALSE,
copy.mode = TRUE, copy.date = FALSE)
{
if (!(nf <- length(from)))
return(logical())
if (!(nt <- length(to)))
stop("no files to copy to")
if (nt == 1 && isTRUE(file.info(to)$isdir)) {
if (recursive && to %in% from)
stop("attempt to copy a directory to itself")
if (.Platform$OS.type == "windows") {
from <- gsub("/", "\\", from, fixed = TRUE)
to <- gsub("/", "\\", to, fixed = TRUE)
}
return(.Internal(file.copy(from, to, overwrite, recursive,
copy.mode, copy.date)))
}
else if (nf > nt)
stop("more 'from' files than 'to' files")
else if (recursive)
warning("'recursive' will be ignored as 'to' is not a single existing directory")
if (nt > nf)
from <- rep_len(from, length.out = nt)
okay <- file.exists(from)
if (!overwrite)
okay[file.exists(to)] <- FALSE
if (any(from[okay] %in% to[okay]))
stop("file can not be copied both 'from' and 'to'")
if (any(okay)) {
okay[okay] <- file.create(to[okay])
if (any(okay)) {
okay[okay] <- file.append(to[okay], from[okay])
if (copy.mode || copy.date) {
fi <- file.info(from[okay])
if (copy.mode)
Sys.chmod(to[okay], fi$mode, TRUE)
if (copy.date)
Sys.setFileTime(to[okay], fi$mtime)
}
}
}
okay
}
file.info <- function (...)
{
res <- .Internal(file.info(fn <- c(...)))
res$mtime <- .POSIXct(res$mtime)
res$ctime <- .POSIXct(res$ctime)
res$atime <- .POSIXct(res$atime)
class(res) <- "data.frame"
attr(res, "row.names") <- fn
res
}
## @type to : character
## @type from : character
file.link <- function (from, to)
{
if (!(length(from)))
stop("no files to link from")
if (!(nt <- length(to)))
stop("no files to link to")
.Internal(file.link(from, to))
}
file.path <- function (..., fsep = .Platform$file.sep)
.Internal(file.path(list(...), fsep))
## @type encoding : character
## @type header : complex|character
file.show <- function (..., header = rep("", nfiles), title = "R Information",
delete.file = FALSE, pager = getOption("pager"), encoding = "")
{
files <- path.expand(c(...))
nfiles <- length(files)
if (nfiles == 0L)
return(invisible(NULL))
if (l10n_info()[["UTF-8"]] && encoding == "UTF-8")
encoding <- ""
if (l10n_info()[["Latin-1"]] && encoding == "latin1")
encoding <- ""
if (!is.na(encoding) && encoding != "") {
for (i in seq_along(files)) {
f <- files[i]
tf <- tempfile()
tmp <- readLines(f, warn = FALSE)
tmp2 <- try(iconv(tmp, encoding, "", "byte"))
if (inherits(tmp2, "try-error"))
file.copy(f, tf)
else writeLines(tmp2, tf)
files[i] <- tf
if (delete.file)
unlink(f)
}
delete.file <- TRUE
}
if (is.function(pager))
pager(files, header = header, title = title, delete.file = delete.file)
else .Internal(file.show(files, header, title, delete.file,
pager))
}
"formals<-" <- function (fun, envir = environment(fun), value)
{
bd <- body(fun)
as.function(c(value, if (is.null(bd) || is.list(bd)) list(bd) else bd),
envir)
}
## @type on : logical
gctorture <- function (on = TRUE)
.Internal(gctorture(on))
## @type x : character
getOption <- function (x, default = NULL)
{
if (missing(default))
return(options(x)[[1L]])
if (x %in% names(options()))
options(x)[[1L]]
else default
}
globalenv <- function () .Primitive("globalenv")
iconvlist <- function ()
{
int <- .Internal(iconv(NULL, "", "", "", TRUE, FALSE))
if (length(int))
return(sort.int(int))
icfile <- system.file("iconvlist", package = "utils")
if (!nchar(icfile, type = "bytes"))
stop("'iconvlist' is not available on this system")
ext <- readLines(icfile)
if (!length(ext))
stop("'iconvlist' is not available on this system")
cnt <- grep("//$", ext)
if (length(cnt)/length(ext) > 0.5) {
ext <- grep("//$", ext, value = TRUE)
ext <- sub("//$", "", ext)
}
sort.int(unlist(strsplit(ext, "[[:space:]]")))
}
## @type num.eq : complex|logical
## @type attrib.as.set : logical
## @type ignore.environment : logical
## @type single.NA : numeric|logical
## @type ignore.bytecode : logical
## @return logical
identical <- function (x, y, num.eq = TRUE, single.NA = TRUE, attrib.as.set = TRUE,
ignore.bytecode = TRUE, ignore.environment = FALSE)
.Internal(identical(x, y, num.eq, single.NA, attrib.as.set, ignore.bytecode,
ignore.environment))
## @optional x
intersect <- function (x, y)
{
y <- as.vector(y)
unique(y[match(as.vector(x), y, 0L)])
}
intToBits <- function (x)
.Internal(intToBits(x))
## @type multiple : logical|character
## @return complex|character
intToUtf8 <- function (x, multiple = FALSE)
.Internal(intToUtf8(x, multiple))
invisible <- function (x) .Primitive("invisible")
is.atomic <- function (x) .Primitive("is.atomic")
is.double <- function (x) .Primitive("is.double")
is.factor <- function (x)
inherits(x, "factor")
is.finite <- function (x) .Primitive("is.finite")
## @type PACKAGE : character
## @type symbol : character
is.loaded <- function (symbol, PACKAGE = "", type = "")
.Internal(is.loaded(symbol, PACKAGE, type))
is.matrix <- function (x) .Primitive("is.matrix")
is.object <- function (x) .Primitive("is.object")
is.single <- function (x) .Primitive("is.single")
is.symbol <- function (x) .Primitive("is.symbol")
## @type mode : character
is.vector <- function (x, mode = "any")
.Internal(is.vector(x, mode))
isRestart <- function (x)
inherits(x, "restart")
l10n_info <- function ()
.Internal(l10n_info())
## @type path : character
## @type full.names : logical
## @type recursive : logical
## @return character
list.dirs <- function (path = ".", full.names = TRUE, recursive = TRUE)
.Internal(list.dirs(path, full.names, recursive))
## @type diag : logical
lower.tri <- function (x, diag = FALSE)
{
x <- as.matrix(x)
if (diag)
row(x) >= col(x)
else row(x) > col(x)
}
## @type choices : character
## @type several.ok : logical
## @type arg : character
match.arg <- function (arg, choices, several.ok = FALSE)
{
if (missing(choices)) {
formal.args <- formals(sys.function(sys.parent()))
choices <- eval(formal.args[[deparse(substitute(arg))]])
}
if (is.null(arg))
return(choices[1L])
else if (!is.character(arg))
stop("'arg' must be NULL or a character vector")
if (!several.ok) {
if (identical(arg, choices))
return(arg[1L])
if (length(arg) > 1L)
stop("'arg' must be of length 1")
}
else if (length(arg) == 0L)
stop("'arg' must be of length >= 1")
i <- pmatch(arg, choices, nomatch = 0L, duplicates.ok = TRUE)
if (all(i == 0L))
stop(gettextf("'arg' should be one of %s", paste(dQuote(choices),
collapse = ", ")), domain = NA)
i <- i[i > 0L]
if (!several.ok && length(i) > 1)
stop("there is more than one match in 'match.arg'")
choices[i]
}
## @type FUN : character
## @type descend : logical
match.fun <- function (FUN, descend = TRUE)
{
if (is.function(FUN))
return(FUN)
if (!(is.character(FUN) && length(FUN) == 1L || is.symbol(FUN))) {
FUN <- eval.parent(substitute(substitute(FUN)))
if (!is.symbol(FUN))
stop(gettextf("'%s' is not a function, character or symbol",
deparse(FUN)), domain = NA)
}
envir <- parent.frame(2)
if (descend)
FUN <- get(as.character(FUN), mode = "function", envir = envir)
else {
FUN <- get(as.character(FUN), mode = "any", envir = envir)
if (!is.function(FUN))
stop(gettextf("found non-function '%s'", FUN), domain = NA)
}
return(FUN)
}
Math.Date <- function (x, ...)
stop(gettextf("%s not defined for \"Date\" objects", .Generic),
domain = NA)
mean.Date <- function (x, ...)
structure(mean(unclass(x), ...), class = "Date")
## @type x : complex|character
## @type is.cmplx : complex|logical|character
## @type drop0trailing : logical
## @type preserve.width : character
## @type decimal.mark : numeric|character
## @type big.mark : character
## @type small.mark : character
## @type zero.print : logical|character
## @return complex|character
prettyNum <- function (x, big.mark = "", big.interval = 3L, small.mark = "",
small.interval = 5L, decimal.mark = ".", preserve.width = c("common",
"individual", "none"), zero.print = NULL, drop0trailing = FALSE,
is.cmplx = NA, ...)
{
if (!is.character(x)) {
is.cmplx <- is.complex(x)
x <- sapply(X = x, FUN = format, ...)
}
nMark <- big.mark == "" && small.mark == "" && decimal.mark ==
"."
nZero <- is.null(zero.print) && !drop0trailing
if (nMark && nZero)
return(x)
if (!is.null(zero.print) && any(i0 <- as.numeric(x) == 0)) {
if (length(zero.print) > 1L)
stop("'zero.print' has length > 1")
if (is.logical(zero.print))
zero.print <- if (zero.print)
"0"
else " "
if (!is.character(zero.print))
stop("'zero.print' must be character, logical or NULL")
blank.chars <- function(no) vapply(no + 1L, function(n) paste(character(n),
collapse = " "), "")
nz <- nchar(zero.print, "c")
nc <- nchar(x[i0], "c")
ind0 <- regexpr("0", x[i0], fixed = TRUE)
substr(x[i0], ind0, (i1 <- ind0 + nz - 1L)) <- zero.print
substr(x[i0], ind0 + nz, nc) <- blank.chars(nc - i1)
}
if (nMark && !drop0trailing)
return(x)
if (is.na(is.cmplx)) {
ina <- is.na(x) | x == "NA"
is.cmplx <- if (all(ina))
FALSE
else length(grep("[0-9].*[-+][0-9].*i$", x)) > 0
}
if (is.cmplx) {
z.sp <- strsplit(sub("([0-9] *)([-+])( *[0-9])", "\\1::\\2::\\3",
x), "::", fixed = TRUE)
i3 <- vapply(z.sp, length, 0L) == 3L
if (any(i3)) {
z.sp <- z.sp[i3]
z.im <- sapply(z.sp, `[[`, 3L)
has.i <- grep("i$", z.im)
z.im[has.i] <- sub("i$", "", z.im[has.i])
r <- lapply(list(sapply(z.sp, `[[`, 1L), z.im), function(.) prettyNum(.,
big.mark = big.mark, big.interval = big.interval,
small.mark = small.mark, small.interval = small.interval,
decimal.mark = decimal.mark, preserve.width = preserve.width,
zero.print = zero.print, drop0trailing = drop0trailing,
is.cmplx = FALSE, ...))
r[[2]][has.i] <- paste0(r[[2]][has.i], "i")
x[i3] <- paste0(r[[1]], sapply(z.sp, `[[`, 2L), r[[2]])
}
return(x)
}
preserve.width <- match.arg(preserve.width)
x.sp <- strsplit(x, ".", fixed = TRUE)
revStr <- function(cc) sapply(lapply(strsplit(cc, NULL),
rev), paste, collapse = "")
B. <- sapply(x.sp, `[`, 1L)
A. <- sapply(x.sp, `[`, 2)
if (any(iN <- is.na(A.)))
A.[iN] <- ""
if (nzchar(big.mark) && length(i.big <- grep(paste0("[0-9]{",
big.interval + 1L, ",}"), B.))) {
B.[i.big] <- revStr(gsub(paste0("([0-9]{", big.interval,
"})\\B"), paste0("\\1", revStr(big.mark)), revStr(B.[i.big])))
}
if (nzchar(small.mark) && length(i.sml <- grep(paste0("[0-9]{",
small.interval + 1L, ",}"), A.))) {
A.[i.sml] <- gsub(paste0("([0-9]{", small.interval, "}\\B)"),
paste0("\\1", small.mark), A.[i.sml])
}
if (drop0trailing) {
a <- A.[!iN]
if (length(hasE <- grep("e", a, fixed = TRUE))) {
a[hasE] <- sub("e[+-]0+$", "", a[hasE])
a[-hasE] <- sub("0+$", "", a[-hasE])
}
else a <- sub("0+$", "", a)
A.[!iN] <- a
iN <- !nzchar(A.)
}
A. <- paste0(B., c(decimal.mark, "")[iN + 1L], A.)
if (preserve.width != "none") {
nnc <- nchar(A., "c")
d.len <- nnc - nchar(x, "c")
if (any(ii <- d.len > 0L)) {
switch(preserve.width, individual = {
A.[ii] <- sapply(which(ii), function(i) sub(sprintf("^ {1,%d}",
d.len[i]), "", A.[i]))
}, common = {
A. <- format(A., justify = "right")
})
}
}
attributes(A.) <- attributes(x)
class(A.) <- NULL
A.
}
## @type prefix : character
## @type digits : complex
print.rle <- function (x, digits = getOption("digits"), prefix = "", ...)
{
if (is.null(digits))
digits <- getOption("digits")
cat("", "Run Length Encoding\n", " lengths:", sep = prefix)
utils::str(x$lengths)
cat("", " values :", sep = prefix)
utils::str(x$values, digits.d = digits)
invisible(x)
}
proc.time <- function () .Primitive("proc.time")
qr.fitted <- function (qr, y, k = qr$rank)
{
if (!is.qr(qr))
stop("argument is not a QR decomposition")
if (is.complex(qr$qr))
stop("not implemented for complex 'qr'")
if (isTRUE(attr(qr, "useLAPACK")))
stop("not supported for LAPACK QR")
n <- as.integer(nrow(qr$qr))
if (is.na(n))
stop("invalid nrow(qr$qr)")
k <- as.integer(k)
if (k > qr$rank)
stop("'k' is too large")
ny <- as.integer(NCOL(y))
if (is.na(ny))
stop("invalid NCOL(y)")
if (NROW(y) != n)
stop("'qr' and 'y' must have the same number of rows")
storage.mode(y) <- "double"
.Fortran(.F_dqrxb, as.double(qr$qr), n, k, as.double(qr$qraux),
y, ny, xb = y)$xb
}
R.Version <- function ()
.Internal(Version())
rawToBits <- function (x)
.Internal(rawToBits(x))
## @type multiple : logical|character
## @return raw|numeric|character
rawToChar <- function (x, multiple = FALSE)
.Internal(rawToChar(x, multiple))
## @type n : complex
## @type encoding : character
## @type warn : logical
## @type skipNul : logical
## @type con : character
## @type ok : logical
readLines <- function (con = stdin(), n = -1L, ok = TRUE, warn = TRUE, encoding = "unknown",
skipNul = FALSE)
{
if (is.character(con)) {
con <- file(con, "r")
on.exit(close(con))
}
.Internal(readLines(con, n, ok, warn, encoding, skipNul))
}
## @type n : complex
## @type simplify : logical|character
replicate <- function (n, expr, simplify = "array")
sapply(integer(n), eval.parent(substitute(function(...) expr)),
simplify = simplify)
row.names <- function (x)
UseMethod("row.names")
seq_along <- function (along.with) .Primitive("seq_along")
## @type connection : raw
## @type xdr : logical
## @type ascii : logical
## @return raw
serialize <- function (object, connection, ascii = FALSE, xdr = TRUE, version = NULL,
refhook = NULL)
{
if (!is.null(connection)) {
if (!inherits(connection, "connection"))
stop("'connection' must be a connection")
if (missing(ascii))
ascii <- summary(connection)$text == "text"
}
if (!ascii && inherits(connection, "sockconn"))
.Internal(serializeb(object, connection, xdr, version,
refhook))
else {
if (!isTRUE(ascii) && !xdr)
ascii <- NA
.Internal(serialize(object, connection, ascii, version,
refhook))
}
}
## @type decreasing : logical
sort.list <- function (x, partial = NULL, na.last = TRUE, decreasing = FALSE,
method = c("shell", "quick", "radix"))
{
if (missing(method) && is.factor(x) && nlevels(x) < 1e+05)
method <- "radix"
method <- match.arg(method)
if (!is.atomic(x))
stop("'x' must be atomic for 'sort.list'\nHave you called 'sort' on a list?")
if (!is.null(partial))
.NotYetUsed("partial != NULL")
if (method == "quick") {
if (is.factor(x))
x <- as.integer(x)
if (is.numeric(x))
return(sort(x, na.last = na.last, decreasing = decreasing,
method = "quick", index.return = TRUE)$ix)
else stop("method = \"quick\" is only for numeric 'x'")
}
if (method == "radix") {
if (!typeof(x) == "integer")
stop("method = \"radix\" is only for integer 'x'")
if (is.na(na.last))
return(.Internal(radixsort(x[!is.na(x)], TRUE, decreasing)))
else return(.Internal(radixsort(x, na.last, decreasing)))
}
if (is.na(na.last))
.Internal(order(TRUE, decreasing, x[!is.na(x)]))
else .Internal(order(na.last, decreasing, x))
}
stopifnot <- function (...)
{
n <- length(ll <- list(...))
if (n == 0L)
return(invisible())
mc <- match.call()
for (i in 1L:n) if (!(is.logical(r <- ll[[i]]) && !anyNA(r) &&
all(r))) {
ch <- deparse(mc[[i + 1]], width.cutoff = 60L)
if (length(ch) > 1L)
ch <- paste(ch[1L], "....")
stop(sprintf(ngettext(length(r), "%s is not TRUE", "%s are not all TRUE"),
ch), call. = FALSE, domain = NA)
}
invisible()
}
structure <- function (.Data, ...)
{
attrib <- list(...)
if (length(attrib)) {
specials <- c(".Dim", ".Dimnames", ".Names", ".Tsp",
".Label")
replace <- c("dim", "dimnames", "names", "tsp", "levels")
m <- match(names(attrib), specials)
ok <- (!is.na(m) & m)
names(attrib)[ok] <- replace[m[ok]]
if ("factor" %in% attrib[["class", exact = TRUE]] &&
typeof(.Data) == "double")
storage.mode(.Data) <- "integer"
attributes(.Data) <- c(attributes(.Data), attrib)
}
return(.Data)
}
## @return character
substring <- function (text, first, last = 1000000L)
{
if (!is.character(text))
text <- as.character(text)
n <- max(lt <- length(text), length(first), length(last))
if (lt && lt < n)
text <- rep_len(text, length.out = n)
.Internal(substr(text, as.integer(first), as.integer(last)))
}
sys.calls <- function ()
.Internal(sys.calls())
## @type paths : character
## @type use_umask : logical
Sys.chmod <- function (paths, mode = "0777", use_umask = TRUE)
.Internal(Sys.chmod(paths, as.octmode(mode), use_umask))
sys.frame <- function (which = 0L)
.Internal(sys.frame(which))
Sys.sleep <- function (time)
.Internal(Sys.sleep(time))
Sys.umask <- function (mode = NA)
.Internal(Sys.umask(if (is.na(mode)) NA_integer_ else as.octmode(mode)))
Sys.which <- function (names)
{
res <- character(length(names))
names(res) <- names
which <- "/usr/bin/which"
if (!nzchar(which)) {
warning("'which' was not found on this platform")
return(res)
}
for (i in seq_along(names)) {
if (is.na(names[i])) {
res[i] <- NA
next
}
ans <- suppressWarnings(system(paste(which, shQuote(names[i])),
intern = TRUE, ignore.stderr = TRUE))
if (grepl("solaris", R.version$os)) {
tmp <- strsplit(ans[1], " ", fixed = TRUE)[[1]]
if (identical(tmp[1:3], c("no", i, "in")))
ans <- ""
}
res[i] <- if (length(ans))
ans[1]
else ""
if (!file.exists(res[i]))
res[i] <- ""
}
res
}
t.default <- function (x)
.Internal(t.default(x))
## @type max.lines : complex
## @type x : integer
traceback <- function (x = NULL, max.lines = getOption("deparse.max.lines"))
{
if (is.null(x) && (exists(".Traceback", envir = baseenv())))
x <- get(".Traceback", envir = baseenv())
else if (is.numeric(x))
x <- .Internal(traceback(x))
n <- length(x)
if (n == 0L)
cat(gettext("No traceback available"), "\n")
else {
for (i in 1L:n) {
label <- paste0(n - i + 1L, ": ")
m <- length(x[[i]])
if (!is.null(srcref <- attr(x[[i]], "srcref"))) {
srcfile <- attr(srcref, "srcfile")
x[[i]][m] <- paste0(x[[i]][m], " at ", basename(srcfile$filename),
"#", srcref[1L])
}
if (m > 1)
label <- c(label, rep(substr(" ", 1L,
nchar(label, type = "w")), m - 1L))
if (is.numeric(max.lines) && max.lines > 0L && max.lines <
m) {
cat(paste0(label[1L:max.lines], x[[i]][1L:max.lines]),
sep = "\n")
cat(label[max.lines + 1L], " ...\n")
}
else cat(paste0(label, x[[i]]), sep = "\n")
}
}
invisible(x)
}
transform <- function (`_data`, ...)
UseMethod("transform")
unix.time <- function (expr, gcFirst = TRUE)
{
ppt <- function(y) {
if (!is.na(y[4L]))
y[1L] <- y[1L] + y[4L]
if (!is.na(y[5L]))
y[2L] <- y[2L] + y[5L]
y[1L:3L]
}
if (!exists("proc.time"))
return(rep(NA_real_, 5L))
if (gcFirst)
gc(FALSE)
time <- proc.time()
on.exit(cat("Timing stopped at:", ppt(proc.time() - time),
"\n"))
expr
new.time <- proc.time()
on.exit()
structure(new.time - time, class = "proc_time")
}
## @type diag : logical
upper.tri <- function (x, diag = FALSE)
{
x <- as.matrix(x)
if (diag)
row(x) <= col(x)
else row(x) < col(x)
}
## @type generic : character
UseMethod <- function (generic, object) .Primitive("UseMethod")
utf8ToInt <- function (x)
.Internal(utf8ToInt(x))
## @type SIMPLIFY : logical|character
## @type USE.NAMES : logical|character
## @type vectorize.args : character
## @return function
Vectorize <- function (FUN, vectorize.args = arg.names, SIMPLIFY = TRUE, USE.NAMES = TRUE)
{
arg.names <- as.list(formals(FUN))
arg.names[["..."]] <- NULL
arg.names <- names(arg.names)
vectorize.args <- as.character(vectorize.args)
if (!length(vectorize.args))
return(FUN)
if (!all(vectorize.args %in% arg.names))
stop("must specify names of formal arguments for 'vectorize'")
FUNV <- function() {
args <- lapply(as.list(match.call())[-1L], eval, parent.frame())
names <- if (is.null(names(args)))
character(length(args))
else names(args)
dovec <- names %in% vectorize.args
do.call("mapply", c(FUN = FUN, args[dovec], MoreArgs = list(args[!dovec]),
SIMPLIFY = SIMPLIFY, USE.NAMES = USE.NAMES))
}
formals(FUNV) <- formals(FUN)
FUNV
}
## @type x : numeric
## @return integer
which.max <- function (x)
.Internal(which.max(x))
## @type x : numeric
## @return integer
which.min <- function (x)
.Internal(which.min(x))
## @type keep.white : character
## @type indent : integer
## @type width : integer
## @type file : character
## @type append : logical|character
write.dcf <- function (x, file = "", append = FALSE, indent = 0.1 * getOption("width"),
width = 0.9 * getOption("width"), keep.white = NULL)
{
if (file == "")
file <- stdout()
else if (is.character(file)) {
file <- file(file, ifelse(append, "a", "w"))
on.exit(close(file))
}
if (!inherits(file, "connection"))
stop("'file' must be a character string or connection")
escape_paragraphs <- function(s) gsub("\n \\.([^\n])", "\n .\\1",
gsub("\n[ \t]*\n", "\n .\n ", s, perl = TRUE, useBytes = TRUE),
perl = TRUE, useBytes = TRUE)
fmt <- function(tag, val, fold = TRUE) {
s <- if (fold)
formatDL(rep.int(tag, length(val)), val, style = "list",
width = width, indent = indent)
else {
sprintf("%s: %s", tag, gsub("\n([^[:blank:]])", "\n \\1",
val))
}
escape_paragraphs(s)
}
if (!is.data.frame(x))
x <- as.data.frame(x, stringsAsFactors = FALSE)
nmx <- names(x)
out <- matrix("", nrow(x), ncol(x))
foldable <- is.na(match(nmx, keep.white))
for (j in seq_along(x)) {
xj <- x[[j]]
if (is.atomic(xj)) {
i <- !is.na(xj)
out[i, j] <- fmt(nmx[j], xj[i], foldable[j])
}
else {
nmxj <- nmx[j]
fold <- foldable[j]
i <- !vapply(xj, function(s) (length(s) == 1L) &&
is.na(s), NA)
out[i, j] <- vapply(xj[i], function(s) {
paste(fmt(nmxj, s, fold), collapse = "\n")
}, "")
}
}
out <- t(out)
is_not_empty <- c(out != "")
eor <- character(sum(is_not_empty))
if (length(eor)) {
eor[diff(c(col(out))[is_not_empty]) >= 1L] <- "\n"
}
writeLines(paste0(c(out[is_not_empty]), eor), file)
}
## @type nchars : integer|character
## @type object : character
## @type eos : character
## @type con : raw|character
## @type useBytes : complex|logical
writeChar <- function (object, con, nchars = nchar(object, type = "chars"),
eos = "", useBytes = FALSE)
{
if (!is.character(object))
stop("can only write character objects")
if (is.character(con)) {
con <- file(con, "wb")
on.exit(close(con))
}
.Internal(writeChar(object, con, as.integer(nchars), eos,
useBytes))
}
"|.hexmode" <- function (a, b)
as.hexmode(bitwOr(as.hexmode(a), as.hexmode(b)))
"|.octmode" <- function (a, b)
as.octmode(bitwOr(as.octmode(a), as.octmode(b)))
"*.difftime" <- function (e1, e2)
{
if (inherits(e1, "difftime") && inherits(e2, "difftime"))
stop("both arguments of * cannot be \"difftime\" objects")
if (inherits(e2, "difftime")) {
tmp <- e1
e1 <- e2
e2 <- tmp
}
.difftime(e2 * unclass(e1), attr(e1, "units"))
}
"[.difftime" <- function (x, ..., drop = TRUE)
{
cl <- oldClass(x)
class(x) <- NULL
val <- NextMethod("[")
class(val) <- cl
attr(val, "units") <- attr(x, "units")
val
}
"[.warnings" <- function (x, ...)
structure(NextMethod("["), class = "warnings")
## @type value : character
"[<-.factor" <- function (x, ..., value)
{
lx <- levels(x)
cx <- oldClass(x)
if (is.factor(value))
value <- levels(value)[value]
m <- match(value, lx)
if (any(is.na(m) & !is.na(value)))
warning("invalid factor level, NA generated")
class(x) <- NULL
x[...] <- m
attr(x, "levels") <- lx
class(x) <- cx
x
}
"[[.POSIXct" <- function (x, ..., drop = TRUE)
{
cl <- oldClass(x)
class(x) <- NULL
val <- NextMethod("[[")
class(val) <- cl
attr(val, "tzone") <- attr(x, "tzone")
val
}
## @type dot : logical
## @type method : character
## @type use.classes : logical
## @type names.arg : character
## @type strict : logical
## @return character
abbreviate <- function (names.arg, minlength = 4L, use.classes = TRUE, dot = FALSE,
strict = FALSE, method = c("left.kept", "both.sides"))
{
if (minlength <= 0L)
return(rep.int("", length(names.arg)))
names.arg <- sub("^ +", "", sub(" +$", "", as.character(names.arg)))
dups <- duplicated(names.arg)
old <- names.arg
if (any(dups))
names.arg <- names.arg[!dups]
x <- names.arg
if (strict) {
x[] <- .Internal(abbreviate(x, minlength, use.classes))
}
else {
method <- match.arg(method)
if (method == "both.sides")
chRev <- function(x) sapply(lapply(strsplit(x, NULL),
rev), paste, collapse = "")
dup2 <- rep.int(TRUE, length(names.arg))
these <- names.arg
repeat {
ans <- .Internal(abbreviate(these, minlength, use.classes))
x[dup2] <- ans
if (!any(dup2 <- duplicated(x)))
break
if (method == "both.sides") {
x[dup2] <- chRev(.Internal(abbreviate(chRev(names.arg[dup2]),
minlength, use.classes)))
if (!any(dup2 <- duplicated(x)))
break
}
minlength <- minlength + 1
dup2 <- dup2 | match(x, x[dup2], 0L)
these <- names.arg[dup2]
}
}
if (any(dups))
x <- x[match(old, names.arg)]
if (dot) {
chgd <- x != old
x[chgd] <- paste0(x[chgd], ".")
}
names(x) <- old
x
}
## @type x : complex
as.complex <- function (x, ...) .Primitive("as.complex")
as.hexmode <- function (x)
{
if (inherits(x, "hexmode"))
return(x)
if (is.double(x) && (x == as.integer(x)))
x <- as.integer(x)
if (is.integer(x))
return(structure(x, class = "hexmode"))
if (is.character(x)) {
z <- strtoi(x, 16L)
if (!any(is.na(z) | z < 0))
return(structure(z, class = "hexmode"))
}
stop("'x' cannot be coerced to class \"hexmode\"")
}
as.integer <- function (x, ...) .Primitive("as.integer")
as.logical <- function (x, ...) .Primitive("as.logical")
as.numeric <- function (x, ...) .Primitive("as.double")
as.octmode <- function (x)
{
if (inherits(x, "octmode"))
return(x)
if (is.double(x) && x == as.integer(x))
x <- as.integer(x)
if (is.integer(x))
return(structure(x, class = "octmode"))
if (is.character(x)) {
z <- strtoi(x, 8L)
if (!any(is.na(z) | z < 0))
return(structure(z, class = "octmode"))
}
stop("'x' cannot be coerced to class \"octmode\"")
}
as.ordered <- function (x)
if (is.ordered(x)) x else ordered(x)
as.POSIXct <- function (x, tz = "", ...)
UseMethod("as.POSIXct")
as.POSIXlt <- function (x, tz = "", ...)
UseMethod("as.POSIXlt")
attributes <- function (obj) .Primitive("attributes")
autoloader <- function (name, package, ...)
{
name <- paste0(name, "")
rm(list = name, envir = .AutoloadEnv, inherits = FALSE)
m <- match.call()
m$name <- NULL
m[[1L]] <- as.name("library")
eval(m, .GlobalEnv)
autoload(name, package, reset = TRUE, ...)
where <- match(paste("package", package, sep = ":"), search())
if (exists(name, where = where, inherits = FALSE))
eval(as.name(name), as.environment(where))
else stop(gettextf("autoloader did not find '%s' in '%s'",
name, package), domain = NA)
}
## @type a : numeric
## @type n : integer
bitwShiftL <- function (a, n)
.Internal(bitwiseShiftL(a, n))
## @type n : integer
## @type a : numeric
## @return integer
bitwShiftR <- function (a, n)
.Internal(bitwiseShiftR(a, n))
## @type simplify : logical
by.default <- function (data, INDICES, FUN, ..., simplify = TRUE)
{
dd <- as.data.frame(data)
if (length(dim(data)))
by(dd, INDICES, FUN, ..., simplify = simplify)
else {
if (!is.list(INDICES)) {
IND <- vector("list", 1L)
IND[[1L]] <- INDICES
names(IND) <- deparse(substitute(INDICES))[1L]
}
else IND <- INDICES
FUNx <- function(x) FUN(dd[x, ], ...)
nd <- nrow(dd)
structure(eval(substitute(tapply(seq_len(nd), IND, FUNx,
simplify = simplify)), dd), call = match.call(),
class = "by")
}
}
## @type value : character
"colnames<-" <- function (x, value)
{
if (is.data.frame(x)) {
names(x) <- value
}
else {
dn <- dimnames(x)
if (is.null(dn)) {
if (is.null(value))
return(x)
if ((nd <- length(dim(x))) < 2L)
stop("attempt to set 'colnames' on an object with less than two dimensions")
dn <- vector("list", nd)
}
if (length(dn) < 2L)
stop("attempt to set 'colnames' on an object with less than two dimensions")
if (is.null(value))
dn[2L] <- list(NULL)
else dn[[2L]] <- value
dimnames(x) <- dn
}
x
}
## @type breaks : complex
## @type start.on.monday : logical
## @type labels : integer
cut.POSIXt <- function (x, breaks, labels = NULL, start.on.monday = TRUE, right = FALSE,
...)
{
if (!inherits(x, "POSIXt"))
stop("'x' must be a date-time object")
x <- as.POSIXct(x)
if (inherits(breaks, "POSIXt")) {
breaks <- sort(as.POSIXct(breaks))
}
else if (is.numeric(breaks) && length(breaks) == 1L) {
}
else if (is.character(breaks) && length(breaks) == 1L) {
by2 <- strsplit(breaks, " ", fixed = TRUE)[[1L]]
if (length(by2) > 2L || length(by2) < 1L)
stop("invalid specification of 'breaks'")
valid <- pmatch(by2[length(by2)], c("secs", "mins", "hours",
"days", "weeks", "months", "years", "DSTdays", "quarters"))
if (is.na(valid))
stop("invalid specification of 'breaks'")
start <- as.POSIXlt(min(x, na.rm = TRUE))
incr <- 1
if (valid > 1L) {
start$sec <- 0L
incr <- 60
}
if (valid > 2L) {
start$min <- 0L
incr <- 3600
}
if (valid > 3L) {
start$hour <- 0L
start$isdst <- -1L
incr <- 86400
}
if (valid == 5L) {
start$mday <- start$mday - start$wday
if (start.on.monday)
start$mday <- start$mday + ifelse(start$wday >
0L, 1L, -6L)
incr <- 7 * 86400
}
if (valid == 8L)
incr <- 25 * 3600
if (valid == 6L) {
start$mday <- 1L
end <- as.POSIXlt(max(x, na.rm = TRUE))
step <- ifelse(length(by2) == 2L, as.integer(by2[1L]),
1L)
end <- as.POSIXlt(end + (31 * step * 86400))
end$mday <- 1L
end$isdst <- -1L
breaks <- seq(start, end, breaks)
}
else if (valid == 7L) {
start$mon <- 0L
start$mday <- 1L
end <- as.POSIXlt(max(x, na.rm = TRUE))
step <- ifelse(length(by2) == 2L, as.integer(by2[1L]),
1L)
end <- as.POSIXlt(end + (366 * step * 86400))
end$mon <- 0L
end$mday <- 1L
end$isdst <- -1L
breaks <- seq(start, end, breaks)
}
else if (valid == 9L) {
qtr <- rep(c(0L, 3L, 6L, 9L), each = 3L)
start$mon <- qtr[start$mon + 1L]
start$mday <- 1L
maxx <- max(x, na.rm = TRUE)
end <- as.POSIXlt(maxx)
step <- ifelse(length(by2) == 2L, as.integer(by2[1L]),
1L)
end <- as.POSIXlt(end + (93 * step * 86400))
end$mon <- qtr[end$mon + 1L]
end$mday <- 1L
end$isdst <- -1L
breaks <- seq(start, end, paste(step * 3, "months"))
lb <- length(breaks)
if (maxx < breaks[lb - 1])
breaks <- breaks[-lb]
}
else {
if (length(by2) == 2L)
incr <- incr * as.integer(by2[1L])
maxx <- max(x, na.rm = TRUE)
breaks <- seq(start, maxx + incr, breaks)
breaks <- breaks[seq_len(1 + max(which(breaks <=
maxx)))]
}
}
else stop("invalid specification of 'breaks'")
res <- cut(unclass(x), unclass(breaks), labels = labels,
right = right, ...)
if (is.null(labels)) {
levels(res) <- as.character(if (is.numeric(breaks)) x[!duplicated(res)] else breaks[-length(breaks)])
}
res
}
data.class <- function (x)
{
if (length(cl <- oldClass(x)))
cl[1L]
else {
l <- length(dim(x))
if (l == 2L)
"matrix"
else if (l)
"array"
else mode(x)
}
}
## @type stringsAsFactors : logical|character
## @type row.names : integer|character
## @type check.names : logical
data.frame <- function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,
stringsAsFactors = default.stringsAsFactors())
{
data.row.names <- if (check.rows && is.null(row.names))
function(current, new, i) {
if (is.character(current))
new <- as.character(new)
if (is.character(new))
current <- as.character(current)
if (anyDuplicated(new))
return(current)
if (is.null(current))
return(new)
if (all(current == new) || all(current == ""))
return(new)
stop(gettextf("mismatch of row names in arguments of 'data.frame', item %d",
i), domain = NA)
}
else function(current, new, i) {
if (is.null(current)) {
if (anyDuplicated(new)) {
warning(gettextf("some row.names duplicated: %s --> row.names NOT used",
paste(which(duplicated(new)), collapse = ",")),
domain = NA)
current
}
else new
}
else current
}
object <- as.list(substitute(list(...)))[-1L]
mirn <- missing(row.names)
mrn <- is.null(row.names)
x <- list(...)
n <- length(x)
if (n < 1L) {
if (!mrn) {
if (is.object(row.names) || !is.integer(row.names))
row.names <- as.character(row.names)
if (anyNA(row.names))
stop("row names contain missing values")
if (anyDuplicated(row.names))
stop(gettextf("duplicate row.names: %s", paste(unique(row.names[duplicated(row.names)]),
collapse = ", ")), domain = NA)
}
else row.names <- integer()
return(structure(list(), names = character(), row.names = row.names,
class = "data.frame"))
}
vnames <- names(x)
if (length(vnames) != n)
vnames <- character(n)
no.vn <- !nzchar(vnames)
vlist <- vnames <- as.list(vnames)
nrows <- ncols <- integer(n)
for (i in seq_len(n)) {
xi <- if (is.character(x[[i]]) || is.list(x[[i]]))
as.data.frame(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors)
else as.data.frame(x[[i]], optional = TRUE)
nrows[i] <- .row_names_info(xi)
ncols[i] <- length(xi)
namesi <- names(xi)
if (ncols[i] > 1L) {
if (length(namesi) == 0L)
namesi <- seq_len(ncols[i])
if (no.vn[i])
vnames[[i]] <- namesi
else vnames[[i]] <- paste(vnames[[i]], namesi, sep = ".")
}
else {
if (length(namesi))
vnames[[i]] <- namesi
else if (no.vn[[i]]) {
tmpname <- deparse(object[[i]])[1L]
if (substr(tmpname, 1L, 2L) == "I(") {
ntmpn <- nchar(tmpname, "c")
if (substr(tmpname, ntmpn, ntmpn) == ")")
tmpname <- substr(tmpname, 3L, ntmpn - 1L)
}
vnames[[i]] <- tmpname
}
}
if (mirn && nrows[i] > 0L) {
rowsi <- attr(xi, "row.names")
nc <- nchar(rowsi, allowNA = FALSE)
nc <- nc[!is.na(nc)]
if (length(nc) && any(nc))
row.names <- data.row.names(row.names, rowsi,
i)
}
nrows[i] <- abs(nrows[i])
vlist[[i]] <- xi
}
nr <- max(nrows)
for (i in seq_len(n)[nrows < nr]) {
xi <- vlist[[i]]
if (nrows[i] > 0L && (nr%%nrows[i] == 0L)) {
xi <- unclass(xi)
fixed <- TRUE
for (j in seq_along(xi)) {
xi1 <- xi[[j]]
if (is.vector(xi1) || is.factor(xi1))
xi[[j]] <- rep(xi1, length.out = nr)
else if (is.character(xi1) && inherits(xi1, "AsIs"))
xi[[j]] <- structure(rep(xi1, length.out = nr),
class = class(xi1))
else if (inherits(xi1, "Date") || inherits(xi1,
"POSIXct"))
xi[[j]] <- rep(xi1, length.out = nr)
else {
fixed <- FALSE
break
}
}
if (fixed) {
vlist[[i]] <- xi
next
}
}
stop(gettextf("arguments imply differing number of rows: %s",
paste(unique(nrows), collapse = ", ")), domain = NA)
}
value <- unlist(vlist, recursive = FALSE, use.names = FALSE)
vnames <- unlist(vnames[ncols > 0L])
noname <- !nzchar(vnames)
if (any(noname))
vnames[noname] <- paste("Var", seq_along(vnames), sep = ".")[noname]
if (check.names)
vnames <- make.names(vnames, unique = TRUE)
names(value) <- vnames
if (!mrn) {
if (length(row.names) == 1L && nr != 1L) {
if (is.character(row.names))
row.names <- match(row.names, vnames, 0L)
if (length(row.names) != 1L || row.names < 1L ||
row.names > length(vnames))
stop("'row.names' should specify one of the variables")
i <- row.names
row.names <- value[[i]]
value <- value[-i]
}
else if (!is.null(row.names) && length(row.names) !=
nr)
stop("row names supplied are of the wrong length")
}
else if (!is.null(row.names) && length(row.names) != nr) {
warning("row names were found from a short variable and have been discarded")
row.names <- NULL
}
if (is.null(row.names))
row.names <- .set_row_names(nr)
else {
if (is.object(row.names) || !is.integer(row.names))
row.names <- as.character(row.names)
if (anyNA(row.names))
stop("row names contain missing values")
if (anyDuplicated(row.names))
stop(gettextf("duplicate row.names: %s", paste(unique(row.names[duplicated(row.names)]),
collapse = ", ")), domain = NA)
}
attr(value, "row.names") <- row.names
attr(value, "class") <- "data.frame"
value
}
"dimnames<-" <- function (x, value) .Primitive("dimnames<-")
## @type showWarnings : logical
## @type path : character
## @type recursive : logical
dir.create <- function (path, showWarnings = TRUE, recursive = FALSE, mode = "0777")
.Internal(dir.create(path, showWarnings, recursive, as.octmode(mode)))
droplevels <- function (x, ...)
UseMethod("droplevels")
duplicated <- function (x, incomparables = FALSE, ...)
UseMethod("duplicated")
## @type x : character
dyn.unload <- function (x)
.Internal(dyn.unload(x))
## @type x : character
enc2native <- function (x) .Primitive("enc2native")
## @type value : character
## @type x : character
"Encoding<-" <- function (x, value)
.Internal(setEncoding(x, value))
expression <- function (...) .Primitive("expression")
## @type wait : complex
## @type step : integer
## @type inhibit_release : logical
gctorture2 <- function (step, wait = step, inhibit_release = FALSE)
.Internal(gctorture2(step, wait, inhibit_release))
getElement <- function (object, name)
{
if (isS4(object))
slot(object, name)
else object[[name, exact = TRUE]]
}
## @type x : complex
is.complex <- function (x) .Primitive("is.complex")
is.element <- function (el, set)
match(el, set, 0L) > 0L
is.integer <- function (x) .Primitive("is.integer")
is.logical <- function (x) .Primitive("is.logical")
is.numeric <- function (x) .Primitive("is.numeric")
is.ordered <- function (x)
inherits(x, "ordered")
isdebugged <- function (fun)
.Internal(isdebugged(fun))
isSeekable <- function (con)
.Internal(isSeekable(con))
La_version <- function ()
.Internal(La_version())
## @type x : numeric
lfactorial <- function (x)
lgamma(x + 1)
## @type path : character
## @type ignore.case : logical
## @type full.names : logical
## @type include.dirs : logical
## @type no.. : logical
## @type all.files : logical
## @type recursive : logical
## @return character
list.files <- function (path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE,
recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE,
no.. = FALSE)
.Internal(list.files(path, pattern, all.files, full.names, recursive,
ignore.case, include.dirs, no..))
## @return character
make.names <- function (names, unique = FALSE, allow_ = TRUE)
{
names <- as.character(names)
names2 <- .Internal(make.names(names, allow_))
if (unique) {
o <- order(names != names2)
names2[o] <- make.unique(names2[o])
}
names2
}
mat.or.vec <- function (nr, nc)
if (nc == 1L) numeric(nr) else matrix(0, nr, nc)
## @type expand.dots : logical
match.call <- function (definition = NULL, call = sys.call(sys.parent()), expand.dots = TRUE)
.Internal(match.call(definition, call, expand.dots))
mem.limits <- function (nsize = NA, vsize = NA)
.Defunct("gc")
## @type generic : character
NextMethod <- function (generic = NULL, object = NULL, ...)
.Internal(NextMethod(generic, object, ...))
## @type value : character
"oldClass<-" <- function (x, value) .Primitive("oldClass<-")
OlsonNames <- function ()
{
if (.Platform$OS.type == "windows")
tzdir <- Sys.getenv("TZDIR", file.path(R.home("share"),
"zoneinfo"))
else {
tzdirs <- c(Sys.getenv("TZDIR"), file.path(R.home("share"),
"zoneinfo"), "/usr/share/zoneinfo", "/usr/share/lib/zoneinfo",
"/usr/lib/zoneinfo", "/usr/local/etc/zoneinfo", "/etc/zoneinfo",
"/usr/etc/zoneinfo")
tzdirs <- tzdirs[file.exists(tzdirs)]
if (!length(tzdirs)) {
warning("no Olson database found")
return(character())
}
else tzdir <- tzdirs[1]
}
x <- list.files(tzdir, recursive = TRUE)
grep("^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]", x, value = TRUE)
}
Ops.factor <- function (e1, e2)
{
ok <- switch(.Generic, `==` = , `!=` = TRUE, FALSE)
if (!ok) {
warning(.Generic, " not meaningful for factors")
return(rep.int(NA, max(length(e1), if (!missing(e2)) length(e2))))
}
nas <- is.na(e1) | is.na(e2)
noNA.levels <- function(f) {
r <- levels(f)
if (any(ina <- is.na(r))) {
n <- " NA "
while (n %in% r) n <- paste(n, ".")
r[ina] <- n
}
r
}
if (nzchar(.Method[1L])) {
l1 <- noNA.levels(e1)
e1 <- l1[e1]
}
if (nzchar(.Method[2L])) {
l2 <- noNA.levels(e2)
e2 <- l2[e2]
}
if (all(nzchar(.Method)) && (length(l1) != length(l2) ||
!all(sort.int(l2) == sort.int(l1))))
stop("level sets of factors are different")
value <- NextMethod(.Generic)
value[nas] <- NA
value
}
Ops.POSIXt <- function (e1, e2)
{
if (nargs() == 1)
stop(gettextf("unary '%s' not defined for \"POSIXt\" objects",
.Generic), domain = NA)
boolean <- switch(.Generic, `<` = , `>` = , `==` = , `!=` = ,
`<=` = , `>=` = TRUE, FALSE)
if (!boolean)
stop(gettextf("'%s' not defined for \"POSIXt\" objects",
.Generic), domain = NA)
if (inherits(e1, "POSIXlt") || is.character(e1))
e1 <- as.POSIXct(e1)
if (inherits(e2, "POSIXlt") || is.character(e2))
e2 <- as.POSIXct(e2)
check_tzones(e1, e2)
NextMethod(.Generic)
}
parent.env <- function (env)
.Internal(parent.env(env))
## @type x : integer
pos.to.env <- function (x) .Primitive("pos.to.env")
print.AsIs <- function (x, ...)
{
cl <- oldClass(x)
oldClass(x) <- cl[cl != "AsIs"]
NextMethod("print")
invisible(x)
}
print.Date <- function (x, max = NULL, ...)
{
if (is.null(max))
max <- getOption("max.print", 9999L)
if (max < length(x)) {
print(format(x[seq_len(max)]), max = max, ...)
cat(" [ reached getOption(\"max.print\") -- omitted",
length(x) - max, "entries ]\n")
}
else print(format(x), max = max, ...)
invisible(x)
}
prop.table <- function (x, margin = NULL)
{
if (length(margin))
sweep(x, margin, margin.table(x, margin), "/", check.margin = FALSE)
else x/sum(x)
}
## @type x : complex
## @type LAPACK : logical
qr.default <- function (x, tol = 1e-07, LAPACK = FALSE, ...)
{
x <- as.matrix(x)
if (is.complex(x))
return(structure(.Internal(La_qr_cmplx(x)), class = "qr"))
if (LAPACK)
return(structure(.Internal(La_qr(x)), useLAPACK = TRUE,
class = "qr"))
p <- as.integer(ncol(x))
if (is.na(p))
stop("invalid ncol(x)")
n <- as.integer(nrow(x))
if (is.na(n))
stop("invalid nrow(x)")
if (1 * n * p > 2147483647)
stop("too large a matrix for LINPACK")
storage.mode(x) <- "double"
res <- .Fortran(.F_dqrdc2, qr = x, n, n, p, as.double(tol),
rank = integer(1L), qraux = double(p), pivot = as.integer(seq_len(p)),
double(2L * p))[c(1, 6, 7, 8)]
if (!is.null(cn <- colnames(x)))
colnames(res$qr) <- cn[res$pivot]
class(res) <- "qr"
res
}
## @type invert : logical
## @type x : character
regmatches <- function (x, m, invert = FALSE)
{
if (length(x) != length(m))
stop(gettextf("%s and %s must have the same length",
sQuote("x"), sQuote("m")), domain = NA)
ili <- is.list(m)
useBytes <- if (ili)
any(unlist(lapply(m, attr, "useBytes")))
else any(attr(m, "useBytes"))
if (useBytes) {
asc <- iconv(x, "latin1", "ASCII")
ind <- is.na(asc) | (asc != x)
if (any(ind))
Encoding(x[ind]) <- "bytes"
}
if (!ili && !invert) {
so <- m[ind <- (!is.na(m) & (m > -1L))]
eo <- so + attr(m, "match.length")[ind] - 1L
return(substring(x[ind], so, eo))
}
y <- if (invert) {
Map(function(u, so, ml) {
if ((n <- length(so)) == 1L) {
if (is.na(so))
return(character())
else if (so == -1L)
return(u)
}
beg <- if (n > 1L) {
eo <- so + ml - 1L
if (any(eo[-n] >= so[-1L]))
stop(gettextf("need non-overlapping matches for %s",
sQuote("invert = TRUE")), domain = NA)
c(1L, eo + 1L)
}
else {
c(1L, so + ml)
}
end <- c(so - 1L, nchar(u))
substring(u, beg, end)
}, x, m, if (ili)
lapply(m, attr, "match.length")
else attr(m, "match.length"), USE.NAMES = FALSE)
}
else {
Map(function(u, so, ml) {
if (length(so) == 1L) {
if (is.na(so) || (so == -1L))
return(character())
}
substring(u, so, so + ml - 1L)
}, x, m, lapply(m, attr, "match.length"), USE.NAMES = FALSE)
}
names(y) <- names(x)
y
}
rep.factor <- function (x, ...)
{
y <- NextMethod()
structure(y, class = class(x), levels = levels(x))
}
retracemem <- function (x, previous = NULL) .Primitive("retracemem")
## @type vstr : complex|character
## @optional vstr
RNGversion <- function (vstr)
{
vnum <- as.numeric(strsplit(vstr, ".", fixed = TRUE)[[1L]])
if (length(vnum) < 2L)
stop("malformed version string")
if (vnum[1L] == 0 && vnum[2L] < 99)
RNGkind("Wichmann-Hill", "Buggy Kinderman-Ramage")
else if (vnum[1L] == 0 || vnum[1L] == 1 && vnum[2L] <= 6)
RNGkind("Marsaglia-Multicarry", "Buggy Kinderman-Ramage")
else RNGkind("Mersenne-Twister", "Inversion")
}
round.Date <- function (x, ...)
{
cl <- oldClass(x)
class(x) <- NULL
val <- NextMethod()
class(val) <- cl
val
}
## @type value : character
"rownames<-" <- function (x, value)
{
if (is.data.frame(x)) {
row.names(x) <- value
}
else {
dn <- dimnames(x)
if (is.null(dn)) {
if (is.null(value))
return(x)
if ((nd <- length(dim(x))) < 1L)
stop("attempt to set 'rownames' on an object with no dimensions")
dn <- vector("list", nd)
}
if (length(dn) < 1L)
stop("attempt to set 'rownames' on an object with no dimensions")
if (is.null(value))
dn[1L] <- list(NULL)
else dn[[1L]] <- value
dimnames(x) <- dn
}
x
}
sample.int <- function (n, size = n, replace = FALSE, prob = NULL)
{
if (!replace && is.null(prob) && n > 1e+07 && size <= n/2)
.Internal(sample2(n, size))
else .Internal(sample(n, size, replace, prob))
}
save.image <- function (file = ".RData", version = NULL, ascii = FALSE, compress = !ascii,
safe = TRUE)
{
if (!is.character(file) || file == "")
stop("'file' must be non-empty string")
opts <- getOption("save.image.defaults")
if (is.null(opts))
opts <- getOption("save.defaults")
if (missing(safe) && !is.null(opts$safe))
safe <- opts$safe
if (missing(ascii) && !is.null(opts$ascii))
ascii <- opts$ascii
if (missing(compress) && !is.null(opts$compress))
compress <- opts$compress
if (missing(version))
version <- opts$version
if (safe) {
outfile <- paste0(file, "Tmp")
i <- 0
while (file.exists(outfile)) {
i <- i + 1
outfile <- paste0(file, "Tmp", i)
}
}
else outfile <- file
on.exit(file.remove(outfile))
save(list = ls(envir = .GlobalEnv, all.names = TRUE), file = outfile,
version = version, ascii = ascii, compress = compress,
envir = .GlobalEnv, precheck = FALSE)
if (safe)
if (!file.rename(outfile, file)) {
on.exit()
stop(gettextf("image could not be renamed and is left in %s",
outfile), domain = NA)
}
on.exit()
}
## @type length.out : integer
seq.POSIXt <- function (from, to, by, length.out = NULL, along.with = NULL,
...)
{
if (missing(from))
stop("'from' must be specified")
if (!inherits(from, "POSIXt"))
stop("'from' must be a \"POSIXt\" object")
cfrom <- as.POSIXct(from)
if (length(cfrom) != 1L)
stop("'from' must be of length 1")
tz <- attr(cfrom, "tzone")
if (!missing(to)) {
if (!inherits(to, "POSIXt"))
stop("'to' must be a \"POSIXt\" object")
if (length(as.POSIXct(to)) != 1)
stop("'to' must be of length 1")
}
if (!missing(along.with)) {
length.out <- length(along.with)
}
else if (!is.null(length.out)) {
if (length(length.out) != 1L)
stop("'length.out' must be of length 1")
length.out <- ceiling(length.out)
}
status <- c(!missing(to), !missing(by), !is.null(length.out))
if (sum(status) != 2L)
stop("exactly two of 'to', 'by' and 'length.out' / 'along.with' must be specified")
if (missing(by)) {
from <- unclass(cfrom)
to <- unclass(as.POSIXct(to))
res <- seq.int(from, to, length.out = length.out)
return(.POSIXct(res, tz))
}
if (length(by) != 1L)
stop("'by' must be of length 1")
valid <- 0L
if (inherits(by, "difftime")) {
by <- switch(attr(by, "units"), secs = 1, mins = 60,
hours = 3600, days = 86400, weeks = 7 * 86400) *
unclass(by)
}
else if (is.character(by)) {
by2 <- strsplit(by, " ", fixed = TRUE)[[1L]]
if (length(by2) > 2L || length(by2) < 1L)
stop("invalid 'by' string")
valid <- pmatch(by2[length(by2)], c("secs", "mins", "hours",
"days", "weeks", "months", "years", "DSTdays", "quarters"))
if (is.na(valid))
stop("invalid string for 'by'")
if (valid <= 5L) {
by <- c(1, 60, 3600, 86400, 7 * 86400)[valid]
if (length(by2) == 2L)
by <- by * as.integer(by2[1L])
}
else by <- if (length(by2) == 2L)
as.integer(by2[1L])
else 1
}
else if (!is.numeric(by))
stop("invalid mode for 'by'")
if (is.na(by))
stop("'by' is NA")
if (valid <= 5L) {
from <- unclass(as.POSIXct(from))
if (!is.null(length.out))
res <- seq.int(from, by = by, length.out = length.out)
else {
to0 <- unclass(as.POSIXct(to))
res <- seq.int(0, to0 - from, by) + from
}
return(.POSIXct(res, tz))
}
else {
r1 <- as.POSIXlt(from)
if (valid == 7L) {
if (missing(to)) {
yr <- seq.int(r1$year, by = by, length.out = length.out)
}
else {
to <- as.POSIXlt(to)
yr <- seq.int(r1$year, to$year, by)
}
r1$year <- yr
}
else if (valid %in% c(6L, 9L)) {
if (valid == 9L)
by <- by * 3
if (missing(to)) {
mon <- seq.int(r1$mon, by = by, length.out = length.out)
}
else {
to0 <- as.POSIXlt(to)
mon <- seq.int(r1$mon, 12 * (to0$year - r1$year) +
to0$mon, by)
}
r1$mon <- mon
}
else if (valid == 8L) {
if (!missing(to)) {
length.out <- 2L + floor((unclass(as.POSIXct(to)) -
unclass(as.POSIXct(from)))/86400)
}
r1$mday <- seq.int(r1$mday, by = by, length.out = length.out)
}
r1$isdst <- -1L
res <- as.POSIXct(r1)
if (!missing(to)) {
to <- as.POSIXct(to)
res <- if (by > 0)
res[res <= to]
else res[res >= to]
}
res
}
}
split.Date <- function (x, f, drop = FALSE, ...)
{
y <- split.default(as.integer(x), f, drop = drop)
for (i in seq_along(y)) class(y[[i]]) <- "Date"
y
}
substitute <- function (expr, env) .Primitive("substitute")
sys.frames <- function ()
.Internal(sys.frames())
## @type names : logical
## @type unset : character
## @type x : character
## @return character
Sys.getenv <- function (x = NULL, unset = "", names = NA)
{
if (is.null(x)) {
x <- strsplit(.Internal(Sys.getenv(character(), "")),
"=", fixed = TRUE)
v <- n <- character(LEN <- length(x))
for (i in 1L:LEN) {
n[i] <- x[[i]][1L]
v[i] <- paste(x[[i]][-1L], collapse = "=")
}
if (!identical(names, FALSE))
v <- structure(v, names = n)
v[sort.list(n)]
}
else {
v <- .Internal(Sys.getenv(as.character(x), as.character(unset)))
if (isTRUE(names) || (length(x) > 1L && !identical(names,
FALSE)))
structure(v, names = x)
else v
}
}
Sys.getpid <- function ()
.Internal(Sys.getpid())
sys.nframe <- function ()
.Internal(sys.nframe())
sys.parent <- function (n = 1L)
.Internal(sys.parent(n))
Sys.setenv <- function (...)
{
x <- list(...)
nm <- names(x)
if (is.null(nm) || "" %in% nm)
stop("all arguments must be named")
.Internal(Sys.setenv(nm, as.character(unlist(x))))
}
sys.source <- function (file, envir = baseenv(), chdir = FALSE, keep.source = getOption("keep.source.pkgs"))
{
if (!(is.character(file) && file.exists(file)))
stop(gettextf("'%s' is not an existing file", file))
keep.source <- as.logical(keep.source)
oop <- options(keep.source = keep.source, topLevelEnvironment = as.environment(envir))
on.exit(options(oop))
if (keep.source) {
lines <- readLines(file, warn = FALSE)
srcfile <- srcfilecopy(file, lines, file.info(file)[1,
"mtime"], isFile = TRUE)
exprs <- parse(text = lines, srcfile = srcfile, keep.source = TRUE)
}
else exprs <- parse(n = -1, file = file, srcfile = NULL,
keep.source = FALSE)
if (length(exprs) == 0L)
return(invisible())
if (chdir && (path <- dirname(file)) != ".") {
owd <- getwd()
if (is.null(owd))
stop("cannot 'chdir' as current directory is unknown")
on.exit(setwd(owd), add = TRUE)
setwd(path)
}
for (i in seq_along(exprs)) eval(exprs[i], envir)
invisible()
}
sys.status <- function ()
list(sys.calls = sys.calls(), sys.parents = sys.parents(), sys.frames = sys.frames())
## @type x : complex
## @type y : complex
tcrossprod <- function (x, y = NULL)
.Internal(tcrossprod(x, y))
trunc.Date <- function (x, ...)
round(x - 0.4999999)
untracemem <- function (x) .Primitive("untracemem")
writeLines <- function (text, con = stdout(), sep = "\n", useBytes = FALSE)
{
if (is.character(con)) {
con <- file(con, "w")
on.exit(close(con))
}
.Internal(writeLines(text, con, sep, useBytes))
}
xtfrm.AsIs <- function (x)
{
if (length(cl <- class(x)) > 1)
oldClass(x) <- cl[-1L]
NextMethod("xtfrm")
}
xtfrm.Date <- function (x)
as.numeric(x)
xtfrm.Surv <- function (x)
if (ncol(x) == 2L) order(x[, 1L], x[, 2L]) else order(x[, 1L],
x[, 2L], x[, 3L])
"[<-.POSIXct" <- function (x, ..., value)
{
if (!length(value))
return(x)
value <- unclass(as.POSIXct(value))
cl <- oldClass(x)
tz <- attr(x, "tzone")
class(x) <- NULL
x <- NextMethod(.Generic)
class(x) <- cl
attr(x, "tzone") <- tz
x
}
## @optional i
"[<-.POSIXlt" <- function (x, i, value)
{
if (!length(value))
return(x)
value <- unclass(as.POSIXlt(value))
cl <- oldClass(x)
class(x) <- NULL
for (n in names(x)) x[[n]][i] <- value[[n]]
class(x) <- cl
x
}
## @type value : character
"[[<-.factor" <- function (x, ..., value)
{
lx <- levels(x)
cx <- oldClass(x)
if (is.factor(value))
value <- levels(value)[value]
m <- match(value, lx)
if (any(is.na(m) & !is.na(value)))
warning("invalid factor level, NA generated")
class(x) <- NULL
x[[...]] <- m
attr(x, "levels") <- lx
class(x) <- cx
x
}
## @type perm : complex|character
## @type keep.class : logical
aperm.table <- function (a, perm = NULL, resize = TRUE, keep.class = TRUE, ...)
{
r <- aperm.default(a, perm, resize = resize)
if (keep.class)
class(r) <- class(a)
r
}
## @type tim : numeric|character
## @type units : character
## @type format : character
as.difftime <- function (tim, format = "%X", units = "auto")
{
if (inherits(tim, "difftime"))
return(tim)
if (is.character(tim)) {
difftime(strptime(tim, format = format), strptime("0:0:0",
format = "%X"), units = units)
}
else {
if (!is.numeric(tim))
stop("'tim' is not character or numeric")
if (units == "auto")
stop("need explicit units for numeric conversion")
if (!(units %in% c("secs", "mins", "hours", "days", "weeks")))
stop("invalid units specified")
structure(tim, units = units, class = "difftime")
}
}
as.function <- function (x, ...)
UseMethod("as.function")
as.pairlist <- function (x)
.Internal(as.vector(x, "pairlist"))
asNamespace <- function (ns, base.OK = TRUE)
{
if (is.character(ns) || is.name(ns))
ns <- getNamespace(ns)
if (!isNamespace(ns))
stop("not a namespace")
else if (!base.OK && isBaseNamespace(ns))
stop("operation not allowed on base namespace")
else ns
}
browserText <- function (n = 1L)
.Internal(browserText(n))
## @type target : character
## @type input : character
## @return character
char.expand <- function (input, target, nomatch = stop("no match"))
{
if (length(input) != 1L)
stop("'input' must have length 1")
if (!(is.character(input) && is.character(target)))
stop("'input' and 'target' must be character vectors")
y <- .Internal(charmatch(input, target, NA_integer_))
if (anyNA(y))
eval(nomatch)
target[y]
}
## @type trailingOnly : logical
## @return character
commandArgs <- function (trailingOnly = FALSE)
{
args <- .Internal(commandArgs())
if (trailingOnly) {
m <- match("--args", args, 0L)
if (m)
args[-seq_len(m)]
else character()
}
else args
}
Cstack_info <- function ()
.Internal(Cstack_info())
## @type right : logical
## @type labels : integer
## @type include.lowest : logical
## @type ordered_result : logical
## @type breaks : complex
## @type x : numeric
## @type dig.lab : complex
cut.default <- function (x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE,
dig.lab = 3L, ordered_result = FALSE, ...)
{
if (!is.numeric(x))
stop("'x' must be numeric")
if (length(breaks) == 1L) {
if (is.na(breaks) || breaks < 2L)
stop("invalid number of intervals")
nb <- as.integer(breaks + 1)
dx <- diff(rx <- range(x, na.rm = TRUE))
if (dx == 0) {
dx <- abs(rx[1L])
breaks <- seq.int(rx[1L] - dx/1000, rx[2L] + dx/1000,
length.out = nb)
}
else {
breaks <- seq.int(rx[1L], rx[2L], length.out = nb)
breaks[c(1L, nb)] <- c(rx[1L] - dx/1000, rx[2L] +
dx/1000)
}
}
else nb <- length(breaks <- sort.int(as.double(breaks)))
if (anyDuplicated(breaks))
stop("'breaks' are not unique")
codes.only <- FALSE
if (is.null(labels)) {
for (dig in dig.lab:max(12L, dig.lab)) {
ch.br <- formatC(0 + breaks, digits = dig, width = 1L)
if (ok <- all(ch.br[-1L] != ch.br[-nb]))
break
}
labels <- if (ok)
paste0(if (right)
"("
else "[", ch.br[-nb], ",", ch.br[-1L], if (right)
"]"
else ")")
else paste("Range", seq_len(nb - 1L), sep = "_")
if (ok && include.lowest) {
if (right)
substr(labels[1L], 1L, 1L) <- "["
else substring(labels[nb - 1L], nchar(labels[nb -
1L], "c")) <- "]"
}
}
else if (is.logical(labels) && !labels)
codes.only <- TRUE
else if (length(labels) != nb - 1L)
stop("lengths of 'breaks' and 'labels' differ")
code <- .bincode(x, breaks, right, include.lowest)
if (codes.only)
code
else factor(code, seq_along(labels), labels, ordered = ordered_result)
}
data.matrix <- function (frame, rownames.force = NA)
{
if (!is.data.frame(frame))
return(as.matrix(frame))
d <- dim(frame)
rn <- if (rownames.force %in% FALSE)
NULL
else if (rownames.force %in% TRUE)
row.names(frame)
else {
if (.row_names_info(frame) <= 0L)
NULL
else row.names(frame)
}
for (i in seq_len(d[2L])) {
xi <- frame[[i]]
if (is.integer(xi) || is.numeric(xi))
next
if (is.logical(xi) || is.factor(xi)) {
frame[[i]] <- as.integer(xi)
next
}
frame[[i]] <- if (isS4(xi))
methods::as(xi, "numeric")
else as.numeric(xi)
}
intOK <- all(unlist(lapply(frame, is.integer)))
x <- matrix(if (intOK)
NA_integer_
else NA_real_, nrow = d[1L], ncol = d[2L], dimnames = list(rn,
names(frame)))
for (i in seq_len(d[2L])) x[, i] <- frame[[i]]
x
}
## @type x : logical|numeric
## @type logarithm : logical
determinant <- function (x, logarithm = TRUE, ...)
UseMethod("determinant")
## @type x : numeric
## @type differences : integer
## @type lag : integer
diff.POSIXt <- function (x, lag = 1L, differences = 1L, ...)
{
ismat <- is.matrix(x)
r <- if (inherits(x, "POSIXlt"))
as.POSIXct(x)
else x
xlen <- if (ismat)
dim(x)[1L]
else length(r)
if (length(lag) != 1L || length(differences) > 1L || lag <
1L || differences < 1L)
stop("'lag' and 'differences' must be integers >= 1")
if (lag * differences >= xlen)
return(.difftime(numeric(), "secs"))
i1 <- -seq_len(lag)
if (ismat)
for (i in seq_len(differences)) r <- r[i1, , drop = FALSE] -
r[-nrow(r):-(nrow(r) - lag + 1), , drop = FALSE]
else for (i in seq_len(differences)) r <- r[i1] - r[-length(r):-(length(r) -
lag + 1L)]
r
}
env.profile <- function (env)
.Internal(env.profile(env))
environment <- function (fun = NULL)
.Internal(environment(fun))
eval.parent <- function (expr, n = 1)
{
p <- parent.frame(n + 1)
eval(expr, p)
}
## @type KEEP.OUT.ATTRS : logical
## @type stringsAsFactors : logical|character
expand.grid <- function (..., KEEP.OUT.ATTRS = TRUE, stringsAsFactors = TRUE)
{
nargs <- length(args <- list(...))
if (!nargs)
return(as.data.frame(list()))
if (nargs == 1L && is.list(a1 <- args[[1L]]))
nargs <- length(args <- a1)
if (nargs == 0L)
return(as.data.frame(list()))
cargs <- vector("list", nargs)
iArgs <- seq_len(nargs)
nmc <- paste0("Var", iArgs)
nm <- names(args)
if (is.null(nm))
nm <- nmc
else if (any(ng0 <- nzchar(nm)))
nmc[ng0] <- nm[ng0]
names(cargs) <- nmc
rep.fac <- 1L
d <- sapply(args, length)
if (KEEP.OUT.ATTRS) {
dn <- vector("list", nargs)
names(dn) <- nmc
}
orep <- prod(d)
if (orep == 0L) {
for (i in iArgs) cargs[[i]] <- args[[i]][FALSE]
}
else {
for (i in iArgs) {
x <- args[[i]]
if (KEEP.OUT.ATTRS)
dn[[i]] <- paste0(nmc[i], "=", if (is.numeric(x))
format(x)
else x)
nx <- length(x)
orep <- orep/nx
x <- x[rep.int(rep.int(seq_len(nx), rep.int(rep.fac,
nx)), orep)]
if (stringsAsFactors && !is.factor(x) && is.character(x))
x <- factor(x, levels = unique(x))
cargs[[i]] <- x
rep.fac <- rep.fac * nx
}
}
if (KEEP.OUT.ATTRS)
attr(cargs, "out.attrs") <- list(dim = d, dimnames = dn)
rn <- .set_row_names(as.integer(prod(d)))
structure(cargs, class = "data.frame", row.names = rn)
}
## @return integer
file.access <- function (names, mode = 0)
{
res <- .Internal(file.access(names, mode))
names(res) <- names
res
}
## @type file1 : character
## @type file2 : character
## @return logical|character
file.append <- function (file1, file2)
.Internal(file.append(file1, file2))
file.choose <- function (new = FALSE)
.Internal(file.choose(new))
## @type showWarnings : logical
## @return logical|character
file.create <- function (..., showWarnings = TRUE)
.Internal(file.create(c(...), showWarnings))
file.exists <- function (...)
.Internal(file.exists(c(...)))
file.remove <- function (...)
.Internal(file.remove(c(...)))
## @type from : character
## @type to : character
file.rename <- function (from, to)
.Internal(file.rename(from, to))
findRestart <- function (name, cond = NULL)
{
i <- 1L
repeat {
r <- .Internal(.getRestart(i))
if (is.null(r))
return(NULL)
else if (name == r[[1L]] && (is.null(cond) || is.null(r$test) ||
r$test(cond)))
return(r)
else i <- i + 1L
}
}
## @type x : numeric
format.AsIs <- function (x, width = 12, ...)
{
if (is.character(x))
return(format.default(x, ...))
if (is.null(width))
width = 12L
n <- length(x)
rvec <- rep.int(NA_character_, n)
for (i in seq_len(n)) {
y <- x[[i]]
cl <- oldClass(y)
if (m <- match("AsIs", cl, 0L))
oldClass(y) <- cl[-m]
rvec[i] <- toString(y, width = width, ...)
}
dim(rvec) <- dim(x)
dimnames(rvec) <- dimnames(x)
format.default(rvec, justify = "right")
}
format.Date <- function (x, ...)
{
xx <- format(as.POSIXlt(x), ...)
names(xx) <- names(x)
xx
}
## @type digits : complex
format.info <- function (x, digits = NULL, nsmall = 0L)
.Internal(format.info(x, digits, nsmall))
## @type pv : numeric
## @type na.form : character
## @return character
format.pval <- function (pv, digits = max(1L, getOption("digits") - 2L), eps = .Machine$double.eps,
na.form = "NA", ...)
{
if ((has.na <- any(ina <- is.na(pv))))
pv <- pv[!ina]
r <- character(length(is0 <- pv < eps))
if (any(!is0)) {
rr <- pv <- pv[!is0]
expo <- floor(log10(ifelse(pv > 0, pv, 1e-50)))
fixp <- expo >= -3 | (expo == -4 & digits > 1)
if (any(fixp))
rr[fixp] <- format(pv[fixp], digits = digits, ...)
if (any(!fixp))
rr[!fixp] <- format(pv[!fixp], digits = digits, ...)
r[!is0] <- rr
}
if (any(is0)) {
digits <- max(1L, digits - 2L)
if (any(!is0)) {
nc <- max(nchar(rr, type = "w"))
if (digits > 1L && digits + 6L > nc)
digits <- max(1L, nc - 7L)
sep <- if (digits == 1L && nc <= 6L)
""
else " "
}
else sep <- if (digits == 1)
""
else " "
r[is0] <- paste("<", format(eps, digits = digits, ...),
sep = sep)
}
if (has.na) {
rok <- r
r <- character(length(ina))
r[!ina] <- rok
r[ina] <- na.form
}
r
}
getRversion <- function ()
package_version(R.version)
getSrcLines <- function (srcfile, first, last)
{
if (first > last)
return(character())
if (inherits(srcfile, "srcfilealias"))
srcfile <- srcfile$original
if (inherits(srcfile, "srcfilecopy")) {
if (is.null(srcfile$fixedNewlines)) {
lines <- srcfile$lines
if (any(grepl("\n", lines, fixed = TRUE)))
srcfile$lines <- unlist(strsplit(sub("$", "\n",
as.character(lines)), "\n"))
srcfile$fixedNewlines <- TRUE
}
last <- min(last, length(srcfile$lines))
if (first > last)
return(character())
else return(srcfile$lines[first:last])
}
if (!.isOpen(srcfile))
on.exit(close(srcfile))
conn <- open(srcfile, first)
lines <- readLines(conn, n = last - first + 1L, warn = FALSE)
if (!is.null(Enc <- srcfile$Enc) && !(Enc %in% c("unknown",
"native.enc")))
lines <- iconv(lines, "", Enc)
srcfile$line <- first + length(lines)
return(lines)
}
## @type sep : character
## @type lex.order : logical
interaction <- function (..., drop = FALSE, sep = ".", lex.order = FALSE)
{
args <- list(...)
narg <- length(args)
if (narg < 1L)
stop("No factors specified")
if (narg == 1L && is.list(args[[1L]])) {
args <- args[[1L]]
narg <- length(args)
}
for (i in narg:1L) {
f <- as.factor(args[[i]])[, drop = drop]
l <- levels(f)
if1 <- as.integer(f) - 1L
if (i == narg) {
ans <- if1
lvs <- l
}
else {
if (lex.order) {
ll <- length(lvs)
ans <- ans + ll * if1
lvs <- paste(rep(l, each = ll), rep(lvs, length(l)),
sep = sep)
}
else {
ans <- ans * length(l) + if1
lvs <- paste(rep(l, length(lvs)), rep(lvs, each = length(l)),
sep = sep)
}
if (anyDuplicated(lvs)) {
ulvs <- unique(lvs)
while ((i <- anyDuplicated(flv <- match(lvs,
ulvs)))) {
lvs <- lvs[-i]
ans[ans + 1L == i] <- match(flv[i], flv[1:(i -
1)]) - 1L
ans[ans + 1L > i] <- ans[ans + 1L > i] - 1L
}
lvs <- ulvs
}
if (drop) {
olvs <- lvs
lvs <- lvs[sort(unique(ans + 1L))]
ans <- match(olvs[ans + 1L], lvs) - 1L
}
}
}
structure(as.integer(ans + 1L), levels = lvs, class = "factor")
}
interactive <- function () .Primitive("interactive")
## @optional x
inverse.rle <- function (x, ...)
{
if (is.null(le <- x$lengths) || is.null(v <- x$values) ||
length(le) != length(v))
stop("invalid 'rle' structure")
rep.int(v, le)
}
is.function <- function (x) .Primitive("is.function")
is.infinite <- function (x) .Primitive("is.infinite")
is.language <- function (x) .Primitive("is.language")
is.pairlist <- function (x) .Primitive("is.pairlist")
## @type na.rm : logical
## @type strictly : logical
## @type x : raw|complex|logical|character
## @return logical
is.unsorted <- function (x, na.rm = FALSE, strictly = FALSE)
{
if (length(x) <= 1L)
return(FALSE)
if (!na.rm && anyNA(x))
return(NA)
if (na.rm && any(ii <- is.na(x)))
x <- x[!ii]
.Internal(is.unsorted(x, strictly))
}
isNamespace <- function (ns)
.Internal(isNamespaceEnv(ns))
ISOdatetime <- function (year, month, day, hour, min, sec, tz = "")
{
if (min(sapply(list(year, month, day, hour, min, sec), length)) ==
0L)
.POSIXct(numeric(), tz = tz)
else {
x <- paste(year, month, day, hour, min, sec, sep = "-")
as.POSIXct(strptime(x, "%Y-%m-%d-%H-%M-%OS", tz = tz),
tz = tz)
}
}
isSymmetric <- function (object, ...)
UseMethod("isSymmetric")
julian.Date <- function (x, origin = as.Date("1970-01-01"), ...)
{
if (length(origin) != 1L)
stop("'origin' must be of length one")
structure(unclass(x) - unclass(origin), origin = origin)
}
## @type sym : character
lockBinding <- function (sym, env)
{
if (is.character(sym))
sym <- as.name(sym)
.Internal(lockBinding(sym, env))
}
## @return character
make.unique <- function (names, sep = ".")
.Internal(make.unique(names, sep))
## @optional x
Math.factor <- function (x, ...)
{
stop(.Generic, " not meaningful for factors")
}
## @optional x
Math.POSIXt <- function (x, ...)
{
stop(gettextf("'%s' not defined for \"POSIXt\" objects",
.Generic), domain = NA)
}
## @type from : raw|character
## @type type : character
## @return raw|character
memCompress <- function (from, type = c("gzip", "bzip2", "xz", "none"))
{
if (is.character(from))
from <- charToRaw(paste(from, collapse = "\n"))
else if (!is.raw(from))
stop("'from' must be raw or character")
type <- match(match.arg(type), c("none", "gzip", "bzip2",
"xz"))
.Internal(memCompress(from, type))
}
months.Date <- function (x, abbreviate = FALSE)
format(x, ifelse(abbreviate, "%b", "%B"))
Ops.ordered <- function (e1, e2)
{
ok <- switch(.Generic, `<` = , `>` = , `<=` = , `>=` = ,
`==` = , `!=` = TRUE, FALSE)
if (!ok) {
warning(sprintf("'%s' is not meaningful for ordered factors",
.Generic))
return(rep.int(NA, max(length(e1), if (!missing(e2)) length(e2))))
}
if (.Generic %in% c("==", "!="))
return(NextMethod(.Generic))
nas <- is.na(e1) | is.na(e2)
ord1 <- FALSE
ord2 <- FALSE
if (nzchar(.Method[1L])) {
l1 <- levels(e1)
ord1 <- TRUE
}
if (nzchar(.Method[2L])) {
l2 <- levels(e2)
ord2 <- TRUE
}
if (all(nzchar(.Method)) && (length(l1) != length(l2) ||
!all(l2 == l1)))
stop("level sets of factors are different")
if (ord1 && ord2) {
e1 <- as.integer(e1)
e2 <- as.integer(e2)
}
else if (!ord1) {
e1 <- match(e1, l2)
e2 <- as.integer(e2)
}
else if (!ord2) {
e2 <- match(e2, l1)
e1 <- as.integer(e1)
}
value <- get(.Generic, mode = "function")(e1, e2)
value[nas] <- NA
value
}
## @type path : character
path.expand <- function (path)
.Internal(path.expand(path))
print.table <- function (x, digits = getOption("digits"), quote = FALSE, na.print = "",
zero.print = "0", justify = "none", ...)
{
d <- dim(x)
if (any(d == 0)) {
cat("< table of extent", paste(d, collapse = " x "),
">\n")
return(invisible(x))
}
xx <- format(unclass(x), digits = digits, justify = justify)
if (any(ina <- is.na(x)))
xx[ina] <- na.print
if (zero.print != "0" && any(i0 <- !ina & x == 0))
xx[i0] <- zero.print
if (is.numeric(x) || is.complex(x))
print(xx, quote = quote, right = TRUE, ...)
else print(xx, quote = quote, ...)
invisible(x)
}
rep.POSIXct <- function (x, ...)
{
y <- NextMethod()
.POSIXct(y, attr(x, "tzone"))
}
rep.POSIXlt <- function (x, ...)
{
y <- lapply(X = x, FUN = rep, ...)
attributes(y) <- attributes(x)
y
}
rev.default <- function (x)
if (length(x)) x[length(x):1L] else x
## @type value : complex|character
"row.names<-" <- function (x, value)
UseMethod("row.names<-")
searchpaths <- function ()
{
s <- search()
paths <- lapply(seq_along(s), function(i) attr(as.environment(i),
"path"))
paths[[length(s)]] <- system.file()
m <- grep("^package:", s)
if (length(m))
paths[-m] <- as.list(s[-m])
unlist(paths)
}
## @type length.out : complex
## @type by : complex
seq.default <- function (from = 1, to = 1, by = ((to - from)/(length.out - 1)),
length.out = NULL, along.with = NULL, ...)
{
if ((One <- nargs() == 1L) && !missing(from)) {
lf <- length(from)
return(if (mode(from) == "numeric" && lf == 1L) {
if (!is.finite(from)) stop("'from' cannot be NA, NaN or infinite")
1L:from
} else if (lf) 1L:lf else integer())
}
if (!missing(along.with)) {
length.out <- length(along.with)
if (One)
return(if (length.out) seq_len(length.out) else integer())
}
else if (!missing(length.out)) {
len <- length(length.out)
if (!len)
stop("argument 'length.out' must be of length 1")
if (len > 1L) {
warning("first element used of 'length.out' argument")
length.out <- length.out[1L]
}
length.out <- ceiling(length.out)
}
if (!missing(...))
warning(sprintf(ngettext(length(list(...)), "extra argument %s will be disregarded",
"extra arguments %s will be disregarded"), paste(sQuote(names(list(...))),
collapse = ", ")), domain = NA)
if (!missing(from) && length(from) != 1L)
stop("'from' must be of length 1")
if (!missing(to) && length(to) != 1L)
stop("'to' must be of length 1")
if (!missing(from) && !is.finite(from))
stop("'from' cannot be NA, NaN or infinite")
if (!missing(to) && !is.finite(to))
stop("'to' cannot be NA, NaN or infinite")
if (is.null(length.out))
if (missing(by))
from:to
else {
del <- to - from
if (del == 0 && to == 0)
return(to)
n <- del/by
if (!(length(n) && is.finite(n))) {
if (length(by) && by == 0 && length(del) && del ==
0)
return(from)
stop("invalid (to - from)/by in seq(.)")
}
if (n < 0L)
stop("wrong sign in 'by' argument")
if (n > .Machine$integer.max)
stop("'by' argument is much too small")
dd <- abs(del)/max(abs(to), abs(from))
if (dd < 100 * .Machine$double.eps)
return(from)
if (is.integer(del) && is.integer(by)) {
n <- as.integer(n)
from + (0L:n) * by
}
else {
n <- as.integer(n + 1e-10)
x <- from + (0L:n) * by
if (by > 0)
pmin(x, to)
else pmax(x, to)
}
}
else if (!is.finite(length.out) || length.out < 0L)
stop("length must be non-negative number")
else if (length.out == 0L)
integer()
else if (One)
seq_len(length.out)
else if (missing(by)) {
if (missing(to))
to <- from + length.out - 1L
if (missing(from))
from <- to - length.out + 1L
if (length.out > 2L)
if (from == to)
rep.int(from, length.out)
else as.vector(c(from, from + seq_len(length.out -
2L) * by, to))
else as.vector(c(from, to))[seq_len(length.out)]
}
else if (missing(to))
from + (0L:(length.out - 1L)) * by
else if (missing(from))
to - ((length.out - 1L):0L) * by
else stop("too many arguments")
}
simpleError <- function (message, call = NULL)
{
class <- c("simpleError", "error", "condition")
structure(list(message = as.character(message), call = call),
class = class)
}
## @type type : character
sink.number <- function (type = c("output", "message"))
{
type <- match.arg(type)
.Internal(sink.number(type != "message"))
}
slice.index <- function (x, MARGIN)
{
d <- dim(x)
if (is.null(d))
d <- length(x)
n <- length(d)
if ((length(MARGIN) > 1L) || (MARGIN < 1L) || (MARGIN > n))
stop("incorrect value for 'MARGIN'")
if (any(d == 0L))
return(array(integer(), d))
y <- rep.int(rep.int(1L:d[MARGIN], prod(d[seq_len(MARGIN -
1L)]) * rep.int(1L, d[MARGIN])), prod(d[seq.int(from = MARGIN +
1L, length.out = n - MARGIN)]))
dim(y) <- d
y
}
srcfilecopy <- function (filename, lines, timestamp = Sys.time(), isFile = FALSE)
{
stopifnot(is.character(filename), length(filename) == 1L)
e <- new.env(parent = emptyenv())
if (any(grepl("\n", lines, fixed = TRUE)))
lines <- unlist(strsplit(sub("$", "\n", as.character(lines)),
"\n"))
e$filename <- filename
e$wd <- getwd()
e$isFile <- isFile
e$lines <- as.character(lines)
e$fixedNewlines <- TRUE
e$timestamp <- timestamp
e$Enc <- "unknown"
class(e) <- c("srcfilecopy", "srcfile")
return(e)
}
## @type first : integer
## @type value : character
## @type text : character
## @type last : integer
"substring<-" <- function (text, first, last = 1000000L, value)
.Internal(`substr<-`(text, as.integer(first), as.integer(last),
value))
sys.on.exit <- function ()
.Internal(sys.on.exit())
sys.parents <- function ()
.Internal(sys.parents())
## @type lib.loc : character
## @type mustWork : logical
## @type package : character
## @return character
system.file <- function (..., package = "base", lib.loc = NULL, mustWork = FALSE)
{
if (nargs() == 0L)
return(file.path(.Library, "base"))
if (length(package) != 1L)
stop("'package' must be of length 1")
packagePath <- find.package(package, lib.loc, quiet = TRUE)
ans <- if (length(packagePath)) {
FILES <- file.path(packagePath, ...)
present <- file.exists(FILES)
if (any(present))
FILES[present]
else ""
}
else ""
if (mustWork && identical(ans, ""))
stop("no file found")
ans
}
system.time <- function (expr, gcFirst = TRUE)
{
ppt <- function(y) {
if (!is.na(y[4L]))
y[1L] <- y[1L] + y[4L]
if (!is.na(y[5L]))
y[2L] <- y[2L] + y[5L]
y[1L:3L]
}
if (!exists("proc.time"))
return(rep(NA_real_, 5L))
if (gcFirst)
gc(FALSE)
time <- proc.time()
on.exit(cat("Timing stopped at:", ppt(proc.time() - time),
"\n"))
expr
new.time <- proc.time()
on.exit()
structure(new.time - time, class = "proc_time")
}
## @type connection : raw
unserialize <- function (connection, refhook = NULL)
{
if (typeof(connection) != "raw" && !is.character(connection) &&
!inherits(connection, "connection"))
stop("'connection' must be a connection")
.Internal(unserialize(connection, refhook))
}
within.list <- function (data, expr, ...)
{
parent <- parent.frame()
e <- evalq(environment(), data, parent)
eval(substitute(expr), e)
l <- as.list(e)
l <- l[!sapply(l, is.null)]
nD <- length(del <- setdiff(names(data), (nl <- names(l))))
data[nl] <- l
if (nD)
data[del] <- if (nD == 1)
NULL
else vector("list", nD)
data
}
withVisible <- function (x)
.Internal(withVisible(x))
xor.hexmode <- function (a, b)
as.hexmode(bitwXor(as.hexmode(a), as.hexmode(b)))
xor.octmode <- function (a, b)
as.octmode(bitwXor(as.octmode(a), as.octmode(b)))
## @type name : character
"$.data.frame" <- function (x, name)
{
a <- x[[name]]
if (!is.null(a))
return(a)
a <- x[[name, exact = FALSE]]
if (!is.null(a) && getOption("warnPartialMatchDollar", default = FALSE)) {
names <- names(x)
warning(gettextf("Partial match of '%s' to '%s' in data frame",
name, names[pmatch(name, names)]))
}
return(a)
}
## @type i : numeric|logical|character
## @type j : numeric|logical|character
## @type drop : logical
"[.data.frame" <- function (x, i, j, drop = if (missing(i)) TRUE else length(cols) ==
1)
{
mdrop <- missing(drop)
Narg <- nargs() - (!mdrop)
has.j <- !missing(j)
if (!all(names(sys.call()) %in% c("", "drop")) && !isS4(x))
warning("named arguments other than 'drop' are discouraged")
if (Narg < 3L) {
if (!mdrop)
warning("'drop' argument will be ignored")
if (missing(i))
return(x)
if (is.matrix(i))
return(as.matrix(x)[i])
nm <- names(x)
if (is.null(nm))
nm <- character()
if (!is.character(i) && anyNA(nm)) {
names(nm) <- names(x) <- seq_along(x)
y <- NextMethod("[")
cols <- names(y)
if (anyNA(cols))
stop("undefined columns selected")
cols <- names(y) <- nm[cols]
}
else {
y <- NextMethod("[")
cols <- names(y)
if (!is.null(cols) && anyNA(cols))
stop("undefined columns selected")
}
if (anyDuplicated(cols))
names(y) <- make.unique(cols)
attr(y, "row.names") <- .row_names_info(x, 0L)
attr(y, "class") <- oldClass(x)
return(y)
}
if (missing(i)) {
if (drop && !has.j && length(x) == 1L)
return(.subset2(x, 1L))
nm <- names(x)
if (is.null(nm))
nm <- character()
if (has.j && !is.character(j) && anyNA(nm)) {
names(nm) <- names(x) <- seq_along(x)
y <- .subset(x, j)
cols <- names(y)
if (anyNA(cols))
stop("undefined columns selected")
cols <- names(y) <- nm[cols]
}
else {
y <- if (has.j)
.subset(x, j)
else x
cols <- names(y)
if (anyNA(cols))
stop("undefined columns selected")
}
if (drop && length(y) == 1L)
return(.subset2(y, 1L))
if (anyDuplicated(cols))
names(y) <- make.unique(cols)
nrow <- .row_names_info(x, 2L)
if (drop && !mdrop && nrow == 1L)
return(structure(y, class = NULL, row.names = NULL))
else {
attr(y, "class") <- oldClass(x)
attr(y, "row.names") <- .row_names_info(x, 0L)
return(y)
}
}
xx <- x
cols <- names(xx)
x <- vector("list", length(x))
x <- .Internal(copyDFattr(xx, x))
oldClass(x) <- attr(x, "row.names") <- NULL
if (has.j) {
nm <- names(x)
if (is.null(nm))
nm <- character()
if (!is.character(j) && anyNA(nm))
names(nm) <- names(x) <- seq_along(x)
x <- x[j]
cols <- names(x)
if (drop && length(x) == 1L) {
if (is.character(i)) {
rows <- attr(xx, "row.names")
i <- pmatch(i, rows, duplicates.ok = TRUE)
}
xj <- .subset2(.subset(xx, j), 1L)
return(if (length(dim(xj)) != 2L) xj[i] else xj[i,
, drop = FALSE])
}
if (anyNA(cols))
stop("undefined columns selected")
if (!is.null(names(nm)))
cols <- names(x) <- nm[cols]
nxx <- structure(seq_along(xx), names = names(xx))
sxx <- match(nxx[j], seq_along(xx))
}
else sxx <- seq_along(x)
rows <- NULL
if (is.character(i)) {
rows <- attr(xx, "row.names")
i <- pmatch(i, rows, duplicates.ok = TRUE)
}
for (j in seq_along(x)) {
xj <- xx[[sxx[j]]]
x[[j]] <- if (length(dim(xj)) != 2L)
xj[i]
else xj[i, , drop = FALSE]
}
if (drop) {
n <- length(x)
if (n == 1L)
return(x[[1L]])
if (n > 1L) {
xj <- x[[1L]]
nrow <- if (length(dim(xj)) == 2L)
dim(xj)[1L]
else length(xj)
drop <- !mdrop && nrow == 1L
}
else drop <- FALSE
}
if (!drop) {
if (is.null(rows))
rows <- attr(xx, "row.names")
rows <- rows[i]
if ((ina <- anyNA(rows)) | (dup <- anyDuplicated(rows))) {
if (!dup && is.character(rows))
dup <- "NA" %in% rows
if (ina)
rows[is.na(rows)] <- "NA"
if (dup)
rows <- make.unique(as.character(rows))
}
if (has.j && anyDuplicated(nm <- names(x)))
names(x) <- make.unique(nm)
if (is.null(rows))
rows <- attr(xx, "row.names")[i]
attr(x, "row.names") <- rows
oldClass(x) <- oldClass(xx)
}
x
}
as.character <- function (x, ...) .Primitive("as.character")
as.Date.date <- function (x, ...)
{
if (inherits(x, "date")) {
x <- (x - 3653)
return(structure(x, class = "Date"))
}
else stop(gettextf("'%s' is not a \"date\" object", deparse(substitute(x))))
}
as.list.Date <- function (x, ...)
lapply(seq_along(x), function(i) x[i])
"attributes<-" <- function (obj, value) .Primitive("attributes<-")
## @type what : character
## @return logical
capabilities <- function (what = NULL)
{
z <- .Internal(capabilities())
if (!is.null(what))
z <- z[match(what, names(z), 0L)]
if (.Platform$OS.type == "windows")
return(z)
nas <- names(z[is.na(z)])
if (any(nas %in% c("X11", "jpeg", "png", "tiff"))) {
z[nas] <- tryCatch(.Internal(capabilitiesX11()), error = function(e) FALSE)
}
z
}
check_tzones <- function (...)
{
tzs <- unique(sapply(list(...), function(x) {
y <- attr(x, "tzone")
if (is.null(y))
""
else y[1L]
}))
tzs <- tzs[tzs != ""]
if (length(tzs) > 1L)
warning("'tzone' attributes are inconsistent")
if (length(tzs))
tzs[1L]
else NULL
}
## @type tol : numeric
## @type LINPACK : logical
## @type x : logical|numeric
chol.default <- function (x, pivot = FALSE, LINPACK = FALSE, tol = -1, ...)
{
if (is.complex(x))
stop("complex matrices not permitted at present")
.Internal(La_chol(as.matrix(x), pivot, tol))
}
contributors <- function ()
{
outFile <- tempfile()
outConn <- file(outFile, open = "w")
writeLines(paste0("R is a project which is attempting to provide a ",
"modern piece of\nstatistical software for the ", "GNU suite of software.\n\n",
"The current R is the result of a collaborative ", "effort with\ncontributions from all over the ",
"world.\n\n"), outConn)
writeLines(readLines(file.path(R.home("doc"), "AUTHORS")),
outConn)
writeLines("", outConn)
writeLines(readLines(file.path(R.home("doc"), "THANKS")),
outConn)
close(outConn)
file.show(outFile, delete.file = TRUE)
}
## @type lag : integer
## @type differences : integer
## @type x : numeric
diff.default <- function (x, lag = 1L, differences = 1L, ...)
{
ismat <- is.matrix(x)
xlen <- if (ismat)
dim(x)[1L]
else length(x)
if (length(lag) != 1L || length(differences) > 1L || lag <
1L || differences < 1L)
stop("'lag' and 'differences' must be integers >= 1")
if (lag * differences >= xlen)
return(x[0L])
r <- unclass(x)
i1 <- -seq_len(lag)
if (ismat)
for (i in seq_len(differences)) r <- r[i1, , drop = FALSE] -
r[-nrow(r):-(nrow(r) - lag + 1L), , drop = FALSE]
else for (i in seq_len(differences)) r <- r[i1] - r[-length(r):-(length(r) -
lag + 1L)]
class(r) <- oldClass(x)
r
}
## @return character
encodeString <- function (x, width = 0L, quote = "", na.encode = TRUE, justify = c("left",
"right", "centre", "none"))
{
at <- attributes(x)
x <- as.character(x)
attributes(x) <- at
oldClass(x) <- NULL
justify <- match(match.arg(justify), c("left", "right", "centre",
"none")) - 1L
.Internal(encodeString(x, width, quote, justify, na.encode))
}
## @type from : character
## @type to : character
## @return logical|character
file.symlink <- function (from, to)
{
if (!(length(from)))
stop("no files to link from")
if (!(nt <- length(to)))
stop("no files/directory to link to")
if (nt == 1 && file.exists(to) && file.info(to)$isdir)
to <- file.path(to, basename(from))
.Internal(file.symlink(from, to))
}
## @type lib.loc : character
## @type verbose : logical
## @type package : character
## @type quiet : logical
find.package <- function (package = NULL, lib.loc = NULL, quiet = FALSE, verbose = getOption("verbose"))
{
if (is.null(package) && is.null(lib.loc) && !verbose) {
return(path.package())
}
if (length(package) == 1L && package %in% c("base", "tools",
"utils", "grDevices", "graphics", "stats", "datasets",
"methods", "grid", "parallel", "splines", "stats4", "tcltk"))
return(file.path(.Library, package))
use_loaded <- FALSE
if (is.null(package))
package <- .packages()
if (is.null(lib.loc)) {
use_loaded <- TRUE
lib.loc <- .libPaths()
}
if (!length(package))
return(character())
bad <- character()
out <- character()
for (pkg in package) {
paths <- character()
for (lib in lib.loc) {
dirs <- list.files(lib, pattern = paste0("^", pkg,
"$"), full.names = TRUE)
paths <- c(paths, dirs[file.info(dirs)$isdir & file.exists(file.path(dirs,
"DESCRIPTION"))])
}
if (use_loaded && pkg %in% loadedNamespaces()) {
dir <- if (pkg == "base")
system.file()
else getNamespaceInfo(pkg, "path")
paths <- c(dir, paths)
}
if (length(paths) && file.exists(file.path(paths[1],
"dummy_for_check"))) {
bad <- c(bad, pkg)
next
}
if (length(paths)) {
paths <- unique(paths)
valid_package_version_regexp <- .standard_regexps()$valid_package_version
db <- lapply(paths, function(p) {
pfile <- file.path(p, "Meta", "package.rds")
info <- if (file.exists(pfile))
readRDS(pfile)$DESCRIPTION[c("Package", "Version")]
else {
info <- tryCatch(read.dcf(file.path(p, "DESCRIPTION"),
c("Package", "Version"))[1, ], error = identity)
if (inherits(info, "error") || (length(info) !=
2L) || anyNA(info))
c(Package = NA, Version = NA)
else info
}
})
db <- do.call("rbind", db)
ok <- (apply(!is.na(db), 1L, all) & (db[, "Package"] ==
pkg) & (grepl(valid_package_version_regexp, db[,
"Version"])))
paths <- paths[ok]
}
if (length(paths) == 0L) {
bad <- c(bad, pkg)
next
}
if (length(paths) > 1L) {
paths <- paths[1L]
if (verbose)
warning(gettextf("package %s found more than once,\nusing the one found in %s",
sQuote(pkg), sQuote(paths)), domain = NA)
}
out <- c(out, paths)
}
if (!quiet && length(bad)) {
if (length(out) == 0L) {
if (length(bad) == 1L) {
stop(gettextf("there is no package called %s",
sQuote(pkg)), domain = NA)
}
else {
stop(ngettext(length(bad), "there is no package called",
"there are no packages called"), " ", paste(sQuote(bad),
collapse = ", "), domain = NA)
}
}
for (pkg in bad) warning(gettextf("there is no package called %s",
sQuote(pkg)), domain = NA)
}
out
}
## @type rightmost.closed : logical
## @type vec : numeric
## @type all.inside : logical
## @type x : numeric
findInterval <- function (x, vec, rightmost.closed = FALSE, all.inside = FALSE)
{
if (anyNA(vec))
stop("'vec' contains NAs")
if (is.unsorted(vec))
stop("'vec' must be sorted non-decreasingly")
.Internal(findInterval(as.double(vec), as.double(x), rightmost.closed,
all.inside))
}
## @type transpose : logical
## @type k : complex
## @type upper.tri : logical
forwardsolve <- function (l, x, k = ncol(l), upper.tri = FALSE, transpose = FALSE)
{
l <- as.matrix(l)
x.mat <- is.matrix(x)
if (!x.mat)
x <- as.matrix(x)
z <- .Internal(backsolve(l, x, k, upper.tri, transpose))
if (x.mat)
z
else drop(z)
}
## @type name : character
getNamespace <- function (name)
{
ns <- .Internal(getRegisteredNamespace(as.name(name)))
if (!is.null(ns))
ns
else tryCatch(loadNamespace(name), error = function(e) stop(e))
}
is.character <- function (x) .Primitive("is.character")
is.primitive <- function (x)
switch(typeof(x), special = , builtin = TRUE, FALSE)
is.recursive <- function (x) .Primitive("is.recursive")
isIncomplete <- function (con)
.Internal(isIncomplete(con))
margin.table <- function (x, margin = NULL)
{
if (!is.array(x))
stop("'x' is not an array")
if (length(margin)) {
z <- apply(x, margin, sum)
dim(z) <- dim(x)[margin]
dimnames(z) <- dimnames(x)[margin]
}
else return(sum(x))
class(z) <- oldClass(x)
z
}
## @type na.rm : logical
mean.default <- function (x, trim = 0, na.rm = FALSE, ...)
{
if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
warning("argument is not numeric or logical: returning NA")
return(NA_real_)
}
if (na.rm)
x <- x[!is.na(x)]
if (!is.numeric(trim) || length(trim) != 1L)
stop("'trim' must be numeric of length one")
n <- length(x)
if (trim > 0 && n) {
if (is.complex(x))
stop("trimmed means are not defined for complex data")
if (anyNA(x))
return(NA_real_)
if (trim >= 0.5)
return(stats::median(x, na.rm = FALSE))
lo <- floor(n * trim) + 1
hi <- n + 1 - lo
x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi]
}
.Internal(mean(x))
}
mean.POSIXct <- function (x, ...)
.POSIXct(mean(unclass(x), ...), attr(x, "tzone"))
mean.POSIXlt <- function (x, ...)
as.POSIXlt(mean(as.POSIXct(x), ...))
open.srcfile <- function (con, line, ...)
{
srcfile <- con
oldline <- srcfile$line
if (!is.null(oldline) && oldline > line)
close(srcfile)
conn <- srcfile$conn
if (is.null(conn)) {
if (!is.null(srcfile$wd)) {
olddir <- setwd(srcfile$wd)
on.exit(setwd(olddir))
}
timestamp <- file.info(srcfile$filename)[1, "mtime"]
if (!is.null(srcfile$timestamp) && !is.na(srcfile$timestamp) &&
(is.na(timestamp) || timestamp != srcfile$timestamp))
warning(gettextf("Timestamp of %s has changed", sQuote(srcfile$filename)),
call. = FALSE, domain = NA)
if (is.null(srcfile$encoding))
encoding <- getOption("encoding")
else encoding <- srcfile$encoding
srcfile$conn <- conn <- file(srcfile$filename, open = "rt",
encoding = encoding)
srcfile$line <- 1L
oldline <- 1L
}
else if (!isOpen(conn)) {
open(conn, open = "rt")
srcfile$line <- 1
oldline <- 1L
}
if (oldline < line) {
readLines(conn, line - oldline, warn = FALSE)
srcfile$line <- line
}
invisible(conn)
}
Ops.difftime <- function (e1, e2)
{
coerceTimeUnit <- function(x) {
switch(attr(x, "units"), secs = x, mins = 60 * x, hours = 60 *
60 * x, days = 60 * 60 * 24 * x, weeks = 60 * 60 *
24 * 7 * x)
}
if (nargs() == 1) {
switch(.Generic, `+` = {
}, `-` = {
e1[] <- -unclass(e1)
}, stop(gettextf("unary '%s' not defined for \"difftime\" objects",
.Generic), domain = NA, call. = FALSE))
return(e1)
}
boolean <- switch(.Generic, `<` = , `>` = , `==` = , `!=` = ,
`<=` = , `>=` = TRUE, FALSE)
if (boolean) {
if (inherits(e1, "difftime") && inherits(e2, "difftime")) {
e1 <- coerceTimeUnit(e1)
e2 <- coerceTimeUnit(e2)
}
NextMethod(.Generic)
}
else if (.Generic == "+" || .Generic == "-") {
if (inherits(e1, "difftime") && !inherits(e2, "difftime"))
return(structure(NextMethod(.Generic), units = attr(e1,
"units"), class = "difftime"))
if (!inherits(e1, "difftime") && inherits(e2, "difftime"))
return(structure(NextMethod(.Generic), units = attr(e2,
"units"), class = "difftime"))
u1 <- attr(e1, "units")
if (attr(e2, "units") == u1) {
structure(NextMethod(.Generic), units = u1, class = "difftime")
}
else {
e1 <- coerceTimeUnit(e1)
e2 <- coerceTimeUnit(e2)
structure(NextMethod(.Generic), units = "secs", class = "difftime")
}
}
else {
stop(gettextf("'%s' not defined for \"difftime\" objects",
.Generic), domain = NA)
}
}
## @type pkgname : character
## @type event : character
## @optional pkgname
packageEvent <- function (pkgname, event = c("onLoad", "attach", "detach", "onUnload"))
{
event <- match.arg(event)
pkgname <- strsplit(pkgname, "_", fixed = TRUE)[[1L]][1L]
paste("UserHook", pkgname, event, sep = "::")
}
"parent.env<-" <- function (env, value)
.Internal(`parent.env<-`(env, value))
parent.frame <- function (n = 1)
.Internal(parent.frame(n))
## @type package : character
## @type quiet : logical
path.package <- function (package = NULL, quiet = FALSE)
{
if (is.null(package))
package <- .packages()
if (length(package) == 0L)
return(character())
s <- search()
searchpaths <- lapply(seq_along(s), function(i) attr(as.environment(i),
"path"))
searchpaths[[length(s)]] <- system.file()
pkgs <- paste("package", package, sep = ":")
pos <- match(pkgs, s)
if (any(m <- is.na(pos))) {
if (!quiet) {
if (all(m))
stop("none of the packages are loaded")
else warning(sprintf(ngettext(as.integer(sum(m)),
"package %s is not loaded", "packages %s are not loaded"),
paste(package[m], collapse = ", ")), domain = NA)
}
pos <- pos[!m]
}
unlist(searchpaths[pos], use.names = FALSE)
}
## @type quote : logical
## @type max.levels : integer
print.factor <- function (x, quote = FALSE, max.levels = NULL, width = getOption("width"),
...)
{
ord <- is.ordered(x)
if (length(x) == 0L)
cat(if (ord)
"ordered"
else "factor", "(0)\n", sep = "")
else {
xx <- x
class(xx) <- NULL
levels(xx) <- NULL
xx[] <- as.character(x)
print(xx, quote = quote, ...)
}
maxl <- if (is.null(max.levels))
TRUE
else max.levels
if (maxl) {
n <- length(lev <- encodeString(levels(x), quote = ifelse(quote,
"\"", "")))
colsep <- if (ord)
" < "
else " "
T0 <- "Levels: "
if (is.logical(maxl))
maxl <- {
width <- width - (nchar(T0, "w") + 3L + 1L +
3L)
lenl <- cumsum(nchar(lev, "w") + nchar(colsep,
"w"))
if (n <= 1L || lenl[n] <= width)
n
else max(1L, which.max(lenl > width) - 1L)
}
drop <- n > maxl
cat(if (drop)
paste(format(n), ""), T0, paste(if (drop)
c(lev[1L:max(1, maxl - 1)], "...", if (maxl > 1) lev[n])
else lev, collapse = colsep), "\n", sep = "")
}
invisible(x)
}
print.listof <- function (x, ...)
{
nn <- names(x)
ll <- length(x)
if (length(nn) != ll)
nn <- paste("Component", seq.int(ll))
for (i in seq_len(ll)) {
cat(nn[i], ":\n")
print(x[[i]], ...)
cat("\n")
}
invisible(x)
}
print.srcref <- function (x, useSource = TRUE, ...)
{
cat(as.character(x, useSource = useSource), sep = "\n")
invisible(x)
}
## @type path : character
## @return logical
readRenviron <- function (path)
.Internal(readRenviron(path))
## @type x : character
## @type invert : logical
"regmatches<-" <- function (x, m, invert = FALSE, value)
{
if (!length(x))
return(x)
ili <- is.list(m)
if (!ili && invert && any(m == -1L)) {
y <- rep_len(list(character()), length(x))
y[m > -1L] <- as.list(regmatches(x, m, FALSE))
}
else {
y <- regmatches(x, m, !invert)
}
if (!ili && !invert) {
value <- as.character(value)
if (anyNA(value))
stop("missing replacement values are not allowed")
pos <- which(sapply(y, length) == 2L)
np <- length(pos)
nv <- length(value)
if (np != nv) {
if (!nv)
stop("must have replacement values for matches")
value <- rep_len(value, np)
}
y <- y[pos]
x[pos] <- paste0(sapply(y, `[`, 1L), value, sapply(y,
`[`, 2L))
return(x)
}
value <- lapply(value, as.character)
if (anyNA(value))
stop("missing replacement values are not allowed")
if (!length(value))
stop("value does not provide any replacement values")
value <- rep_len(value, length(x))
y <- if (invert) {
Map(function(u, v) {
nu <- length(u)
nv <- length(v)
if (nv != (nu + 1L)) {
if (!nv)
stop("must have replacements for non-matches")
v <- rep_len(v, nu + 1L)
}
paste0(v, c(u, ""), collapse = "")
}, y, value, USE.NAMES = FALSE)
}
else {
Map(function(u, v) {
nu <- length(u)
nv <- length(v)
if (nv != (nu - 1L)) {
if (!nv)
stop("must have replacements for matches")
v <- rep_len(v, nu - 1L)
}
paste0(u, c(v, ""), collapse = "")
}, y, value, USE.NAMES = FALSE)
}
y <- unlist(y)
names(y) <- names(x)
y
}
round.POSIXt <- function (x, units = c("secs", "mins", "hours", "days"))
{
if (is.numeric(units) && units == 0)
units <- "secs"
units <- match.arg(units)
x <- as.POSIXct(x)
x <- x + switch(units, secs = 0.5, mins = 30, hours = 1800,
days = 43200)
trunc.POSIXt(x, units = units)
}
## @type transient : logical
setTimeLimit <- function (cpu = Inf, elapsed = Inf, transient = FALSE)
.Internal(setTimeLimit(cpu, elapsed, transient))
## @type write : logical
## @type timeout : numeric
socketSelect <- function (socklist, write = FALSE, timeout = NULL)
{
if (is.null(timeout))
timeout <- -1
else if (timeout < 0)
stop("'timeout' must be NULL or a non-negative number")
if (length(write) < length(socklist))
write <- rep_len(write, length(socklist))
.Internal(sockSelect(socklist, write, timeout))
}
## @type x : complex|logical|character
## @type decreasing : logical
sort.default <- function (x, decreasing = FALSE, na.last = NA, ...)
{
if (is.object(x))
x[order(x, na.last = na.last, decreasing = decreasing)]
else sort.int(x, na.last = na.last, decreasing = decreasing,
...)
}
## @type x : complex|logical|character
## @type decreasing : logical
sort.POSIXlt <- function (x, decreasing = FALSE, na.last = NA, ...)
x[order(as.POSIXct(x), na.last = na.last, decreasing = decreasing)]
## @type filename : character
srcfilealias <- function (filename, srcfile)
{
stopifnot(is.character(filename), length(filename) == 1L)
e <- new.env(parent = emptyenv())
e$filename <- filename
e$original <- srcfile
class(e) <- c("srcfilealias", "srcfile")
return(e)
}
storage.mode <- function (x)
switch(tx <- typeof(x), closure = , builtin = , special = "function",
tx)
## @optional na.rm
Summary.Date <- function (..., na.rm)
{
ok <- switch(.Generic, max = , min = , range = TRUE, FALSE)
if (!ok)
stop(gettextf("%s not defined for \"Date\" objects",
.Generic), domain = NA)
val <- NextMethod(.Generic)
class(val) <- oldClass(list(...)[[1L]])
val
}
sys.function <- function (which = 0L)
.Internal(sys.function(which))
## @type paths : character
Sys.readlink <- function (paths)
.Internal(Sys.readlink(paths))
## @type location : logical|character
## @return character
Sys.timezone <- function (location = TRUE)
{
tz <- Sys.getenv("TZ", names = FALSE)
if (!location || nzchar(tz))
return(Sys.getenv("TZ", unset = NA_character_))
lt <- normalizePath("/etc/localtime")
if (grepl(pat <- "^/usr/share/zoneinfo/", lt))
sub(pat, "", lt)
else NA_character_
}
## @type x : character
## @return logical
Sys.unsetenv <- function (x)
.Internal(Sys.unsetenv(as.character(x)))
t.data.frame <- function (x)
{
x <- as.matrix(x)
NextMethod("t")
}
tracingState <- function (on = NULL)
.Internal(traceOnOff(on))
trunc.POSIXt <- function (x, units = c("secs", "mins", "hours", "days"), ...)
{
units <- match.arg(units)
x <- as.POSIXlt(x)
if (length(x$sec))
switch(units, secs = {
x$sec <- trunc(x$sec)
}, mins = {
x$sec[] <- 0
}, hours = {
x$sec[] <- 0
x$min[] <- 0L
}, days = {
x$sec[] <- 0
x$min[] <- 0L
x$hour[] <- 0L
x$isdst[] <- -1L
})
x
}
## @type fromLast : logical
## @type MARGIN : integer
unique.array <- function (x, incomparables = FALSE, MARGIN = 1, fromLast = FALSE,
...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
dx <- dim(x)
ndim <- length(dx)
if (length(MARGIN) > ndim || any(MARGIN > ndim))
stop(gettextf("MARGIN = %d is invalid for dim = %d",
MARGIN, dx), domain = NA)
collapse <- (ndim > 1L) && (prod(dx[-MARGIN]) > 1L)
temp <- if (collapse)
apply(x, MARGIN, function(x) paste(x, collapse = "\r"))
else x
args <- rep(alist(a = ), ndim)
names(args) <- NULL
args[[MARGIN]] <- !duplicated.default(temp, fromLast = fromLast,
...)
do.call("[", c(list(x), args, list(drop = FALSE)))
}
with.default <- function (data, expr, ...)
eval(substitute(expr), data, enclos = parent.frame())
withRestarts <- function (expr, ...)
{
docall <- function(fun, args) {
if ((is.character(fun) && length(fun) == 1L) || is.name(fun))
fun <- get(as.character(fun), envir = parent.frame(),
mode = "function")
do.call("fun", lapply(args, enquote))
}
makeRestart <- function(name = "", handler = function(...) NULL,
description = "", test = function(c) TRUE, interactive = NULL) {
structure(list(name = name, exit = NULL, handler = handler,
description = description, test = test, interactive = interactive),
class = "restart")
}
makeRestartList <- function(...) {
specs <- list(...)
names <- names(specs)
restarts <- vector("list", length(specs))
for (i in seq_along(specs)) {
spec <- specs[[i]]
name <- names[i]
if (is.function(spec))
restarts[[i]] <- makeRestart(handler = spec)
else if (is.character(spec))
restarts[[i]] <- makeRestart(description = spec)
else if (is.list(spec))
restarts[[i]] <- docall("makeRestart", spec)
else stop("not a valid restart specification")
restarts[[i]]$name <- name
}
restarts
}
withOneRestart <- function(expr, restart) {
doWithOneRestart <- function(expr, restart) {
restart$exit <- environment()
.Internal(.addRestart(restart))
expr
}
restartArgs <- doWithOneRestart(return(expr), restart)
docall(restart$handler, restartArgs)
}
withRestartList <- function(expr, restarts) {
nr <- length(restarts)
if (nr > 1L)
withOneRestart(withRestartList(expr, restarts[-nr]),
restarts[[nr]])
else if (nr == 1L)
withOneRestart(expr, restarts[[1L]])
else expr
}
restarts <- makeRestartList(...)
if (length(restarts) == 0L)
expr
else if (length(restarts) == 1L)
withOneRestart(expr, restarts[[1L]])
else withRestartList(expr, restarts)
}
xtfrm.factor <- function (x)
as.integer(x)
"[.simple.list" <- function (x, i, ...)
structure(NextMethod("["), class = class(x))
## @type exact : logical
"[[.data.frame" <- function (x, ..., exact = TRUE)
{
na <- nargs() - (!missing(exact))
if (!all(names(sys.call()) %in% c("", "exact")))
warning("named arguments other than 'exact' are discouraged")
if (na < 3L)
(function(x, i, exact) if (is.matrix(i))
as.matrix(x)[[i]]
else .subset2(x, i, exact = exact))(x, ..., exact = exact)
else {
col <- .subset2(x, ..2, exact = exact)
i <- if (is.character(..1))
pmatch(..1, row.names(x), duplicates.ok = TRUE)
else ..1
col[[i, exact = exact]]
}
}
## @type check.attributes : logical
## @return logical
all.equal.raw <- function (target, current, ..., check.attributes = TRUE)
{
if (!is.logical(check.attributes))
stop(gettextf("'%s' must be logical", "check.attributes"),
domain = NA)
msg <- if (check.attributes)
attr.all.equal(target, current, ...)
if (data.class(target) != data.class(current)) {
msg <- c(msg, paste0("target is ", data.class(target),
", current is ", data.class(current)))
return(msg)
}
lt <- length(target)
lc <- length(current)
if (lt != lc) {
if (!is.null(msg))
msg <- msg[-grep("\\bLengths\\b", msg)]
msg <- c(msg, paste0("Lengths (", lt, ", ", lc, ") differ (comparison on first ",
ll <- min(lt, lc), " components)"))
ll <- seq_len(ll)
target <- target[ll]
current <- current[ll]
}
nas <- is.na(target)
nasc <- is.na(current)
if (any(nas != nasc)) {
msg <- c(msg, paste("'is.NA' value mismatch:", sum(nasc),
"in current", sum(nas), "in target"))
return(msg)
}
ne <- !nas & (target != current)
if (!any(ne) && is.null(msg))
TRUE
else if (sum(ne) == 1L)
c(msg, paste("1 element mismatch"))
else if (sum(ne) > 1L)
c(msg, paste(sum(ne), "element mismatches"))
else msg
}
anyDuplicated <- function (x, incomparables = FALSE, ...)
UseMethod("anyDuplicated")
anyNA.POSIXlt <- function (x)
anyNA(as.POSIXct(x))
## @type perm : complex|character
aperm.default <- function (a, perm = NULL, resize = TRUE, ...)
.Internal(aperm(a, perm, resize))
## @type optional : logical
## @type row.names : character
as.data.frame <- function (x, row.names = NULL, optional = FALSE, ...)
{
if (is.null(x))
return(as.data.frame(list()))
UseMethod("as.data.frame")
}
as.Date.dates <- function (x, ...)
{
if (inherits(x, "dates")) {
z <- attr(x, "origin")
x <- trunc(as.numeric(x))
if (length(z) == 3L && is.numeric(z))
x <- x + as.numeric(as.Date(paste(z[3L], z[1L], z[2L],
sep = "/")))
return(structure(x, class = "Date"))
}
else stop(gettextf("'%s' is not a \"dates\" object", deparse(substitute(x))))
}
as.expression <- function (x, ...)
UseMethod("as.expression")
## @type simplify : logical
## @optional FUN
by.data.frame <- function (data, INDICES, FUN, ..., simplify = TRUE)
{
if (!is.list(INDICES)) {
IND <- vector("list", 1L)
IND[[1L]] <- INDICES
names(IND) <- deparse(substitute(INDICES))[1L]
}
else IND <- INDICES
FUNx <- function(x) FUN(data[x, , drop = FALSE], ...)
nd <- nrow(data)
structure(eval(substitute(tapply(seq_len(nd), IND, FUNx,
simplify = simplify)), data), call = match.call(), class = "by")
}
clearPushBack <- function (connection)
.Internal(clearPushBack(connection))
close.srcfile <- function (con, ...)
{
srcfile <- con
conn <- srcfile$conn
if (is.null(conn))
return()
else {
close(conn)
rm(list = c("conn", "line"), envir = srcfile)
}
}
conditionCall <- function (c)
UseMethod("conditionCall")
delayedAssign <- function (x, value, eval.env = parent.frame(1), assign.env = parent.frame(1))
.Internal(delayedAssign(x, substitute(value), eval.env, assign.env))
"environment<-" <- function (fun, value) .Primitive("environment<-")
## @type x : numeric
format.factor <- function (x, ...)
format(structure(as.character(x), names = names(x), dim = dim(x),
dimnames = dimnames(x)), ...)
## @type doStop : logical
getCallingDLL <- function (f = sys.function(-1), doStop = FALSE)
{
e <- environment(f)
if (!isNamespace(e)) {
if (doStop)
stop("function is not in a namespace, so cannot locate associated DLL")
else return(NULL)
}
if (is.null(env <- e$.__NAMESPACE__.))
env <- baseenv()
if (exists("DLLs", envir = env) && length(env$DLLs))
return(env$DLLs[[1L]])
else {
if (doStop)
stop("looking for DLL for native routine call, but no DLLs in namespace of call")
else NULL
}
NULL
}
## @type what : complex
getConnection <- function (what)
.Internal(getConnection(what))
geterrmessage <- function ()
.Internal(geterrmessage())
getLoadedDLLs <- function ()
.Internal(getLoadedDLLs())
icuSetCollate <- function (...)
.Internal(icuSetCollate(...))
importIntoEnv <- function (impenv, impnames, expenv, expnames)
{
exports <- getNamespaceInfo(expenv, "exports")
ex <- .Internal(ls(exports, TRUE))
if (!all(expnames %in% ex)) {
miss <- expnames[!expnames %in% ex]
if (all(grepl("^\\.__C__", miss))) {
miss <- sub("^\\.__C__", "", miss)
stop(sprintf(ngettext(length(miss), "class %s is not exported by 'namespace:%s'",
"classes %s are not exported by 'namespace:%s'"),
paste(paste0("\"", miss, "\""), collapse = ", "),
getNamespaceName(expenv)), call. = FALSE, domain = NA)
}
else {
stop(sprintf(ngettext(length(miss), "object %s is not exported by 'namespace:%s'",
"objects %s are not exported by 'namespace:%s'"),
paste(sQuote(miss), collapse = ", "), getNamespaceName(expenv)),
call. = FALSE, domain = NA)
}
}
expnames <- unlist(lapply(expnames, get, envir = exports,
inherits = FALSE))
if (is.null(impnames))
impnames <- character()
if (is.null(expnames))
expnames <- character()
.Internal(importIntoEnv(impenv, impnames, expenv, expnames))
}
invokeRestart <- function (r, ...)
{
if (!isRestart(r)) {
res <- findRestart(r)
if (is.null(res))
stop(gettextf("no 'restart' '%s' found", as.character(r)),
domain = NA)
r <- res
}
.Internal(.invokeRestart(r, list(...)))
}
is.data.frame <- function (x)
inherits(x, "data.frame")
is.expression <- function (x) .Primitive("is.expression")
is.na.POSIXlt <- function (x)
is.na(as.POSIXct(x))
julian.POSIXt <- function (x, origin = as.POSIXct("1970-01-01", tz = "GMT"), ...)
{
origin <- as.POSIXct(origin)
if (length(origin) != 1L)
stop("'origin' must be of length one")
res <- difftime(as.POSIXct(x), origin, units = "days")
structure(res, origin = origin)
}
## @type norm : complex|character
## @type exact : logical
## @type method : character
kappa.default <- function (z, exact = FALSE, norm = NULL, method = c("qr", "direct"),
...)
{
method <- match.arg(method)
z <- as.matrix(z)
norm <- if (!is.null(norm))
match.arg(norm, c("2", "1", "O", "I"))
else "2"
if (exact && norm == "2") {
s <- svd(z, nu = 0, nv = 0)$d
max(s)/min(s[s > 0])
}
else {
if (exact)
warning(gettextf("norm '%s' currently always uses exact = FALSE",
norm))
d <- dim(z)
if (method == "qr" || d[1L] != d[2L])
kappa.qr(qr(if (d[1L] < d[2L])
t(z)
else z), exact = FALSE, norm = norm, ...)
else .kappa_tri(z, exact = FALSE, norm = norm, ...)
}
}
library.dynam <- function (chname, package, lib.loc, verbose = getOption("verbose"),
file.ext = .Platform$dynlib.ext, ...)
{
dll_list <- .dynLibs()
if (missing(chname) || !nzchar(chname))
return(dll_list)
package
lib.loc
r_arch <- .Platform$r_arch
chname1 <- paste0(chname, file.ext)
for (pkg in find.package(package, lib.loc, verbose = verbose)) {
DLLpath <- if (nzchar(r_arch))
file.path(pkg, "libs", r_arch)
else file.path(pkg, "libs")
file <- file.path(DLLpath, chname1)
if (file.exists(file))
break
else file <- ""
}
if (file == "")
if (.Platform$OS.type == "windows")
stop(gettextf("DLL %s not found: maybe not installed for this architecture?",
sQuote(chname)), domain = NA)
else stop(gettextf("shared object %s not found", sQuote(chname1)),
domain = NA)
file <- file.path(normalizePath(DLLpath, "/", TRUE), chname1)
ind <- vapply(dll_list, function(x) x[["path"]] == file,
NA)
if (length(ind) && any(ind)) {
if (verbose)
if (.Platform$OS.type == "windows")
message(gettextf("DLL %s already loaded", sQuote(chname1)),
domain = NA)
else message(gettextf("shared object '%s' already loaded",
sQuote(chname1)), domain = NA)
return(invisible(dll_list[[seq_along(dll_list)[ind]]]))
}
if (.Platform$OS.type == "windows") {
PATH <- Sys.getenv("PATH")
Sys.setenv(PATH = paste(gsub("/", "\\\\", DLLpath), PATH,
sep = ";"))
on.exit(Sys.setenv(PATH = PATH))
}
if (verbose)
message(gettextf("now dyn.load(\"%s\") ...", file), domain = NA)
dll <- if ("DLLpath" %in% names(list(...)))
dyn.load(file, ...)
else dyn.load(file, DLLpath = DLLpath, ...)
.dynLibs(c(dll_list, list(dll)))
invisible(dll)
}
## @type partial : logical
## @type lib.loc : character
## @type package : character
## @optional package
loadNamespace <- function (package, lib.loc = NULL, keep.source = getOption("keep.source.pkgs"),
partial = FALSE, versionCheck = NULL)
{
package <- as.character(package)[[1L]]
dynGet <- function(name, notFound = stop(gettextf("%s not found",
name), domain = NA)) {
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
loading <- dynGet("__NameSpacesLoading__", NULL)
if (match(package, loading, 0L))
stop("cyclic namespace dependency detected when loading ",
sQuote(package), ", already loading ", paste(sQuote(loading),
collapse = ", "), domain = NA)
"__NameSpacesLoading__" <- c(package, loading)
ns <- .Internal(getRegisteredNamespace(as.name(package)))
if (!is.null(ns)) {
if (length(z <- versionCheck) == 3L) {
current <- getNamespaceVersion(ns)
if (!do.call(z$op, list(as.numeric_version(current),
z$version)))
stop(gettextf("namespace %s %s is already loaded, but %s %s is required",
sQuote(package), current, z$op, z$version),
domain = NA)
}
ns
}
else {
runHook <- function(hookname, env, libname, pkgname) {
if (exists(hookname, envir = env, inherits = FALSE)) {
fun <- get(hookname, envir = env, inherits = FALSE)
res <- tryCatch(fun(libname, pkgname), error = identity)
if (inherits(res, "error")) {
stop(gettextf("%s failed in %s() for '%s', details:\n call: %s\n error: %s",
hookname, "loadNamespace", pkgname, deparse(conditionCall(res))[1L],
conditionMessage(res)), call. = FALSE, domain = NA)
}
}
}
runUserHook <- function(pkgname, pkgpath) {
hooks <- getHook(packageEvent(pkgname, "onLoad"))
for (fun in hooks) try(fun(pkgname, pkgpath))
}
makeNamespace <- function(name, version = NULL, lib = NULL) {
impenv <- new.env(parent = .BaseNamespaceEnv, hash = TRUE)
attr(impenv, "name") <- paste("imports", name, sep = ":")
env <- new.env(parent = impenv, hash = TRUE)
name <- as.character(as.name(name))
version <- as.character(version)
info <- new.env(hash = TRUE, parent = baseenv())
assign(".__NAMESPACE__.", info, envir = env)
assign("spec", c(name = name, version = version),
envir = info)
setNamespaceInfo(env, "exports", new.env(hash = TRUE,
parent = baseenv()))
dimpenv <- new.env(parent = baseenv(), hash = TRUE)
attr(dimpenv, "name") <- paste("lazydata", name,
sep = ":")
setNamespaceInfo(env, "lazydata", dimpenv)
setNamespaceInfo(env, "imports", list(base = TRUE))
setNamespaceInfo(env, "path", normalizePath(file.path(lib,
name), "/", TRUE))
setNamespaceInfo(env, "dynlibs", NULL)
setNamespaceInfo(env, "S3methods", matrix(NA_character_,
0L, 3L))
assign(".__S3MethodsTable__.", new.env(hash = TRUE,
parent = baseenv()), envir = env)
.Internal(registerNamespace(name, env))
env
}
sealNamespace <- function(ns) {
namespaceIsSealed <- function(ns) environmentIsLocked(ns)
ns <- asNamespace(ns, base.OK = FALSE)
if (namespaceIsSealed(ns))
stop(gettextf("namespace %s is already sealed in 'loadNamespace'",
sQuote(getNamespaceName(ns))), call. = FALSE,
domain = NA)
lockEnvironment(ns, TRUE)
lockEnvironment(parent.env(ns), TRUE)
}
addNamespaceDynLibs <- function(ns, newlibs) {
dynlibs <- getNamespaceInfo(ns, "dynlibs")
setNamespaceInfo(ns, "dynlibs", c(dynlibs, newlibs))
}
bindTranslations <- function(pkgname, pkgpath) {
std <- c("compiler", "foreign", "grDevices", "graphics",
"grid", "methods", "parallel", "splines", "stats",
"stats4", "tcltk", "tools", "utils")
popath <- if (pkgname %in% std)
.popath
else file.path(pkgpath, "po")
if (!file.exists(popath))
return()
bindtextdomain(pkgname, popath)
bindtextdomain(paste("R", pkgname, sep = "-"), popath)
}
assignNativeRoutines <- function(dll, lib, env, nativeRoutines) {
if (length(nativeRoutines) == 0L)
return(NULL)
if (nativeRoutines$useRegistration) {
fixes <- nativeRoutines$registrationFixes
routines <- getDLLRegisteredRoutines.DLLInfo(dll,
addNames = FALSE)
lapply(routines, function(type) {
lapply(type, function(sym) {
varName <- paste0(fixes[1L], sym$name, fixes[2L])
if (exists(varName, envir = env))
warning(gettextf("failed to assign RegisteredNativeSymbol for %s to %s since %s is already defined in the %s namespace",
sym$name, varName, varName, sQuote(package)),
domain = NA)
else assign(varName, sym, envir = env)
})
})
}
symNames <- nativeRoutines$symbolNames
if (length(symNames) == 0L)
return(NULL)
symbols <- getNativeSymbolInfo(symNames, dll, unlist = FALSE,
withRegistrationInfo = TRUE)
lapply(seq_along(symNames), function(i) {
varName <- names(symNames)[i]
origVarName <- symNames[i]
if (exists(varName, envir = env))
if (origVarName != varName)
warning(gettextf("failed to assign NativeSymbolInfo for %s to %s since %s is already defined in the %s namespace",
origVarName, varName, varName, sQuote(package)),
domain = NA)
else warning(gettextf("failed to assign NativeSymbolInfo for %s since %s is already defined in the %s namespace",
origVarName, varName, sQuote(package)), domain = NA)
else assign(varName, symbols[[origVarName]],
envir = env)
})
symbols
}
pkgpath <- find.package(package, lib.loc, quiet = TRUE)
if (length(pkgpath) == 0L)
stop(gettextf("there is no package called %s", sQuote(package)),
domain = NA)
bindTranslations(package, pkgpath)
package.lib <- dirname(pkgpath)
package <- basename(pkgpath)
if (!packageHasNamespace(package, package.lib)) {
hasNoNamespaceError <- function(package, package.lib,
call = NULL) {
class <- c("hasNoNamespaceError", "error", "condition")
msg <- gettextf("package %s does not have a namespace",
sQuote(package))
structure(list(message = msg, package = package,
package.lib = package.lib, call = call), class = class)
}
stop(hasNoNamespaceError(package, package.lib))
}
nsInfoFilePath <- file.path(pkgpath, "Meta", "nsInfo.rds")
nsInfo <- if (file.exists(nsInfoFilePath))
readRDS(nsInfoFilePath)
else parseNamespaceFile(package, package.lib, mustExist = FALSE)
pkgInfoFP <- file.path(pkgpath, "Meta", "package.rds")
if (file.exists(pkgInfoFP)) {
pkgInfo <- readRDS(pkgInfoFP)
version <- pkgInfo$DESCRIPTION["Version"]
vI <- pkgInfo$Imports
if (is.null(built <- pkgInfo$Built))
stop(gettextf("package %s has not been installed properly\n",
sQuote(basename(pkgpath))), call. = FALSE,
domain = NA)
R_version_built_under <- as.numeric_version(built$R)
if (R_version_built_under < "3.0.0")
stop(gettextf("package %s was built before R 3.0.0: please re-install it",
sQuote(basename(pkgpath))), call. = FALSE,
domain = NA)
dependsMethods <- "methods" %in% names(pkgInfo$Depends)
if (dependsMethods)
loadNamespace("methods")
if (length(z <- versionCheck) == 3L && !do.call(z$op,
list(as.numeric_version(version), z$version)))
stop(gettextf("namespace %s %s is being loaded, but %s %s is required",
sQuote(package), version, z$op, z$version),
domain = NA)
}
ns <- makeNamespace(package, version = version, lib = package.lib)
on.exit(.Internal(unregisterNamespace(package)))
for (i in nsInfo$imports) {
if (is.character(i))
namespaceImport(ns, loadNamespace(i, c(lib.loc,
.libPaths()), versionCheck = vI[[i]]), from = package)
else namespaceImportFrom(ns, loadNamespace(j <- i[[1L]],
c(lib.loc, .libPaths()), versionCheck = vI[[j]]),
i[[2L]], from = package)
}
for (imp in nsInfo$importClasses) namespaceImportClasses(ns,
loadNamespace(j <- imp[[1L]], c(lib.loc, .libPaths()),
versionCheck = vI[[j]]), imp[[2L]], from = package)
for (imp in nsInfo$importMethods) namespaceImportMethods(ns,
loadNamespace(j <- imp[[1L]], c(lib.loc, .libPaths()),
versionCheck = vI[[j]]), imp[[2L]], from = package)
"__LoadingNamespaceInfo__" <- list(libname = package.lib,
pkgname = package)
env <- asNamespace(ns)
assign(".packageName", package, envir = env)
codename <- strsplit(package, "_", fixed = TRUE)[[1L]][1L]
codeFile <- file.path(pkgpath, "R", codename)
if (file.exists(codeFile)) {
res <- try(sys.source(codeFile, env, keep.source = keep.source))
if (inherits(res, "try-error"))
stop(gettextf("unable to load R code in package %s",
sQuote(package)), call. = FALSE, domain = NA)
}
if (partial)
return(ns)
dbbase <- file.path(pkgpath, "R", "sysdata")
if (file.exists(paste0(dbbase, ".rdb")))
lazyLoad(dbbase, env)
dbbase <- file.path(pkgpath, "data", "Rdata")
if (file.exists(paste0(dbbase, ".rdb")))
lazyLoad(dbbase, getNamespaceInfo(ns, "lazydata"))
registerS3methods(nsInfo$S3methods, package, env)
dlls <- list()
dynLibs <- nsInfo$dynlibs
for (i in seq_along(dynLibs)) {
lib <- dynLibs[i]
dlls[[lib]] <- library.dynam(lib, package, package.lib)
assignNativeRoutines(dlls[[lib]], lib, env, nsInfo$nativeRoutines[[lib]])
if (!is.null(names(nsInfo$dynlibs)) && names(nsInfo$dynlibs)[i] !=
"")
assign(names(nsInfo$dynlibs)[i], dlls[[lib]],
envir = env)
setNamespaceInfo(env, "DLLs", dlls)
}
addNamespaceDynLibs(env, nsInfo$dynlibs)
Sys.setenv(`_R_NS_LOAD_` = package)
on.exit(Sys.unsetenv("_R_NS_LOAD_"), add = TRUE)
runHook(".onLoad", env, package.lib, package)
exports <- nsInfo$exports
for (p in nsInfo$exportPatterns) exports <- c(ls(env,
pattern = p, all.names = TRUE), exports)
if (.isMethodsDispatchOn() && methods:::.hasS4MetaData(ns) &&
!identical(package, "methods")) {
methods:::cacheMetaData(ns, TRUE, ns)
for (p in nsInfo$exportPatterns) {
expp <- ls(ns, pattern = p, all.names = TRUE)
newEx <- !(expp %in% exports)
if (any(newEx))
exports <- c(expp[newEx], exports)
}
expClasses <- nsInfo$exportClasses
pClasses <- character()
aClasses <- methods:::getClasses(ns)
classPatterns <- nsInfo$exportClassPatterns
if (!length(classPatterns))
classPatterns <- nsInfo$exportPatterns
for (p in classPatterns) {
pClasses <- c(aClasses[grep(p, aClasses)], pClasses)
}
pClasses <- unique(pClasses)
if (length(pClasses)) {
good <- vapply(pClasses, methods:::isClass, NA,
where = ns)
if (!any(good) && length(nsInfo$exportClassPatterns))
warning(gettextf("'exportClassPattern' specified in 'NAMESPACE' but no matching classes in package %s",
sQuote(package)), call. = FALSE, domain = NA)
expClasses <- c(expClasses, pClasses[good])
}
if (length(expClasses)) {
missingClasses <- !vapply(expClasses, methods:::isClass,
NA, where = ns)
if (any(missingClasses))
stop(gettextf("in package %s classes %s were specified for export but not defined",
sQuote(package), paste(expClasses[missingClasses],
collapse = ", ")), domain = NA)
expClasses <- paste0(methods:::classMetaName(""),
expClasses)
}
allGenerics <- unique(c(methods:::.getGenerics(ns),
methods:::.getGenerics(parent.env(ns))))
expMethods <- nsInfo$exportMethods
addGenerics <- expMethods[is.na(match(expMethods,
exports))]
if (length(addGenerics)) {
nowhere <- sapply(addGenerics, function(what) !exists(what,
mode = "function", envir = ns))
if (any(nowhere)) {
warning(gettextf("no function found corresponding to methods exports from %s for: %s",
sQuote(package), paste(sQuote(sort(unique(addGenerics[nowhere]))),
collapse = ", ")), domain = NA, call. = FALSE)
addGenerics <- addGenerics[!nowhere]
}
if (length(addGenerics)) {
addGenerics <- addGenerics[sapply(addGenerics,
function(what) !is.primitive(get(what, mode = "function",
envir = ns)))]
ok <- sapply(addGenerics, methods:::.findsGeneric,
ns)
if (!all(ok)) {
bad <- sort(unique(addGenerics[!ok]))
msg <- ngettext(length(bad), "Function found when exporting methods from the namespace %s which is not S4 generic: %s",
"Functions found when exporting methods from the namespace %s which are not S4 generic: %s",
domain = "R-base")
stop(sprintf(msg, sQuote(package), paste(sQuote(bad),
collapse = ", ")), domain = NA, call. = FALSE)
}
else if (any(ok > 1L))
addGenerics <- addGenerics[ok < 2L]
}
exports <- c(exports, addGenerics)
}
expTables <- character()
if (length(allGenerics)) {
expMethods <- unique(c(expMethods, exports[!is.na(match(exports,
allGenerics))]))
missingMethods <- !(expMethods %in% allGenerics)
if (any(missingMethods))
stop(gettextf("in %s methods for export not found: %s",
sQuote(package), paste(expMethods[missingMethods],
collapse = ", ")), domain = NA)
tPrefix <- methods:::.TableMetaPrefix()
allMethodTables <- unique(c(methods:::.getGenerics(ns,
tPrefix), methods:::.getGenerics(parent.env(ns),
tPrefix)))
needMethods <- (exports %in% allGenerics) & !(exports %in%
expMethods)
if (any(needMethods))
expMethods <- c(expMethods, exports[needMethods])
pm <- allGenerics[!(allGenerics %in% expMethods)]
if (length(pm)) {
prim <- logical(length(pm))
for (i in seq_along(prim)) {
f <- methods:::getFunction(pm[[i]], FALSE,
FALSE, ns)
prim[[i]] <- is.primitive(f)
}
expMethods <- c(expMethods, pm[prim])
}
for (i in seq_along(expMethods)) {
mi <- expMethods[[i]]
if (!(mi %in% exports) && exists(mi, envir = ns,
mode = "function", inherits = FALSE))
exports <- c(exports, mi)
pattern <- paste0(tPrefix, mi, ":")
ii <- grep(pattern, allMethodTables, fixed = TRUE)
if (length(ii)) {
if (length(ii) > 1L) {
warning(gettextf("multiple methods tables found for %s",
sQuote(mi)), call. = FALSE, domain = NA)
ii <- ii[1L]
}
expTables[[i]] <- allMethodTables[ii]
}
else {
warning(gettextf("failed to find metadata object for %s",
sQuote(mi)), call. = FALSE, domain = NA)
}
}
}
else if (length(expMethods))
stop(gettextf("in package %s methods %s were specified for export but not defined",
sQuote(package), paste(expMethods, collapse = ", ")),
domain = NA)
exports <- unique(c(exports, expClasses, expTables))
}
if (length(exports)) {
stoplist <- c(".__NAMESPACE__.", ".__S3MethodsTable__.",
".packageName", ".First.lib", ".onLoad", ".onAttach",
".conflicts.OK", ".noGenerics")
exports <- exports[!exports %in% stoplist]
}
namespaceExport(ns, exports)
sealNamespace(ns)
runUserHook(package, pkgpath)
on.exit()
Sys.unsetenv("_R_NS_LOAD_")
ns
}
}
Math.difftime <- function (x, ...)
{
switch(.Generic, abs = , sign = , floor = , ceiling = , trunc = ,
round = , signif = {
units <- attr(x, "units")
.difftime(NextMethod(), units)
}, stop(gettextf("'%s' not defined for \"difftime\" objects",
.Generic), domain = NA))
}
mean.difftime <- function (x, ...)
.difftime(mean(unclass(x), ...), attr(x, "units"))
## @type from : raw|character
## @type type : character
## @type asChar : logical|character
memDecompress <- function (from, type = c("unknown", "gzip", "bzip2", "xz", "none"),
asChar = FALSE)
{
type <- match(match.arg(type), c("none", "gzip", "bzip2",
"xz", "unknown"))
ans <- .Internal(memDecompress(from, type))
if (asChar)
rawToChar(ans)
else ans
}
merge.default <- function (x, y, ...)
merge(as.data.frame(x), as.data.frame(y), ...)
months.POSIXt <- function (x, abbreviate = FALSE)
{
format(x, ifelse(abbreviate, "%b", "%B"))
}
names.POSIXlt <- function (x)
names(x$year)
## @type path : character
## @type mustWork : logical
normalizePath <- function (path, winslash = "\\", mustWork = NA)
.Internal(normalizePath(path.expand(path), winslash, mustWork))
## @type max : complex
## @type print.gap : integer
## @type digits : complex
## @type right : logical
## @type quote : logical|character
## @type useSource : logical
## @type na.print : character
print.default <- function (x, digits = NULL, quote = TRUE, na.print = NULL, print.gap = NULL,
right = FALSE, max = NULL, useSource = TRUE, ...)
{
noOpt <- missing(digits) && missing(quote) && missing(na.print) &&
missing(print.gap) && missing(right) && missing(max) &&
missing(useSource) && missing(...)
.Internal(print.default(x, digits, quote, na.print, print.gap,
right, max, useSource, noOpt))
}
print.DLLInfo <- function (x, ...)
{
tmp <- as.data.frame.list(x[c("name", "path", "dynamicLookup")])
names(tmp) <- c("DLL name", "Filename", "Dynamic lookup")
write.dcf(tmp, ...)
invisible(x)
}
print.hexmode <- function (x, ...)
{
print(format(x), ...)
invisible(x)
}
print.noquote <- function (x, ...)
{
if (!is.null(cl <- attr(x, "class"))) {
cl <- cl[cl != "noquote"]
attr(x, "class") <- (if (length(cl))
cl
else NULL)
}
print(x, quote = FALSE, ...)
}
print.octmode <- function (x, ...)
{
print(format(x), ...)
invisible(x)
}
print.POSIXct <- function (x, ...)
{
max.print <- getOption("max.print", 9999L)
if (max.print < length(x)) {
print(format(x[seq_len(max.print)], usetz = TRUE), ...)
cat(" [ reached getOption(\"max.print\") -- omitted",
length(x) - max.print, "entries ]\n")
}
else print(format(x, usetz = TRUE), ...)
invisible(x)
}
print.POSIXlt <- function (x, ...)
{
max.print <- getOption("max.print", 9999L)
if (max.print < length(x)) {
print(format(x[seq_len(max.print)], usetz = TRUE), ...)
cat(" [ reached getOption(\"max.print\") -- omitted",
length(x) - max.print, "entries ]\n")
}
else print(format(x, usetz = TRUE), ...)
invisible(x)
}
print.restart <- function (x, ...)
{
cat(paste("<restart:", x[[1L]], ">\n"))
invisible(x)
}
print.srcfile <- function (x, ...)
{
cat(x$filename, "\n")
invisible(x)
}
## @optional x
quarters.Date <- function (x, ...)
{
x <- (as.POSIXlt(x)$mon)%/%3L
paste0("Q", x + 1L)
}
## @type finite : logical
## @type na.rm : logical
range.default <- function (..., na.rm = FALSE, finite = FALSE)
{
x <- c(..., recursive = TRUE)
if (is.numeric(x)) {
if (finite)
x <- x[is.finite(x)]
else if (na.rm)
x <- x[!is.na(x)]
return(c(min(x), max(x)))
}
c(min(x, na.rm = na.rm), max(x, na.rm = na.rm))
}
## @type open : character
## @type object : raw|character
rawConnection <- function (object, open = "r")
{
.Internal(rawConnection(deparse(substitute(object)), object,
open))
}
reg.finalizer <- function (e, f, onexit = FALSE)
.Internal(reg.finalizer(e, f, onexit))
## @type center : complex|logical
## @type x : numeric
## @type scale : complex|logical
scale.default <- function (x, center = TRUE, scale = TRUE)
{
x <- as.matrix(x)
nc <- ncol(x)
if (is.logical(center)) {
if (center) {
center <- colMeans(x, na.rm = TRUE)
x <- sweep(x, 2L, center, check.margin = FALSE)
}
}
else if (is.numeric(center) && (length(center) == nc))
x <- sweep(x, 2L, center, check.margin = FALSE)
else stop("length of 'center' must equal the number of columns of 'x'")
if (is.logical(scale)) {
if (scale) {
f <- function(v) {
v <- v[!is.na(v)]
sqrt(sum(v^2)/max(1, length(v) - 1L))
}
scale <- apply(x, 2L, f)
x <- sweep(x, 2L, scale, "/", check.margin = FALSE)
}
}
else if (is.numeric(scale) && length(scale) == nc)
x <- sweep(x, 2L, scale, "/", check.margin = FALSE)
else stop("length of 'scale' must equal the number of columns of 'x'")
if (is.numeric(center))
attr(x, "scaled:center") <- center
if (is.numeric(scale))
attr(x, "scaled:scale") <- scale
x
}
simpleMessage <- function (message, call = NULL)
structure(list(message = message, call = call), class = c("simpleMessage",
"message", "condition"))
simpleWarning <- function (message, call = NULL)
{
class <- c("simpleWarning", "warning", "condition")
structure(list(message = as.character(message), call = call),
class = class)
}
## @type tol : complex
## @type b : complex
## @type a : complex
## @type LINPACK : logical
solve.default <- function (a, b, tol = .Machine$double.eps, LINPACK = FALSE, ...)
{
if (is.complex(a) || (!missing(b) && is.complex(b))) {
a <- as.matrix(a)
if (missing(b)) {
b <- diag(1 + (0+0i), nrow(a))
colnames(b) <- rownames(a)
}
return(.Internal(La_solve_cmplx(a, b)))
}
if (is.qr(a)) {
warning("solve.default called with a \"qr\" object: use 'qr.solve'")
return(solve.qr(a, b, tol))
}
a <- as.matrix(a)
if (missing(b)) {
b <- diag(1, nrow(a))
colnames(b) <- rownames(a)
}
.Internal(La_solve(a, b, tol))
}
## @type drop : logical
split.default <- function (x, f, drop = FALSE, sep = ".", ...)
{
if (!missing(...))
.NotYetUsed(deparse(...), error = FALSE)
if (is.list(f))
f <- interaction(f, drop = drop, sep = sep)
else if (!is.factor(f))
f <- as.factor(f)
else if (drop)
f <- factor(f)
storage.mode(f) <- "integer"
if (is.null(attr(x, "class")))
return(.Internal(split(x, f)))
lf <- levels(f)
y <- vector("list", length(lf))
names(y) <- lf
ind <- .Internal(split(seq_along(x), f))
for (k in lf) y[[k]] <- x[ind[[k]]]
y
}
split.POSIXct <- function (x, f, drop = FALSE, ...)
lapply(split.default(as.double(x), f, drop = drop), .POSIXct,
tz = attr(x, "tzone"))
## @type subset : logical
subset.matrix <- function (x, subset, select, drop = FALSE, ...)
{
if (missing(select))
vars <- TRUE
else {
nl <- as.list(1L:ncol(x))
names(nl) <- colnames(x)
vars <- eval(substitute(select), nl, parent.frame())
}
if (missing(subset))
subset <- TRUE
else if (!is.logical(subset))
stop("'subset' must be logical")
x[subset & !is.na(subset), vars, drop = drop]
}
summary.table <- function (object, ...)
{
if (!inherits(object, "table"))
stop(gettextf("'object' must inherit from class %s",
dQuote("table")), domain = NA)
n.cases <- sum(object)
n.vars <- length(dim(object))
y <- list(n.vars = n.vars, n.cases = n.cases)
if (n.vars > 1) {
m <- vector("list", length = n.vars)
relFreqs <- object/n.cases
for (k in 1L:n.vars) m[[k]] <- apply(relFreqs, k, sum)
expected <- apply(do.call("expand.grid", m), 1L, prod) *
n.cases
statistic <- sum((c(object) - expected)^2/expected)
lm <- vapply(m, length, 1L)
parameter <- prod(lm) - 1L - sum(lm - 1L)
y <- c(y, list(statistic = statistic, parameter = parameter,
approx.ok = all(expected >= 5), p.value = stats::pchisq(statistic,
parameter, lower.tail = FALSE), call = attr(object,
"call")))
}
class(y) <- "summary.table"
y
}
## @type category : character
## @return character
Sys.getlocale <- function (category = "LC_ALL")
{
category <- match(category, c("LC_ALL", "LC_COLLATE", "LC_CTYPE",
"LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LC_MESSAGES",
"LC_PAPER", "LC_MEASUREMENT"))
if (is.na(category))
stop("invalid 'category' argument")
.Internal(Sys.getlocale(category))
}
## @type category : character
## @type locale : character
## @return character
Sys.setlocale <- function (category = "LC_ALL", locale = "")
{
category <- match(category, c("LC_ALL", "LC_COLLATE", "LC_CTYPE",
"LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LC_MESSAGES",
"LC_PAPER", "LC_MEASUREMENT"))
if (is.na(category))
stop("invalid 'category' argument")
.Internal(Sys.setlocale(category, locale))
}
## @type MARGIN : integer
## @type fromLast : logical
unique.matrix <- function (x, incomparables = FALSE, MARGIN = 1, fromLast = FALSE,
...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
dx <- dim(x)
ndim <- length(dx)
if (length(MARGIN) > ndim || any(MARGIN > ndim))
stop(gettextf("MARGIN = %d is invalid for dim = %d",
MARGIN, dx), domain = NA)
collapse <- (ndim > 1L) && (prod(dx[-MARGIN]) > 1L)
temp <- if (collapse)
apply(x, MARGIN, function(x) paste(x, collapse = "\r"))
else x
args <- rep(alist(a = ), ndim)
names(args) <- NULL
args[[MARGIN]] <- !duplicated.default(temp, fromLast = fromLast,
...)
do.call("[", c(list(x), args, list(drop = FALSE)))
}
## @type sym : character
unlockBinding <- function (sym, env)
{
if (is.character(sym))
sym <- as.name(sym)
.Internal(unlockBinding(sym, env))
}
weekdays.Date <- function (x, abbreviate = FALSE)
format(x, ifelse(abbreviate, "%a", "%A"))
xtfrm.default <- function (x)
if (is.numeric(x)) unclass(x) else as.vector(rank(x, ties.method = "min",
na.last = "keep"))
xtfrm.POSIXct <- function (x)
as.numeric(x)
xtfrm.POSIXlt <- function (x)
as.double(x)
## @type value : complex
## @type name : character
## @optional name
"$<-.data.frame" <- function (x, name, value)
{
cl <- oldClass(x)
class(x) <- NULL
nrows <- .row_names_info(x, 2L)
if (!is.null(value)) {
N <- NROW(value)
if (N > nrows)
stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N, nrows),
domain = NA)
if (N < nrows)
if (N > 0L && (nrows%%N == 0L) && length(dim(value)) <=
1L)
value <- rep(value, length.out = nrows)
else stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N, nrows),
domain = NA)
if (is.atomic(value) && !is.null(names(value)))
names(value) <- NULL
}
x[[name]] <- value
class(x) <- cl
return(x)
}
## @type i : numeric|logical|character
## @type j : numeric|logical|character
## @type value : complex
"[<-.data.frame" <- function (x, i, j, value)
{
if (!all(names(sys.call()) %in% c("", "value")))
warning("named arguments are discouraged")
nA <- nargs()
if (nA == 4L) {
has.i <- !missing(i)
has.j <- !missing(j)
}
else if (nA == 3L) {
if (is.atomic(value) && !is.null(names(value)))
names(value) <- NULL
if (missing(i) && missing(j)) {
i <- j <- NULL
has.i <- has.j <- FALSE
if (is.null(value))
return(x[logical()])
}
else {
if (is.numeric(i) && is.matrix(i) && ncol(i) == 2) {
index <- rep.int(FALSE, prod(dim(x)))
dim(index) <- dim(x)
tryCatch(index[i] <- TRUE, error = function(e) stop(conditionMessage(e),
call. = FALSE))
o <- order(i[, 2], i[, 1])
N <- length(value)
if (length(o)%%N != 0L)
warning("number of items to replace is not a multiple of replacement length")
if (N < length(o))
value <- rep(value, length.out = length(o))
value <- value[o]
i <- index
}
if (is.logical(i) && is.matrix(i) && all(dim(i) ==
dim(x))) {
nreplace <- sum(i, na.rm = TRUE)
if (!nreplace)
return(x)
N <- length(value)
if (N > 1L && N < nreplace && (nreplace%%N) ==
0L)
value <- rep(value, length.out = nreplace)
if (N > 1L && (length(value) != nreplace))
stop("'value' is the wrong length")
n <- 0L
nv <- nrow(x)
for (v in seq_len(dim(i)[2L])) {
thisvar <- i[, v, drop = TRUE]
nv <- sum(thisvar, na.rm = TRUE)
if (nv) {
if (is.matrix(x[[v]]))
x[[v]][thisvar, ] <- if (N > 1L)
value[n + seq_len(nv)]
else value
else x[[v]][thisvar] <- if (N > 1L)
value[n + seq_len(nv)]
else value
}
n <- n + nv
}
return(x)
}
if (is.matrix(i))
stop("unsupported matrix index in replacement")
j <- i
i <- NULL
has.i <- FALSE
has.j <- TRUE
}
}
else {
stop("need 0, 1, or 2 subscripts")
}
if (has.j && length(j) == 0L)
return(x)
cl <- oldClass(x)
class(x) <- NULL
new.cols <- NULL
nvars <- length(x)
nrows <- .row_names_info(x, 2L)
if (has.i && length(i)) {
rows <- NULL
if (anyNA(i))
stop("missing values are not allowed in subscripted assignments of data frames")
if (char.i <- is.character(i)) {
rows <- attr(x, "row.names")
ii <- match(i, rows)
nextra <- sum(new.rows <- is.na(ii))
if (nextra > 0L) {
ii[new.rows] <- seq.int(from = nrows + 1L, length.out = nextra)
new.rows <- i[new.rows]
}
i <- ii
}
if (all(i >= 0L) && (nn <- max(i)) > nrows) {
if (is.null(rows))
rows <- attr(x, "row.names")
if (!char.i) {
nrr <- (nrows + 1L):nn
if (inherits(value, "data.frame") && (dim(value)[1L]) >=
length(nrr)) {
new.rows <- attr(value, "row.names")[seq_along(nrr)]
repl <- duplicated(new.rows) | match(new.rows,
rows, 0L)
if (any(repl))
new.rows[repl] <- nrr[repl]
}
else new.rows <- nrr
}
x <- xpdrows.data.frame(x, rows, new.rows)
rows <- attr(x, "row.names")
nrows <- length(rows)
}
iseq <- seq_len(nrows)[i]
if (anyNA(iseq))
stop("non-existent rows not allowed")
}
else iseq <- NULL
if (has.j) {
if (anyNA(j))
stop("missing values are not allowed in subscripted assignments of data frames")
if (is.character(j)) {
if ("" %in% j)
stop("column name \"\" cannot match any column")
jj <- match(j, names(x))
nnew <- sum(is.na(jj))
if (nnew > 0L) {
n <- is.na(jj)
jj[n] <- nvars + seq_len(nnew)
new.cols <- j[n]
}
jseq <- jj
}
else if (is.logical(j) || min(j) < 0L)
jseq <- seq_along(x)[j]
else {
jseq <- j
if (max(jseq) > nvars) {
new.cols <- paste0("V", seq.int(from = nvars +
1L, to = max(jseq)))
if (length(new.cols) != sum(jseq > nvars))
stop("new columns would leave holes after existing columns")
if (is.list(value) && !is.null(vnm <- names(value))) {
p <- length(jseq)
if (length(vnm) < p)
vnm <- rep_len(vnm, p)
new.cols <- vnm[jseq > nvars]
}
}
}
}
else jseq <- seq_along(x)
if (anyDuplicated(jseq))
stop("duplicate subscripts for columns")
n <- length(iseq)
if (n == 0L)
n <- nrows
p <- length(jseq)
m <- length(value)
if (!is.list(value)) {
if (p == 1L) {
N <- NROW(value)
if (N > n)
stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N,
n), domain = NA)
if (N < n && N > 0L)
if (n%%N == 0L && length(dim(value)) <= 1L)
value <- rep(value, length.out = n)
else stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N,
nrows), domain = NA)
if (!is.null(names(value)))
names(value) <- NULL
value <- list(value)
}
else {
if (m < n * p && (m == 0L || (n * p)%%m))
stop(sprintf(ngettext(m, "replacement has %d item, need %d",
"replacement has %d items, need %d"), m, n *
p), domain = NA)
value <- matrix(value, n, p)
value <- split(value, col(value))
}
dimv <- c(n, p)
}
else {
value <- unclass(value)
lens <- vapply(value, NROW, 1L)
for (k in seq_along(lens)) {
N <- lens[k]
if (n != N && length(dim(value[[k]])) == 2L)
stop(sprintf(ngettext(N, "replacement element %d is a matrix/data frame of %d row, need %d",
"replacement element %d is a matrix/data frame of %d rows, need %d"),
k, N, n), domain = NA)
if (N > 0L && N < n && n%%N)
stop(sprintf(ngettext(N, "replacement element %d has %d row, need %d",
"replacement element %d has %d rows, need %d"),
k, N, n), domain = NA)
if (N > 0L && N < n)
value[[k]] <- rep(value[[k]], length.out = n)
if (N > n) {
warning(sprintf(ngettext(N, "replacement element %d has %d row to replace %d rows",
"replacement element %d has %d rows to replace %d rows"),
k, N, n), domain = NA)
value[[k]] <- value[[k]][seq_len(n)]
}
}
dimv <- c(n, length(value))
}
nrowv <- dimv[1L]
if (nrowv < n && nrowv > 0L) {
if (n%%nrowv == 0L)
value <- value[rep_len(seq_len(nrowv), n), , drop = FALSE]
else stop(sprintf(ngettext(nrowv, "%d row in value to replace %d rows",
"%d rows in value to replace %d rows"), nrowv, n),
domain = NA)
}
else if (nrowv > n)
warning(sprintf(ngettext(nrowv, "replacement data has %d row to replace %d rows",
"replacement data has %d rows to replace %d rows"),
nrowv, n), domain = NA)
ncolv <- dimv[2L]
jvseq <- seq_len(p)
if (ncolv < p)
jvseq <- rep_len(seq_len(ncolv), p)
else if (ncolv > p) {
warning(sprintf(ngettext(ncolv, "provided %d variable to replace %d variables",
"provided %d variables to replace %d variables"),
ncolv, p), domain = NA)
new.cols <- new.cols[seq_len(p)]
}
if (length(new.cols)) {
nm <- names(x)
rows <- .row_names_info(x, 0L)
a <- attributes(x)
a["names"] <- NULL
x <- c(x, vector("list", length(new.cols)))
attributes(x) <- a
names(x) <- c(nm, new.cols)
attr(x, "row.names") <- rows
}
if (has.i)
for (jjj in seq_len(p)) {
jj <- jseq[jjj]
vjj <- value[[jvseq[[jjj]]]]
if (jj <= nvars) {
if (length(dim(x[[jj]])) != 2L)
x[[jj]][iseq] <- vjj
else x[[jj]][iseq, ] <- vjj
}
else {
x[[jj]] <- vjj[FALSE]
if (length(dim(vjj)) == 2L) {
length(x[[j]]) <- nrows * ncol(vjj)
dim(x[[j]]) <- c(nrows, ncol(vjj))
x[[jj]][iseq, ] <- vjj
}
else {
length(x[[j]]) <- nrows
x[[jj]][iseq] <- vjj
}
}
}
else if (p > 0L)
for (jjj in p:1L) {
o <- order(jseq)
jseq <- jseq[o]
jvseq <- jvseq[o]
jj <- jseq[jjj]
v <- value[[jvseq[[jjj]]]]
if (nrows > 0L && !length(v))
length(v) <- nrows
x[[jj]] <- v
if (!is.null(v) && is.atomic(x[[jj]]) && !is.null(names(x[[jj]])))
names(x[[jj]]) <- NULL
}
if (length(new.cols) > 0L) {
new.cols <- names(x)
if (anyDuplicated(new.cols))
names(x) <- make.unique(new.cols)
}
class(x) <- cl
x
}
## @type check.attributes : logical
## @type use.names : logical|integer|character
## @return logical
all.equal.list <- function (target, current, ..., check.attributes = TRUE, use.names = TRUE)
{
if (!is.logical(check.attributes))
stop(gettextf("'%s' must be logical", "check.attributes"),
domain = NA)
if (!is.logical(use.names))
stop(gettextf("'%s' must be logical", "use.names"), domain = NA)
msg <- if (check.attributes)
attr.all.equal(target, current, ...)
target <- unclass(target)
current <- unclass(current)
if (!is.list(target) && !is.vector(target))
return(c(msg, "target is not list-like"))
if (!is.list(current) && !is.vector(current))
return(c(msg, "current is not list-like"))
if ((n <- length(target)) != length(current)) {
if (!is.null(msg))
msg <- msg[-grep("\\bLengths\\b", msg)]
n <- min(n, length(current))
msg <- c(msg, paste("Length mismatch: comparison on first",
n, "components"))
}
iseq <- seq_len(n)
if (use.names)
use.names <- (length(nt <- names(target)[iseq]) == n &&
length(nc <- names(current)[iseq]) == n)
for (i in iseq) {
mi <- all.equal(target[[i]], current[[i]], check.attributes = check.attributes,
use.names = use.names, ...)
if (is.character(mi))
msg <- c(msg, paste0("Component ", if (use.names &&
nt[i] == nc[i]) dQuote(nt[i]) else i, ": ", mi))
}
if (is.null(msg))
TRUE
else msg
}
as.Date.factor <- function (x, ...)
as.Date(as.character(x), ...)
as.environment <- function (x) .Primitive("as.environment")
as.list.factor <- function (x, ...)
{
res <- vector("list", length(x))
for (i in seq_along(x)) res[[i]] <- x[i]
res
}
## @type check.attributes : logical
## @type check.names : logical
attr.all.equal <- function (target, current, ..., check.attributes = TRUE, check.names = TRUE)
{
if (!is.logical(check.attributes))
stop(gettextf("'%s' must be logical", "check.attributes"),
domain = NA)
if (!is.logical(check.names))
stop(gettextf("'%s' must be logical", "check.names"),
domain = NA)
msg <- NULL
if (mode(target) != mode(current))
msg <- paste0("Modes: ", mode(target), ", ", mode(current))
if (length(target) != length(current))
msg <- c(msg, paste0("Lengths: ", length(target), ", ",
length(current)))
ax <- attributes(target)
ay <- attributes(current)
if (check.names) {
nx <- names(target)
ny <- names(current)
if ((lx <- length(nx)) | (ly <- length(ny))) {
ax$names <- ay$names <- NULL
if (lx && ly) {
if (is.character(m <- all.equal.character(nx,
ny, check.attributes = check.attributes)))
msg <- c(msg, paste("Names:", m))
}
else if (lx)
msg <- c(msg, "names for target but not for current")
else msg <- c(msg, "names for current but not for target")
}
}
else {
ax[["names"]] <- NULL
ay[["names"]] <- NULL
}
if (check.attributes && (length(ax) || length(ay))) {
nx <- names(ax)
ny <- names(ay)
if (length(nx))
ax <- ax[order(nx)]
if (length(ny))
ay <- ay[order(ny)]
tt <- all.equal(ax, ay, ..., check.attributes = check.attributes)
if (is.character(tt))
msg <- c(msg, paste("Attributes: <", tt, ">"))
}
msg
}
bindtextdomain <- function (domain, dirname = NULL)
.Internal(bindtextdomain(domain, dirname))
dim.data.frame <- function (x)
c(.row_names_info(x, 2L), length(x))
findPackageEnv <- function (info)
{
if (info %in% search())
return(as.environment(info))
message(gettextf("Attempting to load the environment %s",
sQuote(info)), domain = NA)
pkg <- substr(info, 9L, 1000L)
if (require(pkg, character.only = TRUE, quietly = TRUE))
return(as.environment(info))
message("Specified environment not found: using '.GlobalEnv' instead")
.GlobalEnv
}
## @type big.mark : complex
## @type small.mark : complex
## @type trim : complex|logical
## @type digits : complex
## @type nsmall : complex
## @type big.interval : complex
## @type na.encode : complex|logical|character
## @type scientific : complex|logical
## @type x : numeric
## @type justify : character
format.default <- function (x, trim = FALSE, digits = NULL, nsmall = 0L, justify = c("left",
"right", "centre", "none"), width = NULL, na.encode = TRUE,
scientific = NA, big.mark = "", big.interval = 3L, small.mark = "",
small.interval = 5L, decimal.mark = ".", zero.print = NULL,
drop0trailing = FALSE, ...)
{
justify <- match.arg(justify)
adj <- match(justify, c("left", "right", "centre", "none")) -
1L
if (is.list(x)) {
if (missing(trim))
trim <- TRUE
if (missing(justify))
justify <- "none"
res <- lapply(X = x, FUN = function(xx, ...) format.default(unlist(xx),
...), trim = trim, digits = digits, nsmall = nsmall,
justify = justify, width = width, na.encode = na.encode,
scientific = scientific, big.mark = big.mark, big.interval = big.interval,
small.mark = small.mark, small.interval = small.interval,
decimal.mark = decimal.mark, zero.print = zero.print,
drop0trailing = drop0trailing, ...)
sapply(res, paste, collapse = ", ")
}
else {
switch(mode(x), `NULL` = "NULL", character = .Internal(format(x,
trim, digits, nsmall, width, adj, na.encode, scientific)),
call = , expression = , `function` = , `(` = deparse(x),
raw = as.character(x), {
prettyNum(.Internal(format(x, trim, digits, nsmall,
width, 3L, na.encode, scientific)), big.mark = big.mark,
big.interval = big.interval, small.mark = small.mark,
small.interval = small.interval, decimal.mark = decimal.mark,
zero.print = zero.print, drop0trailing = drop0trailing,
is.cmplx = is.complex(x), preserve.width = if (trim) "individual" else "common")
})
}
}
## @type upper.case : logical
## @type width : integer
format.hexmode <- function (x, width = NULL, upper.case = FALSE, ...)
{
isna <- is.na(x)
y <- as.integer(x[!isna])
fmt0 <- if (upper.case)
"X"
else "x"
fmt <- if (!is.null(width))
paste0("%0", width, fmt0)
else paste0("%", fmt0)
ans <- rep.int(NA_character_, length(x))
ans0 <- sprintf(fmt, y)
if (is.null(width) && length(y) > 1L) {
nc <- max(nchar(ans0))
ans0 <- sprintf(paste0("%0", nc, fmt0), y)
}
ans[!isna] <- ans0
dim(ans) <- dim(x)
dimnames(ans) <- dimnames(x)
names(ans) <- names(x)
ans
}
## @type width : integer
format.octmode <- function (x, width = NULL, ...)
{
isna <- is.na(x)
y <- as.integer(x[!isna])
fmt <- if (!is.null(width))
paste0("%0", width, "o")
else "%o"
ans <- rep.int(NA_character_, length(x))
ans0 <- sprintf(fmt, y)
if (is.null(width) && length(y) > 1L) {
nc <- max(nchar(ans0))
ans0 <- sprintf(paste0("%0", nc, "o"), y)
}
ans[!isna] <- ans0
dim(ans) <- dim(x)
dimnames(ans) <- dimnames(x)
names(ans) <- names(x)
ans
}
## @type x : character
## @type format : complex|character
## @type tz : character
## @type usetz : logical
format.POSIXct <- function (x, format = "", tz = "", usetz = FALSE, ...)
{
if (!inherits(x, "POSIXct"))
stop("wrong class")
if (missing(tz) && !is.null(tzone <- attr(x, "tzone")))
tz <- tzone
structure(format.POSIXlt(as.POSIXlt(x, tz), format, usetz,
...), names = names(x))
}
## @type usetz : logical
## @type x : character
## @type format : complex|character
format.POSIXlt <- function (x, format = "", usetz = FALSE, ...)
{
if (!inherits(x, "POSIXlt"))
stop("wrong class")
if (format == "") {
times <- unlist(unclass(x)[1L:3L])
secs <- x$sec
secs <- secs[!is.na(secs)]
np <- getOption("digits.secs")
if (is.null(np))
np <- 0L
else np <- min(6L, np)
if (np >= 1L)
for (i in seq_len(np) - 1L) if (all(abs(secs - round(secs,
i)) < 1e-06)) {
np <- i
break
}
format <- if (all(times[!is.na(times)] == 0))
"%Y-%m-%d"
else if (np == 0L)
"%Y-%m-%d %H:%M:%S"
else paste0("%Y-%m-%d %H:%M:%OS", np)
}
y <- .Internal(format.POSIXlt(x, format, usetz))
names(y) <- names(x$year)
y
}
## @optional e
getCallingDLLe <- function (e)
{
if (is.null(env <- e$.__NAMESPACE__.))
env <- baseenv()
if (exists("DLLs", envir = env) && length(env$DLLs))
return(env$DLLs[[1L]])
NULL
}
is.environment <- function (x) .Primitive("is.environment")
## @optional value
"is.na<-.factor" <- function (x, value)
{
lx <- levels(x)
cx <- oldClass(x)
class(x) <- NULL
x[value] <- NA
structure(x, levels = lx, class = cx)
}
labels.default <- function (object, ...)
{
if (length(d <- dim(object))) {
nt <- dimnames(object)
if (is.null(nt))
nt <- vector("list", length(d))
for (i in seq_along(d)) if (!length(nt[[i]]))
nt[[i]] <- as.character(seq_len(d[i]))
}
else {
nt <- names(object)
if (!length(nt))
nt <- as.character(seq_along(object))
}
nt
}
## @optional fun
lazyLoadDBexec <- function (filebase, fun, filter)
{
glue <- function(..., sep = " ", collapse = NULL) .Internal(paste(list(...),
sep, collapse))
readRDS <- function(file) {
halt <- function(message) .Internal(stop(TRUE, message))
gzfile <- function(description, open) .Internal(gzfile(description,
open, "", 6))
close <- function(con) .Internal(close(con, "rw"))
if (!is.character(file))
halt("bad file name")
con <- gzfile(file, "rb")
on.exit(close(con))
.Internal(unserializeFromConn(con, baseenv()))
}
`parent.env<-` <- function(env, value) .Internal(`parent.env<-`(env,
value))
existsInFrame <- function(x, env) .Internal(exists(x, env,
"any", FALSE))
getFromFrame <- function(x, env) .Internal(get(x, env, "any",
FALSE))
set <- function(x, value, env) .Internal(assign(x, value,
env, FALSE))
environment <- function() .Internal(environment(NULL))
mkenv <- function() .Internal(new.env(TRUE, baseenv(), 29L))
mapfile <- glue(filebase, "rdx", sep = ".")
datafile <- glue(filebase, "rdb", sep = ".")
env <- mkenv()
map <- readRDS(mapfile)
vars <- names(map$variables)
rvars <- names(map$references)
compressed <- map$compressed
for (i in seq_along(rvars)) set(rvars[i], map$references[[i]],
env)
envenv <- mkenv()
envhook <- function(n) {
if (existsInFrame(n, envenv))
getFromFrame(n, envenv)
else {
e <- mkenv()
set(n, e, envenv)
key <- getFromFrame(n, env)
data <- lazyLoadDBfetch(key, datafile, compressed,
envhook)
if (is.null(data$enclos))
parent.env(e) <- emptyenv()
else parent.env(e) <- data$enclos
vars <- names(data$bindings)
for (i in seq_along(vars)) set(vars[i], data$bindings[[i]],
e)
if (!is.null(data$attributes))
attributes(e) <- data$attributes
if (!is.null(data$isS4) && data$isS4)
.Internal(setS4Object(e, TRUE, TRUE))
if (!is.null(data$locked) && data$locked)
.Internal(lockEnvironment(e, FALSE))
e
}
}
if (!missing(filter)) {
use <- filter(vars)
vars <- vars[use]
vals <- map$variables[use]
use <- NULL
}
else vals <- map$variables
res <- fun(environment())
map <- NULL
vars <- NULL
vals <- NULL
rvars <- NULL
mapfile <- NULL
readRDS <- NULL
res
}
length.POSIXlt <- function (x)
length(x[[1L]])
levels.default <- function (x)
attr(x, "levels")
memory.profile <- function ()
.Internal(memory.profile())
Ops.data.frame <- function (e1, e2 = NULL)
{
isList <- function(x) !is.null(x) && is.list(x)
unary <- nargs() == 1L
lclass <- nzchar(.Method[1L])
rclass <- !unary && (nzchar(.Method[2L]))
value <- list()
rn <- NULL
FUN <- get(.Generic, envir = parent.frame(), mode = "function")
f <- if (unary)
quote(FUN(left))
else quote(FUN(left, right))
lscalar <- rscalar <- FALSE
if (lclass && rclass) {
nr <- .row_names_info(e1, 2L)
if (.row_names_info(e1) > 0L)
rn <- attr(e1, "row.names")
cn <- names(e1)
if (any(dim(e2) != dim(e1)))
stop(.Generic, " only defined for equally-sized data frames")
}
else if (lclass) {
nr <- .row_names_info(e1, 2L)
if (.row_names_info(e1) > 0L)
rn <- attr(e1, "row.names")
cn <- names(e1)
rscalar <- length(e2) <= 1L
if (isList(e2)) {
if (rscalar)
e2 <- e2[[1L]]
else if (length(e2) != ncol(e1))
stop(gettextf("list of length %d not meaningful",
length(e2)), domain = NA)
}
else {
if (!rscalar)
e2 <- split(rep_len(as.vector(e2), prod(dim(e1))),
rep.int(seq_len(ncol(e1)), rep.int(nrow(e1),
ncol(e1))))
}
}
else {
nr <- .row_names_info(e2, 2L)
if (.row_names_info(e2) > 0L)
rn <- attr(e2, "row.names")
cn <- names(e2)
lscalar <- length(e1) <= 1L
if (isList(e1)) {
if (lscalar)
e1 <- e1[[1L]]
else if (length(e1) != ncol(e2))
stop(gettextf("list of length %d not meaningful",
length(e1)), domain = NA)
}
else {
if (!lscalar)
e1 <- split(rep_len(as.vector(e1), prod(dim(e2))),
rep.int(seq_len(ncol(e2)), rep.int(nrow(e2),
ncol(e2))))
}
}
for (j in seq_along(cn)) {
left <- if (!lscalar)
e1[[j]]
else e1
right <- if (!rscalar)
e2[[j]]
else e2
value[[j]] <- eval(f)
}
if (.Generic %in% c("+", "-", "*", "/", "%%", "%/%")) {
names(value) <- cn
data.frame(value, row.names = rn, check.names = FALSE,
check.rows = FALSE)
}
else matrix(unlist(value, recursive = FALSE, use.names = FALSE),
nrow = nr, dimnames = list(rn, cn))
}
## @type n : complex
## @type x : numeric
## @type high.u.bias : numeric
## @type u5.bias : numeric
## @type shrink.sml : numeric
## @type eps.correct : integer
## @type min.n : complex
## @optional x
pretty.default <- function (x, n = 5, min.n = n%/%3, shrink.sml = 0.75, high.u.bias = 1.5,
u5.bias = 0.5 + 1.5 * high.u.bias, eps.correct = 0, ...)
{
x <- x[is.finite(x <- as.numeric(x))]
if (!length(x))
return(x)
z <- .Internal(pretty(min(x), max(x), n, min.n, shrink.sml,
c(high.u.bias, u5.bias), eps.correct))
s <- seq.int(z$l, z$u, length.out = z$n + 1)
if (!eps.correct && z$n) {
delta <- diff(range(z$l, z$u))/z$n
if (any(small <- abs(s) < 1e-14 * delta))
s[small] <- 0
}
s
}
print.difftime <- function (x, digits = getOption("digits"), ...)
{
if (is.array(x) || length(x) > 1L) {
cat("Time differences in ", attr(x, "units"), "\n", sep = "")
y <- unclass(x)
attr(y, "units") <- NULL
print(y)
}
else cat("Time difference of ", format(unclass(x), digits = digits),
" ", attr(x, "units"), "\n", sep = "")
invisible(x)
}
## @type useSource : logical
print.function <- function (x, useSource = TRUE, ...)
.Internal(print.function(x, useSource, ...))
print.warnings <- function (x, ...)
{
if (n <- length(x)) {
cat(ngettext(n, "Warning message:\n", "Warning messages:\n"))
msgs <- names(x)
for (i in seq_len(n)) {
ind <- if (n == 1L)
""
else paste0(i, ": ")
out <- if (length(x[[i]])) {
temp <- deparse(x[[i]], width.cutoff = 50L, nlines = 2L)
sm <- strsplit(msgs[i], "\n")[[1L]]
nl <- if (nchar(ind, "w") + nchar(temp[1L], "w") +
nchar(sm[1L], "w") <= 75L)
" "
else "\n "
paste(ind, "In ", temp[1L], if (length(temp) >
1L)
" ...", " :", nl, msgs[i], sep = "")
}
else paste0(ind, msgs[i])
do.call("cat", c(list(out), attr(x, "dots"), fill = TRUE))
}
}
invisible(x)
}
pushBackLength <- function (connection)
.Internal(pushBackLength(connection))
restartFormals <- function (r)
formals(r$handler)
## @type na.rm : logical
## @type x : numeric
rowsum.default <- function (x, group, reorder = TRUE, na.rm = FALSE, ...)
{
if (!is.numeric(x))
stop("'x' must be numeric")
if (length(group) != NROW(x))
stop("incorrect length for 'group'")
if (anyNA(group))
warning("missing values for 'group'")
ugroup <- unique(group)
if (reorder)
ugroup <- sort(ugroup, na.last = TRUE, method = "quick")
.Internal(rowsum_matrix(x, group, ugroup, na.rm, as.character(ugroup)))
}
## @type higher : logical
simplify2array <- function (x, higher = TRUE)
{
if (length(common.len <- unique(unlist(lapply(x, length)))) >
1L)
return(x)
if (common.len == 1L)
unlist(x, recursive = FALSE)
else if (common.len > 1L) {
n <- length(x)
r <- as.vector(unlist(x, recursive = FALSE))
if (higher && length(c.dim <- unique(lapply(x, dim))) ==
1 && is.numeric(c.dim <- c.dim[[1L]]) && prod(d <- c(c.dim,
n)) == length(r)) {
iN1 <- is.null(n1 <- dimnames(x[[1L]]))
n2 <- names(x)
dnam <- if (!(iN1 && is.null(n2)))
c(if (iN1) rep.int(list(n1), length(c.dim)) else n1,
list(n2))
array(r, dim = d, dimnames = dnam)
}
else if (prod(d <- c(common.len, n)) == length(r))
array(r, dim = d, dimnames = if (!(is.null(n1 <- names(x[[1L]])) &
is.null(n2 <- names(x))))
list(n1, n2))
else x
}
else x
}
"/.difftime" <- function (e1, e2)
{
if (inherits(e2, "difftime"))
stop("second argument of / cannot be a \"difftime\" object")
.difftime(unclass(e1)/e2, attr(e1, "units"))
}
## @type value : character
"storage.mode<-" <- function (x, value) .Primitive("storage.mode<-")
## @type subset : logical
## @optional x
subset.default <- function (x, subset, ...)
{
if (!is.logical(subset))
stop("'subset' must be logical")
x[subset & !is.na(subset)]
}
Summary.factor <- function (..., na.rm)
stop(.Generic, " not meaningful for factors")
summary.matrix <- function (object, ...)
{
summary.data.frame(as.data.frame.matrix(object), ...)
}
summary.srcref <- function (object, useSource = FALSE, ...)
{
cat(as.character(object, useSource = useSource), sep = "\n")
invisible(object)
}
## @type name : character
## @type quiet : logical
sys.load.image <- function (name, quiet)
{
if (file.exists(name)) {
load(name, envir = .GlobalEnv)
if (!quiet)
message("[Previously saved workspace restored]",
"\n")
}
}
Sys.localeconv <- function ()
.Internal(Sys.localeconv())
## @type name : character
sys.save.image <- function (name)
{
closeAllConnections()
save.image(name)
}
textConnection <- function (object, open = "r", local = FALSE, encoding = c("",
"bytes", "UTF-8"))
{
env <- if (local)
parent.frame()
else .GlobalEnv
type <- match(match.arg(encoding), c("", "bytes", "UTF-8"))
nm <- deparse(substitute(object))
if (length(nm) != 1)
stop("argument 'object' must deparse to a single character string")
.Internal(textConnection(nm, object, open, env, type))
}
## @type nmax : complex
## @type fromLast : logical
unique.default <- function (x, incomparables = FALSE, fromLast = FALSE, nmax = NA,
...)
{
if (is.factor(x)) {
z <- .Internal(unique(x, incomparables, fromLast, min(length(x),
nlevels(x) + 1L)))
return(factor(z, levels = seq_len(nlevels(x)), labels = levels(x),
ordered = is.ordered(x)))
}
z <- .Internal(unique(x, incomparables, fromLast, nmax))
if (inherits(x, "POSIXct"))
structure(z, class = class(x), tzone = attr(x, "tzone"))
else if (inherits(x, "Date"))
structure(z, class = class(x))
else z
}
unique.POSIXlt <- function (x, incomparables = FALSE, ...)
x[!duplicated(x, incomparables, ...)]
units.difftime <- function (x)
attr(x, "units")
xtfrm.difftime <- function (x)
as.numeric(x)
## @type j : numeric|logical|character
## @type i : numeric|logical|character
## @type value : complex
"[[<-.data.frame" <- function (x, i, j, value)
{
if (!all(names(sys.call()) %in% c("", "value")))
warning("named arguments are discouraged")
cl <- oldClass(x)
class(x) <- NULL
nrows <- .row_names_info(x, 2L)
if (is.atomic(value) && !is.null(names(value)))
names(value) <- NULL
if (nargs() < 4L) {
nc <- length(x)
if (!is.null(value)) {
N <- NROW(value)
if (N > nrows)
stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N,
nrows), domain = NA)
if (N < nrows)
if (N > 0L && (nrows%%N == 0L) && length(dim(value)) <=
1L)
value <- rep(value, length.out = nrows)
else stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N,
nrows), domain = NA)
}
x[[i]] <- value
if (length(x) > nc) {
nc <- length(x)
if (names(x)[nc] == "")
names(x)[nc] <- paste0("V", nc)
names(x) <- make.unique(names(x))
}
class(x) <- cl
return(x)
}
if (missing(i) || missing(j))
stop("only valid calls are x[[j]] <- value or x[[i,j]] <- value")
rows <- attr(x, "row.names")
nvars <- length(x)
if (n <- is.character(i)) {
ii <- match(i, rows)
n <- sum(new.rows <- is.na(ii))
if (n > 0L) {
ii[new.rows] <- seq.int(from = nrows + 1L, length.out = n)
new.rows <- i[new.rows]
}
i <- ii
}
if (all(i >= 0L) && (nn <- max(i)) > nrows) {
if (n == 0L) {
nrr <- (nrows + 1L):nn
if (inherits(value, "data.frame") && (dim(value)[1L]) >=
length(nrr)) {
new.rows <- attr(value, "row.names")[seq_len(nrr)]
repl <- duplicated(new.rows) | match(new.rows,
rows, 0L)
if (any(repl))
new.rows[repl] <- nrr[repl]
}
else new.rows <- nrr
}
x <- xpdrows.data.frame(x, rows, new.rows)
rows <- attr(x, "row.names")
nrows <- length(rows)
}
iseq <- seq_len(nrows)[i]
if (anyNA(iseq))
stop("non-existent rows not allowed")
if (is.character(j)) {
if ("" %in% j)
stop("column name \"\" cannot match any column")
jseq <- match(j, names(x))
if (anyNA(jseq))
stop(gettextf("replacing element in non-existent column: %s",
j[is.na(jseq)]), domain = NA)
}
else if (is.logical(j) || min(j) < 0L)
jseq <- seq_along(x)[j]
else {
jseq <- j
if (max(jseq) > nvars)
stop(gettextf("replacing element in non-existent column: %s",
jseq[jseq > nvars]), domain = NA)
}
if (length(iseq) > 1L || length(jseq) > 1L)
stop("only a single element should be replaced")
x[[jseq]][[iseq]] <- value
class(x) <- cl
x
}
## @return logical|integer|character
addTaskCallback <- function (f, data = NULL, name = character())
{
if (!is.function(f))
stop("handler must be a function")
val <- .Call(.C_R_addTaskCallback, f, data, !missing(data),
as.character(name))
val + 1L
}
as.Date.default <- function (x, ...)
{
if (inherits(x, "Date"))
return(x)
if (is.logical(x) && all(is.na(x)))
return(structure(as.numeric(x), class = "Date"))
stop(gettextf("do not know how to convert '%s' to class %s",
deparse(substitute(x)), dQuote("Date")), domain = NA)
}
as.Date.numeric <- function (x, origin, ...)
{
if (missing(origin))
stop("'origin' must be supplied")
as.Date(origin, ...) + x
}
## @type tz : character
as.Date.POSIXct <- function (x, tz = "UTC", ...)
{
if (tz == "UTC") {
z <- floor(unclass(x)/86400)
attr(z, "tzone") <- NULL
structure(z, class = "Date")
}
else as.Date(as.POSIXlt(x, tz = tz))
}
as.Date.POSIXlt <- function (x, ...)
.Internal(POSIXlt2Date(x))
as.list.default <- function (x, ...)
if (typeof(x) == "list") x else .Internal(as.vector(x, "list"))
as.list.POSIXct <- function (x, ...)
{
nms <- names(x)
names(x) <- NULL
y <- lapply(seq_along(x), function(i) x[i])
names(y) <- nms
y
}
as.null.default <- function (x, ...)
NULL
as.POSIXct.Date <- function (x, ...)
.POSIXct(unclass(x) * 86400)
as.POSIXlt.Date <- function (x, ...)
.Internal(Date2POSIXlt(x))
attachNamespace <- function (ns, pos = 2L, depends = NULL)
{
runHook <- function(hookname, env, libname, pkgname) {
if (exists(hookname, envir = env, inherits = FALSE)) {
fun <- get(hookname, envir = env, inherits = FALSE)
res <- tryCatch(fun(libname, pkgname), error = identity)
if (inherits(res, "error")) {
stop(gettextf("%s failed in %s() for '%s', details:\n call: %s\n error: %s",
hookname, "attachNamespace", nsname, deparse(conditionCall(res))[1L],
conditionMessage(res)), call. = FALSE, domain = NA)
}
}
}
runUserHook <- function(pkgname, pkgpath) {
hook <- getHook(packageEvent(pkgname, "attach"))
for (fun in hook) try(fun(pkgname, pkgpath))
}
ns <- asNamespace(ns, base.OK = FALSE)
nsname <- getNamespaceName(ns)
nspath <- getNamespaceInfo(ns, "path")
attname <- paste("package", nsname, sep = ":")
if (attname %in% search())
stop("namespace is already attached")
env <- attach(NULL, pos = pos, name = attname)
on.exit(.Internal(detach(pos)))
attr(env, "path") <- nspath
exports <- getNamespaceExports(ns)
importIntoEnv(env, exports, ns, exports)
dimpenv <- getNamespaceInfo(ns, "lazydata")
dnames <- ls(dimpenv, all.names = TRUE)
.Internal(importIntoEnv(env, dnames, dimpenv, dnames))
if (length(depends))
assign(".Depends", depends, env)
Sys.setenv(`_R_NS_LOAD_` = nsname)
on.exit(Sys.unsetenv("_R_NS_LOAD_"), add = TRUE)
runHook(".onAttach", ns, dirname(nspath), nsname)
lockEnvironment(env, TRUE)
runUserHook(nsname, nspath)
on.exit()
Sys.unsetenv("_R_NS_LOAD_")
invisible(env)
}
## @type sym : character
## @return logical
bindingIsActive <- function (sym, env)
{
if (is.character(sym))
sym <- as.name(sym)
.Internal(bindingIsActive(sym, env))
}
## @type sym : character
bindingIsLocked <- function (sym, env)
{
if (is.character(sym))
sym <- as.name(sym)
.Internal(bindingIsLocked(sym, env))
}
browserSetDebug <- function (n = 1L)
.Internal(browserSetDebug(n))
computeRestarts <- function (cond = NULL)
{
val <- NULL
i <- 1L
repeat {
r <- .Internal(.getRestart(i))
if (is.null(r))
return(val)
else if (is.null(cond) || is.null(r$test) || r$test(cond))
val <- c(val, list(r))
i <- i + 1L
}
}
environmentName <- function (env)
.Internal(environmentName(env))
format.difftime <- function (x, ...)
paste(format(unclass(x), ...), units(x))
## @optional value
"is.na<-.default" <- function (x, value)
{
x[value] <- NA
x
}
is.numeric.Date <- function (x)
FALSE
isBaseNamespace <- function (ns)
identical(ns, .BaseNamespaceEnv)
## @type key : character
## @type compressed : logical
lazyLoadDBfetch <- function (key, file, compressed, hook) .Primitive("lazyLoadDBfetch")
## @type value : integer
## @optional value
"length<-.factor" <- function (x, value)
{
cl <- class(x)
levs <- levels(x)
x <- NextMethod()
structure(x, levels = levs, class = cl)
}
## @type value : complex|character
"levels<-.factor" <- function (x, value)
{
xlevs <- levels(x)
if (is.list(value)) {
nlevs <- rep.int(names(value), lapply(value, length))
value <- unlist(value)
m <- match(value, xlevs, nomatch = 0L)
xlevs[m] <- nlevs[m > 0L]
}
else {
if (length(xlevs) > length(value))
stop("number of levels differs")
nlevs <- xlevs <- as.character(value)
nlevs <- nlevs[!is.na(nlevs)]
}
nlevs <- unique(nlevs)
at <- attributes(x)
at$levels <- nlevs
y <- match(xlevs[x], nlevs)
attributes(y) <- at
y
}
## @type bindings : logical
lockEnvironment <- function (env, bindings = FALSE)
.Internal(lockEnvironment(env, bindings))
Math.data.frame <- function (x, ...)
{
mode.ok <- vapply(x, function(x) is.numeric(x) || is.complex(x),
NA)
if (all(mode.ok)) {
x[] <- lapply(X = x, FUN = .Generic, ...)
return(x)
}
else {
vnames <- names(x)
if (is.null(vnames))
vnames <- seq_along(x)
stop("non-numeric variable in data frame: ", vnames[!mode.ok])
}
}
"names<-.POSIXlt" <- function (x, value)
{
names(x$year) <- value
x
}
namespaceExport <- function (ns, vars)
{
namespaceIsSealed <- function(ns) environmentIsLocked(ns)
if (namespaceIsSealed(ns))
stop("cannot add to exports of a sealed namespace")
ns <- asNamespace(ns, base.OK = FALSE)
if (length(vars)) {
addExports <- function(ns, new) {
exports <- getNamespaceInfo(ns, "exports")
expnames <- names(new)
intnames <- new
objs <- .Internal(ls(exports, TRUE))
ex <- expnames %in% objs
if (any(ex))
warning(sprintf(ngettext(sum(ex), "previous export '%s' is being replaced",
"previous exports '%s' are being replaced"),
paste(sQuote(expnames[ex]), collapse = ", ")),
call. = FALSE, domain = NA)
for (i in seq_along(new)) assign(expnames[i], intnames[i],
envir = exports)
}
makeImportExportNames <- function(spec) {
old <- as.character(spec)
new <- names(spec)
if (is.null(new))
new <- old
else {
change <- !nzchar(new)
new[change] <- old[change]
}
names(old) <- new
old
}
new <- makeImportExportNames(unique(vars))
undef <- new[!new %in% .Internal(ls(ns, TRUE))]
undef <- undef[!vapply(undef, exists, NA, envir = ns)]
if (length(undef)) {
undef <- do.call("paste", as.list(c(undef, sep = ", ")))
stop(gettextf("undefined exports: %s", undef), domain = NA)
}
if (.isMethodsDispatchOn())
.mergeExportMethods(new, ns)
addExports(ns, new)
}
}
namespaceImport <- function (self, ..., from = NULL)
for (ns in list(...)) namespaceImportFrom(self, asNamespace(ns),
from = from)
## @type strict : numeric|logical
## @type x : numeric|character
numeric_version <- function (x, strict = TRUE)
.make_numeric_version(x, strict, .standard_regexps()$valid_numeric_version)
## @type blocking : logical
## @type open : character
open.connection <- function (con, open = "r", blocking = TRUE, ...)
.Internal(open(con, open, blocking))
## @type strict : numeric|logical
## @type x : numeric|character
package_version <- function (x, strict = TRUE)
{
if (is.list(x) && all(c("major", "minor") %in% names(x)))
return(R_system_version(paste(x[c("major", "minor")],
collapse = ".")))
.make_numeric_version(x, strict, .standard_regexps()$valid_package_version,
"package_version")
}
print.condition <- function (x, ...)
{
msg <- conditionMessage(x)
call <- conditionCall(x)
cl <- class(x)[1L]
if (!is.null(call))
cat("<", cl, " in ", deparse(call), ": ", msg, ">\n",
sep = "")
else cat("<", cl, ": ", msg, ">\n", sep = "")
invisible(x)
}
print.proc_time <- function (x, ...)
{
print(summary(x, ...))
invisible(x)
}
## @type sep : character
## @type base : character
provideDimnames <- function (x, sep = "", base = list(LETTERS))
{
dx <- dim(x)
dnx <- dimnames(x)
if (new <- is.null(dnx))
dnx <- vector("list", length(dx))
k <- length(M <- vapply(base, length, 1L))
for (i in which(vapply(dnx, is.null, NA))) {
ii <- 1L + (i - 1L)%%k
ss <- seq_len(dx[i]) - 1L
dnx[[i]] <- make.unique(base[[ii]][1L + (ss%%M[ii])],
sep = sep)
new <- TRUE
}
if (new)
dimnames(x) <- dnx
x
}
## @optional x
quarters.POSIXt <- function (x, ...)
{
x <- (as.POSIXlt(x)$mon)%/%3
paste0("Q", x + 1)
}
## @type where : numeric
## @type origin : character
## @type rw : character
seek.connection <- function (con, where = NA, origin = "start", rw = "", ...)
{
origin <- pmatch(origin, c("start", "current", "end"))
rw <- pmatch(rw, c("read", "write"), 0L)
if (is.na(origin))
stop("'origin' must be one of 'start', 'current' or 'end'")
.Internal(seek(con, as.double(where), origin, rw))
}
## @type all : logical
showConnections <- function (all = FALSE)
{
set <- getAllConnections()
if (!all)
set <- set[set > 2L]
ans <- matrix("", length(set), 7L)
for (i in seq_along(set)) ans[i, ] <- unlist(summary.connection(set[i]))
rownames(ans) <- set
colnames(ans) <- c("description", "class", "mode", "text",
"isopen", "can read", "can write")
if (!all)
ans[ans[, 5L] == "opened", , drop = FALSE]
else ans[, , drop = FALSE]
}
signalCondition <- function (cond)
{
if (!inherits(cond, "condition"))
cond <- simpleCondition(cond)
msg <- conditionMessage(cond)
call <- conditionCall(cond)
.Internal(.signalCondition(cond, msg, call))
}
simpleCondition <- function (message, call = NULL)
{
class <- c("simpleCondition", "condition")
structure(list(message = as.character(message), call = call),
class = class)
}
## @type drop : logical
"split<-.default" <- function (x, f, drop = FALSE, ..., value)
{
ix <- split(seq_along(x), f, drop = drop, ...)
n <- length(value)
j <- 0
for (i in ix) {
j <- j%%n + 1
x[i] <- value[[j]]
}
x
}
standardGeneric <- function (f, fdef) .Primitive("standardGeneric")
## @type digits : complex
summary.default <- function (object, ..., digits = max(3L, getOption("digits") -
3L))
{
if (is.factor(object))
return(summary.factor(object, ...))
else if (is.matrix(object))
return(summary.matrix(object, digits = digits, ...))
value <- if (is.logical(object))
c(Mode = "logical", {
tb <- table(object, exclude = NULL)
if (!is.null(n <- dimnames(tb)[[1L]]) && any(iN <- is.na(n))) dimnames(tb)[[1L]][iN] <- "NA's"
tb
})
else if (is.numeric(object)) {
nas <- is.na(object)
object <- object[!nas]
qq <- stats::quantile(object)
qq <- signif(c(qq[1L:3L], mean(object), qq[4L:5L]), digits)
names(qq) <- c("Min.", "1st Qu.", "Median", "Mean", "3rd Qu.",
"Max.")
if (any(nas))
c(qq, `NA's` = sum(nas))
else qq
}
else if (is.recursive(object) && !is.language(object) &&
(n <- length(object))) {
sumry <- array("", c(n, 3L), list(names(object), c("Length",
"Class", "Mode")))
ll <- numeric(n)
for (i in 1L:n) {
ii <- object[[i]]
ll[i] <- length(ii)
cls <- oldClass(ii)
sumry[i, 2L] <- if (length(cls))
cls[1L]
else "-none-"
sumry[i, 3L] <- mode(ii)
}
sumry[, 1L] <- format(as.integer(ll))
sumry
}
else c(Length = length(object), Class = class(object), Mode = mode(object))
class(value) <- c("summaryDefault", "table")
value
}
Summary.ordered <- function (..., na.rm)
{
ok <- switch(.Generic, max = , min = , range = TRUE, FALSE)
if (!ok)
stop(gettextf("'%s' not defined for ordered factors",
.Generic), domain = NA)
args <- list(...)
levl <- lapply(args, levels)
levset <- levl[[1]]
if (!all(vapply(args, is.ordered, NA)) || !all(sapply(levl,
identical, levset)))
stop(gettextf("'%s' is only meaningful for ordered factors if all arguments have the same level sets",
.Generic))
codes <- lapply(args, as.integer)
ind <- do.call(.Generic, c(codes, na.rm = na.rm))
ordered(levset[ind], levels = levset)
}
## @optional na.rm
Summary.POSIXct <- function (..., na.rm)
{
ok <- switch(.Generic, max = , min = , range = TRUE, FALSE)
if (!ok)
stop(gettextf("'%s' not defined for \"POSIXt\" objects",
.Generic), domain = NA)
args <- list(...)
tz <- do.call("check_tzones", args)
val <- NextMethod(.Generic)
class(val) <- oldClass(args[[1L]])
attr(val, "tzone") <- tz
val
}
Summary.POSIXlt <- function (..., na.rm)
{
ok <- switch(.Generic, max = , min = , range = TRUE, FALSE)
if (!ok)
stop(gettextf("'%s' not defined for \"POSIXt\" objects",
.Generic), domain = NA)
args <- list(...)
tz <- do.call("check_tzones", args)
args <- lapply(args, as.POSIXct)
val <- do.call(.Generic, c(args, na.rm = na.rm))
as.POSIXlt(.POSIXct(val, tz))
}
summary.srcfile <- function (object, ...)
{
cat(utils:::.normalizePath(object$filename, object$wd), "\n")
if (inherits(object$timestamp, "POSIXt"))
cat("Timestamp: ", format(object$timestamp, usetz = TRUE),
"\n", sep = "")
cat("Encoding: \"", object$encoding, "\"", sep = "")
if (!is.null(object$Enc) && object$Enc != object$encoding &&
object$Enc != "unknown")
cat(", re-encoded to \"", object$Enc, "\"", sep = "")
cat("\n")
invisible(object)
}
## @type path : character
Sys.setFileTime <- function (path, time)
{
if (!is.character(path) || length(path) != 1L)
stop("invalid 'path' argument")
time <- as.POSIXct(time)
if (is.na(time))
stop("invalid 'time' argument")
.Internal(setFileTime(path, time))
}
unloadNamespace <- function (ns)
{
runHook <- function(hookname, env, ...) {
if (exists(hookname, envir = env, inherits = FALSE)) {
fun <- get(hookname, envir = env, inherits = FALSE)
res <- tryCatch(fun(...), error = identity)
if (inherits(res, "error")) {
warning(gettextf("%s failed in %s() for '%s', details:\n call: %s\n error: %s",
hookname, "unloadNamespace", nsname, deparse(conditionCall(res))[1L],
conditionMessage(res)), call. = FALSE, domain = NA)
}
}
}
ns <- asNamespace(ns, base.OK = FALSE)
nsname <- getNamespaceName(ns)
pos <- match(paste("package", nsname, sep = ":"), search())
if (!is.na(pos))
detach(pos = pos)
users <- getNamespaceUsers(ns)
if (length(users))
stop(gettextf("namespace %s is imported by %s so cannot be unloaded",
sQuote(getNamespaceName(ns)), paste(sQuote(users),
collapse = ", ")), domain = NA)
nspath <- getNamespaceInfo(ns, "path")
hook <- getHook(packageEvent(nsname, "onUnload"))
for (fun in rev(hook)) try(fun(nsname, nspath))
runHook(".onUnload", ns, nspath)
.Internal(unregisterNamespace(nsname))
if (.isMethodsDispatchOn() && methods:::.hasS4MetaData(ns))
methods:::cacheMetaData(ns, FALSE, ns)
.Internal(lazyLoadDBflush(paste0(nspath, "/R/", nsname, ".rdb")))
invisible()
}
weekdays.POSIXt <- function (x, abbreviate = FALSE)
{
format(x, ifelse(abbreviate, "%a", "%A"))
}
## @type check.attributes : logical
## @return logical|character
all.equal.factor <- function (target, current, ..., check.attributes = TRUE)
{
if (!inherits(target, "factor"))
return("'target' is not a factor")
if (!inherits(current, "factor"))
return("'current' is not a factor")
msg <- if (check.attributes)
attr.all.equal(target, current, ...)
n <- all.equal(as.character(target), as.character(current),
check.attributes = check.attributes, ...)
if (is.character(n))
msg <- c(msg, n)
if (is.null(msg))
TRUE
else msg
}
## @type scale : numeric
## @type tolerance : numeric
## @optional scale
all.equal.POSIXt <- function (target, current, ..., tolerance = 0.001, scale)
{
target <- as.POSIXct(target)
current <- as.POSIXct(current)
check_tzones(target, current)
attr(target, "tzone") <- attr(current, "tzone") <- NULL
all.equal.numeric(target, current, ..., tolerance = tolerance,
scale = 1)
}
as.array.default <- function (x, ...)
{
if (is.array(x))
return(x)
n <- names(x)
dim(x) <- length(x)
if (length(n))
dimnames(x) <- list(n)
return(x)
}
as.data.frame.ts <- function (x, ...)
{
if (is.matrix(x))
as.data.frame.matrix(x, ...)
else as.data.frame.vector(x, ...)
}
as.list.function <- function (x, ...)
c(formals(x), list(body(x)))
as.POSIXct.dates <- function (x, ...)
{
if (inherits(x, "dates")) {
z <- attr(x, "origin")
x <- as.numeric(x) * 86400
if (length(z) == 3L && is.numeric(z))
x <- x + as.numeric(ISOdate(z[3L], z[1L], z[2L],
0))
return(.POSIXct(x))
}
else stop(gettextf("'%s' is not a \"dates\" object", deparse(substitute(x))))
}
as.POSIXlt.dates <- function (x, ...)
as.POSIXlt(as.POSIXct(x), ...)
as.table.default <- function (x, ...)
{
if (is.table(x))
return(x)
else if (is.array(x) || is.numeric(x)) {
x <- as.array(x)
if (any(dim(x) == 0L))
stop("cannot coerce to a table")
structure(class = c("table", oldClass(x)), provideDimnames(x))
}
else stop("cannot coerce to a table")
}
## @type mode : character
## @return numeric|character
as.vector.factor <- function (x, mode = "any")
{
if (mode == "list")
as.list(x)
else if (mode == "any" || mode == "character" || mode ==
"logical")
as.vector(levels(x)[x], mode)
else as.vector(unclass(x), mode)
}
browserCondition <- function (n = 1L)
.Internal(browserCondition(n))
## @type deparse.level : integer
cbind.data.frame <- function (..., deparse.level = 1)
data.frame(..., check.names = FALSE)
## @type type : character
close.connection <- function (con, type = "rw", ...)
.Internal(close(con, type))
conditionMessage <- function (c)
UseMethod("conditionMessage")
## @type fromLast : logical
duplicated.array <- function (x, incomparables = FALSE, MARGIN = 1L, fromLast = FALSE,
...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
dx <- dim(x)
ndim <- length(dx)
if (length(MARGIN) > ndim || any(MARGIN > ndim))
stop(gettextf("MARGIN = %d is invalid for dim = %d",
MARGIN, dx), domain = NA)
collapse <- (ndim > 1L) && (prod(dx[-MARGIN]) > 1L)
temp <- if (collapse)
apply(x, MARGIN, function(x) paste(x, collapse = "\r"))
else x
res <- duplicated.default(temp, fromLast = fromLast, ...)
dim(res) <- dim(temp)
dimnames(res) <- dimnames(temp)
res
}
flush.connection <- function (con)
.Internal(flush(con))
getExportedValue <- function (ns, name)
{
getInternalExportName <- function(name, ns) {
exports <- getNamespaceInfo(ns, "exports")
if (exists(name, envir = exports, inherits = FALSE))
get(get(name, envir = exports, inherits = FALSE),
envir = ns)
else {
ld <- getNamespaceInfo(ns, "lazydata")
if (exists(name, envir = ld, inherits = FALSE))
get(name, envir = ld, inherits = FALSE)
else stop(gettextf("'%s' is not an exported object from 'namespace:%s'",
name, getNamespaceName(ns)), call. = FALSE, domain = NA)
}
}
ns <- asNamespace(ns)
if (isBaseNamespace(ns))
get(name, envir = ns, inherits = FALSE)
else getInternalExportName(name, ns)
}
getNamespaceInfo <- function (ns, which)
{
ns <- asNamespace(ns, base.OK = FALSE)
info <- get(".__NAMESPACE__.", envir = ns, inherits = FALSE)
get(which, envir = info, inherits = FALSE)
}
## @return character
getNamespaceName <- function (ns)
{
ns <- asNamespace(ns)
if (isBaseNamespace(ns))
"base"
else getNamespaceInfo(ns, "spec")["name"]
}
is.na.data.frame <- function (x)
{
y <- if (length(x)) {
do.call("cbind", lapply(x, "is.na"))
}
else matrix(FALSE, length(row.names(x)), 0)
if (.row_names_info(x) > 0L)
rownames(y) <- row.names(x)
y
}
loadedNamespaces <- function ()
ls(.Internal(getNamespaceRegistry()), all.names = TRUE)
## @type all.x : logical
## @type sort : logical
## @type all : logical
## @type suffixes : character
## @type all.y : logical
merge.data.frame <- function (x, y, by = intersect(names(x), names(y)), by.x = by,
by.y = by, all = FALSE, all.x = all, all.y = all, sort = TRUE,
suffixes = c(".x", ".y"), incomparables = NULL, ...)
{
fix.by <- function(by, df) {
if (is.null(by))
by <- numeric()
by <- as.vector(by)
nc <- ncol(df)
if (is.character(by)) {
poss <- c("row.names", names(df))
if (any(bad <- !charmatch(by, poss, 0L)))
stop(ngettext(sum(bad), "'by' must specify a uniquely valid column",
"'by' must specify uniquely valid columns"),
domain = NA)
by <- match(by, poss) - 1L
}
else if (is.numeric(by)) {
if (any(by < 0L) || any(by > nc))
stop("'by' must match numbers of columns")
}
else if (is.logical(by)) {
if (length(by) != nc)
stop("'by' must match number of columns")
by <- seq_along(by)[by]
}
else stop("'by' must specify one or more columns as numbers, names or logical")
if (any(bad <- is.na(by)))
stop(ngettext(sum(bad), "'by' must specify a uniquely valid column",
"'by' must specify uniquely valid columns"),
domain = NA)
unique(by)
}
nx <- nrow(x <- as.data.frame(x))
ny <- nrow(y <- as.data.frame(y))
if (nx >= 2^31 || ny >= 2^31)
stop("long vectors are not supported")
by.x <- fix.by(by.x, x)
by.y <- fix.by(by.y, y)
if ((l.b <- length(by.x)) != length(by.y))
stop("'by.x' and 'by.y' specify different numbers of columns")
if (l.b == 0L) {
nm <- nm.x <- names(x)
nm.y <- names(y)
has.common.nms <- any(cnm <- nm.x %in% nm.y)
if (has.common.nms) {
names(x)[cnm] <- paste0(nm.x[cnm], suffixes[1L])
cnm <- nm.y %in% nm
names(y)[cnm] <- paste0(nm.y[cnm], suffixes[2L])
}
if (nx == 0L || ny == 0L) {
res <- cbind(x[FALSE, ], y[FALSE, ])
}
else {
ij <- expand.grid(seq_len(nx), seq_len(ny))
res <- cbind(x[ij[, 1L], , drop = FALSE], y[ij[,
2L], , drop = FALSE])
}
}
else {
if (any(by.x == 0L)) {
x <- cbind(Row.names = I(row.names(x)), x)
by.x <- by.x + 1L
}
if (any(by.y == 0L)) {
y <- cbind(Row.names = I(row.names(y)), y)
by.y <- by.y + 1L
}
row.names(x) <- NULL
row.names(y) <- NULL
if (l.b == 1L) {
bx <- x[, by.x]
if (is.factor(bx))
bx <- as.character(bx)
by <- y[, by.y]
if (is.factor(by))
by <- as.character(by)
}
else {
if (!is.null(incomparables))
stop("'incomparables' is supported only for merging on a single column")
bx <- x[, by.x, drop = FALSE]
by <- y[, by.y, drop = FALSE]
names(bx) <- names(by) <- paste0("V", seq_len(ncol(bx)))
bz <- do.call("paste", c(rbind(bx, by), sep = "\r"))
bx <- bz[seq_len(nx)]
by <- bz[nx + seq_len(ny)]
}
comm <- match(bx, by, 0L)
bxy <- bx[comm > 0L]
xinds <- match(bx, bxy, 0L, incomparables)
yinds <- match(by, bxy, 0L, incomparables)
if (nx > 0L && ny > 0L)
m <- .Internal(merge(xinds, yinds, all.x, all.y))
else m <- list(xi = integer(), yi = integer(), x.alone = seq_len(nx),
y.alone = seq_len(ny))
nm <- nm.x <- names(x)[-by.x]
nm.by <- names(x)[by.x]
nm.y <- names(y)[-by.y]
ncx <- ncol(x)
if (all.x)
all.x <- (nxx <- length(m$x.alone)) > 0L
if (all.y)
all.y <- (nyy <- length(m$y.alone)) > 0L
lxy <- length(m$xi)
has.common.nms <- any(cnm <- nm.x %in% nm.y)
if (has.common.nms && nzchar(suffixes[1L]))
nm.x[cnm] <- paste0(nm.x[cnm], suffixes[1L])
x <- x[c(m$xi, if (all.x) m$x.alone), c(by.x, seq_len(ncx)[-by.x]),
drop = FALSE]
names(x) <- c(nm.by, nm.x)
if (all.y) {
ya <- y[m$y.alone, by.y, drop = FALSE]
names(ya) <- nm.by
xa <- x[rep.int(NA_integer_, nyy), nm.x, drop = FALSE]
names(xa) <- nm.x
x <- rbind(x, cbind(ya, xa))
}
if (has.common.nms && nzchar(suffixes[2L])) {
cnm <- nm.y %in% nm
nm.y[cnm] <- paste0(nm.y[cnm], suffixes[2L])
}
y <- y[c(m$yi, if (all.x) rep.int(1L, nxx), if (all.y) m$y.alone),
-by.y, drop = FALSE]
if (all.x) {
zap <- (lxy + 1L):(lxy + nxx)
for (i in seq_along(y)) {
if (is.matrix(y[[1]]))
y[[1]][zap, ] <- NA
else is.na(y[[i]]) <- zap
}
}
if (has.common.nms)
names(y) <- nm.y
nm <- c(names(x), names(y))
if (any(d <- duplicated(nm)))
if (sum(d) > 1L)
warning("column names ", paste(sQuote(nm[d]),
collapse = ", "), " are duplicated in the result",
domain = NA)
else warning("column name ", sQuote(nm[d]), " is duplicated in the result",
domain = NA)
res <- cbind(x, y)
if (sort)
res <- res[if (all.x || all.y)
do.call("order", x[, seq_len(l.b), drop = FALSE])
else sort.list(bx[m$xi]), , drop = FALSE]
}
attr(res, "row.names") <- .set_row_names(nrow(res))
res
}
"mostattributes<-" <- function (obj, value)
{
if (length(value)) {
if (!is.list(value))
stop("'value' must be a list")
if (h.nam <- !is.na(inam <- match("names", names(value)))) {
n1 <- value[[inam]]
value <- value[-inam]
}
if (h.dim <- !is.na(idin <- match("dim", names(value)))) {
d1 <- value[[idin]]
value <- value[-idin]
}
if (h.dmn <- !is.na(idmn <- match("dimnames", names(value)))) {
dn1 <- value[[idmn]]
value <- value[-idmn]
}
attributes(obj) <- value
dm <- attr(obj, "dim")
L <- length(if (is.list(obj)) unclass(obj) else obj)
if (h.dim && L == prod(d1))
attr(obj, "dim") <- dm <- d1
if (h.dmn && !is.null(dm)) {
ddn <- sapply(dn1, length)
if (all((dm == ddn)[ddn > 0]))
attr(obj, "dimnames") <- dn1
}
if (h.nam && is.null(dm) && L == length(n1))
attr(obj, "names") <- n1
}
obj
}
open.srcfilecopy <- function (con, line, ...)
{
srcfile <- con
oldline <- srcfile$line
if (!is.null(oldline) && oldline > line)
close(srcfile)
conn <- srcfile$conn
if (is.null(conn)) {
srcfile$conn <- conn <- textConnection(srcfile$lines,
open = "r")
srcfile$line <- 1L
oldline <- 1L
}
else if (!isOpen(conn)) {
open(conn, open = "r")
srcfile$line <- 1L
oldline <- 1L
}
if (oldline < line) {
readLines(conn, line - oldline, warn = FALSE)
srcfile$line <- line
}
invisible(conn)
}
print.connection <- function (x, ...)
{
print(unlist(summary(x)))
invisible(x)
}
## @type right : logical
## @type digits : complex
## @type row.names : logical|character
## @type quote : logical
print.data.frame <- function (x, ..., digits = NULL, quote = FALSE, right = TRUE,
row.names = TRUE)
{
n <- length(row.names(x))
if (length(x) == 0L) {
cat(gettextf("data frame with 0 columns and %d rows\n",
n))
}
else if (n == 0L) {
print.default(names(x), quote = FALSE)
cat(gettext("<0 rows> (or 0-length row.names)\n"))
}
else {
m <- as.matrix(format.data.frame(x, digits = digits,
na.encode = FALSE))
if (!isTRUE(row.names))
dimnames(m)[[1L]] <- if (identical(row.names, FALSE))
rep.int("", n)
else row.names
print(m, ..., quote = quote, right = right)
}
invisible(x)
}
print.libraryIQR <- function (x, ...)
{
s <- format(x)
if (!length(s)) {
message("no packages found")
}
else {
outFile <- tempfile("RlibraryIQR")
writeLines(s, outFile)
file.show(outFile, delete.file = TRUE, title = gettext("R packages available"))
}
invisible(x)
}
## @type strict : numeric|logical
## @type x : numeric|character
R_system_version <- function (x, strict = TRUE)
.make_numeric_version(x, strict, .standard_regexps()$valid_R_system_version,
c("R_system_version", "package_version"))
## @type deparse.level : integer
rbind.data.frame <- function (..., deparse.level = 1)
{
match.names <- function(clabs, nmi) {
if (identical(clabs, nmi))
NULL
else if (length(nmi) == length(clabs) && all(nmi %in%
clabs)) {
m <- pmatch(nmi, clabs, 0L)
if (any(m == 0L))
stop("names do not match previous names")
m
}
else stop("names do not match previous names")
}
Make.row.names <- function(nmi, ri, ni, nrow) {
if (nzchar(nmi)) {
if (ni == 0L)
character()
else if (ni > 1L)
paste(nmi, ri, sep = ".")
else nmi
}
else if (nrow > 0L && identical(ri, seq_len(ni)))
as.integer(seq.int(from = nrow + 1L, length.out = ni))
else ri
}
allargs <- list(...)
allargs <- allargs[vapply(allargs, length, 1L) > 0L]
if (length(allargs)) {
nr <- vapply(allargs, function(x) if (is.data.frame(x))
.row_names_info(x, 2L)
else if (is.list(x))
length(x[[1L]])
else length(x), 1L)
if (any(nr > 0L))
allargs <- allargs[nr > 0L]
else return(allargs[[1L]])
}
n <- length(allargs)
if (n == 0L)
return(structure(list(), class = "data.frame", row.names = integer()))
nms <- names(allargs)
if (is.null(nms))
nms <- character(n)
cl <- NULL
perm <- rows <- rlabs <- vector("list", n)
nrow <- 0L
value <- clabs <- NULL
all.levs <- list()
for (i in seq_len(n)) {
xi <- allargs[[i]]
nmi <- nms[i]
if (is.matrix(xi))
allargs[[i]] <- xi <- as.data.frame(xi)
if (inherits(xi, "data.frame")) {
if (is.null(cl))
cl <- oldClass(xi)
ri <- attr(xi, "row.names")
ni <- length(ri)
if (is.null(clabs))
clabs <- names(xi)
else {
if (length(xi) != length(clabs))
stop("numbers of columns of arguments do not match")
pi <- match.names(clabs, names(xi))
if (!is.null(pi))
perm[[i]] <- pi
}
rows[[i]] <- seq.int(from = nrow + 1L, length.out = ni)
rlabs[[i]] <- Make.row.names(nmi, ri, ni, nrow)
nrow <- nrow + ni
if (is.null(value)) {
value <- unclass(xi)
nvar <- length(value)
all.levs <- vector("list", nvar)
has.dim <- logical(nvar)
facCol <- logical(nvar)
ordCol <- logical(nvar)
for (j in seq_len(nvar)) {
xj <- value[[j]]
if (!is.null(levels(xj))) {
all.levs[[j]] <- levels(xj)
facCol[j] <- TRUE
}
else facCol[j] <- is.factor(xj)
ordCol[j] <- is.ordered(xj)
has.dim[j] <- length(dim(xj)) == 2L
}
}
else for (j in seq_len(nvar)) {
xij <- xi[[j]]
if (is.null(pi) || is.na(jj <- pi[[j]]))
jj <- j
if (facCol[jj]) {
if (length(lij <- levels(xij))) {
all.levs[[jj]] <- unique(c(all.levs[[jj]],
lij))
ordCol[jj] <- ordCol[jj] & is.ordered(xij)
}
else if (is.character(xij))
all.levs[[jj]] <- unique(c(all.levs[[jj]],
xij))
}
}
}
else if (is.list(xi)) {
ni <- range(vapply(xi, length, 1L))
if (ni[1L] == ni[2L])
ni <- ni[1L]
else stop("invalid list argument: all variables should have the same length")
rows[[i]] <- ri <- as.integer(seq.int(from = nrow +
1L, length.out = ni))
nrow <- nrow + ni
rlabs[[i]] <- Make.row.names(nmi, ri, ni, nrow)
if (length(nmi <- names(xi)) > 0L) {
if (is.null(clabs))
clabs <- nmi
else {
if (length(xi) != length(clabs))
stop("numbers of columns of arguments do not match")
pi <- match.names(clabs, nmi)
if (!is.null(pi))
perm[[i]] <- pi
}
}
}
else if (length(xi)) {
rows[[i]] <- nrow <- nrow + 1L
rlabs[[i]] <- if (nzchar(nmi))
nmi
else as.integer(nrow)
}
}
nvar <- length(clabs)
if (nvar == 0L)
nvar <- max(vapply(allargs, length, 1L))
if (nvar == 0L)
return(structure(list(), class = "data.frame", row.names = integer()))
pseq <- seq_len(nvar)
if (is.null(value)) {
value <- list()
value[pseq] <- list(logical(nrow))
all.levs <- vector("list", nvar)
has.dim <- logical(nvar)
facCol <- logical(nvar)
ordCol <- logical(nvar)
}
names(value) <- clabs
for (j in pseq) if (length(lij <- all.levs[[j]]))
value[[j]] <- factor(as.vector(value[[j]]), lij, ordered = ordCol[j])
if (any(has.dim)) {
rmax <- max(unlist(rows))
for (i in pseq[has.dim]) if (!inherits(xi <- value[[i]],
"data.frame")) {
dn <- dimnames(xi)
rn <- dn[[1L]]
if (length(rn) > 0L)
length(rn) <- rmax
pi <- dim(xi)[2L]
length(xi) <- rmax * pi
value[[i]] <- array(xi, c(rmax, pi), list(rn, dn[[2L]]))
}
}
for (i in seq_len(n)) {
xi <- unclass(allargs[[i]])
if (!is.list(xi))
if (length(xi) != nvar)
xi <- rep(xi, length.out = nvar)
ri <- rows[[i]]
pi <- perm[[i]]
if (is.null(pi))
pi <- pseq
for (j in pseq) {
jj <- pi[j]
xij <- xi[[j]]
if (has.dim[jj]) {
value[[jj]][ri, ] <- xij
rownames(value[[jj]])[ri] <- rownames(xij)
}
else {
value[[jj]][ri] <- if (is.factor(xij))
as.vector(xij)
else xij
if (!is.null(nm <- names(xij)))
names(value[[jj]])[ri] <- nm
}
}
}
rlabs <- unlist(rlabs)
if (anyDuplicated(rlabs))
rlabs <- make.unique(as.character(unlist(rlabs)), sep = "")
if (is.null(cl)) {
as.data.frame(value, row.names = rlabs)
}
else {
class(value) <- cl
attr(value, "row.names") <- rlabs
value
}
}
registerS3method <- function (genname, class, method, envir = parent.frame())
{
addNamespaceS3method <- function(ns, generic, class, method) {
regs <- getNamespaceInfo(ns, "S3methods")
regs <- rbind(regs, c(generic, class, method))
setNamespaceInfo(ns, "S3methods", regs)
}
groupGenerics <- c("Math", "Ops", "Summary", "Complex")
defenv <- if (genname %in% groupGenerics)
.BaseNamespaceEnv
else {
genfun <- get(genname, envir = envir)
if (.isMethodsDispatchOn() && methods:::is(genfun, "genericFunction"))
genfun <- methods:::finalDefaultMethod(genfun@default)
if (typeof(genfun) == "closure")
environment(genfun)
else .BaseNamespaceEnv
}
if (!exists(".__S3MethodsTable__.", envir = defenv, inherits = FALSE))
assign(".__S3MethodsTable__.", new.env(hash = TRUE, parent = baseenv()),
envir = defenv)
table <- get(".__S3MethodsTable__.", envir = defenv, inherits = FALSE)
if (is.character(method)) {
assignWrapped <- function(x, method, home, envir) {
method <- method
home <- home
delayedAssign(x, get(method, envir = home), assign.env = envir)
}
if (!exists(method, envir = envir)) {
warning(gettextf("S3 method %s was declared but not found",
sQuote(method)), call. = FALSE)
}
else {
assignWrapped(paste(genname, class, sep = "."), method,
home = envir, envir = table)
}
}
else if (is.function(method))
assign(paste(genname, class, sep = "."), method, envir = table)
else stop("bad method")
if (isNamespace(envir) && !identical(envir, .BaseNamespaceEnv))
addNamespaceS3method(envir, genname, class, method)
}
## @type quietly : logical
## @type package : character
## @optional package
requireNamespace <- function (package, ..., quietly = FALSE)
{
package <- as.character(package)[[1L]]
ns <- .Internal(getRegisteredNamespace(as.name(package)))
res <- TRUE
if (is.null(ns)) {
if (!quietly)
packageStartupMessage(gettextf("Loading required namespace: %s",
package), domain = NA)
value <- tryCatch(loadNamespace(package, ...), error = function(e) e)
if (inherits(value, "error")) {
if (!quietly) {
msg <- conditionMessage(value)
cat("Failed with error: ", sQuote(msg), "\n",
file = stderr(), sep = "")
.Internal(printDeferredWarnings())
}
res <- FALSE
}
}
invisible(res)
}
setNamespaceInfo <- function (ns, which, val)
{
ns <- asNamespace(ns, base.OK = FALSE)
info <- get(".__NAMESPACE__.", envir = ns, inherits = FALSE)
assign(which, val, envir = info)
}
## @type open : character
## @type blocking : logical
## @type timeout : numeric
## @type server : logical
## @type host : character
## @type port : complex
## @type encoding : character
socketConnection <- function (host = "localhost", port, server = FALSE, blocking = FALSE,
open = "a+", encoding = getOption("encoding"), timeout = getOption("timeout"))
.Internal(socketConnection(host, port, server, blocking, open,
encoding, timeout))
## @type drop : logical
split.data.frame <- function (x, f, drop = FALSE, ...)
lapply(split(x = seq_len(nrow(x)), f = f, drop = drop, ...),
function(ind) x[ind, , drop = FALSE])
Summary.difftime <- function (..., na.rm)
{
coerceTimeUnit <- function(x) {
as.vector(switch(attr(x, "units"), secs = x, mins = 60 *
x, hours = 60 * 60 * x, days = 60 * 60 * 24 * x,
weeks = 60 * 60 * 24 * 7 * x))
}
ok <- switch(.Generic, max = , min = , sum = , range = TRUE,
FALSE)
if (!ok)
stop(gettextf("'%s' not defined for \"difftime\" objects",
.Generic), domain = NA)
x <- list(...)
Nargs <- length(x)
if (Nargs == 0) {
.difftime(do.call(.Generic), "secs")
}
else {
units <- sapply(x, function(x) attr(x, "units"))
if (all(units == units[1L])) {
args <- c(lapply(x, as.vector), na.rm = na.rm)
}
else {
args <- c(lapply(x, coerceTimeUnit), na.rm = na.rm)
units <- "secs"
}
.difftime(do.call(.Generic, args), units[[1L]])
}
}
suppressMessages <- function (expr)
withCallingHandlers(expr, message = function(c) invokeRestart("muffleMessage"))
suppressWarnings <- function (expr)
{
ops <- options(warn = -1)
on.exit(options(ops))
withCallingHandlers(expr, warning = function(w) invokeRestart("muffleWarning"))
}
toString.default <- function (x, width = NULL, ...)
{
string <- paste(x, collapse = ", ")
if (missing(width) || is.null(width) || width == 0)
return(string)
if (width < 0)
stop("'width' must be positive")
if (nchar(string, type = "w") > width) {
width <- max(6, width)
string <- paste0(strtrim(string, width - 4), "....")
}
string
}
## @type value : character
"units<-.difftime" <- function (x, value)
{
from <- units(x)
if (from == value)
return(x)
if (!(value %in% c("secs", "mins", "hours", "days", "weeks")))
stop("invalid units specified")
sc <- cumprod(c(secs = 1, mins = 60, hours = 60, days = 24,
weeks = 7))
newx <- unclass(x) * as.vector(sc[from]/sc[value])
.difftime(newx, value)
}
## @type x : numeric|character
"$.package_version" <- function (x, name)
{
name <- pmatch(name, c("major", "minor", "patchlevel"))
x <- unclass(x)
switch(name, major = vapply(x, "[", 0L, 1L), minor = vapply(x,
"[", 0L, 2L), patchlevel = vapply(x, "[", 0L, 3L))
}
## @type x : numeric|character
## @optional i
"[.numeric_version" <- function (x, i, j)
{
y <- if (missing(j))
unclass(x)[i]
else lapply(unclass(x)[i], "[", j)
bad <- vapply(y, function(t) is.null(t) || anyNA(t), NA)
if (any(bad))
y[bad] <- rep.int(list(integer()), length(bad))
class(y) <- class(x)
y
}
all.equal.default <- function (target, current, ...)
{
if (is.language(target) || is.function(target) || is.environment(target))
return(all.equal.language(target, current, ...))
if (is.recursive(target))
return(all.equal.list(target, current, ...))
msg <- switch(mode(target), integer = , complex = , numeric = all.equal.numeric(target,
current, ...), character = all.equal.character(target,
current, ...), logical = , raw = all.equal.raw(target,
current, ...), S4 = attr.all.equal(target, current, ...),
if (data.class(target) != data.class(current)) {
gettextf("target is %s, current is %s", data.class(target),
data.class(current))
} else NULL)
if (is.null(msg))
TRUE
else msg
}
all.equal.formula <- function (target, current, ...)
{
if (length(target) != length(current))
return(paste("target, current differ in having response: ",
length(target) == 3L, ", ", length(current) == 3L,
sep = ""))
if (!identical(deparse(target), deparse(current)))
"formulas differ in contents"
else TRUE
}
## @type tolerance : numeric
## @type check.attributes : logical
## @type scale : numeric
## @return logical
all.equal.numeric <- function (target, current, tolerance = .Machine$double.eps^0.5,
scale = NULL, ..., check.attributes = TRUE)
{
if (!is.numeric(tolerance))
stop("'tolerance' should be numeric")
if (!is.numeric(scale) && !is.null(scale))
stop("'scale' should be numeric or NULL")
if (!is.logical(check.attributes))
stop(gettextf("'%s' must be logical", "check.attributes"),
domain = NA)
msg <- if (check.attributes)
attr.all.equal(target, current, tolerance = tolerance,
scale = scale, ...)
if (data.class(target) != data.class(current)) {
msg <- c(msg, paste0("target is ", data.class(target),
", current is ", data.class(current)))
return(msg)
}
lt <- length(target)
lc <- length(current)
cplx <- is.complex(target)
if (lt != lc) {
if (!is.null(msg))
msg <- msg[-grep("\\bLengths\\b", msg)]
msg <- c(msg, paste0(if (cplx) "Complex" else "Numeric",
": lengths (", lt, ", ", lc, ") differ"))
return(msg)
}
target <- as.vector(target)
current <- as.vector(current)
out <- is.na(target)
if (any(out != is.na(current))) {
msg <- c(msg, paste("'is.NA' value mismatch:", sum(is.na(current)),
"in current", sum(out), "in target"))
return(msg)
}
out <- out | target == current
if (all(out)) {
if (is.null(msg))
return(TRUE)
else return(msg)
}
target <- target[!out]
current <- current[!out]
if (is.integer(target) && is.integer(current))
target <- as.double(target)
xy <- mean((if (cplx)
Mod
else abs)(target - current))
what <- if (is.null(scale)) {
xn <- mean(abs(target))
if (is.finite(xn) && xn > tolerance) {
xy <- xy/xn
"relative"
}
else "absolute"
}
else {
xy <- xy/scale
if (scale == 1)
"absolute"
else "scaled"
}
if (cplx)
what <- paste(what, "Mod")
if (is.na(xy) || xy > tolerance)
msg <- c(msg, paste("Mean", what, "difference:", format(xy)))
if (is.null(msg))
TRUE
else msg
}
as.character.Date <- function (x, ...)
format(x, ...)
## @type row.names : character
## @type optional : logical
as.data.frame.raw <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type format : character
as.Date.character <- function (x, format = "", ...)
{
charToDate <- function(x) {
xx <- x[1L]
if (is.na(xx)) {
j <- 1L
while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
if (is.na(xx))
f <- "%Y-%m-%d"
}
if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d",
tz = "GMT")) || !is.na(strptime(xx, f <- "%Y/%m/%d",
tz = "GMT")))
return(strptime(x, f))
stop("character string is not in a standard unambiguous format")
}
res <- if (missing(format))
charToDate(x)
else strptime(x, format, tz = "GMT")
as.Date(res)
}
as.double.POSIXlt <- function (x, ...)
as.double(as.POSIXct(x))
as.logical.factor <- function (x, ...)
as.logical(levels(x))[x]
as.matrix.default <- function (x, ...)
{
if (is.matrix(x))
x
else array(x, c(length(x), 1L), if (!is.null(names(x)))
list(names(x), NULL)
else NULL)
}
as.matrix.noquote <- function (x, ...)
noquote(NextMethod("as.matrix", x))
as.matrix.POSIXlt <- function (x, ...)
{
as.matrix(as.data.frame(unclass(x)), ...)
}
as.POSIXlt.factor <- function (x, ...)
{
y <- as.POSIXlt(as.character(x), ...)
names(y$year) <- names(x)
y
}
as.single.default <- function (x, ...)
structure(.Internal(as.vector(x, "double")), Csingle = TRUE)
c.numeric_version <- function (..., recursive = FALSE)
{
x <- lapply(list(...), as.numeric_version)
classes <- if (length(unique(lapply(x, class))) == 1L)
class(x[[1L]])
else "numeric_version"
structure(unlist(x, recursive = FALSE), class = classes)
}
droplevels.factor <- function (x, ...)
factor(x)
## @type fromLast : logical
duplicated.matrix <- function (x, incomparables = FALSE, MARGIN = 1L, fromLast = FALSE,
...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
dx <- dim(x)
ndim <- length(dx)
if (length(MARGIN) > ndim || any(MARGIN > ndim))
stop(gettextf("MARGIN = %d is invalid for dim = %d",
MARGIN, dx), domain = NA)
collapse <- (ndim > 1L) && (prod(dx[-MARGIN]) > 1L)
temp <- if (collapse)
apply(x, MARGIN, function(x) paste(x, collapse = "\r"))
else x
res <- duplicated.default(temp, fromLast = fromLast, ...)
dim(res) <- dim(temp)
dimnames(res) <- dimnames(temp)
res
}
## @type justify : character
## @type x : numeric
format.data.frame <- function (x, ..., justify = "none")
{
nr <- .row_names_info(x, 2L)
nc <- length(x)
rval <- vector("list", nc)
for (i in seq_len(nc)) rval[[i]] <- format(x[[i]], ..., justify = justify)
lens <- sapply(rval, NROW)
if (any(lens != nr)) {
warning("corrupt data frame: columns will be truncated or padded with NAs")
for (i in seq_len(nc)) {
len <- NROW(rval[[i]])
if (len == nr)
next
if (length(dim(rval[[i]])) == 2L) {
rval[[i]] <- if (len < nr)
rbind(rval[[i]], matrix(NA, nr - len, ncol(rval[[i]])))
else rval[[i]][seq_len(nr), ]
}
else {
rval[[i]] <- if (len < nr)
c(rval[[i]], rep.int(NA, nr - len))
else rval[[i]][seq_len(nr)]
}
}
}
for (i in seq_len(nc)) {
if (is.character(rval[[i]]) && inherits(rval[[i]], "character"))
oldClass(rval[[i]]) <- "AsIs"
}
cn <- names(x)
m <- match(c("row.names", "check.rows", "check.names", ""),
cn, 0L)
if (any(m))
cn[m] <- paste0("..dfd.", cn[m])
long <- nchar(cn, "bytes") > 256L
cn[long] <- paste(substr(cn[long], 1L, 250L), "...")
names(rval) <- cn
rval$check.names <- FALSE
rval$row.names <- row.names(x)
x <- do.call("data.frame", rval)
if (any(m))
names(x) <- sub("^..dfd.", "", names(x))
x
}
## @optional x
format.libraryIQR <- function (x, ...)
{
db <- x$results
if (!nrow(db))
return(character())
libs <- db[, "LibPath"]
libs <- factor(libs, levels = unique(libs))
out <- lapply(split(1:nrow(db), libs), function(ind) db[ind,
c("Package", "Title"), drop = FALSE])
c(unlist(Map(function(lib, sep) {
c(gettextf("%sPackages in library %s:\n", sep, sQuote(lib)),
formatDL(out[[lib]][, "Package"], out[[lib]][, "Title"]))
}, names(out), c("", rep.int("\n", length(out) - 1L)))),
x$footer)
}
getAllConnections <- function ()
.Internal(getAllConnections())
getNamespaceUsers <- function (ns)
{
nsname <- getNamespaceName(asNamespace(ns))
users <- character()
for (n in loadedNamespaces()) {
inames <- names(getNamespaceImports(n))
if (match(nsname, inames, 0L))
users <- c(n, users)
}
users
}
is.numeric.POSIXt <- function (x)
FALSE
## @type sym : character
makeActiveBinding <- function (sym, fun, env)
{
if (is.character(sym))
sym <- as.name(sym)
.Internal(makeActiveBinding(sym, fun, env))
}
open.srcfilealias <- function (con, line, ...)
open(con$original, line, ...)
print.DLLInfoList <- function (x, ...)
{
if (length(x)) {
m <- data.frame(Filename = sapply(x, function(x) x[["path"]]),
`Dynamic Lookup` = sapply(x, function(x) x[["dynamicLookup"]]))
print(m, ...)
}
invisible(x)
}
print.packageInfo <- function (x, ...)
{
outFile <- tempfile("RpackageInfo")
writeLines(format(x), outFile)
file.show(outFile, delete.file = TRUE, title = gettextf("Documentation for package %s",
sQuote(x$name)))
invisible(x)
}
print.simple.list <- function (x, ...)
print(noquote(cbind(`_` = unlist(x))), ...)
## @optional package
registerS3methods <- function (info, package, env)
{
n <- NROW(info)
if (n == 0L)
return()
assignWrapped <- function(x, method, home, envir) {
method <- method
home <- home
delayedAssign(x, get(method, envir = home), assign.env = envir)
}
.registerS3method <- function(genname, class, method, nm,
envir) {
defenv <- if (!is.na(w <- .knownS3Generics[genname]))
asNamespace(w)
else {
if (!exists(genname, envir = parent.env(envir)))
stop(gettextf("object '%s' not found whilst loading namespace '%s'",
genname, package), call. = FALSE, domain = NA)
genfun <- get(genname, envir = parent.env(envir))
if (.isMethodsDispatchOn() && methods:::is(genfun,
"genericFunction"))
genfun <- genfun@default
if (typeof(genfun) == "closure")
environment(genfun)
else .BaseNamespaceEnv
}
if (!exists(".__S3MethodsTable__.", envir = defenv, inherits = FALSE))
assign(".__S3MethodsTable__.", new.env(hash = TRUE,
parent = baseenv()), envir = defenv)
table <- get(".__S3MethodsTable__.", envir = defenv,
inherits = FALSE)
assignWrapped(nm, method, home = envir, envir = table)
}
methname <- paste(info[, 1], info[, 2], sep = ".")
z <- is.na(info[, 3])
info[z, 3] <- methname[z]
Info <- cbind(info, methname)
loc <- .Internal(ls(env, TRUE))
notex <- !(info[, 3] %in% loc)
if (any(notex))
warning(sprintf(ngettext(sum(notex), "S3 method %s was declared in NAMESPACE but not found",
"S3 methods %s were declared in NAMESPACE but not found"),
paste(sQuote(info[notex, 3]), collapse = ", ")),
call. = FALSE, domain = NA)
Info <- Info[!notex, , drop = FALSE]
l2 <- localGeneric <- Info[, 1] %in% loc
if (.isMethodsDispatchOn())
for (i in which(localGeneric)) {
genfun <- get(Info[i, 1], envir = env)
if (methods:::is(genfun, "genericFunction")) {
localGeneric[i] <- FALSE
registerS3method(Info[i, 1], Info[i, 2], Info[i,
3], env)
}
}
if (any(localGeneric)) {
lin <- Info[localGeneric, , drop = FALSE]
S3MethodsTable <- get(".__S3MethodsTable__.", envir = env,
inherits = FALSE)
.Internal(importIntoEnv(S3MethodsTable, lin[, 4], env,
lin[, 3]))
}
fin <- Info[!l2, , drop = FALSE]
for (i in seq_len(nrow(fin))) .registerS3method(fin[i, 1],
fin[i, 2], fin[i, 3], fin[i, 4], env)
setNamespaceInfo(env, "S3methods", rbind(info, getNamespaceInfo(env,
"S3methods")))
}
row.names.default <- function (x)
if (!is.null(dim(x))) rownames(x)
## @type na.rm : logical
## @type x : numeric
rowsum.data.frame <- function (x, group, reorder = TRUE, na.rm = FALSE, ...)
{
if (!is.data.frame(x))
stop("not a data frame")
if (length(group) != NROW(x))
stop("incorrect length for 'group'")
if (anyNA(group))
warning("missing values for 'group'")
ugroup <- unique(group)
if (reorder)
ugroup <- sort(ugroup, na.last = TRUE, method = "quick")
.Internal(rowsum_df(x, group, ugroup, na.rm, as.character(ugroup)))
}
## @type subset : logical
subset.data.frame <- function (x, subset, select, drop = FALSE, ...)
{
r <- if (missing(subset))
rep_len(TRUE, nrow(x))
else {
e <- substitute(subset)
r <- eval(e, x, parent.frame())
if (!is.logical(r))
stop("'subset' must be logical")
r & !is.na(r)
}
vars <- if (missing(select))
TRUE
else {
nl <- as.list(seq_along(x))
names(nl) <- names(x)
eval(substitute(select), nl, parent.frame())
}
x[r, vars, drop = drop]
}
## @optional object
summary.proc_time <- function (object, ...)
{
if (!is.na(object[4L]))
object[1L] <- object[1L] + object[4L]
if (!is.na(object[5L]))
object[2L] <- object[2L] + object[5L]
object <- object[1L:3L]
names(object) <- c(gettext("user"), gettext("system"), gettext("elapsed"))
object
}
transform.default <- function (`_data`, ...)
transform.data.frame(data.frame(`_data`), ...)
## @type fromLast : logical
## @optional x
unique.data.frame <- function (x, incomparables = FALSE, fromLast = FALSE, ...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
x[!duplicated(x, fromLast = fromLast, ...), , drop = FALSE]
}
within.data.frame <- function (data, expr, ...)
{
parent <- parent.frame()
e <- evalq(environment(), data, parent)
eval(substitute(expr), e)
l <- as.list(e)
l <- l[!sapply(l, is.null)]
nD <- length(del <- setdiff(names(data), (nl <- names(l))))
data[nl] <- l
if (nD)
data[del] <- if (nD == 1)
NULL
else vector("list", nD)
data
}
## @type x : numeric|character
"[[.numeric_version" <- function (x, ..., exact = NA)
{
if (length(list(...)) < 2L)
structure(list(unclass(x)[[..., exact = exact]]), class = oldClass(x))
else unclass(x)[[..1, exact = exact]][..2]
}
all.equal.language <- function (target, current, ...)
{
mt <- mode(target)
mc <- mode(current)
if (mt == "expression" && mc == "expression")
return(all.equal.list(target, current, ...))
ttxt <- paste(deparse(target), collapse = "\n")
ctxt <- paste(deparse(current), collapse = "\n")
msg <- c(if (mt != mc) paste0("Modes of target, current: ",
mt, ", ", mc), if (ttxt != ctxt) {
if (pmatch(ttxt, ctxt, 0L)) "target is a subset of current" else if (pmatch(ctxt,
ttxt, 0L)) "current is a subset of target" else "target, current do not match when deparsed"
})
if (is.null(msg))
TRUE
else msg
}
as.character.error <- function (x, ...)
{
msg <- conditionMessage(x)
call <- conditionCall(x)
if (!is.null(call))
paste0("Error in ", deparse(call)[1L], ": ", msg, "\n")
else paste0("Error: ", msg, "\n")
}
## @type row.names : character
## @type optional : logical
as.data.frame.AsIs <- function (x, row.names = NULL, optional = FALSE, ...)
{
if (length(dim(x)) == 2L)
as.data.frame.model.matrix(x, row.names, optional)
else {
nrows <- length(x)
nm <- paste(deparse(substitute(x), width.cutoff = 500L),
collapse = " ")
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows &&
!anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
}
as.data.frame.Date <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type row.names : character
## @type stringsAsFactors : logical|character
## @type optional : logical
as.data.frame.list <- function (x, row.names = NULL, optional = FALSE, ..., stringsAsFactors = default.stringsAsFactors())
{
cn <- names(x)
m <- match(c("row.names", "check.rows", "check.names", "stringsAsFactors"),
cn, 0L)
if (any(m)) {
cn[m] <- paste0("..adfl.", cn[m])
names(x) <- cn
}
x <- eval(as.call(c(expression(data.frame), x, check.names = !optional,
stringsAsFactors = stringsAsFactors)))
if (any(m))
names(x) <- sub("^\\.\\.adfl\\.", "", names(x))
if (!is.null(row.names)) {
if (length(row.names) != dim(x)[[1L]])
stop(sprintf(ngettext(length(row.names), "supplied %d row name for %d rows",
"supplied %d row names for %d rows"), length(row.names),
dim(x)[[1L]]), domain = NA)
attr(x, "row.names") <- row.names
}
x
}
## @type units : character
## @return numeric|character
as.double.difftime <- function (x, units = "auto", ...)
{
if (units != "auto")
units(x) <- units
as.vector(x, "double")
}
as.list.data.frame <- function (x, ...)
{
x <- unclass(x)
attr(x, "row.names") <- NULL
x
}
## @type x : numeric|character
as.numeric_version <- function (x)
{
if (is.numeric_version(x))
x
else if (is.package_version(x)) {
structure(x, class = c(class(x), "numeric_version"))
}
else numeric_version(x)
}
## @type x : numeric|character
as.package_version <- function (x)
if (is.package_version(x)) x else package_version(x)
as.POSIXct.default <- function (x, tz = "", ...)
{
if (inherits(x, "POSIXct"))
return(x)
if (is.character(x) || is.factor(x))
return(as.POSIXct(as.POSIXlt(x, tz, ...), tz, ...))
if (is.logical(x) && all(is.na(x)))
return(.POSIXct(as.numeric(x)))
stop(gettextf("do not know how to convert '%s' to class %s",
deparse(substitute(x)), dQuote("POSIXct")), domain = NA)
}
as.POSIXct.numeric <- function (x, tz = "", origin, ...)
{
if (missing(origin))
stop("'origin' must be supplied")
.POSIXct(as.POSIXct(origin, tz = "GMT", ...) + x, tz)
}
as.POSIXct.POSIXlt <- function (x, tz = "", ...)
{
tzone <- attr(x, "tzone")
if (missing(tz) && !is.null(tzone))
tz <- tzone[1L]
y <- .Internal(as.POSIXct(x, tz))
names(y) <- names(x$year)
.POSIXct(y, tz)
}
as.POSIXlt.default <- function (x, tz = "", ...)
{
if (inherits(x, "POSIXlt"))
return(x)
if (is.logical(x) && all(is.na(x)))
return(as.POSIXlt(as.POSIXct.default(x), tz = tz))
stop(gettextf("do not know how to convert '%s' to class %s",
deparse(substitute(x)), dQuote("POSIXlt")), domain = NA)
}
as.POSIXlt.numeric <- function (x, tz = "", origin, ...)
{
if (missing(origin))
stop("'origin' must be supplied")
as.POSIXlt(as.POSIXct(origin, tz = "UTC", ...) + x, tz = tz)
}
as.POSIXlt.POSIXct <- function (x, tz = "", ...)
{
if ((missing(tz) || is.null(tz)) && !is.null(tzone <- attr(x,
"tzone")))
tz <- tzone[1L]
.Internal(as.POSIXlt(x, tz))
}
close.srcfilealias <- function (con, ...)
close(con$original, ...)
## @type logarithm : logical
## @type x : logical|numeric
determinant.matrix <- function (x, logarithm = TRUE, ...)
{
if ((n <- ncol(x)) != nrow(x))
stop("'x' must be a square matrix")
if (n < 1L)
return(structure(list(modulus = structure(if (logarithm) 0 else 1,
logarithm = logarithm), sign = 1L), class = "det"))
if (is.complex(x))
stop("'determinant' not currently defined for complex matrices")
.Internal(det_ge_real(x, logarithm))
}
## @type fromLast : logical
## @type nmax : complex
duplicated.default <- function (x, incomparables = FALSE, fromLast = FALSE, nmax = NA,
...)
.Internal(duplicated(x, incomparables, fromLast, if (is.factor(x)) min(length(x),
nlevels(x) + 1L) else nmax))
duplicated.POSIXlt <- function (x, incomparables = FALSE, ...)
{
x <- as.POSIXct(x)
NextMethod("duplicated", x)
}
format.packageInfo <- function (x, ...)
{
if (!inherits(x, "packageInfo"))
stop("wrong class")
vignetteMsg <- gettextf("Further information is available in the following vignettes in directory %s:",
sQuote(file.path(x$path, "doc")))
headers <- sprintf("\n%s\n", c(gettext("Description:"), gettext("Index:"),
paste(strwrap(vignetteMsg), collapse = "\n")))
formatDocEntry <- function(entry) {
if (is.list(entry) || is.matrix(entry))
formatDL(entry, style = "list")
else entry
}
c(gettextf("\n\t\tInformation on package %s", sQuote(x$name)),
unlist(lapply(which(!vapply(x$info, is.null, NA)), function(i) c(headers[i],
formatDocEntry(x$info[[i]])))))
}
## @type x : numeric|character
is.numeric_version <- function (x)
inherits(x, "numeric_version")
## @type x : numeric|character
is.package_version <- function (x)
inherits(x, "package_version")
## @type tol : numeric
## @return logical
isSymmetric.matrix <- function (object, tol = 100 * .Machine$double.eps, ...)
{
if (!is.matrix(object))
return(FALSE)
d <- dim(object)
if (d[1L] != d[2L])
return(FALSE)
test <- if (is.complex(object))
all.equal.numeric(object, Conj(t(object)), tolerance = tol,
...)
else all.equal(object, t(object), tolerance = tol, ...)
isTRUE(test)
}
## @type package.lib : character
## @type mustExist : logical
## @type package : character
parseNamespaceFile <- function (package, package.lib, mustExist = TRUE)
{
namespaceFilePath <- function(package, package.lib) file.path(package.lib,
package, "NAMESPACE")
nativeRoutineMap <- function(useRegistration, symbolNames,
fixes) {
proto <- list(useRegistration = FALSE, symbolNames = character())
class(proto) <- "NativeRoutineMap"
mergeNativeRoutineMaps(proto, useRegistration, symbolNames,
fixes)
}
mergeNativeRoutineMaps <- function(map, useRegistration,
symbolNames, fixes) {
if (!useRegistration)
names(symbolNames) <- paste0(fixes[1L], names(symbolNames),
fixes[2L])
else map$registrationFixes <- fixes
map$useRegistration <- map$useRegistration || useRegistration
map$symbolNames <- c(map$symbolNames, symbolNames)
map
}
nsFile <- namespaceFilePath(package, package.lib)
descfile <- file.path(package.lib, package, "DESCRIPTION")
enc <- if (file.exists(descfile)) {
read.dcf(file = descfile, "Encoding")[1L]
}
else NA_character_
if (file.exists(nsFile))
directives <- if (!is.na(enc) && !Sys.getlocale("LC_CTYPE") %in%
c("C", "POSIX")) {
con <- file(nsFile, encoding = enc)
on.exit(close(con))
parse(con, srcfile = NULL)
}
else parse(nsFile, srcfile = NULL)
else if (mustExist)
stop(gettextf("package %s has no 'NAMESPACE' file", sQuote(package)),
domain = NA)
else directives <- NULL
exports <- character()
exportPatterns <- character()
exportClasses <- character()
exportClassPatterns <- character()
exportMethods <- character()
imports <- list()
importMethods <- list()
importClasses <- list()
dynlibs <- character()
nS3methods <- 1000L
S3methods <- matrix(NA_character_, nS3methods, 3L)
nativeRoutines <- list()
nS3 <- 0L
parseDirective <- function(e) {
asChar <- function(cc) {
r <- as.character(cc)
if (any(r == ""))
stop(gettextf("empty name in directive '%s' in 'NAMESPACE' file",
as.character(e[[1L]])), domain = NA)
r
}
switch(as.character(e[[1L]]), `if` = if (eval(e[[2L]],
.GlobalEnv)) parseDirective(e[[3L]]) else if (length(e) ==
4L) parseDirective(e[[4L]]), `{` = for (ee in as.list(e[-1L])) parseDirective(ee),
`=` = , `<-` = {
parseDirective(e[[3L]])
if (as.character(e[[3L]][[1L]]) == "useDynLib") names(dynlibs)[length(dynlibs)] <<- asChar(e[[2L]])
}, export = {
exp <- e[-1L]
exp <- structure(asChar(exp), names = names(exp))
exports <<- c(exports, exp)
}, exportPattern = {
pat <- asChar(e[-1L])
exportPatterns <<- c(pat, exportPatterns)
}, exportClassPattern = {
pat <- asChar(e[-1L])
exportClassPatterns <<- c(pat, exportClassPatterns)
}, exportClass = , exportClasses = {
exportClasses <<- c(asChar(e[-1L]), exportClasses)
}, exportMethods = {
exportMethods <<- c(asChar(e[-1L]), exportMethods)
}, import = imports <<- c(imports, as.list(asChar(e[-1L]))),
importFrom = {
imp <- e[-1L]
ivars <- imp[-1L]
inames <- names(ivars)
imp <- list(asChar(imp[1L]), structure(asChar(ivars),
names = inames))
imports <<- c(imports, list(imp))
}, importClassFrom = , importClassesFrom = {
imp <- asChar(e[-1L])
pkg <- imp[[1L]]
impClasses <- imp[-1L]
imp <- list(asChar(pkg), asChar(impClasses))
importClasses <<- c(importClasses, list(imp))
}, importMethodsFrom = {
imp <- asChar(e[-1L])
pkg <- imp[[1L]]
impMethods <- imp[-1L]
imp <- list(asChar(pkg), asChar(impMethods))
importMethods <<- c(importMethods, list(imp))
}, useDynLib = {
dyl <- as.character(e[2L])
dynlibs <<- structure(c(dynlibs, dyl), names = c(names(dynlibs),
ifelse(!is.null(names(e)) && names(e)[2L] !=
"", names(e)[2L], "")))
if (length(e) > 2L) {
symNames <- as.character(e[-c(1L, 2L)])
names(symNames) <- names(e[-c(1, 2)])
if (length(names(symNames)) == 0L) names(symNames) = symNames else if (any(w <- names(symNames) ==
"")) {
names(symNames)[w] = symNames[w]
}
dup <- duplicated(names(symNames))
if (any(dup)) warning(gettextf("duplicate symbol names %s in useDynLib(\"%s\")",
paste(sQuote(names(symNames)[dup]), collapse = ", "),
dyl), domain = NA)
symNames <- symNames[!dup]
fixes <- c("", "")
idx <- match(".fixes", names(symNames))
if (!is.na(idx)) {
if (symNames[idx] != "") {
e <- parse(text = symNames[idx], srcfile = NULL)[[1L]]
if (is.call(e)) val <- eval(e) else val <- as.character(e)
if (length(val)) fixes[seq_along(val)] <- val
}
symNames <- symNames[-idx]
}
useRegistration <- FALSE
idx <- match(".registration", names(symNames))
if (!is.na(idx)) {
useRegistration <- as.logical(symNames[idx])
symNames <- symNames[-idx]
}
nativeRoutines[[dyl]] <<- if (dyl %in% names(nativeRoutines)) mergeNativeRoutineMaps(nativeRoutines[[dyl]],
useRegistration, symNames, fixes) else nativeRoutineMap(useRegistration,
symNames, fixes)
}
}, S3method = {
spec <- e[-1L]
if (length(spec) != 2L && length(spec) != 3L) stop(gettextf("bad 'S3method' directive: %s",
deparse(e)), call. = FALSE, domain = NA)
nS3 <<- nS3 + 1L
if (nS3 > nS3methods) {
old <- S3methods
nold <- nS3methods
nS3methods <<- nS3methods * 2L
new <- matrix(NA_character_, nS3methods, 3L)
ind <- seq_len(nold)
for (i in 1:3) new[ind, i] <- old[ind, i]
S3methods <<- new
rm(old, new)
}
S3methods[nS3, seq_along(spec)] <<- asChar(spec)
}, stop(gettextf("unknown namespace directive: %s",
deparse(e, nlines = 1L)), call. = FALSE, domain = NA))
}
for (e in directives) parseDirective(e)
dynlibs <- dynlibs[!duplicated(dynlibs)]
list(imports = imports, exports = exports, exportPatterns = unique(exportPatterns),
importClasses = importClasses, importMethods = importMethods,
exportClasses = unique(exportClasses), exportMethods = unique(exportMethods),
exportClassPatterns = unique(exportClassPatterns), dynlibs = dynlibs,
nativeRoutines = nativeRoutines, S3methods = unique(S3methods[seq_len(nS3),
, drop = FALSE]))
}
## @type con : raw
rawConnectionValue <- function (con)
.Internal(rawConnectionValue(con))
## @type id : integer|character
## @return logical|integer|character
removeTaskCallback <- function (id)
{
if (!is.character(id))
id <- as.integer(id)
.Call(.C_R_removeTaskCallback, id)
}
restartDescription <- function (r)
r$description
## @type drop : logical
"split<-.data.frame" <- function (x, f, drop = FALSE, ..., value)
{
ix <- split(seq_len(nrow(x)), f, drop = drop, ...)
n <- length(value)
j <- 0
for (i in ix) {
j <- j%%n + 1
x[i, ] <- value[[j]]
}
x
}
summary.connection <- function (object, ...)
.Internal(summary.connection(object))
Summary.data.frame <- function (..., na.rm)
{
args <- list(...)
args <- lapply(args, function(x) {
x <- as.matrix(x)
if (!is.numeric(x) && !is.complex(x))
stop("only defined on a data frame with all numeric variables")
x
})
do.call(.Generic, c(args, na.rm = na.rm))
}
xpdrows.data.frame <- function (x, old.rows, new.rows)
{
nc <- length(x)
nro <- length(old.rows)
nrn <- length(new.rows)
nr <- nro + nrn
for (i in seq_len(nc)) {
y <- x[[i]]
dy <- dim(y)
cy <- oldClass(y)
class(y) <- NULL
if (length(dy) == 2L) {
dny <- dimnames(y)
if (length(dny[[1L]]) > 0L)
dny[[1L]] <- c(dny[[1L]], new.rows)
z <- array(y[1L], dim = c(nr, nc), dimnames = dny)
z[seq_len(nro), ] <- y
class(z) <- cy
x[[i]] <- z
}
else {
ay <- attributes(y)
if (length(names(y)) > 0L)
ay$names <- c(ay$names, new.rows)
length(y) <- nr
attributes(y) <- ay
class(y) <- cy
x[[i]] <- y
}
}
attr(x, "row.names") <- c(old.rows, new.rows)
x
}
## @type check.attributes : logical
## @return logical
all.equal.character <- function (target, current, ..., check.attributes = TRUE)
{
if (!is.logical(check.attributes))
stop(gettextf("'%s' must be logical", "check.attributes"),
domain = NA)
msg <- if (check.attributes)
attr.all.equal(target, current, ...)
if (data.class(target) != data.class(current)) {
msg <- c(msg, paste0("target is ", data.class(target),
", current is ", data.class(current)))
return(msg)
}
lt <- length(target)
lc <- length(current)
if (lt != lc) {
if (!is.null(msg))
msg <- msg[-grep("\\bLengths\\b", msg)]
msg <- c(msg, paste0("Lengths (", lt, ", ", lc, ") differ (string compare on first ",
ll <- min(lt, lc), ")"))
ll <- seq_len(ll)
target <- target[ll]
current <- current[ll]
}
nas <- is.na(target)
nasc <- is.na(current)
if (any(nas != nasc)) {
msg <- c(msg, paste("'is.NA' value mismatch:", sum(nasc),
"in current", sum(nas), "in target"))
return(msg)
}
ne <- !nas & (target != current)
if (!any(ne) && is.null(msg))
TRUE
else if (sum(ne) == 1L)
c(msg, paste("1 string mismatch"))
else if (sum(ne) > 1L)
c(msg, paste(sum(ne), "string mismatches"))
else msg
}
## @type fromLast : logical
anyDuplicated.array <- function (x, incomparables = FALSE, MARGIN = 1L, fromLast = FALSE,
...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
dx <- dim(x)
ndim <- length(dx)
if (length(MARGIN) > ndim || any(MARGIN > ndim))
stop(gettextf("MARGIN = %d is invalid for dim = %d",
MARGIN, dx), domain = NA)
collapse <- (ndim > 1L) && (prod(dx[-MARGIN]) > 1L)
temp <- if (collapse)
apply(x, MARGIN, function(x) paste(x, collapse = "\r"))
else x
anyDuplicated.default(temp, fromLast = fromLast)
}
as.character.factor <- function (x, ...)
levels(x)[x]
## @type x : character
as.character.POSIXt <- function (x, ...)
format(x, ...)
as.character.srcref <- function (x, useSource = TRUE, ...)
{
srcfile <- attr(x, "srcfile")
if (!is.null(srcfile) && !inherits(srcfile, "srcfile")) {
cat("forcing class on")
print(str(srcfile))
class(srcfile) <- c("srcfilealias", "srcfile")
}
if (useSource) {
if (inherits(srcfile, "srcfilecopy") || inherits(srcfile,
"srcfilealias"))
lines <- try(getSrcLines(srcfile, x[7L], x[8L]),
TRUE)
else lines <- try(getSrcLines(srcfile, x[1L], x[3L]),
TRUE)
}
if (!useSource || inherits(lines, "try-error"))
lines <- paste("<srcref: file \"", srcfile$filename,
"\" chars ", x[1L], ":", x[5L], " to ", x[3L], ":",
x[6L], ">", sep = "")
else if (length(lines)) {
enc <- Encoding(lines)
Encoding(lines) <- "latin1"
if (length(lines) < x[3L] - x[1L] + 1L)
x[4L] <- .Machine$integer.max
lines[length(lines)] <- substring(lines[length(lines)],
1L, x[4L])
lines[1L] <- substring(lines[1L], x[2L])
Encoding(lines) <- enc
}
lines
}
## @type optional : logical
## @type row.names : character
as.data.frame.array <- function (x, row.names = NULL, optional = FALSE, ...)
{
d <- dim(x)
if (length(d) == 1L) {
value <- as.data.frame.vector(drop(x), row.names, optional,
...)
if (!optional)
names(value) <- deparse(substitute(x))[[1L]]
value
}
else if (length(d) == 2L) {
as.data.frame.matrix(x, row.names, optional, ...)
}
else {
dn <- dimnames(x)
dim(x) <- c(d[1L], prod(d[-1L]))
if (!is.null(dn)) {
if (length(dn[[1L]]))
rownames(x) <- dn[[1L]]
for (i in 2L:length(d)) if (is.null(dn[[i]]))
dn[[i]] <- seq_len(d[i])
colnames(x) <- interaction(expand.grid(dn[-1L]))
}
as.data.frame.matrix(x, row.names, optional, ...)
}
}
as.data.frame.table <- function (x, row.names = NULL, ..., responseName = "Freq", stringsAsFactors = TRUE,
sep = "", base = list(LETTERS))
{
ex <- quote(data.frame(do.call("expand.grid", c(dimnames(provideDimnames(x,
sep = sep, base = base)), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = stringsAsFactors)),
Freq = c(x), row.names = row.names))
names(ex)[3L] <- responseName
eval(ex)
}
as.function.default <- function (x, envir = parent.frame(), ...)
if (is.function(x)) x else .Internal(as.function.default(x, envir))
as.list.environment <- function (x, all.names = FALSE, ...)
.Internal(env2list(x, all.names))
closeAllConnections <- function ()
{
i <- sink.number(type = "message")
if (i > 0L)
sink(stderr(), type = "message")
n <- sink.number()
if (n > 0L)
for (i in seq_len(n)) sink()
set <- getAllConnections()
set <- set[set > 2L]
for (i in seq_along(set)) close(getConnection(set[i]))
invisible()
}
dimnames.data.frame <- function (x)
list(row.names(x), names(x))
environmentIsLocked <- function (env)
.Internal(environmentIsLocked(env))
getNamespaceExports <- function (ns)
{
ns <- asNamespace(ns)
if (isBaseNamespace(ns))
ls(.BaseNamespaceEnv, all.names = TRUE)
else ls(getNamespaceInfo(ns, "exports"), all.names = TRUE)
}
getNamespaceImports <- function (ns)
{
ns <- asNamespace(ns)
if (isBaseNamespace(ns))
NULL
else getNamespaceInfo(ns, "imports")
}
getNamespaceVersion <- function (ns)
{
ns <- asNamespace(ns)
if (isBaseNamespace(ns))
c(version = paste(R.version$major, R.version$minor, sep = "."))
else getNamespaceInfo(ns, "spec")["version"]
}
## @type withRegistrationInfo : logical
## @type name : character
## @type unlist : complex|logical|character
getNativeSymbolInfo <- function (name, PACKAGE, unlist = TRUE, withRegistrationInfo = FALSE)
{
if (missing(PACKAGE))
PACKAGE <- ""
if (is.character(PACKAGE))
pkgName <- PACKAGE
else if (inherits(PACKAGE, "DLLInfo")) {
pkgName <- PACKAGE[["path"]]
PACKAGE <- PACKAGE[["info"]]
}
else if (inherits(PACKAGE, "DLLInfoReference")) {
pkgName <- character()
}
else stop(gettextf("must pass a package name, %s or %s object",
dQuote("DLLInfo"), dQuote("DllInfoReference")), domain = NA)
syms <- lapply(name, function(id) {
v <- .Internal(getSymbolInfo(as.character(id), PACKAGE,
as.logical(withRegistrationInfo)))
if (is.null(v)) {
msg <- paste("no such symbol", id)
if (length(pkgName) && nzchar(pkgName))
msg <- paste(msg, "in package", pkgName)
stop(msg, domain = NA)
}
names(v) <- c("name", "address", "package", "numParameters")[seq_along(v)]
v
})
if (length(name) == 1L && unlist)
syms <- syms[[1L]]
else names(syms) <- name
syms
}
is.numeric.difftime <- function (x)
FALSE
## @optional packages, generics
namespaceImportFrom <- function (self, ns, vars, generics, packages, from = "non-package environment")
{
addImports <- function(ns, from, what) {
imp <- structure(list(what), names = getNamespaceName(from))
imports <- getNamespaceImports(ns)
setNamespaceInfo(ns, "imports", c(imports, imp))
}
namespaceIsSealed <- function(ns) environmentIsLocked(ns)
makeImportExportNames <- function(spec) {
old <- as.character(spec)
new <- names(spec)
if (is.null(new))
new <- old
else {
change <- !nzchar(new)
new[change] <- old[change]
}
names(old) <- new
old
}
whichMethodMetaNames <- function(impvars) {
if (!.isMethodsDispatchOn())
return(numeric())
mm <- ".__T__"
seq_along(impvars)[substr(impvars, 1L, nchar(mm, type = "c")) ==
mm]
}
genericPackage <- function(f) {
if (methods::is(f, "genericFunction"))
f@package
else if (is.primitive(f))
"base"
else "<unknown>"
}
if (is.character(self))
self <- getNamespace(self)
ns <- asNamespace(ns)
nsname <- getNamespaceName(ns)
impvars <- if (missing(vars)) {
stoplist <- c(".__NAMESPACE__.", ".__S3MethodsTable__.",
".packageName", ".First.lib", ".Last.lib", ".onLoad",
".onAttach", ".onDetach", ".conflicts.OK", ".noGenerics")
vars <- getNamespaceExports(ns)
vars <- vars[!vars %in% stoplist]
}
else vars
impvars <- makeImportExportNames(impvars)
impnames <- names(impvars)
if (anyDuplicated(impnames)) {
stop(gettextf("duplicate import names %s", paste(sQuote(impnames[duplicated(impnames)]),
collapse = ", ")), domain = NA)
}
if (isNamespace(self) && isBaseNamespace(self)) {
impenv <- self
msg <- gettext("replacing local value with import %s when loading %s")
register <- FALSE
}
else if (isNamespace(self)) {
if (namespaceIsSealed(self))
stop("cannot import into a sealed namespace")
impenv <- parent.env(self)
msg <- gettext("replacing previous import by %s when loading %s")
register <- TRUE
}
else if (is.environment(self)) {
impenv <- self
msg <- gettext("replacing local value with import %s when loading %s")
register <- FALSE
}
else stop("invalid import target")
which <- whichMethodMetaNames(impvars)
if (length(which)) {
delete <- integer()
for (i in which) {
methodsTable <- .mergeImportMethods(impenv, ns, impvars[[i]])
if (is.null(methodsTable)) {
}
else {
delete <- c(delete, i)
if (!missing(generics)) {
genName <- generics[[i]]
fdef <- methods:::getGeneric(genName, where = impenv,
package = packages[[i]])
if (is.null(fdef))
warning(gettextf("found methods to import for function %s but not the generic itself",
sQuote(genName)), call. = FALSE, domain = NA)
else methods:::.updateMethodsInTable(fdef,
ns, TRUE)
}
}
}
if (length(delete)) {
impvars <- impvars[-delete]
impnames <- impnames[-delete]
}
}
for (n in impnames) if (exists(n, envir = impenv, inherits = FALSE)) {
if (.isMethodsDispatchOn() && methods:::isGeneric(n,
ns)) {
genNs <- genericPackage(get(n, envir = ns))
genImp <- get(n, envir = impenv)
if (identical(genNs, genericPackage(genImp)))
next
genImpenv <- environmentName(environment(genImp))
if (!identical(genNs, genImpenv) || methods:::isGeneric(n,
impenv)) {
}
else next
}
warning(sprintf(msg, sQuote(paste(nsname, n, sep = "::")),
sQuote(from)), call. = FALSE, domain = NA)
}
importIntoEnv(impenv, impnames, ns, impvars)
if (register)
addImports(self, ns, if (missing(vars))
TRUE
else impvars)
}
Ops.numeric_version <- function (e1, e2)
{
if (nargs() == 1L)
stop(gettextf("unary '%s' not defined for \"numeric_version\" objects",
.Generic), domain = NA)
boolean <- switch(.Generic, `<` = , `>` = , `==` = , `!=` = ,
`<=` = , `>=` = TRUE, FALSE)
if (!boolean)
stop(gettextf("'%s' not defined for \"numeric_version\" objects",
.Generic), domain = NA)
if (!is.numeric_version(e1))
e1 <- as.numeric_version(e1)
if (!is.numeric_version(e2))
e2 <- as.numeric_version(e2)
base <- max(unlist(e1), unlist(e2), 0) + 1
e1 <- .encode_numeric_version(e1, base = base)
e2 <- .encode_numeric_version(e2, base = base)
NextMethod(.Generic)
}
## @type package : character
## @type package.lib : character
packageHasNamespace <- function (package, package.lib)
{
namespaceFilePath <- function(package, package.lib) file.path(package.lib,
package, "NAMESPACE")
file.exists(namespaceFilePath(package, package.lib))
}
print.summary.table <- function (x, digits = max(1L, getOption("digits") - 3L), ...)
{
if (!inherits(x, "summary.table"))
stop(gettextf("'x' must inherit from class %s", dQuote("summary.table")),
domain = NA)
if (!is.null(x$call)) {
cat("Call: ")
print(x$call)
}
cat("Number of cases in table:", x$n.cases, "\n")
cat("Number of factors:", x$n.vars, "\n")
if (x$n.vars > 1) {
cat("Test for independence of all factors:\n")
ch <- x$statistic
cat("\tChisq = ", format(round(ch, max(0, digits - log10(ch)))),
", df = ", x$parameter, ", p-value = ", format.pval(x$p.value,
digits, eps = 0), "\n", sep = "")
if (!x$approx.ok)
cat("\tChi-squared approximation may be incorrect\n")
}
invisible(x)
}
## @type x : numeric|character
rep.numeric_version <- function (x, ...)
structure(NextMethod("rep"), class = oldClass(x))
## @type value : complex|character
"row.names<-.default" <- function (x, value)
`rownames<-`(x, value)
setSessionTimeLimit <- function (cpu = Inf, elapsed = Inf)
.Internal(setSessionTimeLimit(cpu, elapsed))
## @type verbose : logical
## @type registered : logical
## @return logical
taskCallbackManager <- function (handlers = list(), registered = FALSE, verbose = FALSE)
{
suspended <- FALSE
.verbose <- verbose
add <- function(f, data = NULL, name = NULL, register = TRUE) {
if (is.null(name))
name <- as.character(length(handlers) + 1L)
handlers[[name]] <<- list(f = f)
if (!missing(data))
handlers[[name]][["data"]] <<- data
if (!registered && register) {
register()
}
name
}
remove <- function(which) {
if (is.character(which)) {
tmp <- seq_along(handlers)[!is.na(match(which, names(handlers)))]
if (length(tmp))
stop(gettextf("no such element '%s'", which),
domain = NA)
which <- tmp
}
else which <- as.integer(which)
handlers <<- handlers[-which]
return(TRUE)
}
evaluate <- function(expr, value, ok, visible) {
if (suspended)
return(TRUE)
discard <- character()
for (i in names(handlers)) {
h <- handlers[[i]]
if (length(h) > 1L) {
val <- h[["f"]](expr, value, ok, visible, i[["data"]])
}
else {
val <- h[["f"]](expr, value, ok, visible)
}
if (!val) {
discard <- c(discard, i)
}
}
if (length(discard)) {
if (.verbose)
cat(gettextf("Removing %s", paste(discard, collapse = ", ")),
"\n")
idx <- is.na(match(names(handlers), discard))
if (length(idx))
handlers <<- handlers[idx]
else handlers <<- list()
}
return(TRUE)
}
suspend <- function(status = TRUE) {
suspended <<- status
}
register <- function(name = "R-taskCallbackManager", verbose = .verbose) {
if (verbose)
cat(gettext("Registering 'evaluate' as low-level callback\n"))
id <- addTaskCallback(evaluate, name = name)
registered <<- TRUE
id
}
list(add = add, evaluate = evaluate, remove = remove, register = register,
suspend = suspend, callbacks = function() handlers)
}
textConnectionValue <- function (con)
.Internal(textConnectionValue(con))
truncate.connection <- function (con, ...)
{
if (!isOpen(con))
stop("can only truncate an open connection")
.Internal(truncate(con))
}
withCallingHandlers <- function (expr, ...)
{
handlers <- list(...)
classes <- names(handlers)
parentenv <- parent.frame()
if (length(classes) != length(handlers))
stop("bad handler specification")
.Internal(.addCondHands(classes, handlers, parentenv, NULL,
TRUE))
expr
}
## @type x : numeric|character
"[[<-.numeric_version" <- function (x, ..., value)
{
z <- unclass(x)
if (nargs() < 4L) {
if (length(..1) < 2L) {
if (is.character(value) && length(value) == 1L)
value <- unclass(as.numeric_version(value))[[1L]]
else if (!is.integer(value))
stop("invalid 'value'")
}
else {
value <- as.integer(value)
if (length(value) != 1L)
stop("invalid 'value'")
}
z[[..1]] <- value
}
else {
value <- as.integer(value)
if (length(value) != 1L)
stop("invalid 'value'")
z[[..1]][..2] <- value
}
structure(z, class = oldClass(x))
}
## @type fromLast : logical
anyDuplicated.matrix <- function (x, incomparables = FALSE, MARGIN = 1L, fromLast = FALSE,
...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
dx <- dim(x)
ndim <- length(dx)
if (length(MARGIN) > ndim || any(MARGIN > ndim))
stop(gettextf("MARGIN = %d is invalid for dim = %d",
MARGIN, dx), domain = NA)
collapse <- (ndim > 1L) && (prod(dx[-MARGIN]) > 1L)
temp <- if (collapse)
apply(x, MARGIN, function(x) paste(x, collapse = "\r"))
else x
anyDuplicated.default(temp, fromLast = fromLast)
}
as.character.default <- function (x, ...)
.Internal(as.vector(x, "character"))
as.character.hexmode <- function (x, ...)
format.hexmode(x, ...)
as.character.octmode <- function (x, ...)
format.octmode(x, ...)
## @type optional : logical
## @type row.names : character
as.data.frame.factor <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type row.names : character
## @type optional : logical
## @type stringsAsFactors : logical|character
as.data.frame.matrix <- function (x, row.names = NULL, optional = FALSE, ..., stringsAsFactors = default.stringsAsFactors())
{
d <- dim(x)
nrows <- d[1L]
ir <- seq_len(nrows)
ncols <- d[2L]
ic <- seq_len(ncols)
dn <- dimnames(x)
if (is.null(row.names))
row.names <- dn[[1L]]
collabs <- dn[[2L]]
if (any(empty <- !nzchar(collabs)))
collabs[empty] <- paste0("V", ic)[empty]
value <- vector("list", ncols)
if (mode(x) == "character" && stringsAsFactors) {
for (i in ic) value[[i]] <- as.factor(x[, i])
}
else {
for (i in ic) value[[i]] <- as.vector(x[, i])
}
if (is.null(row.names) || length(row.names) != nrows)
row.names <- .set_row_names(nrows)
if (length(collabs) == ncols)
names(value) <- collabs
else if (!optional)
names(value) <- paste0("V", ic)
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type row.names : character
## @type optional : logical
as.data.frame.vector <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type rownames.force : logical|character
as.matrix.data.frame <- function (x, rownames.force = NA, ...)
{
dm <- dim(x)
rn <- if (rownames.force %in% FALSE)
NULL
else if (rownames.force %in% TRUE)
row.names(x)
else {
if (.row_names_info(x) <= 0L)
NULL
else row.names(x)
}
dn <- list(rn, names(x))
if (any(dm == 0L))
return(array(NA, dim = dm, dimnames = dn))
p <- dm[2L]
pseq <- seq_len(p)
n <- dm[1L]
X <- x
class(X) <- NULL
non.numeric <- non.atomic <- FALSE
all.logical <- TRUE
for (j in pseq) {
if (inherits(X[[j]], "data.frame") && ncol(xj) > 1L)
X[[j]] <- as.matrix(X[[j]])
xj <- X[[j]]
j.logic <- is.logical(xj)
if (all.logical && !j.logic)
all.logical <- FALSE
if (length(levels(xj)) > 0L || !(j.logic || is.numeric(xj) ||
is.complex(xj)) || (!is.null(cl <- attr(xj, "class")) &&
any(cl %in% c("Date", "POSIXct", "POSIXlt"))))
non.numeric <- TRUE
if (!is.atomic(xj))
non.atomic <- TRUE
}
if (non.atomic) {
for (j in pseq) {
xj <- X[[j]]
if (!is.recursive(xj))
X[[j]] <- as.list(as.vector(xj))
}
}
else if (all.logical) {
}
else if (non.numeric) {
for (j in pseq) {
if (is.character(X[[j]]))
next
xj <- X[[j]]
miss <- is.na(xj)
xj <- if (length(levels(xj)))
as.vector(xj)
else format(xj)
is.na(xj) <- miss
X[[j]] <- xj
}
}
collabs <- as.list(dn[[2L]])
for (j in pseq) {
xj <- X[[j]]
dj <- dim(xj)
if (length(dj) == 2L && dj[2L] > 1L) {
dnj <- colnames(xj)
collabs[[j]] <- paste(collabs[[j]], if (length(dnj))
dnj
else seq_len(dj[2L]), sep = ".")
}
}
X <- unlist(X, recursive = FALSE, use.names = FALSE)
dim(X) <- c(n, length(X)/n)
dimnames(X) <- list(dn[[1L]], unlist(collabs, use.names = FALSE))
X
}
as.POSIXlt.character <- function (x, tz = "", format, ...)
{
x <- unclass(x)
if (!missing(format)) {
res <- strptime(x, format, tz = tz)
if (nzchar(tz))
attr(res, "tzone") <- tz
return(res)
}
xx <- x[!is.na(x)]
if (!length(xx)) {
res <- strptime(x, "%Y/%m/%d")
if (nzchar(tz))
attr(res, "tzone") <- tz
return(res)
}
else if (all(!is.na(strptime(xx, f <- "%Y-%m-%d %H:%M:%OS",
tz = tz))) || all(!is.na(strptime(xx, f <- "%Y/%m/%d %H:%M:%OS",
tz = tz))) || all(!is.na(strptime(xx, f <- "%Y-%m-%d %H:%M",
tz = tz))) || all(!is.na(strptime(xx, f <- "%Y/%m/%d %H:%M",
tz = tz))) || all(!is.na(strptime(xx, f <- "%Y-%m-%d",
tz = tz))) || all(!is.na(strptime(xx, f <- "%Y/%m/%d",
tz = tz)))) {
res <- strptime(x, f, tz = tz)
if (nzchar(tz))
attr(res, "tzone") <- tz
return(res)
}
stop("character string is not in a standard unambiguous format")
}
getTaskCallbackNames <- function ()
.Call(.C_R_getTaskCallbackNames)
library.dynam.unload <- function (chname, libpath, verbose = getOption("verbose"), file.ext = .Platform$dynlib.ext)
{
dll_list <- .dynLibs()
if (missing(chname) || (nc_chname <- nchar(chname, "c")) ==
0L)
if (.Platform$OS.type == "windows")
stop("no DLL was specified")
else stop("no shared object was specified")
libpath <- normalizePath(libpath, "/", TRUE)
chname1 <- paste0(chname, file.ext)
file <- if (nzchar(.Platform$r_arch))
file.path(libpath, "libs", .Platform$r_arch, chname1)
else file.path(libpath, "libs", chname1)
pos <- which(vapply(dll_list, function(x) x[["path"]] ==
file, NA))
if (!length(pos))
if (.Platform$OS.type == "windows")
stop(gettextf("DLL %s was not loaded", sQuote(chname1)),
domain = NA)
else stop(gettextf("shared object %s was not loaded",
sQuote(chname1)), domain = NA)
if (!file.exists(file))
if (.Platform$OS.type == "windows")
stop(gettextf("DLL %s not found", sQuote(chname1)),
domain = NA)
else stop(gettextf("shared object '%s' not found", sQuote(chname1)),
domain = NA)
if (verbose)
message(gettextf("now dyn.unload(\"%s\") ...", file),
domain = NA)
dyn.unload(file)
.dynLibs(dll_list[-pos])
invisible(dll_list[[pos]])
}
loadingNamespaceInfo <- function ()
{
dynGet <- function(name, notFound = stop(gettextf("%s not found",
sQuote(name)), domain = NA)) {
n <- sys.nframe()
while (n > 1) {
n <- n - 1
env <- sys.frame(n)
if (exists(name, envir = env, inherits = FALSE))
return(get(name, envir = env, inherits = FALSE))
}
notFound
}
dynGet("__LoadingNamespaceInfo__", stop("not loading a namespace"))
}
print.summaryDefault <- function (x, ...)
{
xx <- if (is.numeric(x) || is.complex(x))
zapsmall(x)
else x
class(xx) <- class(x)[-1]
m <- match("NA's", names(xx), 0)
if (inherits(x, "Date") || inherits(x, "POSIXct")) {
xx <- if (length(a <- attr(x, "NAs")))
c(format(xx), `NA's` = as.character(a))
else format(xx)
print(xx, ...)
return(invisible(x))
}
else if (m && !is.character(x))
xx <- c(format(xx[-m]), `NA's` = as.character(xx[m]))
print.table(xx, ...)
invisible(x)
}
row.names.data.frame <- function (x)
as.character(attr(x, "row.names"))
transform.data.frame <- function (`_data`, ...)
{
e <- eval(substitute(list(...)), `_data`, parent.frame())
tags <- names(e)
inx <- match(tags, names(`_data`))
matched <- !is.na(inx)
if (any(matched)) {
`_data`[inx[matched]] <- e[matched]
`_data` <- data.frame(`_data`)
}
if (!all(matched))
do.call("data.frame", c(list(`_data`), e[!matched]))
else `_data`
}
## @type fromLast : logical
anyDuplicated.default <- function (x, incomparables = FALSE, fromLast = FALSE, ...)
.Internal(anyDuplicated(x, incomparables, fromLast))
## @type x : numeric|character
anyNA.numeric_version <- function (x)
anyNA(.encode_numeric_version(x))
## @type optional : logical
## @type row.names : character
as.data.frame.complex <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
as.data.frame.default <- function (x, ...)
stop(gettextf("cannot coerce class \"%s\" to a data.frame", deparse(class(x))),
domain = NA)
## @type row.names : character
## @type optional : logical
as.data.frame.integer <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type optional : logical
## @type row.names : character
as.data.frame.logical <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type row.names : character
## @type optional : logical
as.data.frame.numeric <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type optional : logical
## @type row.names : character
as.data.frame.ordered <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
as.data.frame.POSIXct <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
as.data.frame.POSIXlt <- function (x, row.names = NULL, optional = FALSE, ...)
{
value <- as.data.frame.POSIXct(as.POSIXct(x), row.names,
optional, ...)
if (!optional)
names(value) <- deparse(substitute(x))[[1L]]
value
}
as.expression.default <- function (x, ...)
.Internal(as.vector(x, "expression"))
"dimnames<-.data.frame" <- function (x, value)
{
d <- dim(x)
if (!is.list(value) || length(value) != 2L)
stop("invalid 'dimnames' given for data frame")
value[[1L]] <- as.character(value[[1L]])
value[[2L]] <- as.character(value[[2L]])
if (d[[1L]] != length(value[[1L]]) || d[[2L]] != length(value[[2L]]))
stop("invalid 'dimnames' given for data frame")
row.names(x) <- value[[1L]]
names(x) <- value[[2L]]
x
}
droplevels.data.frame <- function (x, except = NULL, ...)
{
ix <- vapply(x, is.factor, NA)
if (!is.null(except))
ix[except] <- FALSE
x[ix] <- lapply(x[ix], factor)
x
}
## @type fromLast : logical
duplicated.data.frame <- function (x, incomparables = FALSE, fromLast = FALSE, ...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
if (length(x) != 1L)
duplicated(do.call("paste", c(x, sep = "\r")), fromLast = fromLast)
else duplicated(x[[1L]], fromLast = fromLast, ...)
}
format.summaryDefault <- function (x, ...)
{
xx <- if (is.numeric(x) || is.complex(x))
zapsmall(x)
else x
class(xx) <- class(x)[-1]
m <- match("NA's", names(x), 0)
if (inherits(x, "Date") || inherits(x, "POSIXct")) {
if (length(a <- attr(x, "NAs")))
c(format(xx, ...), `NA's` = as.character(a))
else format(xx)
}
else if (m && !is.character(x))
xx <- c(format(xx[-m], ...), `NA's` = as.character(xx[m]))
else format(xx, ...)
}
## @type x : numeric|character
is.na.numeric_version <- function (x)
is.na(.encode_numeric_version(x))
## @type appendLF : logical|character
packageStartupMessage <- function (..., domain = NULL, appendLF = TRUE)
{
call <- sys.call()
msg <- .makeMessage(..., domain = domain, appendLF = appendLF)
message(.packageStartupMessage(msg, call))
}
## @type x : numeric|character
print.numeric_version <- function (x, ...)
{
y <- as.character(x)
if (!length(y))
writeLines(gettext("<0 elements>"))
else print(noquote(ifelse(is.na(y), NA_character_, sQuote(y))),
...)
invisible(x)
}
## @type x : numeric|character
xtfrm.numeric_version <- function (x)
.encode_numeric_version(x)
as.character.condition <- function (x, ...)
{
msg <- conditionMessage(x)
call <- conditionCall(x)
cl <- class(x)[1L]
if (!is.null(call))
paste0(cl, " in ", deparse(call)[1L], ": ", msg, "\n")
else paste0(cl, ": ", msg, "\n")
}
## @type row.names : character
## @type optional : logical
as.data.frame.difftime <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
## @type x : numeric|character
format.numeric_version <- function (x, ...)
{
x <- unclass(x)
y <- rep.int(NA_character_, length(x))
names(y) <- names(x)
ind <- vapply(x, length, 1L) > 0L
y[ind] <- unlist(lapply(x[ind], paste, collapse = "."))
y
}
namespaceImportClasses <- function (self, ns, vars, from = NULL)
{
for (i in seq_along(vars)) vars[[i]] <- methods:::classMetaName(vars[[i]])
namespaceImportFrom(self, asNamespace(ns), vars, from = from)
}
namespaceImportMethods <- function (self, ns, vars, from = NULL)
{
allVars <- character()
generics <- character()
packages <- character()
allFuns <- methods:::.getGenerics(ns)
allPackages <- attr(allFuns, "package")
pkg <- methods:::getPackageName(ns)
if (!all(vars %in% allFuns)) {
message(gettextf("No methods found in \"%s\" for requests: %s",
pkg, paste(vars[is.na(match(vars, allFuns))], collapse = ", ")),
domain = NA)
vars <- vars[vars %in% allFuns]
}
tPrefix <- methods:::.TableMetaPrefix()
allMethodTables <- methods:::.getGenerics(ns, tPrefix)
if (any(is.na(match(vars, allFuns))))
stop(gettextf("requested methods not found in environment/package %s: %s",
sQuote(pkg), paste(vars[is.na(match(vars, allFuns))],
collapse = ", ")), call. = FALSE, domain = NA)
for (i in seq_along(allFuns)) {
g <- allFuns[[i]]
p <- allPackages[[i]]
if (exists(g, envir = self, inherits = FALSE) || g %in%
vars) {
tbl <- methods:::.TableMetaName(g, p)
if (is.null(.mergeImportMethods(self, ns, tbl))) {
allVars <- c(allVars, tbl)
generics <- c(generics, g)
packages <- c(packages, p)
}
}
if (g %in% vars && !exists(g, envir = self, inherits = FALSE)) {
if (exists(g, envir = ns) && methods:::is(get(g,
envir = ns), "genericFunction")) {
allVars <- c(allVars, g)
generics <- c(generics, g)
packages <- c(packages, p)
}
else {
fun <- methods::getFunction(g, mustFind = FALSE,
where = self)
if (is.primitive(fun) || methods::is(fun, "genericFunction")) {
}
else warning(gettextf("No generic function found corresponding to requested imported methods for \"%s\" from package \"%s\" (malformed exports?)",
g, pkg), domain = NA)
}
}
}
namespaceImportFrom(self, asNamespace(ns), allVars, generics,
packages, from = from)
}
## @type value : complex|character
"row.names<-.data.frame" <- function (x, value)
{
if (!is.data.frame(x))
x <- as.data.frame(x)
n <- .row_names_info(x, 2L)
if (is.null(value)) {
attr(x, "row.names") <- .set_row_names(n)
return(x)
}
if (is.object(value) || !is.integer(value))
value <- as.character(value)
if (n == 0L) {
if (!is.null(attr(x, "row.names")) && length(value) >
0L)
stop("invalid 'row.names' length")
}
else if (length(value) != n)
stop("invalid 'row.names' length")
if (anyDuplicated(value)) {
nonuniq <- sort(unique(value[duplicated(value)]))
warning(ngettext(length(nonuniq), sprintf("non-unique value when setting 'row.names': %s",
sQuote(nonuniq[1L])), sprintf("non-unique values when setting 'row.names': %s",
paste(sQuote(nonuniq), collapse = ", "))), domain = NA,
call. = FALSE)
stop("duplicate 'row.names' are not allowed")
}
if (anyNA(value))
stop("missing values in 'row.names' are not allowed")
attr(x, "row.names") <- value
x
}
## @type x : numeric|character
unique.numeric_version <- function (x, incomparables = FALSE, ...)
x[!duplicated(x, incomparables, ...)]
## @type stringsAsFactors : logical|character
as.data.frame.character <- function (x, ..., stringsAsFactors = default.stringsAsFactors())
{
nm <- deparse(substitute(x), width.cutoff = 500L)
if (stringsAsFactors)
x <- factor(x)
if (!"nm" %in% names(list(...)))
as.data.frame.vector(x, ..., nm = nm)
else as.data.frame.vector(x, ...)
}
## @type x : numeric|character
as.list.numeric_version <- function (x, ...)
{
nms <- names(x)
names(x) <- NULL
y <- lapply(seq_along(x), function(i) x[i])
names(y) <- nms
y
}
conditionCall.condition <- function (c)
c$call
print.NativeRoutineList <- function (x, ...)
{
m <- data.frame(numParameters = sapply(x, function(x) x$numParameters),
row.names = sapply(x, function(x) x$name))
print(m, ...)
invisible(x)
}
Summary.numeric_version <- function (..., na.rm)
{
ok <- switch(.Generic, max = , min = , range = TRUE, FALSE)
if (!ok)
stop(gettextf("%s not defined for \"numeric_version\" objects",
.Generic), domain = NA)
x <- do.call("c", lapply(list(...), as.numeric_version))
v <- .encode_numeric_version(x)
if (!na.rm && length(pos <- which(is.na(v)))) {
y <- x[pos[1L]]
if (as.character(.Generic) == "range")
c(y, y)
else y
}
else switch(.Generic, max = x[which.max(v)], min = x[which.min(v)],
range = x[c(which.min(v), which.max(v))])
}
testPlatformEquivalence <- function (built, run)
{
built <- gsub("([^-]*)-([^-]*)-(.*)", "\\1-\\3", built)
run <- gsub("([^-]*)-([^-]*)-(.*)", "\\1-\\3", run)
if (length(grep("^universal-darwin", built)) && nzchar(.Platform$r_arch))
built <- sub("^universal", R.version$arch, built)
length(agrep(built, run)) > 0
}
## @type fromLast : logical
anyDuplicated.data.frame <- function (x, incomparables = FALSE, fromLast = FALSE, ...)
{
if (!identical(incomparables, FALSE))
.NotYetUsed("incomparables != FALSE")
anyDuplicated(do.call("paste", c(x, sep = "\r")), fromLast = fromLast)
}
## @type row.names : character
as.data.frame.data.frame <- function (x, row.names = NULL, ...)
{
cl <- oldClass(x)
i <- match("data.frame", cl)
if (i > 1L)
class(x) <- cl[-(1L:(i - 1L))]
if (!is.null(row.names)) {
nr <- .row_names_info(x, 2L)
if (length(row.names) == nr)
attr(x, "row.names") <- row.names
else stop(sprintf(ngettext(nr, "invalid 'row.names', length %d for a data frame with %d row",
"invalid 'row.names', length %d for a data frame with %d rows"),
length(row.names), nr), domain = NA)
}
x
}
default.stringsAsFactors <- function ()
{
val <- getOption("stringsAsFactors")
if (is.null(val))
val <- TRUE
if (!is.logical(val) || is.na(val) || length(val) != 1L)
stop("options(\"stringsAsFactors\") not set to TRUE or FALSE")
val
}
## @type dll : character
## @type addNames : raw|logical|character
getDLLRegisteredRoutines <- function (dll, addNames = TRUE)
UseMethod("getDLLRegisteredRoutines")
## @type row.names : character
## @type optional : logical
as.data.frame.model.matrix <- function (x, row.names = NULL, optional = FALSE, ...)
{
d <- dim(x)
nrows <- d[1L]
dn <- dimnames(x)
row.names <- dn[[1L]]
value <- list(x)
if (!is.null(row.names)) {
row.names <- as.character(row.names)
if (length(row.names) != nrows)
stop(sprintf(ngettext(length(row.names), "supplied %d row name for %d rows",
"supplied %d row names for %d rows"), length(row.names),
nrows), domain = NA)
}
else row.names <- .set_row_names(nrows)
if (!optional)
names(value) <- deparse(substitute(x))[[1L]]
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
conditionMessage.condition <- function (c)
c$message
## @type x : numeric|character
duplicated.numeric_version <- function (x, incomparables = FALSE, ...)
{
x <- .encode_numeric_version(x)
NextMethod("duplicated")
}
invokeRestartInteractively <- function (r)
{
if (!interactive())
stop("not an interactive session")
if (!isRestart(r)) {
res <- findRestart(r)
if (is.null(res))
stop(gettextf("no 'restart' '%s' found", as.character(r)),
domain = NA)
r <- res
}
if (is.null(r$interactive)) {
pars <- names(restartFormals(r))
args <- NULL
if (length(pars)) {
cat("Enter values for restart arguments:\n\n")
for (p in pars) {
if (p == "...") {
prompt <- "... (a list): "
args <- c(args, eval(parse(prompt = prompt)))
}
else {
prompt <- paste0(p, ": ")
args <- c(args, list(eval(parse(prompt = prompt))))
}
}
}
}
else args <- r$interactive()
.Internal(.invokeRestart(r, args))
}
print.DLLRegisteredRoutines <- function (x, ...)
{
n <- vapply(x, length, 1L)
x <- x[n > 0]
n <- max(n)
d <- list()
sapply(names(x), function(id) {
d[[id]] <<- rep.int("", n)
names <- vapply(x[[id]], function(x) x$name, "")
if (length(names))
d[[id]][seq_along(names)] <<- names
d[[paste(id, "numParameters")]] <<- rep.int("", n)
names <- sapply(x[[id]], function(x) x$numParameters)
if (length(names))
d[[paste(id, "numParameters")]][seq_along(names)] <<- names
})
print(as.data.frame(d), ...)
invisible(x)
}
## @type x : numeric|character
as.character.numeric_version <- function (x, ...)
as.character(format(x))
## @type x : numeric|character
as.data.frame.numeric_version <- function (x, row.names = NULL, optional = FALSE, ..., nm = paste(deparse(substitute(x),
width.cutoff = 500L), collapse = " "))
{
force(nm)
nrows <- length(x)
if (is.null(row.names)) {
if (nrows == 0L)
row.names <- character()
else if (length(row.names <- names(x)) == nrows && !anyDuplicated(row.names)) {
}
else row.names <- .set_row_names(nrows)
}
if (!is.null(names(x)))
names(x) <- NULL
value <- list(x)
if (!optional)
names(value) <- nm
attr(value, "row.names") <- row.names
class(value) <- "data.frame"
value
}
suppressPackageStartupMessages <- function (expr)
withCallingHandlers(expr, packageStartupMessage = function(c) invokeRestart("muffleMessage"))
## @type addNames : raw|logical|character
## @type dll : character
getDLLRegisteredRoutines.DLLInfo <- function (dll, addNames = TRUE)
{
if (!inherits(dll, "DLLInfo"))
stop(gettextf("must specify DLL via a %s object. See getLoadedDLLs()",
dQuote("DLLInfo")), domain = NA)
info <- dll[["info"]]
els <- .Internal(getRegisteredRoutines(info))
if (addNames) {
els <- lapply(els, function(x) {
if (length(x))
names(x) <- vapply(x, function(z) z$name, "")
x
})
}
class(els) <- "DLLRegisteredRoutines"
els
}
## @type dll : character
## @type addNames : raw|logical|character
getDLLRegisteredRoutines.character <- function (dll, addNames = TRUE)
{
dlls <- getLoadedDLLs()
w <- vapply(dlls, function(x) x[["name"]] == dll || x[["path"]] ==
dll, NA)
if (!any(w))
stop(gettextf("No DLL currently loaded with name or path %s",
sQuote(dll)), domain = NA)
dll <- which.max(w)
if (sum(w) > 1L)
warning(gettextf("multiple DLLs match '%s'. Using '%s'",
dll, dll[["path"]]), domain = NA)
getDLLRegisteredRoutines(dlls[[dll]], addNames)
} |
lemma replace_1: assumes "j < n" "a \<in> s" and p: "\<forall>x\<in>s - {a}. x j = p" and "x \<in> s" shows "a \<le> x" |
/-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Anne Baanen
! This file was ported from Lean 3 source module order.hom.order
! leanprover-community/mathlib commit ba2245edf0c8bb155f1569fd9b9492a9b384cde6
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Logic.Function.Iterate
import Mathlib.Order.GaloisConnection
import Mathlib.Order.Hom.Basic
/-!
# Lattice structure on order homomorphisms
This file defines the lattice structure on order homomorphisms, which are bundled
monotone functions.
## Main definitions
* `OrderHom.CompleteLattice`: if `β` is a complete lattice, so is `α →o β`
## Tags
monotone map, bundled morphism
-/
namespace OrderHom
variable {α β : Type _}
section Preorder
variable [Preorder α]
instance [SemilatticeSup β] : Sup (α →o β) where
sup f g := ⟨fun a => f a ⊔ g a, f.mono.sup g.mono⟩
--Porting note: this is the lemma that could have been generated by `@[simps]` on the
--above instance but with a nicer name
@[simp] lemma coe_sup [SemilatticeSup β] (f g : α →o β) :
((f ⊔ g : α →o β) : α → β) = (f : α → β) ⊔ g := rfl
instance [SemilatticeSup β] : SemilatticeSup (α →o β) :=
{ (_ : PartialOrder (α →o β)) with
sup := Sup.sup
le_sup_left := fun _ _ _ => le_sup_left
le_sup_right := fun _ _ _ => le_sup_right
sup_le := fun _ _ _ h₀ h₁ x => sup_le (h₀ x) (h₁ x) }
instance [SemilatticeInf β] : Inf (α →o β) where
inf f g := ⟨fun a => f a ⊓ g a, f.mono.inf g.mono⟩
--Porting note: this is the lemma that could have been generated by `@[simps]` on the
--above instance but with a nicer name
@[simp] lemma coe_inf [SemilatticeInf β] (f g : α →o β) :
((f ⊓ g : α →o β) : α → β) = (f : α → β) ⊓ g := rfl
instance [SemilatticeInf β] : SemilatticeInf (α →o β) :=
{ (_ : PartialOrder (α →o β)), (dualIso α β).symm.toGaloisInsertion.liftSemilatticeInf with
inf := (· ⊓ ·) }
instance lattice [Lattice β] : Lattice (α →o β) :=
{ (_ : SemilatticeSup (α →o β)), (_ : SemilatticeInf (α →o β)) with }
@[simps]
instance [Preorder β] [OrderBot β] : Bot (α →o β) where
bot := const α ⊥
instance orderBot [Preorder β] [OrderBot β] : OrderBot (α →o β) where
bot := ⊥
bot_le _ _ := bot_le
@[simps]
instance [Preorder β] [OrderTop β] : Top (α →o β) where
top := const α ⊤
instance orderTop [Preorder β] [OrderTop β] : OrderTop (α →o β) where
top := ⊤
le_top _ _ := le_top
instance [CompleteLattice β] : InfSet (α →o β) where
infₛ s := ⟨fun x => ⨅ f ∈ s, (f : _) x, fun _ _ h => infᵢ₂_mono fun f _ => f.mono h⟩
@[simp]
theorem infₛ_apply [CompleteLattice β] (s : Set (α →o β)) (x : α) :
infₛ s x = ⨅ f ∈ s, (f : _) x :=
rfl
#align order_hom.Inf_apply OrderHom.infₛ_apply
theorem infᵢ_apply {ι : Sort _} [CompleteLattice β] (f : ι → α →o β) (x : α) :
(⨅ i, f i) x = ⨅ i, f i x :=
(infₛ_apply _ _).trans infᵢ_range
#align order_hom.infi_apply OrderHom.infᵢ_apply
@[simp, norm_cast]
theorem coe_infᵢ {ι : Sort _} [CompleteLattice β] (f : ι → α →o β) :
((⨅ i, f i : α →o β) : α → β) = ⨅ i, (f i : α → β) := by
funext x; simp [infᵢ_apply]
#align order_hom.coe_infi OrderHom.coe_infᵢ
instance [CompleteLattice β] : SupSet (α →o β) where
supₛ s := ⟨fun x => ⨆ f ∈ s, (f : _) x, fun _ _ h => supᵢ₂_mono fun f _ => f.mono h⟩
@[simp]
theorem supₛ_apply [CompleteLattice β] (s : Set (α →o β)) (x : α) :
supₛ s x = ⨆ f ∈ s, (f : _) x :=
rfl
#align order_hom.Sup_apply OrderHom.supₛ_apply
theorem supᵢ_apply {ι : Sort _} [CompleteLattice β] (f : ι → α →o β) (x : α) :
(⨆ i, f i) x = ⨆ i, f i x :=
(supₛ_apply _ _).trans supᵢ_range
#align order_hom.supr_apply OrderHom.supᵢ_apply
@[simp, norm_cast]
theorem coe_supᵢ {ι : Sort _} [CompleteLattice β] (f : ι → α →o β) :
((⨆ i, f i : α →o β) : α → β) = ⨆ i, (f i : α → β) := by
funext x; simp [supᵢ_apply]
#align order_hom.coe_supr OrderHom.coe_supᵢ
instance [CompleteLattice β] : CompleteLattice (α →o β) :=
{ (_ : Lattice (α →o β)), OrderHom.orderTop, OrderHom.orderBot with
-- supₛ := SupSet.supₛ -- Porting note: removed, unecessary?
-- Porting note: Added `by apply`, was `fun s f hf x => le_supᵢ_of_le f (le_supᵢ _ hf)`
le_supₛ := fun s f hf x => le_supᵢ_of_le f (by apply le_supᵢ _ hf)
supₛ_le := fun s f hf x => supᵢ₂_le fun g hg => hf g hg x
--inf := infₛ -- Porting note: removed, unecessary?
le_infₛ := fun s f hf x => le_infᵢ₂ fun g hg => hf g hg x
infₛ_le := fun s f hf x => infᵢ_le_of_le f (infᵢ_le _ hf)
}
theorem iterate_sup_le_sup_iff {α : Type _} [SemilatticeSup α] (f : α →o α) :
(∀ n₁ n₂ a₁ a₂, (f^[n₁ + n₂]) (a₁ ⊔ a₂) ≤ (f^[n₁]) a₁ ⊔ (f^[n₂]) a₂) ↔
∀ a₁ a₂, f (a₁ ⊔ a₂) ≤ f a₁ ⊔ a₂ := by
constructor <;> intro h
· exact h 1 0
· intro n₁ n₂ a₁ a₂
have h' : ∀ n a₁ a₂, (f^[n]) (a₁ ⊔ a₂) ≤ (f^[n]) a₁ ⊔ a₂ := by
intro n
induction' n with n ih <;> intro a₁ a₂
· rfl
· calc
(f^[n + 1]) (a₁ ⊔ a₂) = (f^[n]) (f (a₁ ⊔ a₂)) := Function.iterate_succ_apply f n _
_ ≤ (f^[n]) (f a₁ ⊔ a₂) := f.mono.iterate n (h a₁ a₂)
_ ≤ (f^[n]) (f a₁) ⊔ a₂ := ih _ _
_ = (f^[n + 1]) a₁ ⊔ a₂ := by rw [← Function.iterate_succ_apply]
calc
(f^[n₁ + n₂]) (a₁ ⊔ a₂) = (f^[n₁]) ((f^[n₂]) (a₁ ⊔ a₂)) :=
Function.iterate_add_apply f n₁ n₂ _
_ = (f^[n₁]) ((f^[n₂]) (a₂ ⊔ a₁)) := by rw [sup_comm]
_ ≤ (f^[n₁]) ((f^[n₂]) a₂ ⊔ a₁) := f.mono.iterate n₁ (h' n₂ _ _)
_ = (f^[n₁]) (a₁ ⊔ (f^[n₂]) a₂) := by rw [sup_comm]
_ ≤ (f^[n₁]) a₁ ⊔ (f^[n₂]) a₂ := h' n₁ a₁ _
#align order_hom.iterate_sup_le_sup_iff OrderHom.iterate_sup_le_sup_iff
end Preorder
end OrderHom
|
proposition homotopic_paths_rinv: assumes "path p" "path_image p \<subseteq> s" shows "homotopic_paths s (p +++ reversepath p) (linepath (pathstart p) (pathstart p))" |
[STATEMENT]
lemma crel_vs_fun_app:
"\<lbrakk>Transfer.Rel (crel_vs R0) x x\<^sub>T; Transfer.Rel (crel_vs (R0 ===>\<^sub>T R1)) f f\<^sub>T\<rbrakk> \<Longrightarrow> Transfer.Rel (crel_vs R1) (App f x) (f\<^sub>T . x\<^sub>T)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>Rel (crel_vs R0) x x\<^sub>T; Rel (crel_vs (R0 ===>\<^sub>T R1)) f f\<^sub>T\<rbrakk> \<Longrightarrow> Rel (crel_vs R1) (App f x) (f\<^sub>T . x\<^sub>T)
[PROOF STEP]
unfolding Rel_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>crel_vs R0 x x\<^sub>T; crel_vs (R0 ===>\<^sub>T R1) f f\<^sub>T\<rbrakk> \<Longrightarrow> crel_vs R1 (App f x) (f\<^sub>T . x\<^sub>T)
[PROOF STEP]
using fun_app_lifted_transfer[THEN rel_funD, THEN rel_funD]
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>crel_vs (?R0.2 ===>\<^sub>T ?R1.2) ?x1 ?y1; crel_vs ?R0.2 ?x ?y\<rbrakk> \<Longrightarrow> crel_vs ?R1.2 (App ?x1 ?x) (?y1 . ?y)
goal (1 subgoal):
1. \<lbrakk>crel_vs R0 x x\<^sub>T; crel_vs (R0 ===>\<^sub>T R1) f f\<^sub>T\<rbrakk> \<Longrightarrow> crel_vs R1 (App f x) (f\<^sub>T . x\<^sub>T)
[PROOF STEP]
. |
-- Andreas, 2012-01-17
-- {-# OPTIONS -v tc.proj.like:50 #-}
-- {-# OPTIONS -v tc.conv.atom:50 #-}
module Issue553c where
postulate
A : Set
a : A
data Bool : Set where
true false : Bool
data WrapBool (C : Set) : Set where
wrap : Bool -> WrapBool C
-- a projection-like function (must not be constructor-headed!)
-- the dummy C is to make Agda accept f as projection like
f : {C : Set} -> WrapBool C -> A
f (wrap true) = a
f (wrap false) = a
data _≡_ {A : Set}(a : A) : A -> Set where
refl : a ≡ a
-- it is important that f does not reduce, in order to enter compareAtom
test : (b : Bool) -> f {C = A} (wrap b) ≡ f (wrap b)
test b = refl
-- An internal error has occurred. Please report this as a bug.
-- Location of the error: src/full/Agda/TypeChecking/Conversion.hs:335
-- the problem is fixed now, since f is no longer projection-like
-- because of deep matching |
module maybe where
open import level
open import eq
open import bool
----------------------------------------------------------------------
-- datatypes
----------------------------------------------------------------------
data maybe {ℓ}(A : Set ℓ) : Set ℓ where
just : A → maybe A
nothing : maybe A
----------------------------------------------------------------------
-- operations
----------------------------------------------------------------------
_≫=maybe_ : ∀ {ℓ}{A B : Set ℓ} → maybe A → (A → maybe B) → maybe B
nothing ≫=maybe f = nothing
(just x) ≫=maybe f = f x
return-maybe : ∀ {ℓ}{A : Set ℓ} → A → maybe A
return-maybe a = just a
down-≡ : ∀{ℓ}{A : Set ℓ}{a a' : A} → just a ≡ just a' → a ≡ a'
down-≡ refl = refl
isJust : ∀{ℓ}{A : Set ℓ} → maybe A → 𝔹
isJust nothing = ff
isJust (just _) = tt
maybe-extract : ∀{ℓ}{A : Set ℓ} → (x : maybe A) → isJust x ≡ tt → A
maybe-extract (just x) p = x
maybe-extract nothing ()
maybe-map : ∀{ℓ}{A B : Set ℓ} → (A → B) → maybe A → maybe B
maybe-map f (just x) = just (f x)
maybe-map f nothing = nothing |
(* Title: HOL/Auth/flash_data_cub_lemma_on_inv__97.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 flash_data_cub Protocol Case Study*}
theory flash_data_cub_lemma_on_inv__97 imports flash_data_cub_base
begin
section{*All lemmas on causal relation between inv__97 and some rule r*}
lemma n_PI_Remote_GetVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_Get src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_Get src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_PI_Remote_GetXVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_PI_Remote_GetX src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_PI_Remote_GetX src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_NakVsinv__97:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Nak dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Nak dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__0Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Nak__part__2Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__0Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Get__part__1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Get__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Field (Ident ''Sta'') ''ShWbMsg'') ''Cmd'')) (Const SHWB_ShWb)) (eqn (IVar (Field (Field (Ident ''Sta'') ''Dir'') ''Pending'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_HeadVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Head N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_PutVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_Get_Put_DirtyVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_Get_Put_Dirty src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_NakVsinv__97:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_Get_PutVsinv__97:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_Get_Put src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''Proc'') p__Inv4) ''CacheState'')) (Const CACHE_E))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P3 s"
apply (cut_tac a1 a2 b1, simp, rule_tac x="(neg (andForm (andForm (andForm (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''Cmd'')) (Const UNI_Get)) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') p__Inv4) ''HomeProc'')) (Const false))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''Cmd'')) (Const UNI_Get))) (eqn (IVar (Field (Para (Field (Ident ''Sta'') ''UniMsg'') src) ''HomeProc'')) (Const false))))" in exI, auto) done
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__0Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_Nak__part__2Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_Nak__part__2 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__0Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__0 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_GetX__part__1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_GetX__part__1 src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_2Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_2 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_3Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_3 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_4Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_4 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_5Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_5 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_6Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_6 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__0Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7__part__1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__0Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_7_NODE_Get__part__1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_7_NODE_Get__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_HomeVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_Home_NODE_GetVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_8_Home_NODE_Get N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8Vsinv__97:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_8_NODE_GetVsinv__97:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_8_NODE_Get N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__0Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__0 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_9__part__1Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_9__part__1 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10_HomeVsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_10_Home N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_10Vsinv__97:
assumes a1: "(\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src pp where a1:"src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_Local_GetX_PutX_10 N src pp" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>pp~=p__Inv4)\<or>(src~=p__Inv4\<and>pp=p__Inv4)\<or>(src~=p__Inv4\<and>pp~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>pp~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>pp~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Local_GetX_PutX_11Vsinv__97:
assumes a1: "(\<exists> src. src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src where a1:"src\<le>N\<and>r=n_NI_Local_GetX_PutX_11 N src" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4)\<or>(src~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_NakVsinv__97:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_Nak src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_GetX_PutXVsinv__97:
assumes a1: "(\<exists> src dst. src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain src dst where a1:"src\<le>N\<and>dst\<le>N\<and>src~=dst\<and>r=n_NI_Remote_GetX_PutX src dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(src=p__Inv4\<and>dst~=p__Inv4)\<or>(src~=p__Inv4\<and>dst=p__Inv4)\<or>(src~=p__Inv4\<and>dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(src=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(src~=p__Inv4\<and>dst~=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutVsinv__97:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Put dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_Put dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_Remote_PutXVsinv__97:
assumes a1: "(\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_PutX dst)" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a1 obtain dst where a1:"dst\<le>N\<and>r=n_NI_Remote_PutX dst" apply fastforce done
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "(dst=p__Inv4)\<or>(dst~=p__Inv4)" apply (cut_tac a1 a2, auto) done
moreover {
assume b1: "(dst=p__Inv4)"
have "?P1 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
moreover {
assume b1: "(dst~=p__Inv4)"
have "?P2 s"
proof(cut_tac a1 a2 b1, auto) qed
then have "invHoldForRule s f r (invariants N)" by auto
}
ultimately show "invHoldForRule s f r (invariants N)" by satx
qed
lemma n_NI_FAckVsinv__97:
assumes a1: "(r=n_NI_FAck )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_ShWbVsinv__97:
assumes a1: "(r=n_NI_ShWb N )" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)" (is "?P1 s \<or> ?P2 s \<or> ?P3 s")
proof -
from a2 obtain p__Inv4 where a2:"p__Inv4\<le>N\<and>f=inv__97 p__Inv4" apply fastforce done
have "?P1 s"
proof(cut_tac a1 a2 , auto) qed
then show "invHoldForRule s f r (invariants N)" by auto
qed
lemma n_NI_Remote_GetX_PutX_HomeVsinv__97:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_PutX_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__0Vsinv__97:
assumes a1: "r=n_PI_Local_GetX_PutX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_WbVsinv__97:
assumes a1: "r=n_NI_Wb " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_StoreVsinv__97:
assumes a1: "\<exists> src data. src\<le>N\<and>data\<le>N\<and>r=n_Store src data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_3Vsinv__97:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_3 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_1Vsinv__97:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_1 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__1Vsinv__97:
assumes a1: "r=n_PI_Local_GetX_GetX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_GetX__part__0Vsinv__97:
assumes a1: "r=n_PI_Local_GetX_GetX__part__0 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_ReplaceVsinv__97:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_PI_Remote_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_Store_HomeVsinv__97:
assumes a1: "\<exists> data. data\<le>N\<and>r=n_Store_Home data" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_ReplaceVsinv__97:
assumes a1: "r=n_PI_Local_Replace " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_existsVsinv__97:
assumes a1: "\<exists> src pp. src\<le>N\<and>pp\<le>N\<and>src~=pp\<and>r=n_NI_InvAck_exists src pp" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Remote_PutXVsinv__97:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_PI_Remote_PutX dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Put_HomeVsinv__97:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Put_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvVsinv__97:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Inv dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_PutXVsinv__97:
assumes a1: "r=n_PI_Local_PutX " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_PutVsinv__97:
assumes a1: "r=n_PI_Local_Get_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__0Vsinv__97:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__0 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_ReplaceVsinv__97:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_Replace src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_GetX_Nak_HomeVsinv__97:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_GetX_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutXAcksDoneVsinv__97:
assumes a1: "r=n_NI_Local_PutXAcksDone " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX__part__1Vsinv__97:
assumes a1: "r=n_PI_Local_GetX_PutX__part__1 " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Remote_Get_Nak_HomeVsinv__97:
assumes a1: "\<exists> dst. dst\<le>N\<and>r=n_NI_Remote_Get_Nak_Home dst" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_exists_HomeVsinv__97:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_exists_Home src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Replace_HomeVsinv__97:
assumes a1: "r=n_NI_Replace_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Local_PutVsinv__97:
assumes a1: "r=n_NI_Local_Put " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_ClearVsinv__97:
assumes a1: "r=n_NI_Nak_Clear " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_Get_GetVsinv__97:
assumes a1: "r=n_PI_Local_Get_Get " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_Nak_HomeVsinv__97:
assumes a1: "r=n_NI_Nak_Home " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_NI_InvAck_2Vsinv__97:
assumes a1: "\<exists> src. src\<le>N\<and>r=n_NI_InvAck_2 N src" and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
lemma n_PI_Local_GetX_PutX_HeadVld__part__1Vsinv__97:
assumes a1: "r=n_PI_Local_GetX_PutX_HeadVld__part__1 N " and
a2: "(\<exists> p__Inv4. p__Inv4\<le>N\<and>f=inv__97 p__Inv4)"
shows "invHoldForRule s f r (invariants N)"
apply (rule noEffectOnRule, cut_tac a1 a2, auto) done
end
|
Require Import Coq.Bool.Bool.
Require Import Coq.Arith.Arith.
Require Import Coq.Arith.EqNat.
Require Import Coq.omega.Omega.
Require Import Coq.Lists.List.
Import ListNotations.
Require Import Maps.
Definition state := total_map nat.
Definition empty_state : state := t_empty 0.
Inductive aexp : Type :=
| ANum : nat -> aexp
| AId : id -> aexp
| APlus : aexp -> aexp -> aexp
| AMinus : aexp -> aexp -> aexp
| AMult : aexp -> aexp -> aexp.
Definition X : id := Id 0.
Definition Y : id := Id 1.
Definition Z : id := Id 2.
Inductive bexp : Type :=
| BTrue : bexp
| BFalse : bexp
| BEq : aexp -> aexp -> bexp
| BLe : aexp -> aexp -> bexp
| BNot : bexp -> bexp
| BAnd : bexp -> bexp -> bexp.
Fixpoint aeval (st : state) (a : aexp) : nat :=
match a with
| ANum n => n
| AId x => st x
| APlus a1 a2 => (aeval st a1) + (aeval st a2)
| AMinus a1 a2 => (aeval st a1) - (aeval st a2)
| AMult a1 a2 => (aeval st a1) * (aeval st a2)
end.
Fixpoint beval (st : state) (b : bexp) : bool :=
match b with
| BTrue => true
| BFalse => false
| BEq a1 a2 => beq_nat (aeval st a1) (aeval st a2)
| BLe a1 a2 => leb (aeval st a1) (aeval st a2)
| BNot b1 => negb (beval st b1)
| BAnd b1 b2 => andb (beval st b1) (beval st b2)
end.
Inductive com : Type :=
| CSkip : com
| CAss : id -> aexp -> com
| CSeq : com -> com -> com
| CIf : bexp -> com -> com -> com
| CWhile : bexp -> com -> com.
Notation "'SKIP'" :=
CSkip.
Notation "x '::=' a" :=
(CAss x a) (at level 60).
Notation "c1 ;; c2" :=
(CSeq c1 c2) (at level 80, right associativity).
Notation "'WHILE' b 'DO' c 'END'" :=
(CWhile b c) (at level 80, right associativity).
Notation "'IFB' c1 'THEN' c2 'ELSE' c3 'FI'" :=
(CIf c1 c2 c3) (at level 80, right associativity).
(* Examples *)
Definition fact_in_coq : com :=
Z ::= AId X;;
Y ::= ANum 1;;
WHILE BNot (BEq (AId Z) (ANum 0)) DO
Y ::= AMult (AId Y) (AId Z);;
Z ::= AMinus (AId Z) (ANum 1)
END.
Definition plus2 : com :=
X ::= (APlus (AId X) (ANum 2)).
Definition XtimesYinZ : com :=
Z ::= (AMult (AId X) (AId Y)).
Definition subtract_slowly_body : com :=
Z ::= AMinus (AId Z) (ANum 1) ;;
X ::= AMinus (AId X) (ANum 1).
Definition subtract_slowly : com :=
WHILE BNot (BEq (AId X) (ANum 0)) DO
subtract_slowly_body
END.
Definition subtract_3_from_5_slowly : com :=
X ::= ANum 3 ;;
Z ::= ANum 5 ;;
subtract_slowly.
Definition infinite_loop : com :=
WHILE BTrue DO
SKIP
END.
(* ----------------------------------------------------------------- *)
(** *** Operational Semantics *)
(*
---------------- (E_Skip)
SKIP / st \\ st
aeval st a1 = n
-------------------------------- (E_Ass)
x := a1 / st \\ (t_update st x n)
c1 / st \\ st'
c2 / st' \\ st''
------------------- (E_Seq)
c1;;c2 / st \\ st''
beval st b1 = true
c1 / st \\ st'
------------------------------------- (E_IfTrue)
IF b1 THEN c1 ELSE c2 FI / st \\ st'
beval st b1 = false
c2 / st \\ st'
------------------------------------- (E_IfFalse)
IF b1 THEN c1 ELSE c2 FI / st \\ st'
beval st b = false
------------------------------ (E_WhileEnd)
WHILE b DO c END / st \\ st
beval st b = true
c / st \\ st'
WHILE b DO c END / st' \\ st''
--------------------------------- (E_WhileLoop)
WHILE b DO c END / st \\ st''
*)
Reserved Notation "c1 '/' st '\\' st'"
(at level 40, st at level 39).
Inductive ceval : com -> state -> state -> Prop :=
| E_Skip : forall st,
SKIP / st \\ st
| E_Ass : forall st a1 n x,
aeval st a1 = n ->
(x ::= a1) / st \\ (t_update st x n)
| E_Seq : forall c1 c2 st st' st'',
c1 / st \\ st' ->
c2 / st' \\ st'' ->
(c1 ;; c2) / st \\ st''
| E_IfTrue : forall st st' b c1 c2,
beval st b = true ->
c1 / st \\ st' ->
(IFB b THEN c1 ELSE c2 FI) / st \\ st'
| E_IfFalse : forall st st' b c1 c2,
beval st b = false ->
c2 / st \\ st' ->
(IFB b THEN c1 ELSE c2 FI) / st \\ st'
| E_WhileEnd : forall b st c,
beval st b = false ->
(WHILE b DO c END) / st \\ st
| E_WhileLoop : forall st st' st'' b c,
beval st b = true ->
c / st \\ st' ->
(WHILE b DO c END) / st' \\ st'' ->
(WHILE b DO c END) / st \\ st''
where "c1 '/' st '\\' st'" := (ceval c1 st st').
Example ceval_example1:
(X ::= ANum 2;;
IFB BLe (AId X) (ANum 1)
THEN Y ::= ANum 3
ELSE Z ::= ANum 4
FI)
/ empty_state
\\ (t_update (t_update empty_state X 2) Z 4).
Proof.
apply E_Seq with (t_update empty_state X 2).
apply E_Ass. reflexivity.
apply E_IfFalse.
reflexivity.
apply E_Ass. reflexivity.
Qed.
Example ceval_example2:
(X ::= ANum 0;; Y ::= ANum 1;; Z ::= ANum 2) / empty_state \\
(t_update (t_update (t_update empty_state X 0) Y 1) Z 2).
Proof.
(* FILL IN HERE *) Admitted.
Theorem ceval_deterministic: forall c st st1 st2,
c / st \\ st1 ->
c / st \\ st2 ->
st1 = st2.
Proof.
intros c st st1 st2 E1 E2.
generalize dependent st2.
induction E1;
intros st2 E2; inversion E2; subst.
- (* E_Skip *) reflexivity.
- (* E_Ass *) reflexivity.
- (* E_Seq *)
assert (st' = st'0) as EQ1.
{ (* Proof of assertion *) apply IHE1_1; assumption. }
subst st'0.
apply IHE1_2. assumption.
- (* E_IfTrue, b1 evaluates to true *)
apply IHE1. assumption.
- (* E_IfTrue, b1 evaluates to false (contradiction) *)
rewrite H in H5. inversion H5.
- (* E_IfFalse, b1 evaluates to true (contradiction) *)
rewrite H in H5. inversion H5.
- (* E_IfFalse, b1 evaluates to false *)
apply IHE1. assumption.
- (* E_WhileEnd, b1 evaluates to false *)
reflexivity.
- (* E_WhileEnd, b1 evaluates to true (contradiction) *)
rewrite H in H2. inversion H2.
- (* E_WhileLoop, b1 evaluates to false (contradiction) *)
rewrite H in H4. inversion H4.
- (* E_WhileLoop, b1 evaluates to true *)
assert (st' = st'0) as EQ1.
{ (* Proof of assertion *) apply IHE1_1; assumption. }
subst st'0.
apply IHE1_2. assumption. Qed.
Theorem plus2_spec : forall st n st',
st X = n ->
plus2 / st \\ st' ->
st' X = n + 2.
Proof.
intros st n st' HX Heval.
inversion Heval. subst. clear Heval. simpl.
apply t_update_eq.
Qed.
Theorem loop_never_stops : forall st st',
~(infinite_loop / st \\ st').
Proof.
intros st st' contra. unfold infinite_loop in contra.
remember (WHILE BTrue DO SKIP END) as loopdef
eqn:Heqloopdef.
(* FILL IN HERE *) Admitted.
Fixpoint no_whiles (c : com) : bool :=
match c with
| SKIP => true
| _ ::= _ => true
| c1 ;; c2 => andb (no_whiles c1) (no_whiles c2)
| IFB _ THEN ct ELSE cf FI => andb (no_whiles ct) (no_whiles cf)
| WHILE _ DO _ END => false
end.
|
The sound quality of the NS @-@ 10 has polarised opinions , characterised as " love them or hate them " . Many professionals find it indispensable , even though they may not particularly enjoy listening to it ; others refuse to give it space in their studio but will happily admit that it is an effective professional tool . The reliance on the NS @-@ 10 by top independent producers became a viral phenomenon ; thousands of studios equipped themselves with NS @-@ 10s to attract big named producers , making the speakers an industry standard .
|
<center><h1><strong>taudata Analytics</strong></h1></center>
<center><h2><strong><font color="blue">PDE 01: Pendahuluan Fungsi dan Turunannya</font></strong></h2></center>
<center></center>
<b><center>(C) Taufik Sutanto</center>
<center><h3><font color="blue">https://taudataid.github.io/pde01/</font></h3></center>
<center></center>
* Maksud pemetaan satu dan hanya satu, 1-1, & pada
* Di kalkuluas fungsi biasanya fungsi real, di machine learning domain bisa berupa angka (numerik) atau bukan angka kategorik.
image source: Yuliani Wibowo - https://slideplayer.info/slide/12403959/
```python
def fungsi(x):
return 2*x+1
fungsi(5)
```
<center><h2><strong><font color="blue">Berbagai macam fungsi</font></strong></h2></center>
```python
import numpy as np
np.cos, dsb
```
<center><h2><strong><font color="blue">Limit Paradox</font></strong></h2></center>
limit-paradox.png
<center><h2><strong><font color="blue">Limit</font></strong></h2></center>
```python
from sympy import *
x = symbols('x')
expr = sin(3 * x)/x;
print("Expression : {}".format(expr))
# Use sympy.limit() method
limit_expr = limit(expr, x, 0)
print("Limit of the expression tends to 0 : {}".format(limit_expr))
```
<center><h2><strong><font color="blue">Limit dan Kontinu </font></strong></h2></center>
- Animasi dari swf
```python
from sympy import Symbol, S
from sympy.calculus.util import continuous_domain
x = Symbol("x")
f = sin(x)/x
continuous_domain(f, x, S.Reals)
Union(Interval.open(-oo, 0), Interval.open(0, oo))
```
<center><h2><strong><font color="blue">Limit dan Turunan</font></strong></h2></center>
```python
from sympy import *
x, y, z = symbols('x y z')
diff(cos(x), x)
```
<center><h2><strong><font color="blue">Makna turunan dan optimasi</font></strong></h2></center>
<center><h2><strong><font color="blue">Solusi akar dan nilai optimal</font></strong></h2></center>
- refer ke link di taudata
```python
# optimasi di Python
from scipy.optimize import minimize
from numpy.random import rand
# objective function
def objective(x):
return x[0]**2.0 + x[1]**2.0
# Plot Fungsinya
# define range for input
r_min, r_max = -5.0, 5.0
```
```python
# define the starting point as a random sample from the domain
pt = r_min + rand(2) * (r_max - r_min)
# perform the l-bfgs-b algorithm search
result = minimize(objective, pt, method='L-BFGS-B')
# summarize the result
print('Status : %s' % result['message'])
print('Total Evaluations: %d' % result['nfev'])
# evaluate solution
solution = result['x']
evaluation = objective(solution)
print('Solution: f(%s) = %.5f' % (solution, evaluation))
```
<center><h2><strong><font color="blue">PDB dan PDP</font></strong></h2></center>
<center><h2><strong><font color="blue">Sifat dasar turunan</font></strong></h2></center>
- chainrule, dsb
<center><h2><strong><font color="blue"> ... </font></strong></h2></center>
# <center><font color="blue"> Akhir Modul PDE 01, Next: " _Pemodelan dan Persamaan Differensial_ "</font></center>
<hr />
|
import Partition
import Data.String
main : IO ()
main = do
argv <- getArgs
n <- pure $ index' 1 argv >>= parsePositive
ls <- pure $ naiveAllParN <$> n
printLn ls
printLn $ length <$> ls
|
fir_filter_sim/dspba_library_package.vhd
fir_filter_sim/dspba_library.vhd
fir_filter_sim/auk_dspip_math_pkg_hpfir.vhd
fir_filter_sim/auk_dspip_lib_pkg_hpfir.vhd
fir_filter_sim/auk_dspip_avalon_streaming_controller_hpfir.vhd
fir_filter_sim/auk_dspip_avalon_streaming_sink_hpfir.vhd
fir_filter_sim/auk_dspip_avalon_streaming_source_hpfir.vhd
fir_filter_sim/auk_dspip_roundsat_hpfir.vhd
fir_filter_sim/altera_avalon_sc_fifo.v
fir_filter_sim/fir_filter_rtl_core.vhd
fir_filter_sim/fir_filter_ast.vhd
fir_filter_sim/fir_filter.vhd
fir_filter_sim/fir_filter_nativelink.tcl
fir_filter_sim/fir_filter_msim.tcl
fir_filter_sim/fir_filter_tb.vhd
fir_filter_sim/fir_filter_mlab.m
fir_filter_sim/fir_filter_model.m
fir_filter_sim/fir_filter_coef_int.txt
fir_filter_sim/fir_filter_input.txt
fir_filter_sim/fir_filter_param.txt
|
[STATEMENT]
lemma Proc_CFG_sourcelabel_less_num_nodes:
"prog \<turnstile> Label l -et\<rightarrow>\<^sub>p n' \<Longrightarrow> l < #:prog"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. prog \<turnstile> Label l -et\<rightarrow>\<^sub>p n' \<Longrightarrow> l < #:prog
[PROOF STEP]
proof(induct prog "Label l" et n' arbitrary:l rule:Proc_CFG.induct)
[PROOF STATE]
proof (state)
goal (17 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>1 et n' c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p n'; l < #:c\<^sub>1; n' \<noteq> Exit\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>c\<^sub>1 et c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p Exit; l < #:c\<^sub>1; Label l \<noteq> Entry\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
6. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
7. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
10. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
A total of 17 subgoals...
[PROOF STEP]
case (Proc_CFG_SeqFirst c\<^sub>1 et n' c\<^sub>2 l)
[PROOF STATE]
proof (state)
this:
c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p n'
l < #:c\<^sub>1
n' \<noteq> Exit
goal (17 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>1 et n' c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p n'; l < #:c\<^sub>1; n' \<noteq> Exit\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>c\<^sub>1 et c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p Exit; l < #:c\<^sub>1; Label l \<noteq> Entry\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
6. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
7. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
10. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
A total of 17 subgoals...
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p n'
l < #:c\<^sub>1
n' \<noteq> Exit
goal (1 subgoal):
1. l < #:c\<^sub>1;; c\<^sub>2
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l < #:c\<^sub>1;; c\<^sub>2
goal (16 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>1 et c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p Exit; l < #:c\<^sub>1; Label l \<noteq> Entry\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
10. \<And>b c'. 0 < #:while (b) c'
A total of 16 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (16 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>1 et c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p Exit; l < #:c\<^sub>1; Label l \<noteq> Entry\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
10. \<And>b c'. 0 < #:while (b) c'
A total of 16 subgoals...
[PROOF STEP]
case (Proc_CFG_SeqConnect c\<^sub>1 et c\<^sub>2 l)
[PROOF STATE]
proof (state)
this:
c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p Exit
l < #:c\<^sub>1
Label l \<noteq> Entry
goal (16 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>1 et c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p Exit; l < #:c\<^sub>1; Label l \<noteq> Entry\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
10. \<And>b c'. 0 < #:while (b) c'
A total of 16 subgoals...
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
c\<^sub>1 \<turnstile> Label l -et\<rightarrow>\<^sub>p Exit
l < #:c\<^sub>1
Label l \<noteq> Entry
goal (1 subgoal):
1. l < #:c\<^sub>1;; c\<^sub>2
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l < #:c\<^sub>1;; c\<^sub>2
goal (15 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 0 < #:while (b) c'
A total of 15 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (15 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 0 < #:while (b) c'
A total of 15 subgoals...
[PROOF STEP]
case (Proc_CFG_SeqSecond c\<^sub>2 n et n' c\<^sub>1 l)
[PROOF STATE]
proof (state)
this:
c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'
n = Label ?l \<Longrightarrow> ?l < #:c\<^sub>2
n \<noteq> Entry
n \<oplus> #:c\<^sub>1 = Label l
goal (15 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 0 < #:while (b) c'
A total of 15 subgoals...
[PROOF STEP]
note n = \<open>n \<oplus> #:c\<^sub>1 = Label l\<close>
[PROOF STATE]
proof (state)
this:
n \<oplus> #:c\<^sub>1 = Label l
goal (15 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 0 < #:while (b) c'
A total of 15 subgoals...
[PROOF STEP]
note IH = \<open>\<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2\<close>
[PROOF STATE]
proof (state)
this:
n = Label ?l \<Longrightarrow> ?l < #:c\<^sub>2
goal (15 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 0 < #:while (b) c'
A total of 15 subgoals...
[PROOF STEP]
from n
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> #:c\<^sub>1 = Label l
[PROOF STEP]
obtain l' where l':"n = Label l'"
[PROOF STATE]
proof (prove)
using this:
n \<oplus> #:c\<^sub>1 = Label l
goal (1 subgoal):
1. (\<And>l'. n = Label l' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases n) auto
[PROOF STATE]
proof (state)
this:
n = Label l'
goal (15 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 0 < #:while (b) c'
A total of 15 subgoals...
[PROOF STEP]
from IH[OF this]
[PROOF STATE]
proof (chain)
picking this:
l' < #:c\<^sub>2
[PROOF STEP]
have "l' < #:c\<^sub>2"
[PROOF STATE]
proof (prove)
using this:
l' < #:c\<^sub>2
goal (1 subgoal):
1. l' < #:c\<^sub>2
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
l' < #:c\<^sub>2
goal (15 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>c\<^sub>2 n et n' c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 = Label l\<rbrakk> \<Longrightarrow> l < #:c\<^sub>1;; c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 0 < #:while (b) c'
A total of 15 subgoals...
[PROOF STEP]
with n l'
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> #:c\<^sub>1 = Label l
n = Label l'
l' < #:c\<^sub>2
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
n \<oplus> #:c\<^sub>1 = Label l
n = Label l'
l' < #:c\<^sub>2
goal (1 subgoal):
1. l < #:c\<^sub>1;; c\<^sub>2
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l < #:c\<^sub>1;; c\<^sub>2
goal (14 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 1 < #:while (b) c'
A total of 14 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (14 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 1 < #:while (b) c'
A total of 14 subgoals...
[PROOF STEP]
case (Proc_CFG_CondThen c\<^sub>1 n et n' b c\<^sub>2 l)
[PROOF STATE]
proof (state)
this:
c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'
n = Label ?l \<Longrightarrow> ?l < #:c\<^sub>1
n \<noteq> Entry
n \<oplus> 1 = Label l
goal (14 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 1 < #:while (b) c'
A total of 14 subgoals...
[PROOF STEP]
note n = \<open>n \<oplus> 1 = Label l\<close>
[PROOF STATE]
proof (state)
this:
n \<oplus> 1 = Label l
goal (14 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 1 < #:while (b) c'
A total of 14 subgoals...
[PROOF STEP]
note IH = \<open>\<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1\<close>
[PROOF STATE]
proof (state)
this:
n = Label ?l \<Longrightarrow> ?l < #:c\<^sub>1
goal (14 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 1 < #:while (b) c'
A total of 14 subgoals...
[PROOF STEP]
from n
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> 1 = Label l
[PROOF STEP]
obtain l' where l':"n = Label l'"
[PROOF STATE]
proof (prove)
using this:
n \<oplus> 1 = Label l
goal (1 subgoal):
1. (\<And>l'. n = Label l' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases n) auto
[PROOF STATE]
proof (state)
this:
n = Label l'
goal (14 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 1 < #:while (b) c'
A total of 14 subgoals...
[PROOF STEP]
from IH[OF this]
[PROOF STATE]
proof (chain)
picking this:
l' < #:c\<^sub>1
[PROOF STEP]
have "l' < #:c\<^sub>1"
[PROOF STATE]
proof (prove)
using this:
l' < #:c\<^sub>1
goal (1 subgoal):
1. l' < #:c\<^sub>1
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
l' < #:c\<^sub>1
goal (14 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>1 n et n' b c\<^sub>2 l. \<lbrakk>c\<^sub>1 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>1; n \<noteq> Entry; n \<oplus> 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 0 < #:while (b) c'
10. \<And>b c'. 1 < #:while (b) c'
A total of 14 subgoals...
[PROOF STEP]
with n l'
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> 1 = Label l
n = Label l'
l' < #:c\<^sub>1
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
n \<oplus> 1 = Label l
n = Label l'
l' < #:c\<^sub>1
goal (1 subgoal):
1. l < #:if (b) c\<^sub>1 else c\<^sub>2
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l < #:if (b) c\<^sub>1 else c\<^sub>2
goal (13 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 1 < #:while (b) c'
10. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 13 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (13 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 1 < #:while (b) c'
10. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 13 subgoals...
[PROOF STEP]
case (Proc_CFG_CondElse c\<^sub>2 n et n' b c\<^sub>1 l)
[PROOF STATE]
proof (state)
this:
c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'
n = Label ?l \<Longrightarrow> ?l < #:c\<^sub>2
n \<noteq> Entry
n \<oplus> #:c\<^sub>1 + 1 = Label l
goal (13 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 1 < #:while (b) c'
10. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 13 subgoals...
[PROOF STEP]
note n = \<open>n \<oplus> (#:c\<^sub>1 + 1) = Label l\<close>
[PROOF STATE]
proof (state)
this:
n \<oplus> #:c\<^sub>1 + 1 = Label l
goal (13 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 1 < #:while (b) c'
10. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 13 subgoals...
[PROOF STEP]
note IH = \<open>\<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2\<close>
[PROOF STATE]
proof (state)
this:
n = Label ?l \<Longrightarrow> ?l < #:c\<^sub>2
goal (13 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 1 < #:while (b) c'
10. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 13 subgoals...
[PROOF STEP]
from n
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> #:c\<^sub>1 + 1 = Label l
[PROOF STEP]
obtain l' where l':"n = Label l'"
[PROOF STATE]
proof (prove)
using this:
n \<oplus> #:c\<^sub>1 + 1 = Label l
goal (1 subgoal):
1. (\<And>l'. n = Label l' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases n) auto
[PROOF STATE]
proof (state)
this:
n = Label l'
goal (13 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 1 < #:while (b) c'
10. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 13 subgoals...
[PROOF STEP]
from IH[OF this]
[PROOF STATE]
proof (chain)
picking this:
l' < #:c\<^sub>2
[PROOF STEP]
have "l' < #:c\<^sub>2"
[PROOF STATE]
proof (prove)
using this:
l' < #:c\<^sub>2
goal (1 subgoal):
1. l' < #:c\<^sub>2
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
l' < #:c\<^sub>2
goal (13 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>c\<^sub>2 n et n' b c\<^sub>1 l. \<lbrakk>c\<^sub>2 \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c\<^sub>2; n \<noteq> Entry; n \<oplus> #:c\<^sub>1 + 1 = Label l\<rbrakk> \<Longrightarrow> l < #:if (b) c\<^sub>1 else c\<^sub>2
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 0 < #:while (b) c'
9. \<And>b c'. 1 < #:while (b) c'
10. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 13 subgoals...
[PROOF STEP]
with n l'
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> #:c\<^sub>1 + 1 = Label l
n = Label l'
l' < #:c\<^sub>2
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
n \<oplus> #:c\<^sub>1 + 1 = Label l
n = Label l'
l' < #:c\<^sub>2
goal (1 subgoal):
1. l < #:if (b) c\<^sub>1 else c\<^sub>2
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l < #:if (b) c\<^sub>1 else c\<^sub>2
goal (12 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 12 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (12 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 12 subgoals...
[PROOF STEP]
case (Proc_CFG_WhileBody c' n et n' b l)
[PROOF STATE]
proof (state)
this:
c' \<turnstile> n -et\<rightarrow>\<^sub>p n'
n = Label ?l \<Longrightarrow> ?l < #:c'
n \<noteq> Entry
n' \<noteq> Exit
n \<oplus> 2 = Label l
goal (12 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 12 subgoals...
[PROOF STEP]
note n = \<open>n \<oplus> 2 = Label l\<close>
[PROOF STATE]
proof (state)
this:
n \<oplus> 2 = Label l
goal (12 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 12 subgoals...
[PROOF STEP]
note IH = \<open>\<And>l. n = Label l \<Longrightarrow> l < #:c'\<close>
[PROOF STATE]
proof (state)
this:
n = Label ?l \<Longrightarrow> ?l < #:c'
goal (12 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 12 subgoals...
[PROOF STEP]
from n
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> 2 = Label l
[PROOF STEP]
obtain l' where l':"n = Label l'"
[PROOF STATE]
proof (prove)
using this:
n \<oplus> 2 = Label l
goal (1 subgoal):
1. (\<And>l'. n = Label l' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases n) auto
[PROOF STATE]
proof (state)
this:
n = Label l'
goal (12 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 12 subgoals...
[PROOF STEP]
from IH[OF this]
[PROOF STATE]
proof (chain)
picking this:
l' < #:c'
[PROOF STEP]
have "l' < #:c'"
[PROOF STATE]
proof (prove)
using this:
l' < #:c'
goal (1 subgoal):
1. l' < #:c'
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
l' < #:c'
goal (12 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et n' b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p n'; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n' \<noteq> Exit; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
A total of 12 subgoals...
[PROOF STEP]
with n l'
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> 2 = Label l
n = Label l'
l' < #:c'
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
n \<oplus> 2 = Label l
n = Label l'
l' < #:c'
goal (1 subgoal):
1. l < #:while (b) c'
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l < #:while (b) c'
goal (11 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>p es rets. 0 < #:Call p es rets
A total of 11 subgoals...
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (11 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>p es rets. 0 < #:Call p es rets
A total of 11 subgoals...
[PROOF STEP]
case (Proc_CFG_WhileBodyExit c' n et b l)
[PROOF STATE]
proof (state)
this:
c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit
n = Label ?l \<Longrightarrow> ?l < #:c'
n \<noteq> Entry
n \<oplus> 2 = Label l
goal (11 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>p es rets. 0 < #:Call p es rets
A total of 11 subgoals...
[PROOF STEP]
note n = \<open>n \<oplus> 2 = Label l\<close>
[PROOF STATE]
proof (state)
this:
n \<oplus> 2 = Label l
goal (11 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>p es rets. 0 < #:Call p es rets
A total of 11 subgoals...
[PROOF STEP]
note IH = \<open>\<And>l. n = Label l \<Longrightarrow> l < #:c'\<close>
[PROOF STATE]
proof (state)
this:
n = Label ?l \<Longrightarrow> ?l < #:c'
goal (11 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>p es rets. 0 < #:Call p es rets
A total of 11 subgoals...
[PROOF STEP]
from n
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> 2 = Label l
[PROOF STEP]
obtain l' where l':"n = Label l'"
[PROOF STATE]
proof (prove)
using this:
n \<oplus> 2 = Label l
goal (1 subgoal):
1. (\<And>l'. n = Label l' \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by(cases n) auto
[PROOF STATE]
proof (state)
this:
n = Label l'
goal (11 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>p es rets. 0 < #:Call p es rets
A total of 11 subgoals...
[PROOF STEP]
from IH[OF this]
[PROOF STATE]
proof (chain)
picking this:
l' < #:c'
[PROOF STEP]
have "l' < #:c'"
[PROOF STATE]
proof (prove)
using this:
l' < #:c'
goal (1 subgoal):
1. l' < #:c'
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
l' < #:c'
goal (11 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>c' n et b l. \<lbrakk>c' \<turnstile> n -et\<rightarrow>\<^sub>p Exit; \<And>l. n = Label l \<Longrightarrow> l < #:c'; n \<noteq> Entry; n \<oplus> 2 = Label l\<rbrakk> \<Longrightarrow> l < #:while (b) c'
10. \<And>p es rets. 0 < #:Call p es rets
A total of 11 subgoals...
[PROOF STEP]
with n l'
[PROOF STATE]
proof (chain)
picking this:
n \<oplus> 2 = Label l
n = Label l'
l' < #:c'
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
n \<oplus> 2 = Label l
n = Label l'
l' < #:c'
goal (1 subgoal):
1. l < #:while (b) c'
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
l < #:while (b) c'
goal (10 subgoals):
1. 0 < #:Skip
2. \<And>V e. 0 < #:V:=e
3. \<And>V e. 1 < #:V:=e
4. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
5. \<And>b c\<^sub>1 c\<^sub>2. 0 < #:if (b) c\<^sub>1 else c\<^sub>2
6. \<And>b c'. 0 < #:while (b) c'
7. \<And>b c'. 0 < #:while (b) c'
8. \<And>b c'. 1 < #:while (b) c'
9. \<And>p es rets. 0 < #:Call p es rets
10. \<And>p es rets. 1 < #:Call p es rets
[PROOF STEP]
qed (auto simp:num_inner_nodes_gr_0) |
import .lib .integers .floats .maps .errors
namespace ast
open integers maps errors floats
/- * Syntactic elements -/
/- Identifiers (names of local variables, of global symbols and functions,
etc) are represented by the type [positive] of positive integers. -/
def ident := pos_num
instance pos_num_eq : decidable_eq pos_num := by tactic.mk_dec_eq_instance
instance ident_eq : decidable_eq ident := by tactic.mk_dec_eq_instance
/- The intermediate languages are weakly typed, using the following types: -/
inductive typ : Type
| Tint /- 32-bit integers or pointers -/
| Tfloat /- 64-bit double-precision floats -/
| Tlong /- 64-bit integers -/
| Tsingle /- 32-bit single-precision floats -/
| Tany32 /- any 32-bit value -/
| Tany64 /- any 64-bit value, i.e. any value -/
def typ.Tptr : typ := if archi.ptr64 then typ.Tlong else typ.Tint
open typ
instance typ_eq : decidable_eq typ := by tactic.mk_dec_eq_instance
def typesize : typ → ℤ
| Tint := 4
| Tfloat := 8
| Tlong := 8
| Tsingle := 4
| Tany32 := 4
| Tany64 := 8
lemma typesize_pos (ty) : typesize ty > 0 :=
by cases ty; exact dec_trivial
lemma typesize_Tptr : typesize Tptr = if archi.ptr64 then 8 else 4 :=
by delta Tptr; cases archi.ptr64; refl
/- All values of size 32 bits are also of type [Tany32]. All values
are of type [Tany64]. This corresponds to the following subtyping
relation over types. -/
def subtype : typ → typ → bool
| Tint Tint := tt
| Tlong Tlong := tt
| Tfloat Tfloat := tt
| Tsingle Tsingle := tt
| Tint Tany32 := tt
| Tsingle Tany32 := tt
| Tany32 Tany32 := tt
| _ Tany64 := tt
| _ _ := ff
def subtype_list : list typ → list typ → bool
| [] [] := tt
| (ty1::tys1) (ty2::tys2) := subtype ty1 ty2 && subtype_list tys1 tys2
| _ _ := ff
/- Additionally, function definitions and function calls are annotated
by function signatures indicating:
- the number and types of arguments;
- the type of the returned value, if any;
- additional information on which calling convention to use.
These signatures are used in particular to determine appropriate
calling conventions for the function. -/
structure calling_convention : Type := mkcallconv ::
(cc_vararg : bool) /- variable-arity function -/
(cc_unproto : bool) /- old-style unprototyped function -/
(cc_structret : bool) /- function returning a struct -/
instance calling_convention_eq : decidable_eq calling_convention := by tactic.mk_dec_eq_instance
def cc_default : calling_convention :=
{ cc_vararg := false, cc_unproto := false, cc_structret := false }
structure signature : Type :=
(sig_args : list typ)
(sig_res : option typ)
(sig_cc : calling_convention)
def proj_sig_res (s : signature) : typ :=
s.sig_res.get_or_else Tint
instance signature_eq : decidable_eq signature := by tactic.mk_dec_eq_instance
def signature_main : signature :=
{ sig_args := [], sig_res := some Tint, sig_cc := cc_default }
/- Memory accesses (load and store instructions) are annotated by
a ``memory chunk'' indicating the type, size and signedness of the
chunk of memory being accessed. -/
inductive memory_chunk : Type
| Mint8signed /- 8-bit signed integer -/
| Mint8unsigned /- 8-bit unsigned integer -/
| Mint16signed /- 16-bit signed integer -/
| Mint16unsigned /- 16-bit unsigned integer -/
| Mint32 /- 32-bit integer, or pointer -/
| Mint64 /- 64-bit integer -/
| Mfloat32 /- 32-bit single-precision float -/
| Mfloat64 /- 64-bit double-precision float -/
| Many32 /- any value that fits in 32 bits -/
| Many64 /- any value -/
open memory_chunk
instance chunk_eq : decidable_eq memory_chunk := by tactic.mk_dec_eq_instance
def Mptr : memory_chunk := if archi.ptr64 then Mint64 else Mint32.
/- The type (integer/pointer or float) of a chunk. -/
def memory_chunk.type : memory_chunk → typ
| Mint8signed := Tint
| Mint8unsigned := Tint
| Mint16signed := Tint
| Mint16unsigned := Tint
| Mint32 := Tint
| Mint64 := Tlong
| Mfloat32 := Tsingle
| Mfloat64 := Tfloat
| Many32 := Tany32
| Many64 := Tany64
lemma memory_chunk.Mptr.type : Mptr.type = Tptr :=
by delta Mptr Tptr; cases archi.ptr64; refl
def chunk_of_type : typ → memory_chunk
| Tint := Mint32
| Tfloat := Mfloat64
| Tlong := Mint64
| Tsingle := Mfloat32
| Tany32 := Many32
| Tany64 := Many64
lemma chunk_of_Tptr : chunk_of_type Tptr = Mptr :=
by delta Mptr Tptr; cases archi.ptr64; refl
/- * Properties of memory chunks -/
/- Memory reads and writes are performed by quantities called memory chunks,
encoding the type, size and signedness of the chunk being addressed.
The following functions extract the size information from a chunk. -/
def memory_chunk.size : memory_chunk → ℕ
| Mint8signed := 1
| Mint8unsigned := 1
| Mint16signed := 2
| Mint16unsigned := 2
| Mint32 := 4
| Mint64 := 8
| Mfloat32 := 4
| Mfloat64 := 8
| Many32 := 4
| Many64 := 8
lemma memory_chunk.size_pos (chunk) : memory_chunk.size chunk > 0 :=
by cases chunk; exact dec_trivial
lemma memory_chunk.Mptr.size_eq : Mptr.size = if archi.ptr64 then 8 else 4 :=
by delta Mptr; cases archi.ptr64; refl
/- Memory reads and writes must respect alignment constraints:
the byte offset of the location being addressed should be an exact
multiple of the natural alignment for the chunk being addressed.
This natural alignment is defined by the following
[align_chunk] function. Some target architectures
(e.g. PowerPC and x86) have no alignment constraints, which we could
reflect by taking [align_chunk chunk = 1]. However, other architectures
have stronger alignment requirements. The following definition is
appropriate for PowerPC, ARM and x86. -/
def memory_chunk.align : memory_chunk → ℕ
| Mint8signed := 1
| Mint8unsigned := 1
| Mint16signed := 2
| Mint16unsigned := 2
| Mint32 := 4
| Mint64 := 8
| Mfloat32 := 4
| Mfloat64 := 4
| Many32 := 4
| Many64 := 4
lemma memory_chunk.align_pos (chunk) : memory_chunk.align chunk > 0 :=
by cases chunk; exact dec_trivial
lemma memory_chunk.Mptr.align : Mptr.align = if archi.ptr64 then 8 else 4 :=
by delta Mptr; cases archi.ptr64; refl
lemma align_size_chunk_dvd (chunk : memory_chunk) : chunk.align ∣ chunk.size := sorry'
lemma align_le_dvd (chunk1 chunk2 : memory_chunk) (h : chunk1.align ≤ chunk2.align) :
chunk1.align ∣ chunk2.align := sorry'
/- Initialization data for global variables. -/
inductive init_data : Type
| int8 : int32 → init_data
| int16 : int32 → init_data
| int32 : int32 → init_data
| int64 : int64 → init_data
| float32 : float32 → init_data
| float64 : float → init_data
| space : ℕ → init_data
| addrof : ident → ptrofs → init_data /- address of symbol + offset -/
namespace init_data
def size : init_data → ℕ
| (int8 _) := 1
| (int16 _) := 2
| (int32 _) := 4
| (int64 _) := 8
| (float32 _) := 4
| (float64 _) := 8
| (addrof _ _) := if archi.ptr64 then 8 else 4
| (space n) := n
def align : init_data → ℕ
| (int8 _) := 1
| (int16 _) := 2
| (int32 _) := 4
| (int64 _) := 8
| (float32 _) := 4
| (float64 _) := 4
| (addrof _ _) := if archi.ptr64 then 8 else 4
| (space _) := 1
def list_size : list init_data → ℕ
| [] := 0
| (i :: il') := i.size + list_size il'
lemma size_pos (i : init_data) : i.size ≥ 0 := sorry'
lemma list_size_pos (il) : list_size il ≥ 0 := sorry'
def list_aligned : ℕ → list init_data → Prop
| p [] := true
| p (i1 :: il) := i1.align ∣ p ∧ list_aligned (p + i1.size) il
end init_data
/- Information attached to global variables. -/
structure globvar (V : Type) : Type :=
(info : V) /- language-dependent info, e.g. a type -/
(init : list init_data) /- initialization data -/
(readonly : bool) /- read-only variable? (const) -/
(volatile : bool) /- volatile variable? -/
/- Whole programs consist of:
- a collection of global definitions (name and description);
- a set of public names (the names that are visible outside
this compilation unit);
- the name of the ``main'' function that serves as entry point in the program.
A global definition is either a global function or a global variable.
The type of function descriptions and that of additional information
for variables vary among the various intermediate languages and are
taken as parameters to the [program] type. The other parts of whole
programs are common to all languages. -/
inductive globdef (F V : Type) : Type
| Gfun {} (f : F) : globdef
| Gvar {} (v : globvar V) : globdef
export globdef
structure program (F V : Type) : Type :=
(defs : list (ident × globdef F V))
(public : list ident)
(main : ident)
def program.defs_names {F V : Type} (p : program F V) : list ident :=
p.defs.map prod.fst
/- The "definition map" of a program maps names of globals to their definitions.
If several definitions have the same name, the one appearing last in [p.defs] wins. -/
section defmap
variables {F V : Type}
variable p : program F V
def prog_defmap : PTree (globdef F V) :=
PTree.of_list p.defs
lemma in_prog_defmap {id : ident} {g} : (prog_defmap p ^! id) = some g →
(id, g) ∈ p.defs := sorry'
lemma prog_defmap_dom {id : ident} : id ∈ p.defs_names →
∃ g, (prog_defmap p^!id) = some g := sorry'
lemma prog_defmap_unique (defs1 id g defs2) :
p.defs = defs1 ++ (id, g) :: defs2 →
id ∉ defs2.map prod.fst →
(prog_defmap p^!id) = some g := sorry'
lemma prog_defmap_nodup {id : ident} {g} :
p.defs_names.nodup →
(id, g) ∈ p.defs →
(prog_defmap p ^! id) = some g := sorry'
end defmap
/- * Generic transformations over programs -/
/- We now define a general iterator over programs that applies a given
code transformation function to all function descriptions and leaves
the other parts of the program unchanged. -/
section transf_program
parameters {A B V : Type} (transf : A → B)
def transform_program_globdef : ident × globdef A V → ident × globdef B V
| (id, Gfun f) := (id, Gfun (transf f))
| (id, Gvar v) := (id, Gvar v)
def transform_program : program A V → program B V
| ⟨defs, pub, main⟩ := ⟨defs.map transform_program_globdef, pub, main⟩
end transf_program
/- The following is a more general presentation of [transform_program]:
- Global variable information can be transformed, in addition to function
definitions.
- The transformation functions can fail and return an error message.
- The transformation for function definitions receives a global context
(derived from the compilation unit being transformed) as additiona
argument.
- The transformation functions receive the name of the global as
additional argument. -/
section transf_program_gen
parameters {A B V W : Type}
parameter transf_fun : ident → A → res B.
parameter transf_var : ident → V → res W.
def transf_globvar (i : ident) : globvar V → res (globvar W)
| ⟨info, init, ro, vo⟩ := do info' ← transf_var i info, OK ⟨info', init, ro, vo⟩
def transf_globdefs : list (ident × globdef A V) → res (list (ident × globdef B W))
| [] := OK []
| ((id, Gfun f) :: l') :=
match transf_fun id f with
| error msg := error (MSG "In function " :: CTX id :: MSG ": " :: msg)
| OK tf :=
do tl' ← transf_globdefs l', OK ((id, Gfun tf) :: tl')
end
| ((id, Gvar v) :: l') :=
match transf_globvar id v with
| error msg := error (MSG "In variable " :: CTX id :: MSG ": " :: msg)
| OK tv :=
do tl' ← transf_globdefs l', OK ((id, Gvar tv) :: tl')
end
def transform_partial_program2 : program A V → res (program B W)
| ⟨defs, pub, main⟩ := do gl' ← transf_globdefs defs, OK ⟨gl', pub, main⟩
end transf_program_gen
/- The following is a special case of [transform_partial_program2],
where only function definitions are transformed, but not variable definitions. -/
def transform_partial_program {A B V} (transf_fun : A → res B) : program A V → res (program B V) :=
transform_partial_program2 (λ i, transf_fun) (λ i, OK)
lemma transform_program_partial_program {A B V} (transf_fun : A → B) (p : program A V) :
transform_partial_program (λ f, OK (transf_fun f)) p = OK (transform_program transf_fun p) := sorry'
/- * External functions -/
/- For most languages, the functions composing the program are either
internal functions, defined within the language, or external functions,
defined outside. External functions include system calls but also
compiler built-in functions. We define a type for external functions
and associated operations. -/
inductive external_function : Type
| EF_external (name : string) (sg : signature)
/- A system call or library function. Produces an event
in the trace. -/
| EF_builtin (name : string) (sg : signature)
/- A compiler built-in function. Behaves like an external, but
can be inlined by the compiler. -/
| EF_runtime (name : string) (sg : signature)
/- A function from the run-time library. Behaves like an
external, but must not be redefined. -/
| EF_vload (chunk : memory_chunk)
/- A volatile read operation. If the adress given as first argument
points within a volatile global variable, generate an
event and return the value found in this event. Otherwise,
produce no event and behave like a regular memory load. -/
| EF_vstore (chunk : memory_chunk)
/- A volatile store operation. If the adress given as first argument
points within a volatile global variable, generate an event.
Otherwise, produce no event and behave like a regular memory store. -/
| EF_malloc
/- Dynamic memory allocation. Takes the requested size in bytes
as argument; returns a pointer to a fresh block of the given size.
Produces no observable event. -/
| EF_free
/- Dynamic memory deallocation. Takes a pointer to a block
allocated by an [EF_malloc] external call and frees the
corresponding block.
Produces no observable event. -/
| EF_memcpy (sz al : ℕ)
/- Block copy, of [sz] bytes, between addresses that are [al]-aligned. -/
| EF_annot (text : string) (targs : list typ)
/- A programmer-supplied annotation. Takes zero, one or several arguments,
produces an event carrying the text and the values of these arguments,
and returns no value. -/
| EF_annot_val (text : string) (targ : typ)
/- Another form of annotation that takes one argument, produces
an event carrying the text and the value of this argument,
and returns the value of the argument. -/
| EF_inline_asm (text : string) (sg : signature) (clobbers : list string)
/- Inline [asm] statements. Semantically, treated like an
annotation with no parameters ([EF_annot text nil]). To be
used with caution, as it can invalidate the semantic
preservation theorem. Generated only if [-finline-asm] is
given. -/
| EF_debug (kind : pos_num) (text : ident) (targs : list typ)
/- Transport debugging information from the front-end to the generated
assembly. Takes zero, one or several arguments like [EF_annot].
Unlike [EF_annot], produces no observable event. -/
export external_function
/- The type signature of an external function. -/
def ef_sig : external_function → signature
| (EF_external name sg) := sg
| (EF_builtin name sg) := sg
| (EF_runtime name sg) := sg
| (EF_vload chunk) := ⟨[Tptr], some chunk.type, cc_default⟩
| (EF_vstore chunk) := ⟨[Tptr, chunk.type], none, cc_default⟩
| (EF_malloc) := ⟨[Tptr], some Tptr, cc_default⟩
| (EF_free) := ⟨[Tptr], none, cc_default⟩
| (EF_memcpy sz al) := ⟨[Tptr, Tptr], none, cc_default⟩
| (EF_annot text targs) := ⟨targs, none, cc_default⟩
| (EF_annot_val text targ) := ⟨[Tptr], some targ, cc_default⟩
| (EF_inline_asm text sg clob) := sg
| (EF_debug kind text targs) := ⟨targs, none, cc_default⟩
/- Whether an external function should be inlined by the compiler. -/
def ef_inline : external_function → bool
| (EF_external name sg) := ff
| (EF_builtin name sg) := tt
| (EF_runtime name sg) := ff
| (EF_vload chunk) := tt
| (EF_vstore chunk) := tt
| (EF_malloc) := ff
| (EF_free) := ff
| (EF_memcpy sz al) := tt
| (EF_annot text targs) := tt
| (EF_annot_val text targ) := tt
| (EF_inline_asm text sg clob) := tt
| (EF_debug kind text targs) := tt
/- Whether an external function must reload its arguments. -/
def ef_reloads : external_function → bool
| (EF_annot text targs) := ff
| (EF_debug kind text targs) := ff
| _ := tt
/- Equality between external functions. Used in module [Allocation]. -/
instance external_function_eq : decidable_eq external_function := by tactic.mk_dec_eq_instance
/- Function definitions are the union of internal and external functions. -/
inductive fundef (F : Type) : Type
| Internal {} : F → fundef
| External {} : external_function → fundef
open fundef
section transf_fundef
parameters {A B : Type} (transf : A → B)
def transf_fundef : fundef A → fundef B
| (Internal f) := Internal (transf f)
| (External ef) := External ef
end transf_fundef
section transf_partial_fundef
parameters {A B : Type} (transf_partial : A → res B)
def transf_partial_fundef : fundef A → res (fundef B)
| (Internal f) := do f' ← transf_partial f, OK (Internal f')
| (External ef) := OK (External ef)
end transf_partial_fundef
/- * Register pairs -/
/- In some intermediate languages (LTL, Mach), 64-bit integers can be
split into two 32-bit halves and held in a pair of registers.
Syntactically, this is captured by the type [rpair] below. -/
inductive rpair (A : Type) : Type
| One (r : A) : rpair
| Twolong (rhi rlo : A) : rpair
open rpair
def typ_rpair {A} (typ_of : A → typ) : rpair A → typ
| (One r) := typ_of r
| (Twolong rhi rlo) := Tlong
def map_rpair {A B} (f : A → B) : rpair A → rpair B
| (One r) := One (f r)
| (Twolong rhi rlo) := Twolong (f rhi) (f rlo)
def regs_of_rpair {A} : rpair A → list A
| (One r) := [r]
| (Twolong rhi rlo) := [rhi, rlo]
def regs_of_rpairs {A} : list (rpair A) → list A
| [] := []
| (p :: l) := regs_of_rpair p ++ regs_of_rpairs l
lemma in_regs_of_rpair {A} (x : A) (p) (hm : x ∈ regs_of_rpair p) (l : list (rpair A)) (hp : p ∈ l) :
x ∈ regs_of_rpairs l := sorry'
lemma in_regs_of_rpairs_inv {A} (x : A) (l : list (rpair A)) (hm : x ∈ regs_of_rpairs l) :
∃ p, p ∈ l ∧ x ∈ regs_of_rpair p := sorry'
def forall_rpair {A} (P : A → Prop) : rpair A → Prop
| (One r) := P r
| (Twolong rhi rlo) := P rhi ∧ P rlo
/- * Arguments and results to builtin functions -/
inductive builtin_arg (A : Type) : Type
| BA {} (x : A) : builtin_arg
| BA_int {} (n : int32) : builtin_arg
| BA_long {} (n : int64) : builtin_arg
| BA_float {} (f : float) : builtin_arg
| BA_single {} (f : float32) : builtin_arg
| BA_loadstack {} (chunk : memory_chunk) (ofs : ptrofs) : builtin_arg
| BA_addrstack {} (ofs : ptrofs) : builtin_arg
| BA_loadglobal {} (chunk : memory_chunk) (id : ident) (ofs : ptrofs) : builtin_arg
| BA_addrglobal {} (id : ident) (ofs : ptrofs) : builtin_arg
| BA_splitlong {} (hi lo : builtin_arg) : builtin_arg
export builtin_arg
inductive builtin_res (A : Type) : Type
| BR {} (x : A) : builtin_res
| BR_none {} : builtin_res
| BR_splitlong {} (hi lo : builtin_res) : builtin_res
open builtin_res
def globals_of_builtin_arg {A : Type} : builtin_arg A → list ident
| (BA_loadglobal chunk id ofs) := [id]
| (BA_addrglobal id ofs) := [id]
| (BA_splitlong hi lo) := globals_of_builtin_arg hi ++ globals_of_builtin_arg lo
| _ := []
def globals_of_builtin_args {A} (al : list (builtin_arg A)) : list ident :=
al.foldr (λ a l, globals_of_builtin_arg a ++ l) []
def params_of_builtin_arg {A} : builtin_arg A → list A
| (BA x) := [x]
| (BA_splitlong hi lo) := params_of_builtin_arg hi ++ params_of_builtin_arg lo
| _ := []
def params_of_builtin_args {A} (al : list (builtin_arg A)) : list A :=
al.foldr (λ a l, params_of_builtin_arg a ++ l) []
def params_of_builtin_res {A} : builtin_res A → list A
| (BR x) := [x]
| BR_none := []
| (BR_splitlong hi lo) := params_of_builtin_res hi ++ params_of_builtin_res lo
def map_builtin_arg {A B} (f : A → B) : builtin_arg A → builtin_arg B
| (BA x) := BA (f x)
| (BA_int n) := BA_int n
| (BA_long n) := BA_long n
| (BA_float n) := BA_float n
| (BA_single n) := BA_single n
| (BA_loadstack chunk ofs) := BA_loadstack chunk ofs
| (BA_addrstack ofs) := BA_addrstack ofs
| (BA_loadglobal chunk id ofs) := BA_loadglobal chunk id ofs
| (BA_addrglobal id ofs) := BA_addrglobal id ofs
| (BA_splitlong hi lo) := BA_splitlong (map_builtin_arg hi) (map_builtin_arg lo)
def map_builtin_res {A B} (f : A → B) : builtin_res A → builtin_res B
| (BR x) := BR (f x)
| BR_none := BR_none
| (BR_splitlong hi lo) := BR_splitlong (map_builtin_res hi) (map_builtin_res lo)
/- Which kinds of builtin arguments are supported by which external function. -/
inductive builtin_arg_constraint : Type
| OK_default
| OK_const
| OK_addrstack
| OK_addrglobal
| OK_addrany
| OK_all
open builtin_arg_constraint
def builtin_arg_ok {A} : builtin_arg A → builtin_arg_constraint → bool
| (BA _) _ := tt
| (BA_splitlong (BA _) (BA _)) _ := tt
| (BA_int _) OK_const := tt
| (BA_long _) OK_const := tt
| (BA_float _) OK_const := tt
| (BA_single _) OK_const := tt
| (BA_addrstack _) OK_addrstack := tt
| (BA_addrstack _) OK_addrany := tt
| (BA_addrglobal _ _) OK_addrglobal := tt
| (BA_addrglobal _ _) OK_addrany := tt
| _ OK_all := tt
| _ _ := ff
end ast |
{-# OPTIONS --cubical --no-import-sorts --safe #-}
module Cubical.Categories.Morphism where
open import Cubical.Foundations.Prelude
open import Cubical.Data.Sigma
open import Cubical.Categories.Category
private
variable
ℓ ℓ' : Level
module _ {C : Precategory ℓ ℓ'} where
open Precategory C
private
variable
x y z w : ob
isMonic : (Hom[ x , y ]) → Type (ℓ-max ℓ ℓ')
isMonic {x} {y} f = ∀ {z : ob} {a a' : Hom[ z , x ]}
→ (f ∘ a ≡ f ∘ a') → (a ≡ a')
isEpic : (Hom[ x , y ]) → Type (ℓ-max ℓ ℓ')
isEpic {x} {y} g = ∀ {z : ob} {b b' : Hom[ y , z ]}
→ (b ∘ g ≡ b' ∘ g) → (b ≡ b')
-- A morphism is split monic if it has a *retraction*
isSplitMon : (Hom[ x , y ]) → Type ℓ'
isSplitMon {x} {y} f = ∃[ r ∈ Hom[ y , x ] ] r ∘ f ≡ id x
-- A morphism is split epic if it has a *section*
isSplitEpi : (Hom[ x , y ]) → Type ℓ'
isSplitEpi {x} {y} g = ∃[ s ∈ Hom[ y , x ] ] g ∘ s ≡ id y
record areInv (f : Hom[ x , y ]) (g : Hom[ y , x ]) : Type ℓ' where
field
sec : g ⋆ f ≡ id y
ret : f ⋆ g ≡ id x
open areInv
symAreInv : ∀ {f : Hom[ x , y ]} {g : Hom[ y , x ]}
→ areInv f g
→ areInv g f
symAreInv record { sec = sec ; ret = ret } = record { sec = ret ; ret = sec }
-- equational reasoning with inverses
invMoveR : ∀ {f : Hom[ x , y ]} {g : Hom[ y , x ]} {h : Hom[ z , x ]} {k : Hom[ z , y ]}
→ areInv f g
→ h ⋆ f ≡ k
→ h ≡ k ⋆ g
invMoveR {f = f} {g} {h} {k} ai p
= h
≡⟨ sym (⋆IdR _) ⟩
(h ⋆ id _)
≡⟨ cong (h ⋆_) (sym (ai .ret)) ⟩
(h ⋆ (f ⋆ g))
≡⟨ sym (⋆Assoc _ _ _) ⟩
((h ⋆ f) ⋆ g)
≡⟨ cong (_⋆ g) p ⟩
k ⋆ g
∎
invMoveL : ∀ {f : Hom[ x , y ]} {g : Hom[ y , x ]} {h : Hom[ y , z ]} {k : Hom[ x , z ]}
→ areInv f g
→ f ⋆ h ≡ k
→ h ≡ g ⋆ k
invMoveL {f = f} {g} {h} {k} ai p
= h
≡⟨ sym (⋆IdL _) ⟩
id _ ⋆ h
≡⟨ cong (_⋆ h) (sym (ai .sec)) ⟩
(g ⋆ f) ⋆ h
≡⟨ ⋆Assoc _ _ _ ⟩
g ⋆ (f ⋆ h)
≡⟨ cong (g ⋆_) p ⟩
(g ⋆ k)
∎
record isIso (f : Hom[ x , y ]) : Type ℓ' where
field
inv : Hom[ y , x ]
sec : inv ⋆ f ≡ id y
ret : f ⋆ inv ≡ id x
open isIso
isIso→areInv : ∀ {f : Hom[ x , y ]}
→ (isI : isIso f)
→ areInv f (isI .inv)
isIso→areInv record { inv = inv ; sec = sec ; ret = ret } = record { sec = sec ; ret = ret }
open CatIso
-- isIso agrees with CatIso
isIso→CatIso : ∀ {f : C [ x , y ]}
→ isIso f
→ CatIso {C = C} x y
isIso→CatIso {f = f} record { inv = f⁻¹ ; sec = sec ; ret = ret } = catiso f f⁻¹ sec ret
CatIso→isIso : (cIso : CatIso {C = C} x y)
→ isIso (cIso .mor)
CatIso→isIso (catiso mor inv sec ret) = record { inv = inv ; sec = sec ; ret = ret }
CatIso→areInv : (cIso : CatIso {C = C} x y)
→ areInv (cIso .mor) (cIso .inv)
CatIso→areInv cIso = isIso→areInv (CatIso→isIso cIso)
-- reverse of an iso is also an iso
symCatIso : ∀ {x y}
→ CatIso {C = C} x y
→ CatIso {C = C} y x
symCatIso (catiso mor inv sec ret) = catiso inv mor ret sec
|
Formal statement is: lemma setdist_neq_0_sing_2: "\<lbrakk>setdist S {x} = a; a \<noteq> 0\<rbrakk> \<Longrightarrow> S \<noteq> {} \<and> x \<notin> closure S" Informal statement is: If the distance between a set $S$ and a point $x$ is nonzero, then $S$ is nonempty and $x$ is not in the closure of $S$. |
> We also have support for forums. Should Xubuntu have forums on the site?
> There has been some interest in it before.
Do kubuntu or edubuntu have separate forums? |
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj20synthconj3_hyp: forall (lv0 : natural) (lv1 : natural) (lv2 : natural), (@eq natural (plus lv0 lv1) (mult lv1 (Succ lv2))) -> (@eq natural (Succ (plus lv0 (plus lv1 lv2))) (plus (mult lv1 (plus lv2 (Succ Zero))) (plus lv2 (Succ Zero)))).
Admitted.
QuickChick conj20synthconj3_hyp.
|
(* Author: Tobias Nipkow *)
section \<open>Function \textit{isin} for Tree2\<close>
theory Isin2
imports
Tree2
Cmp
Set_Specs
begin
fun isin :: "('a::linorder*'b) tree \<Rightarrow> 'a \<Rightarrow> bool" where
"isin Leaf x = False" |
"isin (Node l (a,_) r) x =
(case cmp x a of
LT \<Rightarrow> isin l x |
EQ \<Rightarrow> True |
GT \<Rightarrow> isin r x)"
lemma isin_set_inorder: "sorted(inorder t) \<Longrightarrow> isin t x = (x \<in> set(inorder t))"
by (induction t rule: tree2_induct) (auto simp: isin_simps)
lemma isin_set_tree: "bst t \<Longrightarrow> isin t x \<longleftrightarrow> x \<in> set_tree t"
by(induction t rule: tree2_induct) auto
end
|
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj26eqsynthconj1 : forall (lv0 : natural), (@eq natural (lv0) (plus Zero (plus Zero lv0))).
Admitted.
QuickChick conj26eqsynthconj1.
|
(** **********************************************************
Ralph Matthes
2019, change to [z_iso] as base notion in 2021
*)
(** **********************************************************
Contents :
- build monoidal category for the endofunctors
************************************************************)
Require Import UniMath.Foundations.PartD.
Require Import UniMath.MoreFoundations.Tactics.
Require Import UniMath.CategoryTheory.Core.Categories.
(* Require Import UniMath.CategoryTheory.Core.Functors.
Require Import UniMath.CategoryTheory.FunctorCategory.
Require Import UniMath.CategoryTheory.UnitorsAndAssociatorsForEndofunctors.
Require Import UniMath.CategoryTheory.Core.NaturalTransformations.
Require Import UniMath.CategoryTheory.HorizontalComposition. *)
Require Import UniMath.CategoryTheory.Monoidal.AlternativeDefinitions.MonoidalCategoriesTensored.
Require Import UniMath.Bicategories.MonoidalCategories.MonoidalFromBicategory.
Require Import UniMath.Bicategories.Core.Examples.BicatOfCats.
Local Open Scope cat.
Section Endofunctors_as_monoidal_category.
Context (C : category).
(*
(** The category of endofunctors on [C] *)
Local Notation "'EndC'":= ([C, C]) .
Local Lemma is_nat_trans_left_unitor_data: is_nat_trans (I_pretensor (functorial_composition _ _ _) (functor_identity C)) (functor_identity [C, C]) (@λ_functors C C).
Proof.
intros F F' m.
apply nat_trans_eq_alt.
intro c. cbn.
rewrite (functor_id F).
do 2 rewrite id_left.
apply id_right.
Qed.
Definition left_unitor_of_endofunctors: left_unitor (functorial_composition _ _ _) (functor_identity C).
Proof.
use make_nat_z_iso.
+ use make_nat_trans.
* intro F. apply λ_functors.
* apply is_nat_trans_left_unitor_data.
+ red. intro F. cbn.
use nat_trafo_z_iso_if_pointwise_z_iso.
intro c.
use tpair.
* exact (identity (pr1 F c)).
* abstract ( apply Isos.is_inverse_in_precat_identity ).
Defined.
Local Lemma is_nat_trans_right_unitor_data: is_nat_trans (I_posttensor (functorial_composition _ _ _) (functor_identity C))
(functor_identity [C, C]) (@ρ_functors C C).
Proof.
intros F F' m.
apply nat_trans_eq_alt.
intro c. cbn.
rewrite id_left.
rewrite id_right.
apply id_right.
Qed.
Definition right_unitor_of_endofunctors: right_unitor (functorial_composition _ _ _) (functor_identity C).
Proof.
use make_nat_z_iso.
+ use make_nat_trans.
* intro F. apply ρ_functors.
* apply is_nat_trans_right_unitor_data.
+ red. intro F. cbn.
use nat_trafo_z_iso_if_pointwise_z_iso.
intro c.
use tpair.
* exact (identity (pr1 F c)).
* abstract ( apply Isos.is_inverse_in_precat_identity ).
Defined.
Definition associator_of_endofunctors: associator (functorial_composition _ _ _) :=
associativity_as_nat_z_iso C C C C.
Lemma triangle_eq_of_endofunctors: triangle_eq (functorial_composition _ _ _) (functor_identity C)
left_unitor_of_endofunctors right_unitor_of_endofunctors associator_of_endofunctors.
Proof.
intros F G.
apply nat_trans_eq_alt.
intro c.
cbn.
rewrite functor_id.
do 3 rewrite id_right.
apply functor_id.
Qed.
Lemma pentagon_eq_of_endofunctors: pentagon_eq (functorial_composition _ _ _) associator_of_endofunctors.
Proof.
intros F G H I.
apply nat_trans_eq_alt.
intro c.
cbn.
do 4 rewrite id_right.
do 3 rewrite functor_id.
rewrite id_right.
apply pathsinv0, functor_id.
Qed.
Definition monoidal_cat_of_endofunctors: monoidal_cat.
Proof.
use make_monoidal_cat.
- exact EndC.
- apply functorial_composition.
- apply functor_identity.
- exact left_unitor_of_endofunctors.
- exact right_unitor_of_endofunctors.
- exact associator_of_endofunctors.
- exact triangle_eq_of_endofunctors.
- exact pentagon_eq_of_endofunctors.
Defined.
*)
Definition monoidal_cat_of_endofunctors: monoidal_cat := monoidal_cat_from_bicat_and_ob(C:=bicat_of_cats) C.
(** we need this high-level view in order to be able to instantiate [montrafotargetbicat_moncat] in [ActionBasedStrongFunctorsMonoidal] *)
End Endofunctors_as_monoidal_category.
|
[STATEMENT]
lemma objI_trg:
assumes "arr a" and "trg a = a"
shows "obj a"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. obj a
[PROOF STEP]
using assms obj_def'
[PROOF STATE]
proof (prove)
using this:
arr a
trg a = a
obj ?a = (arr ?a \<and> trg ?a = ?a)
goal (1 subgoal):
1. obj a
[PROOF STEP]
by simp |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric #-}
-- |
-- Module : Statistics.Distribution.Normal
-- Copyright : (c) 2009 Bryan O'Sullivan
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- The normal distribution. This is a continuous probability
-- distribution that describes data that cluster around a mean.
module Statistics.Distribution.Normal
(
NormalDistribution
-- * Constructors
, normalDistr
, normalFromSample
, standard
) where
import Data.Aeson (FromJSON, ToJSON)
import Control.Applicative ((<$>), (<*>))
import Data.Binary (Binary)
import Data.Binary (put, get)
import Data.Data (Data, Typeable)
import GHC.Generics (Generic)
import Numeric.MathFunctions.Constants (m_sqrt_2, m_sqrt_2_pi)
import Numeric.SpecFunctions (erfc, invErfc)
import qualified Statistics.Distribution as D
import qualified Statistics.Sample as S
import qualified System.Random.MWC.Distributions as MWC
-- | The normal distribution.
data NormalDistribution = ND {
mean :: {-# UNPACK #-} !Double
, stdDev :: {-# UNPACK #-} !Double
, ndPdfDenom :: {-# UNPACK #-} !Double
, ndCdfDenom :: {-# UNPACK #-} !Double
} deriving (Eq, Read, Show, Typeable, Data, Generic)
instance FromJSON NormalDistribution
instance ToJSON NormalDistribution
instance Binary NormalDistribution where
put (ND w x y z) = put w >> put x >> put y >> put z
get = ND <$> get <*> get <*> get <*> get
instance D.Distribution NormalDistribution where
cumulative = cumulative
complCumulative = complCumulative
instance D.ContDistr NormalDistribution where
logDensity = logDensity
quantile = quantile
instance D.MaybeMean NormalDistribution where
maybeMean = Just . D.mean
instance D.Mean NormalDistribution where
mean = mean
instance D.MaybeVariance NormalDistribution where
maybeStdDev = Just . D.stdDev
maybeVariance = Just . D.variance
instance D.Variance NormalDistribution where
stdDev = stdDev
instance D.Entropy NormalDistribution where
entropy d = 0.5 * log (2 * pi * exp 1 * D.variance d)
instance D.MaybeEntropy NormalDistribution where
maybeEntropy = Just . D.entropy
instance D.ContGen NormalDistribution where
genContVar d = MWC.normal (mean d) (stdDev d)
-- | Standard normal distribution with mean equal to 0 and variance equal to 1
standard :: NormalDistribution
standard = ND { mean = 0.0
, stdDev = 1.0
, ndPdfDenom = log m_sqrt_2_pi
, ndCdfDenom = m_sqrt_2
}
-- | Create normal distribution from parameters.
--
-- IMPORTANT: prior to 0.10 release second parameter was variance not
-- standard deviation.
normalDistr :: Double -- ^ Mean of distribution
-> Double -- ^ Standard deviation of distribution
-> NormalDistribution
normalDistr m sd
| sd > 0 = ND { mean = m
, stdDev = sd
, ndPdfDenom = log $ m_sqrt_2_pi * sd
, ndCdfDenom = m_sqrt_2 * sd
}
| otherwise =
error $ "Statistics.Distribution.Normal.normalDistr: standard deviation must be positive. Got " ++ show sd
-- | Create distribution using parameters estimated from
-- sample. Variance is estimated using maximum likelihood method
-- (biased estimation).
normalFromSample :: S.Sample -> NormalDistribution
normalFromSample xs
= normalDistr m (sqrt v)
where
(m,v) = S.meanVariance xs
logDensity :: NormalDistribution -> Double -> Double
logDensity d x = (-xm * xm / (2 * sd * sd)) - ndPdfDenom d
where xm = x - mean d
sd = stdDev d
cumulative :: NormalDistribution -> Double -> Double
cumulative d x = erfc ((mean d - x) / ndCdfDenom d) / 2
complCumulative :: NormalDistribution -> Double -> Double
complCumulative d x = erfc ((x - mean d) / ndCdfDenom d) / 2
quantile :: NormalDistribution -> Double -> Double
quantile d p
| p == 0 = -inf
| p == 1 = inf
| p == 0.5 = mean d
| p > 0 && p < 1 = x * ndCdfDenom d + mean d
| otherwise =
error $ "Statistics.Distribution.Normal.quantile: p must be in [0,1] range. Got: "++show p
where x = - invErfc (2 * p)
inf = 1/0
|
In December 2009 , Anderson was working on a new script tentatively titled The Master , about a " charismatic intellectual " who starts a new religion in the 1950s . An associate of Anderson stated that the idea for the film had been in Anderson 's head for about twelve years . Though the film makes no reference to the movement , it has " long been widely assumed to be based on Scientology . " The Master was released on September 14 , 2012 by The Weinstein Company in the United States and Canada to critical acclaim . The film received three nominations at the 85th Academy Awards : Joaquin Phoenix for Best Leading Actor , Philip Seymour Hoffman for Best Supporting Actor and Amy Adams for Best Supporting Actress .
|
open import Agda.Primitive
variable
@0 ℓ : Level
A : Set ℓ
levelOf : A → Level
levelOf {a} _ = a
|
function [newVar newMean state] = hlp_adaptExpWinMovVar(varargin)
% estimate exponential window moving variance (and mean). The
% moving variance is calculated in place based on new data values and
% previous data.
g = arg_define(varargin, ...
arg_norep({'values'},[],[],'data values. can be scalar, vector or matrix'), ...
arg_nogui({'instate','State'},[],[],'state'), ...
arg_sub({'adaptOpts'},{},@hlp_scaleLimits,'Adaptation options'), ...
arg({'reset'},false,[],'Reset adaptation state') ...
);
state = g.instate;
if g.reset || ~isfield(g,'instate') || isempty(state)
% initialize state
state.lastVar = 1;
state.lastMean = 0;
state.numRunsSoFar = 0;
end
% adapt limits using exponential window moving average
[state.lastVar state.lastMean] = hlp_expWinMovVar(g.values,state.lastVar, state.lastMean, ...
state.numRunsSoFar,rmfield(g.adaptOpts,'arg_direct'));
state.numRunsSoFar = state.numRunsSoFar + 1;
newVar = state.lastVar;
newMean = state.lastMean; |
#!/usr/bin/env Rscript
# From https://github.com/berkeley-dsep-infra/datahub/issues/814
# https://github.com/berkeley-dsep-infra/datahub/issues/897
source("/tmp/class-libs.R")
class_name = "IA C188"
class_libs = c(
"rdd", "0.57",
"stargazer", "5.2.2",
"lm.beta", "1.5-1",
"multcomp", "1.4-8",
"lfe", "2.8-2"
)
class_libs_install_version(class_name, class_libs)
|
Address(Monticello Dam,38.513433,122.104453) holds back Putah Creek to form Lake Berryessa. It is in the gap between Blue Ridge/Rocky Ridge to the north and Pleasants Ridge to the south leading to Mount Vaca. While most dams have a spillway to the side to manage high waters, Monticello Dam features the lessconventional Morning Glory Spillway morning glory spillway, which is basically a concrete funnel surrounded on all sides by water. Putah Creek is recommenced from the waters discharged from the dam.
The http://www.sidwater.org/ Solano Irrigation District operates the dam with permission of the http://www.usbr.gov/ United States Bureau of Reclamation. Solano Irrigation District provides water to many farmers in Solano County.
When the dam was built, the town of Monticello had to be razed. Allegedly, two large bulldozers linked together by a chain were used to flatten the remains. When the lake is low, the foundations of the town are visible.
Engineering estimates state that if the dam was completely vaporized (i.e., no rubble at all remained) it would flood Davis with about 3 meters of water. However the dam would never actually disappear without leaving any rubble behind. It would probably be an event like the wiki:Wikipedia:St. Francis Dam disaster. Users/StevenDaubert notes that plenty of rubble remained in the St Francis Dam disaster... The Winters Express newspaper is known as the Gateway to the Monticello Dam and uses the dam in their masthead.
For news about Lake Berryessa, including current lake level information, check out the http://www.lakeberryessanews.com/ Lake Berryessa enews
Pictures
|
\subsection{Surfaces}
|
Formal statement is: lemma connected_component_nonoverlap: "connected_component_set S a \<inter> connected_component_set S b = {} \<longleftrightarrow> a \<notin> S \<or> b \<notin> S \<or> connected_component_set S a \<noteq> connected_component_set S b" Informal statement is: The connected components of a set $S$ are pairwise disjoint if and only if they are distinct. |
(* Title: RTS/Common/Semantics.thy *)
(* Author: Susannah Mansky, UIUC 2020 *)
section "Semantics model"
theory Semantics
imports Main
begin
text "General model for small-step semantics:"
locale Semantics =
fixes
small :: "'prog \<Rightarrow> 'state \<Rightarrow> 'state set" and
endset :: "'state set"
assumes
endset_final: "\<sigma> \<in> endset \<Longrightarrow> \<forall>P. small P \<sigma> = {}"
context Semantics begin
subsection "Extending @{term small} to multiple steps"
primrec small_nstep :: "'prog \<Rightarrow> 'state \<Rightarrow> nat \<Rightarrow> 'state set" where
small_nstep_base:
"small_nstep P \<sigma> 0 = {\<sigma>}" |
small_nstep_Rec:
"small_nstep P \<sigma> (Suc n) =
{ \<sigma>2. \<exists>\<sigma>1. \<sigma>1 \<in> small_nstep P \<sigma> n \<and> \<sigma>2 \<in> small P \<sigma>1 }"
lemma small_nstep_Rec2:
"small_nstep P \<sigma> (Suc n) =
{ \<sigma>2. \<exists>\<sigma>1. \<sigma>1 \<in> small P \<sigma> \<and> \<sigma>2 \<in> small_nstep P \<sigma>1 n }"
proof(induct n arbitrary: \<sigma>)
case (Suc n)
have right: "\<And>\<sigma>'. \<sigma>' \<in> small_nstep P \<sigma> (Suc(Suc n))
\<Longrightarrow> \<exists>\<sigma>1. \<sigma>1 \<in> small P \<sigma> \<and> \<sigma>' \<in> small_nstep P \<sigma>1 (Suc n)"
proof -
fix \<sigma>'
assume "\<sigma>' \<in> small_nstep P \<sigma> (Suc(Suc n))"
then obtain \<sigma>1 where Sucnstep: "\<sigma>1 \<in> small_nstep P \<sigma> (Suc n)" "\<sigma>' \<in> small P \<sigma>1" by fastforce
obtain \<sigma>12 where nstep: "\<sigma>12 \<in> small P \<sigma> \<and> \<sigma>1 \<in> small_nstep P \<sigma>12 n"
using Suc Sucnstep(1) by fastforce
then show "\<exists>\<sigma>1. \<sigma>1 \<in> small P \<sigma> \<and> \<sigma>' \<in> small_nstep P \<sigma>1 (Suc n)"
using Sucnstep by fastforce
qed
have left: "\<And>\<sigma>' . \<exists>\<sigma>1. \<sigma>1 \<in> small P \<sigma> \<and> \<sigma>' \<in> small_nstep P \<sigma>1 (Suc n)
\<Longrightarrow> \<sigma>' \<in> small_nstep P \<sigma> (Suc(Suc n))"
proof -
fix \<sigma>'
assume "\<exists>\<sigma>1. \<sigma>1 \<in> small P \<sigma> \<and> \<sigma>' \<in> small_nstep P \<sigma>1 (Suc n)"
then obtain \<sigma>1 where Sucnstep: "\<sigma>1 \<in> small P \<sigma>" "\<sigma>' \<in> small_nstep P \<sigma>1 (Suc n)"
by fastforce
obtain \<sigma>12 where nstep: "\<sigma>12 \<in> small_nstep P \<sigma>1 n \<and> \<sigma>' \<in> small P \<sigma>12"
using Sucnstep(2) by auto
then show "\<sigma>' \<in> small_nstep P \<sigma> (Suc(Suc n))" using Suc Sucnstep by fastforce
qed
show ?case using right left by fast
qed(simp)
lemma small_nstep_SucD:
assumes "\<sigma>' \<in> small_nstep P \<sigma> (Suc n)"
shows "\<exists>\<sigma>1. \<sigma>1 \<in> small P \<sigma> \<and> \<sigma>' \<in> small_nstep P \<sigma>1 n"
using small_nstep_Rec2 case_prodD assms by fastforce
lemma small_nstep_Suc_nend: "\<sigma>' \<in> small_nstep P \<sigma> (Suc n1) \<Longrightarrow> \<sigma> \<notin> endset"
using endset_final small_nstep_SucD by fastforce
subsection "Extending @{term small} to a big-step semantics"
definition big :: "'prog \<Rightarrow> 'state \<Rightarrow> 'state set" where
"big P \<sigma> \<equiv> { \<sigma>'. \<exists>n. \<sigma>' \<in> small_nstep P \<sigma> n \<and> \<sigma>' \<in> endset }"
lemma bigI:
"\<lbrakk> \<sigma>' \<in> small_nstep P \<sigma> n; \<sigma>' \<in> endset \<rbrakk> \<Longrightarrow> \<sigma>' \<in> big P \<sigma>"
by (fastforce simp add: big_def)
lemma bigD:
"\<lbrakk> \<sigma>' \<in> big P \<sigma> \<rbrakk> \<Longrightarrow> \<exists>n. \<sigma>' \<in> small_nstep P \<sigma> n \<and> \<sigma>' \<in> endset"
by (simp add: big_def)
lemma big_def2:
"\<sigma>' \<in> big P \<sigma> \<longleftrightarrow> (\<exists>n. \<sigma>' \<in> small_nstep P \<sigma> n \<and> \<sigma>' \<in> endset)"
proof(rule iffI)
assume "\<sigma>' \<in> big P \<sigma>"
then show "\<exists>n. \<sigma>' \<in> small_nstep P \<sigma> n \<and> \<sigma>' \<in> endset" using bigD big_def by auto
next
assume "\<exists>n. \<sigma>' \<in> small_nstep P \<sigma> n \<and> \<sigma>' \<in> endset"
then show "\<sigma>' \<in> big P \<sigma>" using big_def big_def by auto
qed
lemma big_stepD:
assumes big: "\<sigma>' \<in> big P \<sigma>" and nend: "\<sigma> \<notin> endset"
shows "\<exists>\<sigma>1. \<sigma>1 \<in> small P \<sigma> \<and> \<sigma>' \<in> big P \<sigma>1"
proof -
obtain n where n: "\<sigma>' \<in> small_nstep P \<sigma> n" "\<sigma>' \<in> endset"
using big_def2 big by auto
then show ?thesis using small_nstep_SucD nend big_def2 by(cases n, simp) blast
qed
(***)
lemma small_nstep_det_last_eq:
assumes det: "\<forall>\<sigma>. small P \<sigma> = {} \<or> (\<exists>\<sigma>'. small P \<sigma> = {\<sigma>'})"
shows "\<lbrakk> \<sigma>' \<in> big P \<sigma>; \<sigma>' \<in> small_nstep P \<sigma> n; \<sigma>' \<in> small_nstep P \<sigma> n' \<rbrakk> \<Longrightarrow> n = n'"
proof(induct n arbitrary: n' \<sigma> \<sigma>')
case 0
have "\<sigma>' = \<sigma>" using "0.prems"(2) small_nstep_base by blast
then have endset: "\<sigma> \<in> endset" using "0.prems"(1) bigD by blast
show ?case
proof(cases n')
case Suc then show ?thesis using "0.prems"(3) small_nstep_SucD endset_final[OF endset] by blast
qed(simp)
next
case (Suc n1)
then have endset: "\<sigma>' \<in> endset" using Suc.prems(1) bigD by blast
have nend: "\<sigma> \<notin> endset" using small_nstep_Suc_nend[OF Suc.prems(2)] by simp
then have neq: "\<sigma>' \<noteq> \<sigma>" using endset by auto
obtain \<sigma>1 where \<sigma>1: "\<sigma>1 \<in> small P \<sigma>" "\<sigma>' \<in> small_nstep P \<sigma>1 n1"
using small_nstep_SucD[OF Suc.prems(2)] by clarsimp
then have big: "\<sigma>' \<in> big P \<sigma>1" using endset by(auto simp: big_def)
show ?case
proof(cases n')
case 0 then show ?thesis using neq Suc.prems(3) using small_nstep_base by blast
next
case Suc': (Suc n1')
then obtain \<sigma>1' where \<sigma>1': "\<sigma>1' \<in> small P \<sigma>" "\<sigma>' \<in> small_nstep P \<sigma>1' n1'"
using small_nstep_SucD[where \<sigma>=\<sigma> and \<sigma>'=\<sigma>' and n=n1'] Suc.prems(3) by blast
then have "\<sigma>1=\<sigma>1'" using \<sigma>1(1) det by auto
then show ?thesis using Suc.hyps(1)[OF big \<sigma>1(2)] \<sigma>1'(2) Suc' by blast
qed
qed
end \<comment> \<open> Semantics \<close>
end |
lemma cauchy_def: "Cauchy S \<longleftrightarrow> (\<forall>e>0. \<exists>N. \<forall>m n. m \<ge> N \<and> n \<ge> N \<longrightarrow> dist (S m) (S n) < e)" |
import tactic
open tactic
/-!
This file contains three tactic-programming exercises of increasing difficulty.
They were (hastily) written to follow the metaprogramming tutorial at
Lean for the Curious Mathematician 2020.
If you're looking for more (better) exercises, we strongly recommend the
exercises by Blanchette et al
for the course Logical Verification at the Vrije Universiteit Amsterdam,
and the corresponding chapter of the course notes:
https://github.com/blanchette/logical_verification_2020/blob/master/lean/love07_metaprogramming_exercise_sheet.lean
https://github.com/blanchette/logical_verification_2020/raw/master/hitchhikers_guide.pdf
## Exercise 1
Write a `contradiction` tactic.
The tactic should look through the hypotheses in the local context
trying to find two that contradict each other,
i.e. proving `P` and `¬ P` for some proposition `P`.
It should use this contradiction to close the goal.
Bonus: handle `P → false` as well as `¬ P`.
This exercise is to practice manipulating the hypotheses and goal.
Note: this exists as `tactic.interactive.contradiction`.
-/
meta def tactic.interactive.contr : tactic unit := sorry
-- it only costs a factor of two to check all pairs, let's start with that
-- mmap reduces to the case of having one expr and checking for a contradiction
-- to start, can we just trace the pair h, p for all p in the context
example (P Q R : Prop) (hp : P) (hq : Q) (hr : ¬ R) (hnq : ¬ Q) : false :=
by contr
example (P Q R : Prop) (hnq : ¬ Q) (hp : P) (hq : Q) (hr : ¬ R) : 0 = 1 :=
by contr
example (P Q R : Prop) (hp : P) (hq : Q) (hr : ¬ R) (hnq : Q → false) : false :=
by contr
/-!
## Exercise 2
Write a tactic that proves a given `nat`-valued declaration is nonnegative.
The tactic should take the name of a declaration whose return type is `ℕ`
(presumably with some arguments), e.g. `nat.add : ℕ → ℕ → ℕ`
or `list.length : Π α : Type, list α → ℕ`.
It should add a new declaration to the environment which proves all applications
of this function are nonnegative,
e.g. `nat.add_nonneg : ∀ m n : ℕ, 0 ≤ nat.add m n`.
Bonus: create reasonable names for these declarations, and/or take an optional argument
for the new name.
This tactic is not useful by itself, but it's a good way to practice
querying and modifying an environment and working under binders.
It is not a tactic to be used during a proof, but rather as a command.
Hints:
* For looking at declarations in the environment, you will need the `declaration` type,
as well as the tactics `get_decl` and `add_decl`.
* You will have to manipulate an expression under binders.
The tactics `mk_local_pis` and `pis`, or their lambda equivalents, will be helpful here.
* `mk_mapp` is a variant of `mk_app` that lets you provide implicit arguments.
-/
meta def add_nonneg_proof (n : name) : tactic unit := sorry
run_cmd add_nonneg_proof `nat.add
run_cmd add_nonneg_proof `list.length
#check nat.add_nonneg
#check list.length_nonneg
/-!
## Exercise 3 (challenge!)
The mathlib tactic `cancel_denoms` is intended to get rid of division by numerals
in expressions where this makes sense. For example,
-/
example (q : ℚ) (h : q / 3 > 0) : q > 0 :=
begin
cancel_denoms at h, exact h
end
/-!
But it is not complete. In particular, it doesn't like nested division
or other operators in denominators. These all fail:
-/
example (q : ℚ) (h : q / (3 / 4) > 0) : false :=
begin
cancel_denoms at h,
end
example (p q : ℚ) (h : q / 2 / 3 < q) : false :=
begin
cancel_denoms at h,
end
example (p q : ℚ) (h : q / 2 < 3 / (4*q)) : false :=
begin
cancel_denoms at h,
end
-- this one succeeds but doesn't do what it should
example (p q : ℚ) (h : q / (2*3) < q) : false :=
begin
cancel_denoms at h,
end
/-!
Look at the code in `src/tactic/cancel_denoms.lean` and try to fix it.
See if you can solve any or all of these failing test cases.
If you succeed, a pull request to mathlib is strongly encouraged!
-/
|
Motherhood, mayhem, and mirth: Playing catch-up.
Christmas morning, our little Tinkerbell and Sleeping Beauty.
The girls just being silly.
One of my many resolutions for the year is to change my attitude. As I typed those words, I heard my Mom’s voice say them. My parents will be so happy that I’ve finally decided to do this because as a teen it’s the one phrase I’m sure I heard everyday. So there it is. I’m changing my attitude. See?
In the vein of being positive with a good attitude, I thought I’d share some pictures of the girls. Nothing like a little shot of cute kids to remind you to have a good attitude.
No matter what the situation, I attempt to find something good about it. Whenever I lose it with the kids, I have to remind myself: I am thankful we have them!
to see my horse THeo.He's so cute!
Just yesterday I got an email from my sister in law sharing the website www.acomplaintfreeworld.org She said that The premise is to monitor how much you complain each day, in turn spreading more positive energy to yourself and to the world. I haven't checked it out yet, but I will. It sounds like something I need too!
Hugs to you Kathy! I hope your world is starting to smooth out.
BTW met someone at a party Saturday night who went to PC with you. She knows Claudine very well too. Her initials are ML (hint: French Basque). She's a doll. |
module Inductive.Examples.Product where
open import Inductive
open import Tuple
open import Data.Fin
open import Data.Product hiding (_×_; <_,_>)
open import Data.List
open import Data.Vec
_×_ : Set → Set → Set
A × B = Inductive (((A ∷ (B ∷ [])) , []) ∷ [])
<_,_> : {A B : Set} → A → B → A × B
< a , b > = construct zero (a ∷ (b ∷ [])) []
fst : {A B : Set} → A × B → A
fst = rec ((λ a b → a) ∷ [])
snd : {A B : Set} → A × B → B
snd = rec ((λ a b → b) ∷ [])
|
"""
DATAQ 4108 Device Level code
author: Valentyn Stadnytskyi
Date: November 2017- April 2019
fully python3 compatible.
The main purpose of this module is to provide useful interface between DI-4108 and a server system level code that does all numbercrynching. This modules only job is to attend DI-4108 and insure that all data is collected and stored in a circular buffer.
The communication in this module is done via XLI module developed by Valentyn Stadnytskyi. This module is based on python sockets.
"""#!/usr/bin/env python3
"""
Simple IOC based on caproto library.
It has
"""
from caproto.server import pvproperty, PVGroup, ioc_arg_parser, run
import caproto
from textwrap import dedent
from pdb import pm
from numpy import random, array, zeros, ndarray, nan, isnan
from time import time, sleep, ctime
if __name__ == '__main__':
from icarus_nmr.device_server import Server
from icarus_nmr.device_daq import DI4108_DL
device = DI4108_DL()
device.pr_buffer_size = (6400,10)
from icarus_nmr.mock_driver import Driver
driver = Driver()
device.bind_driver(driver)
device.init()
ioc_options, run_options = ioc_arg_parser(
default_prefix='device_dl:',
desc=dedent(Server.__doc__))
ioc = Server(**ioc_options)
device.pr_pracket_size = 128
ioc.device = device
run(ioc.pvdb, **run_options)
|
--
-- copyright (c) 2017 Simon Beaumont
--
||| This module defines an AST for the Dirac notation of linear algebra.
module Language.Dirac.AST
import public Data.Complex -- for complex amplitides
import Data.Fin -- finite domain
import Data.Vect -- for finite lists
import Data.Matrix -- for matrices (in one intepretation)
||| The types in Dirac notation - the attempt here is to keep these as
||| abstract as possible and then provide concrete implmentations.
data Typ =
||| A real valued expression (R)
Real |
||| A complex valued expression (C)
Amplitude |
||| The primary type of state
Ket Nat |
||| Adjoint dual of a Ket
Bra Nat |
||| Unitary operator
Operator Nat |
||| Self adjoint operator
Measure Nat |
||| A typed functional language
Function Typ Typ
||| Transform AST type to a concrete Idris type
interpTyp : Typ -> Type
interpTyp Real = Double
interpTyp Amplitude = Complex Double
interpTyp (Ket n) = Vect n (Complex Double)
interpTyp (Bra n) = Vect n (Complex Double)
interpTyp (Operator n) = Matrix n n (Complex Double)
interpTyp (Measure n) = Matrix n n (Complex Double)
interpTyp (Function a t) = interpTyp a -> interpTyp t
-- Context of language evaluation - taken from well typed interpreter
-- example in Idris documentation
using (G : Vect n Typ)
||| Variables are deBruijn indexed
data HasType : (i : Fin n) -> Vect n Typ -> Typ -> Type where
Stop : HasType FZ (t :: G) t
Pop : HasType k G t -> HasType (FS k) (u :: G) t
||| Type indexed expressions
data Expr : Vect n Typ -> Typ -> Type where
||| Variable constructor
Var : HasType i G t -> Expr G t
||| Real value
RVal : (x : Double) -> Expr G Real
||| Complex value
CVal : (z : (Complex Double)) -> Expr G Amplitude
||| Arbitrary binary op -- TODO might need more sophisitcated ops
Op : (interpTyp a -> interpTyp b -> interpTyp c) -> Expr G a -> Expr G b -> Expr G c
||| Lambda
Lam : Expr (a :: G) t -> Expr G (Function a t)
||| Function application
App : Expr G (Function a t) -> Expr G a -> Expr G t
||| Get a value from the enviroment of in scope expressions
data Env : Vect n Typ -> Type where
Nil : Env Nil
(::) : interpTyp a -> Env G -> Env (a :: G)
lookup : HasType i G t -> Env G -> interpTyp t
lookup Stop (x :: xs) = x
lookup (Pop k) (x :: xs) = lookup k xs
||| An interpreter takes an expression in an environment
||| into an Idris value
interp : Env G -> Expr G t -> interpTyp t
interp env (Var i) = lookup i env
interp env (RVal x) = x
interp env (CVal z) = z
interp env (Lam sc) = \x => interp (x :: env) sc
interp env (App f s) = interp env f (interp env s)
interp env (Op op x y) = op (interp env x) (interp env y)
-- Examples
||| Add two complex amplitudes
add : Expr G (Function Amplitude (Function Amplitude Amplitude))
add = Lam (Lam (Op (+) (Var Stop) (Var (Pop Stop))))
-- ||| Add two Kets (Qubits)
sum : Expr G (Function (Ket 2) (Function (Ket 2) (Ket 2)))
sum = Lam (Lam (Op (Data.Vect.zipWith (+)) (Var Stop) (Var (Pop Stop))))
-- Local Variables:
-- idris-load-packages: ("base" "contrib")
-- End:
|
[STATEMENT]
lemma ring_chain: "R \<in> C \<Longrightarrow> ring R"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. R \<in> C \<Longrightarrow> ring R
[PROOF STEP]
using field.is_ring[OF field_chain]
[PROOF STATE]
proof (prove)
using this:
?R \<in> C \<Longrightarrow> ring ?R
goal (1 subgoal):
1. R \<in> C \<Longrightarrow> ring R
[PROOF STEP]
by blast |
Load LFindLoad.
From lfind Require Import LFind.
From QuickChick Require Import QuickChick.
From adtind Require Import goal33.
Derive Show for natural.
Derive Arbitrary for natural.
Instance Dec_Eq_natural : Dec_Eq natural.
Proof. dec_eq. Qed.
Lemma conj22eqsynthconj3 : forall (lv0 : natural) (lv1 : natural), (@eq natural (plus lv0 lv1) (plus lv1 (plus lv0 Zero))).
Admitted.
QuickChick conj22eqsynthconj3.
|
/-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.affine_space.affine_map
import Mathlib.algebra.invertible
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4 u_5 l u_6 u_7 u_8 u_9 u_10
namespace Mathlib
/-!
# Affine equivalences
In this file we define `affine_equiv k P₁ P₂` (notation: `P₁ ≃ᵃ[k] P₂`) to be the type of affine
equivalences between `P₁` and `P₂, i.e., equivalences such that both forward and inverse maps are
affine maps.
We define the following equivalences:
* `affine_equiv.refl k P`: the identity map as an `affine_equiv`;
* `e.symm`: the inverse map of an `affine_equiv` as an `affine_equiv`;
* `e.trans e'`: composition of two `affine_equiv`s; note that the order follows `mathlib`'s
`category_theory` convention (apply `e`, then `e'`), not the convention used in function
composition and compositions of bundled morphisms.
## Tags
affine space, affine equivalence
-/
/-- An affine equivalence is an equivalence between affine spaces such that both forward
and inverse maps are affine.
We define it using an `equiv` for the map and a `linear_equiv` for the linear part in order
to allow affine equivalences with good definitional equalities. -/
structure affine_equiv (k : Type u_1) (P₁ : Type u_2) (P₂ : Type u_3) {V₁ : Type u_4} {V₂ : Type u_5} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂]
extends P₁ ≃ P₂
where
linear : linear_equiv k V₁ V₂
map_vadd' : ∀ (p : P₁) (v : V₁), coe_fn _to_equiv (v +ᵥ p) = coe_fn linear v +ᵥ coe_fn _to_equiv p
protected instance affine_equiv.has_coe_to_fun (k : Type u_1) {V1 : Type u_2} (P1 : Type u_3) {V2 : Type u_4} (P2 : Type u_5) [ring k] [add_comm_group V1] [module k V1] [add_torsor V1 P1] [add_comm_group V2] [module k V2] [add_torsor V2 P2] : has_coe_to_fun (affine_equiv k P1 P2) :=
has_coe_to_fun.mk (fun (e : affine_equiv k P1 P2) => P1 → P2)
fun (e : affine_equiv k P1 P2) => equiv.to_fun (affine_equiv.to_equiv e)
namespace linear_equiv
/-- Interpret a linear equivalence between modules as an affine equivalence. -/
def to_affine_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_comm_group V₂] [semimodule k V₂] (e : linear_equiv k V₁ V₂) : affine_equiv k V₁ V₂ :=
affine_equiv.mk (to_equiv e) e sorry
@[simp] theorem coe_to_affine_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_comm_group V₂] [semimodule k V₂] (e : linear_equiv k V₁ V₂) : ⇑(to_affine_equiv e) = ⇑e :=
rfl
end linear_equiv
namespace affine_equiv
/-- Identity map as an `affine_equiv`. -/
def refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : affine_equiv k P₁ P₁ :=
mk (equiv.refl P₁) (linear_equiv.refl k V₁) sorry
@[simp] theorem coe_refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : ⇑(refl k P₁) = id :=
rfl
theorem refl_apply (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : coe_fn (refl k P₁) x = x :=
rfl
@[simp] theorem to_equiv_refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : to_equiv (refl k P₁) = equiv.refl P₁ :=
rfl
@[simp] theorem linear_refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : linear (refl k P₁) = linear_equiv.refl k V₁ :=
rfl
@[simp] theorem map_vadd {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (p : P₁) (v : V₁) : coe_fn e (v +ᵥ p) = coe_fn (linear e) v +ᵥ coe_fn e p :=
map_vadd' e p v
@[simp] theorem coe_to_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : ⇑(to_equiv e) = ⇑e :=
rfl
/-- Reinterpret an `affine_equiv` as an `affine_map`. -/
def to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : affine_map k P₁ P₂ :=
affine_map.mk (⇑e) (↑(linear e)) (map_vadd' e)
@[simp] theorem coe_to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : ⇑(to_affine_map e) = ⇑e :=
rfl
@[simp] theorem to_affine_map_mk {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (f : P₁ ≃ P₂) (f' : linear_equiv k V₁ V₂) (h : ∀ (p : P₁) (v : V₁), coe_fn f (v +ᵥ p) = coe_fn f' v +ᵥ coe_fn f p) : to_affine_map (mk f f' h) = affine_map.mk (⇑f) (↑f') h :=
rfl
@[simp] theorem linear_to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : affine_map.linear (to_affine_map e) = ↑(linear e) :=
rfl
theorem injective_to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] : function.injective to_affine_map := sorry
@[simp] theorem to_affine_map_inj {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂} {e' : affine_equiv k P₁ P₂} : to_affine_map e = to_affine_map e' ↔ e = e' :=
function.injective.eq_iff injective_to_affine_map
theorem ext {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂} {e' : affine_equiv k P₁ P₂} (h : ∀ (x : P₁), coe_fn e x = coe_fn e' x) : e = e' :=
injective_to_affine_map (affine_map.ext h)
theorem injective_coe_fn {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] : function.injective fun (e : affine_equiv k P₁ P₂) (x : P₁) => coe_fn e x := sorry
@[simp] theorem coe_fn_inj {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂} {e' : affine_equiv k P₁ P₂} : ⇑e = ⇑e' ↔ e = e' :=
function.injective.eq_iff injective_coe_fn
theorem injective_to_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] : function.injective to_equiv :=
fun (e e' : affine_equiv k P₁ P₂) (H : to_equiv e = to_equiv e') => ext (iff.mp equiv.ext_iff H)
@[simp] theorem to_equiv_inj {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂} {e' : affine_equiv k P₁ P₂} : to_equiv e = to_equiv e' ↔ e = e' :=
function.injective.eq_iff injective_to_equiv
/-- Construct an affine equivalence by verifying the relation between the map and its linear part at
one base point. Namely, this function takes an equivalence `e : P₁ ≃ P₂`, a linear equivalece
`e' : V₁ ≃ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have
`e p' = e' (p' -ᵥ p) +ᵥ e p`. -/
def mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : P₁ ≃ P₂) (e' : linear_equiv k V₁ V₂) (p : P₁) (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) : affine_equiv k P₁ P₂ :=
mk e e' sorry
@[simp] theorem coe_mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : P₁ ≃ P₂) (e' : linear_equiv k V₁ V₂) (p : P₁) (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) : ⇑(mk' e e' p h) = ⇑e :=
rfl
@[simp] theorem to_equiv_mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : P₁ ≃ P₂) (e' : linear_equiv k V₁ V₂) (p : P₁) (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) : to_equiv (mk' e e' p h) = e :=
rfl
@[simp] theorem linear_mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : P₁ ≃ P₂) (e' : linear_equiv k V₁ V₂) (p : P₁) (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) : linear (mk' e e' p h) = e' :=
rfl
/-- Inverse of an affine equivalence as an affine equivalence. -/
def symm {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : affine_equiv k P₂ P₁ :=
mk (equiv.symm (to_equiv e)) (linear_equiv.symm (linear e)) sorry
@[simp] theorem symm_to_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : equiv.symm (to_equiv e) = to_equiv (symm e) :=
rfl
@[simp] theorem symm_linear {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : linear_equiv.symm (linear e) = linear (symm e) :=
rfl
protected theorem bijective {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : function.bijective ⇑e :=
equiv.bijective (to_equiv e)
protected theorem surjective {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : function.surjective ⇑e :=
equiv.surjective (to_equiv e)
protected theorem injective {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : function.injective ⇑e :=
equiv.injective (to_equiv e)
@[simp] theorem range_eq {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : set.range ⇑e = set.univ :=
function.surjective.range_eq (affine_equiv.surjective e)
@[simp] theorem apply_symm_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (p : P₂) : coe_fn e (coe_fn (symm e) p) = p :=
equiv.apply_symm_apply (to_equiv e) p
@[simp] theorem symm_apply_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (p : P₁) : coe_fn (symm e) (coe_fn e p) = p :=
equiv.symm_apply_apply (to_equiv e) p
theorem apply_eq_iff_eq_symm_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) {p₁ : P₁} {p₂ : P₂} : coe_fn e p₁ = p₂ ↔ p₁ = coe_fn (symm e) p₂ :=
equiv.apply_eq_iff_eq_symm_apply (to_equiv e)
@[simp] theorem apply_eq_iff_eq {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) {p₁ : P₁} {p₂ : P₁} : coe_fn e p₁ = coe_fn e p₂ ↔ p₁ = p₂ :=
equiv.apply_eq_iff_eq (to_equiv e)
@[simp] theorem symm_refl {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : symm (refl k P₁) = refl k P₁ :=
rfl
/-- Composition of two `affine_equiv`alences, applied left to right. -/
def trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4} {P₁ : Type u_6} {P₂ : Type u_7} {P₃ : Type u_8} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [semimodule k V₃] [add_torsor V₃ P₃] (e : affine_equiv k P₁ P₂) (e' : affine_equiv k P₂ P₃) : affine_equiv k P₁ P₃ :=
mk (equiv.trans (to_equiv e) (to_equiv e')) (linear_equiv.trans (linear e) (linear e')) sorry
@[simp] theorem coe_trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4} {P₁ : Type u_6} {P₂ : Type u_7} {P₃ : Type u_8} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [semimodule k V₃] [add_torsor V₃ P₃] (e : affine_equiv k P₁ P₂) (e' : affine_equiv k P₂ P₃) : ⇑(trans e e') = ⇑e' ∘ ⇑e :=
rfl
theorem trans_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4} {P₁ : Type u_6} {P₂ : Type u_7} {P₃ : Type u_8} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [semimodule k V₃] [add_torsor V₃ P₃] (e : affine_equiv k P₁ P₂) (e' : affine_equiv k P₂ P₃) (p : P₁) : coe_fn (trans e e') p = coe_fn e' (coe_fn e p) :=
rfl
theorem trans_assoc {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4} {V₄ : Type u_5} {P₁ : Type u_6} {P₂ : Type u_7} {P₃ : Type u_8} {P₄ : Type u_9} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [semimodule k V₃] [add_torsor V₃ P₃] [add_comm_group V₄] [semimodule k V₄] [add_torsor V₄ P₄] (e₁ : affine_equiv k P₁ P₂) (e₂ : affine_equiv k P₂ P₃) (e₃ : affine_equiv k P₃ P₄) : trans (trans e₁ e₂) e₃ = trans e₁ (trans e₂ e₃) :=
ext fun (_x : P₁) => rfl
@[simp] theorem trans_refl {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : trans e (refl k P₂) = e :=
ext fun (_x : P₁) => rfl
@[simp] theorem refl_trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : trans (refl k P₁) e = e :=
ext fun (_x : P₁) => rfl
@[simp] theorem trans_symm {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : trans e (symm e) = refl k P₁ :=
ext (symm_apply_apply e)
@[simp] theorem symm_trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : trans (symm e) e = refl k P₂ :=
ext (apply_symm_apply e)
@[simp] theorem apply_line_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (a : P₁) (b : P₁) (c : k) : coe_fn e (coe_fn (affine_map.line_map a b) c) = coe_fn (affine_map.line_map (coe_fn e a) (coe_fn e b)) c :=
affine_map.apply_line_map (to_affine_map e) a b c
protected instance group {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : group (affine_equiv k P₁ P₁) :=
group.mk (fun (e e' : affine_equiv k P₁ P₁) => trans e' e) sorry (refl k P₁) trans_refl refl_trans symm
(div_inv_monoid.div._default (fun (e e' : affine_equiv k P₁ P₁) => trans e' e) sorry (refl k P₁) trans_refl refl_trans
symm)
trans_symm
theorem one_def {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : 1 = refl k P₁ :=
rfl
@[simp] theorem coe_one {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : ⇑1 = id :=
rfl
theorem mul_def {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (e : affine_equiv k P₁ P₁) (e' : affine_equiv k P₁ P₁) : e * e' = trans e' e :=
rfl
@[simp] theorem coe_mul {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (e : affine_equiv k P₁ P₁) (e' : affine_equiv k P₁ P₁) : ⇑(e * e') = ⇑e ∘ ⇑e' :=
rfl
theorem inv_def {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (e : affine_equiv k P₁ P₁) : e⁻¹ = symm e :=
rfl
/-- The map `v ↦ v +ᵥ b` as an affine equivalence between a module `V` and an affine space `P` with
tangent space `V`. -/
def vadd_const (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) : affine_equiv k V₁ P₁ :=
mk (equiv.vadd_const b) (linear_equiv.refl k V₁) sorry
@[simp] theorem linear_vadd_const (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) : linear (vadd_const k b) = linear_equiv.refl k V₁ :=
rfl
@[simp] theorem vadd_const_apply (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) (v : V₁) : coe_fn (vadd_const k b) v = v +ᵥ b :=
rfl
@[simp] theorem vadd_const_symm_apply (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) (p : P₁) : coe_fn (symm (vadd_const k b)) p = p -ᵥ b :=
rfl
/-- `p' ↦ p -ᵥ p'` as an equivalence. -/
def const_vsub (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (p : P₁) : affine_equiv k P₁ V₁ :=
mk (equiv.const_vsub p) (linear_equiv.neg k) sorry
@[simp] theorem coe_const_vsub (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (p : P₁) : ⇑(const_vsub k p) = has_vsub.vsub p :=
rfl
@[simp] theorem coe_const_vsub_symm (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (p : P₁) : ⇑(symm (const_vsub k p)) = fun (v : V₁) => -v +ᵥ p :=
rfl
/-- The map `p ↦ v +ᵥ p` as an affine automorphism of an affine space. -/
def const_vadd (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) : affine_equiv k P₁ P₁ :=
mk (equiv.const_vadd P₁ v) (linear_equiv.refl k V₁) sorry
@[simp] theorem linear_const_vadd (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) : linear (const_vadd k P₁ v) = linear_equiv.refl k V₁ :=
rfl
@[simp] theorem const_vadd_apply (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (p : P₁) : coe_fn (const_vadd k P₁ v) p = v +ᵥ p :=
rfl
@[simp] theorem const_vadd_symm_apply (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (p : P₁) : coe_fn (symm (const_vadd k P₁ v)) p = -v +ᵥ p :=
rfl
/-- Point reflection in `x` as a permutation. -/
def point_reflection (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : affine_equiv k P₁ P₁ :=
trans (const_vsub k x) (vadd_const k x)
theorem point_reflection_apply (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) (y : P₁) : coe_fn (point_reflection k x) y = x -ᵥ y +ᵥ x :=
rfl
@[simp] theorem point_reflection_symm (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : symm (point_reflection k x) = point_reflection k x :=
injective_to_equiv (equiv.point_reflection_symm x)
@[simp] theorem to_equiv_point_reflection (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : to_equiv (point_reflection k x) = equiv.point_reflection x :=
rfl
@[simp] theorem point_reflection_self (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : coe_fn (point_reflection k x) x = x :=
vsub_vadd x x
theorem point_reflection_involutive (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : function.involutive ⇑(point_reflection k x) :=
equiv.point_reflection_involutive x
/-- `x` is the only fixed point of `point_reflection x`. This lemma requires
`x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/
theorem point_reflection_fixed_iff_of_injective_bit0 (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] {x : P₁} {y : P₁} (h : function.injective bit0) : coe_fn (point_reflection k x) y = y ↔ y = x :=
equiv.point_reflection_fixed_iff_of_injective_bit0 h
theorem injective_point_reflection_left_of_injective_bit0 (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (h : function.injective bit0) (y : P₁) : function.injective fun (x : P₁) => coe_fn (point_reflection k x) y :=
equiv.injective_point_reflection_left_of_injective_bit0 h y
theorem injective_point_reflection_left_of_module (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [invertible (bit0 1)] (y : P₁) : function.injective fun (x : P₁) => coe_fn (point_reflection k x) y := sorry
theorem point_reflection_fixed_iff_of_module (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [invertible (bit0 1)] {x : P₁} {y : P₁} : coe_fn (point_reflection k x) y = y ↔ y = x :=
iff.trans (function.injective.eq_iff' (injective_point_reflection_left_of_module k y) (point_reflection_self k y))
eq_comm
end affine_equiv
namespace affine_map
theorem line_map_vadd {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (v' : V₁) (p : P₁) (c : k) : coe_fn (line_map v v') c +ᵥ p = coe_fn (line_map (v +ᵥ p) (v' +ᵥ p)) c :=
affine_equiv.apply_line_map (affine_equiv.vadd_const k p) v v' c
theorem line_map_vsub {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (p₁ : P₁) (p₂ : P₁) (p₃ : P₁) (c : k) : coe_fn (line_map p₁ p₂) c -ᵥ p₃ = coe_fn (line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₃)) c :=
affine_equiv.apply_line_map (affine_equiv.symm (affine_equiv.vadd_const k p₃)) p₁ p₂ c
theorem vsub_line_map {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (p₁ : P₁) (p₂ : P₁) (p₃ : P₁) (c : k) : p₁ -ᵥ coe_fn (line_map p₂ p₃) c = coe_fn (line_map (p₁ -ᵥ p₂) (p₁ -ᵥ p₃)) c :=
affine_equiv.apply_line_map (affine_equiv.const_vsub k p₁) p₂ p₃ c
theorem vadd_line_map {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (p₁ : P₁) (p₂ : P₁) (c : k) : v +ᵥ coe_fn (line_map p₁ p₂) c = coe_fn (line_map (v +ᵥ p₁) (v +ᵥ p₂)) c :=
affine_equiv.apply_line_map (affine_equiv.const_vadd k P₁ v) p₁ p₂ c
theorem homothety_neg_one_apply {V₁ : Type u_2} {P₁ : Type u_6} [add_comm_group V₁] [add_torsor V₁ P₁] {R' : Type u_10} [comm_ring R'] [semimodule R' V₁] (c : P₁) (p : P₁) : coe_fn (homothety c (-1)) p = coe_fn (affine_equiv.point_reflection R' c) p := sorry
|
```python
import numpy as np
import matplotlib.pyplot as plt
import scipy
from sklearn.model_selection import ParameterGrid
from sklearn.manifold import Isomap
import time
from tqdm import tqdm
import librosa
from librosa import cqt
from librosa.core import amplitude_to_db
from librosa.display import specshow
import os
import glob
```
```python
data_dir = '/Users/sripathisridhar/Desktop/SOL'
```
```python
file_paths= sorted(glob.glob(os.path.join(data_dir, '**', '*.wav')))
file_names= []
for file_path in file_paths:
file_names.append(os.path.basename(file_path))
```
```python
hop_size= 512
q= 24
```
```python
import h5py
with h5py.File("SOL.h5", "r") as f:
features_dict = {key:f[key][()] for key in f.keys()}
```
```python
grid = {
'Q': [24],
'k': [3],
'comp': ['log'],
'instr': ['all'],
'dyn': ['all']
}
settings = list(ParameterGrid(grid))
for setting in settings:
if setting["instr"] == 'all':
setting['instr'] = ''
if setting['dyn'] == 'all':
setting['dyn'] = ''
```
```python
batch_str = []
CQT_OCTAVES = 7
features_keys = list(features_dict.keys())
for setting in settings:
q = setting['Q']
# Batch process and store in a folder
batch_str = [setting['instr'], setting['dyn']]
batch_features = []
for feature_key in features_keys:
# Get features that match setting
if all(x in feature_key for x in batch_str):
batch_features.append(features_dict[feature_key])
batch_features = np.stack(batch_features, axis=1)
# Isomap parameters
hop_size = 512
compression = 'log'
features = amplitude_to_db(batch_features)
n_neighbors = setting['k']
n_dimensions = 3
n_octaves = 3
# Prune feature matrix
bin_low = np.where((np.std(features, axis=1) / np.std(features)) > 0.1)[0][0] + q
bin_high = bin_low + n_octaves*q
X = features[bin_low:bin_high, :]
# Z-score Standardization- improves contrast in correlation matrix
mus = np.mean(X, axis=1)
sigmas = np.std(X, axis=1)
X_std = (X - mus[:, np.newaxis]) / (1e-6 + sigmas[:, np.newaxis]) # 1e-6 to avoid runtime division by zero
# Pearson correlation matrix
rho_std = np.dot(X_std, X_std.T) / X_std.shape[1]
# Isomap embedding
isomap = Isomap(n_components= n_dimensions, n_neighbors= n_neighbors)
coords = isomap.fit_transform(rho_std)
# Get note value
freqs= librosa.cqt_frequencies(q*CQT_OCTAVES, fmin=librosa.note_to_hz('C1'), bins_per_octave=q) #librosa CQT default fmin is C1
chroma_list= librosa.core.hz_to_note(freqs[bin_low:bin_high])
notes = []
reps = q//12
for chroma in chroma_list:
for i in range(reps):
notes.append(chroma)
```
```python
curr_fig= plt.figure(figsize=(5.5, 2.75))
ax= curr_fig.add_subplot(121)
ax.axis('off')
import colorcet as cc
subsampled_color_ids = np.floor(np.linspace(0, 256, q, endpoint=False)).astype('int')
color_list= [cc.cyclic_mygbm_30_95_c78[i] for i in subsampled_color_ids]
# Plot embedding with color
for i in range(coords.shape[0]):
plt.scatter(coords[i, 0], coords[i, 1], color= color_list[i%q], s=30.0)
plt.plot(coords[:, 0], coords[:, 1], color='black', linewidth=0.2)
# Plot Pearson correlation matrix
rho_frequencies = freqs[bin_low:bin_high]
freq_ticklabels = ['A2', 'A3', 'A4']
freq_ticks = librosa.core.note_to_hz(freq_ticklabels)
tick_bins = []
tick_labels= []
for i,freq_tick in enumerate(freq_ticks):
tick_bin = np.argmin(np.abs(rho_frequencies-freq_tick))
tick_bins.append(tick_bin)
tick_labels.append(freq_ticklabels[i])
plt.figure(figsize=(2.5,2.5))
plt.imshow(np.abs(rho_std), cmap='magma_r')
plt.xticks(tick_bins)
plt.gca().set_xticklabels(freq_ticklabels)
# plt.xlabel('Log-frequency (octaves)')
plt.yticks(tick_bins)
plt.gca().set_yticklabels(freq_ticklabels)
# plt.ylabel('Log-frequency (octaves)')
plt.gca().invert_yaxis()
plt.clim(0, 1)
```
### Circle projection
```python
import circle_fit
import importlib
importlib.reload(circle_fit)
from circle_fit import circle_fit
A = np.transpose(coords[:,:-1])
x, r, circle_residual = circle_fit(A, verbose=True)
```
```python
import matplotlib
matplotlib.rc('font', family='serif')
fig, axes = plt.subplots()
plt.scatter(A[0,:],A[1,:])
plt.plot(x[0],x[1],'rx')
circle = plt.Circle(x, radius=r, fill=False, linestyle='-.')
axes.set_aspect(1)
axes.add_artist(circle)
# axes.set_ylim([-5,6])
# axes.set_xlim([-2,8])
plt.title('Circle fit: TinySOL all instr', pad=10.0)
plt.show()
print(np.sqrt(circle_residual)/72)
```
```python
r
```
6.355528108736576
```python
def d_squared(a, b):
# Takes two n-D tuples and returns euclidean distance between them
# Cast to array for computation
# Cast first to tuple in case a or b are Sympy Point objects
p_a = np.array(tuple(a), dtype='float')
p_b = np.array(tuple(b), dtype='float')
return np.sum(np.square(p_a - p_b))
```
```python
import sympy
from sympy.geometry import Circle, Point, Line
center = Point(x, evaluate=False)
c = Circle(center, r, evaluate=False)
l = Line(Point(coords[0,:-1]), center, evaluate=False)
points = [tuple(p) for p in l.points]
xy_prime = []
# TODO: Optimize to a more pythonic manner
for x,y in coords[:,:2]:
intersections = c.intersection(Line(Point(x,y), center, evaluate=False))
if d_squared((x,y),intersections[0]) < d_squared((x,y), intersections[1]):
xy_prime.append([float(p) for p in intersections[0]])
else:
xy_prime.append([float(p) for p in intersections[1]])
```
```python
fig, axes = plt.subplots()
plt.scatter(np.array(xy_prime)[:,0],np.array(xy_prime)[:,1], s=10,
label='projected points')
plt.scatter(A[0,:],A[1,:], s=0.5, label='isomap embedding points (2D)')
plt.plot(center[0],center[1],'rx')
circle = plt.Circle([float(p) for p in center], radius=r, fill=False,
linestyle='--', label='estimated circle fit')
axes.set_aspect(1)
axes.add_artist(circle)
plt.title('Projected points on circle', pad=10.0)
plt.legend(bbox_to_anchor=(1,1))
plt.show()
```
### Line projection
```python
z = np.arange(len(coords[:,2]))
z_fit = scipy.stats.linregress(z, coords[:,2])
print(z_fit.stderr)
```
0.0052234352623828605
```python
plt.figure()
plt.title('Line fit: TinySOL all instr')
plt.scatter(np.arange(len(coords[:,2])), coords[:,2])
plt.plot(z_fit.intercept + z_fit.slope*z, 'b')
```
```python
# New line coordinates
z_prime = [i * z_fit.slope + z_fit.intercept for i,_ in enumerate(coords[:,2])]
```
```python
coords_prime = np.append(np.array(xy_prime), np.expand_dims(np.array(z_prime), axis=1), axis=1)
coords_length = coords_prime.shape[0]
```
### Distance matrices
```python
# Projected helix self-distance matrix
D_proj = np.zeros((coords_length, coords_length))
for i in range(coords_length):
for j in range(i,coords_length):
D_proj[i][j] = d_squared(coords_prime[i,:], coords_prime[j,:])
```
```python
# Isomap embedding self-distance matrix
D_isomap = np.zeros((coords_length, coords_length)) # Projected points same no. as isomap
for i in range(coords_length):
for j in range(i, coords_length):
D_isomap[i][j] = d_squared(coords[i,:], coords[j,:])
```
```python
# Geodesic self-distance matrix
D_geodesic = isomap.dist_matrix_
# Convert to upper triangular sparse matrix
for i in range(coords_length):
for j in range(i):
D_geodesic[i,j] = 0
```
```python
## Centering matrix
def centered(A, Q=24, J=3):
# Returns centered distance matrix
'''
Inputs
-----
A - squared distance matrix
Q - quality factor, 24 by default
J - number of octaves, 3 by default
Returns
-----
tau - MDS style diagonalized matrix of A
'''
coords_length = A.shape[0]
H = np.zeros((coords_length, coords_length))
const = 1/(Q*J)
for i in range(coords_length):
for j in range(coords_length):
if j==i:
H[i,j] = 1 - const
else:
H[i,j] = -const
return -0.5 * np.matmul(np.matmul(H, A), H)
```
```python
def frobenius_distance(A, B):
# Given two nxn matrices, return their 'Frobenius distance'
return np.sqrt(np.sum(np.square(A - B)))
```
```python
loss_isomap = frobenius_distance(centered(D_geodesic), centered(D_isomap))/coords_length
loss_total = frobenius_distance(centered(D_geodesic), centered(D_proj))/coords_length
loss_proj = frobenius_distance(centered(D_isomap), centered(D_proj))/coords_length
```
```python
print(f"Isomap loss= {loss_isomap}")
print(f"Projection loss= {loss_proj}")
print(f"Total loss= {loss_total}")
```
Isomap loss= 20.242536163460947
Projection loss= 2.3225511781614396
Total loss= 20.914716613612924
```python
(loss_total) - (loss_isomap + loss_proj) < 0
```
True
|
To Walter Jackson Bate , the use of spondees in lines 31 – 34 creates a feeling of slow flight , and " in the final stanza . . . the distinctive use of scattered spondees , together with initial inversion , lend [ s ] an approximate phonetic suggestion of the peculiar spring and bounce of the bird in its flight . "
|
function [gmu, gsigmavar, factors] = gpPosteriorGradMeanCovar(model, X);
% GPPOSTERIORGRADMEANCOVAR Gadient of the mean and variances of the posterior at points given by X.
% FORMAT
% DESC computes the gradient of the mean and covariances of the
% posterior distribution of a Gaussian process with respect to the
% input locations.
% ARG model : the model for which gradients are to be computed.
% ARG X : the input locations where gradients are to be computed.
% RETURN gmu : the gradient of the posterior mean with respect to
% the input locations.
% RETURN gCovar : the gradients of the posterior covariance with
% respect to the input locations. By raw, we mean that the gradient
% has not yet been multiplied by any output scale in that direction
% (as is done for gpPosteriorGradMeanCovar). The gradients are
% stored in a cell array of dimension MODEL.q x MODEL.d.
%
% DESC computes the gradient of the mean and covariances of the
% posterior distribution of a Gaussian process with respect to the
% input locations. Returns a compact representation for the
% covariances which separates the factors associated with the
% different dimensions from the covariance gradients.
% ARG model : the model for which gradients are to be computed.
% ARG X : the input locations where gradients are to be computed.
% RETURN gmu : the gradient of the posterior mean with respect to
% the input locations.
% RETURN grCovar : the 'raw' gradient of the posterior covariance with
% respect to the input locations. By raw, we mean that the gradient
% has not yet been multiplied by any output scale in that direction
% (as is done for gpPosteriorGradMeanCovar). The gradients are
% stored in a cell array of length MODEL.q.
% RETURN factors : the factors for multiplying the 'raw' gradients
% of the covariances by.
%
% SEEALSO : gpCreate, gpPosteriorMeanVar
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2006, 2009
% GP
if ~isfield(model, 'alpha')
model = gpComputeAlpha(model);
end
switch model.approx
case 'ftc'
gX = kernGradX(model.kern, X, model.X);
kX_star = kernCompute(model.kern, X, model.X)';
case {'dtc', 'dtcvar', 'fitc', 'pitc'}
gX = kernGradX(model.kern, X, model.X_u);
kX_star = kernCompute(model.kern, X, model.X_u)';
otherwise
error('Unrecognised approximation type');
end
K = kernGradX(model.kern, X);
if ~model.isMissingData
for i = 1:model.q
switch model.approx
case 'ftc'
KinvgK = model.invK_uu*squeeze(gX(:, i, :));
case {'dtc', 'dtcvar', 'fitc', 'pitc'}
KinvgK = (model.invK_uu - (1/model.beta)*model.Ainv)*squeeze(gX(:, i, :));
otherwise
error('Unrecognised approximation type');
end
kXTKinvgK = kX_star'*KinvgK;
gCovar{i} = squeeze(K(:, i, :))-kXTKinvgK - diag(diag(kXTKinvgK));
gmu{i} = squeeze(gX(:, i, :))'*model.alpha.*repmat(model.scale, ...
size(X, 1), 1);
end
% Deal with scaling.
if nargout < 3
for i = 1:model.q
for j = 1:model.d
gsigmavar{i, j} = gCovar{i}*model.scale(j)*model.scale(j);
end
end
else
factors = model.scale.*model.scale;
gsigmavar = gCovar;
end
else
error('Not yet implemented for models trained on missing data.');
end
|
module tree-test where
open import tree
open import nat
open import bool
open import bool-to-string
open import list
test-tree = node 2 ( (leaf 3) :: (node 4 ( (leaf 5) :: (leaf 7) :: [] )) :: (leaf 6) :: (leaf 7) :: [])
perfect3 = perfect-binary-tree 3 tt
perfect3-string = 𝕋-to-string 𝔹-to-string perfect3 |
If $f$ and $g$ are asymptotically equivalent and $f$ tends to $c$, then $g$ tends to $c$. |
// This file is auto-generated, don't edit it. Thanks.
#ifndef ALIBABACLOUD_CDT20210813_H_
#define ALIBABACLOUD_CDT20210813_H_
#include <alibabacloud/open_api.hpp>
#include <boost/throw_exception.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>
using namespace std;
namespace Alibabacloud_CDT20210813 {
class GetCdtServiceStatusRequest : public Darabonba::Model {
public:
shared_ptr<long> ownerId{};
GetCdtServiceStatusRequest() {}
explicit GetCdtServiceStatusRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (ownerId) {
res["OwnerId"] = boost::any(*ownerId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) {
ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"]));
}
}
virtual ~GetCdtServiceStatusRequest() = default;
};
class GetCdtServiceStatusResponseBody : public Darabonba::Model {
public:
shared_ptr<string> requestId{};
shared_ptr<bool> enabled{};
GetCdtServiceStatusResponseBody() {}
explicit GetCdtServiceStatusResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
if (enabled) {
res["Enabled"] = boost::any(*enabled);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
if (m.find("Enabled") != m.end() && !m["Enabled"].empty()) {
enabled = make_shared<bool>(boost::any_cast<bool>(m["Enabled"]));
}
}
virtual ~GetCdtServiceStatusResponseBody() = default;
};
class GetCdtServiceStatusResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<GetCdtServiceStatusResponseBody> body{};
GetCdtServiceStatusResponse() {}
explicit GetCdtServiceStatusResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetCdtServiceStatusResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetCdtServiceStatusResponseBody>(model1);
}
}
}
virtual ~GetCdtServiceStatusResponse() = default;
};
class OpenCdtServiceRequest : public Darabonba::Model {
public:
shared_ptr<long> ownerId{};
OpenCdtServiceRequest() {}
explicit OpenCdtServiceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (ownerId) {
res["OwnerId"] = boost::any(*ownerId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) {
ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"]));
}
}
virtual ~OpenCdtServiceRequest() = default;
};
class OpenCdtServiceResponseBody : public Darabonba::Model {
public:
shared_ptr<string> requestId{};
shared_ptr<string> orderId{};
OpenCdtServiceResponseBody() {}
explicit OpenCdtServiceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
if (orderId) {
res["OrderId"] = boost::any(*orderId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
if (m.find("OrderId") != m.end() && !m["OrderId"].empty()) {
orderId = make_shared<string>(boost::any_cast<string>(m["OrderId"]));
}
}
virtual ~OpenCdtServiceResponseBody() = default;
};
class OpenCdtServiceResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<OpenCdtServiceResponseBody> body{};
OpenCdtServiceResponse() {}
explicit OpenCdtServiceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
OpenCdtServiceResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<OpenCdtServiceResponseBody>(model1);
}
}
}
virtual ~OpenCdtServiceResponse() = default;
};
class GetCdtCbServiceStatusRequest : public Darabonba::Model {
public:
shared_ptr<long> ownerId{};
GetCdtCbServiceStatusRequest() {}
explicit GetCdtCbServiceStatusRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (ownerId) {
res["OwnerId"] = boost::any(*ownerId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) {
ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"]));
}
}
virtual ~GetCdtCbServiceStatusRequest() = default;
};
class GetCdtCbServiceStatusResponseBody : public Darabonba::Model {
public:
shared_ptr<string> requestId{};
shared_ptr<bool> enabled{};
GetCdtCbServiceStatusResponseBody() {}
explicit GetCdtCbServiceStatusResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
if (enabled) {
res["Enabled"] = boost::any(*enabled);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
if (m.find("Enabled") != m.end() && !m["Enabled"].empty()) {
enabled = make_shared<bool>(boost::any_cast<bool>(m["Enabled"]));
}
}
virtual ~GetCdtCbServiceStatusResponseBody() = default;
};
class GetCdtCbServiceStatusResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<GetCdtCbServiceStatusResponseBody> body{};
GetCdtCbServiceStatusResponse() {}
explicit GetCdtCbServiceStatusResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
GetCdtCbServiceStatusResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<GetCdtCbServiceStatusResponseBody>(model1);
}
}
}
virtual ~GetCdtCbServiceStatusResponse() = default;
};
class OpenCdtCbServiceRequest : public Darabonba::Model {
public:
shared_ptr<long> ownerId{};
OpenCdtCbServiceRequest() {}
explicit OpenCdtCbServiceRequest(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (ownerId) {
res["OwnerId"] = boost::any(*ownerId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("OwnerId") != m.end() && !m["OwnerId"].empty()) {
ownerId = make_shared<long>(boost::any_cast<long>(m["OwnerId"]));
}
}
virtual ~OpenCdtCbServiceRequest() = default;
};
class OpenCdtCbServiceResponseBody : public Darabonba::Model {
public:
shared_ptr<string> requestId{};
shared_ptr<string> orderId{};
OpenCdtCbServiceResponseBody() {}
explicit OpenCdtCbServiceResponseBody(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (requestId) {
res["RequestId"] = boost::any(*requestId);
}
if (orderId) {
res["OrderId"] = boost::any(*orderId);
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("RequestId") != m.end() && !m["RequestId"].empty()) {
requestId = make_shared<string>(boost::any_cast<string>(m["RequestId"]));
}
if (m.find("OrderId") != m.end() && !m["OrderId"].empty()) {
orderId = make_shared<string>(boost::any_cast<string>(m["OrderId"]));
}
}
virtual ~OpenCdtCbServiceResponseBody() = default;
};
class OpenCdtCbServiceResponse : public Darabonba::Model {
public:
shared_ptr<map<string, string>> headers{};
shared_ptr<OpenCdtCbServiceResponseBody> body{};
OpenCdtCbServiceResponse() {}
explicit OpenCdtCbServiceResponse(const std::map<string, boost::any> &config) : Darabonba::Model(config) {
fromMap(config);
};
void validate() override {
if (!headers) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("headers is required.")));
}
if (!body) {
BOOST_THROW_EXCEPTION(boost::enable_error_info(std::runtime_error("body is required.")));
}
}
map<string, boost::any> toMap() override {
map<string, boost::any> res;
if (headers) {
res["headers"] = boost::any(*headers);
}
if (body) {
res["body"] = body ? boost::any(body->toMap()) : boost::any(map<string,boost::any>({}));
}
return res;
}
void fromMap(map<string, boost::any> m) override {
if (m.find("headers") != m.end() && !m["headers"].empty()) {
map<string, string> map1 = boost::any_cast<map<string, string>>(m["headers"]);
map<string, string> toMap1;
for (auto item:map1) {
toMap1[item.first] = item.second;
}
headers = make_shared<map<string, string>>(toMap1);
}
if (m.find("body") != m.end() && !m["body"].empty()) {
if (typeid(map<string, boost::any>) == m["body"].type()) {
OpenCdtCbServiceResponseBody model1;
model1.fromMap(boost::any_cast<map<string, boost::any>>(m["body"]));
body = make_shared<OpenCdtCbServiceResponseBody>(model1);
}
}
}
virtual ~OpenCdtCbServiceResponse() = default;
};
class Client : Alibabacloud_OpenApi::Client {
public:
explicit Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config);
string getEndpoint(shared_ptr<string> productId,
shared_ptr<string> regionId,
shared_ptr<string> endpointRule,
shared_ptr<string> network,
shared_ptr<string> suffix,
shared_ptr<map<string, string>> endpointMap,
shared_ptr<string> endpoint);
GetCdtServiceStatusResponse getCdtServiceStatusWithOptions(shared_ptr<GetCdtServiceStatusRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetCdtServiceStatusResponse getCdtServiceStatus(shared_ptr<GetCdtServiceStatusRequest> request);
OpenCdtServiceResponse openCdtServiceWithOptions(shared_ptr<OpenCdtServiceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
OpenCdtServiceResponse openCdtService(shared_ptr<OpenCdtServiceRequest> request);
GetCdtCbServiceStatusResponse getCdtCbServiceStatusWithOptions(shared_ptr<GetCdtCbServiceStatusRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
GetCdtCbServiceStatusResponse getCdtCbServiceStatus(shared_ptr<GetCdtCbServiceStatusRequest> request);
OpenCdtCbServiceResponse openCdtCbServiceWithOptions(shared_ptr<OpenCdtCbServiceRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime);
OpenCdtCbServiceResponse openCdtCbService(shared_ptr<OpenCdtCbServiceRequest> request);
virtual ~Client() = default;
};
} // namespace Alibabacloud_CDT20210813
#endif
|
They can be divided into two separate clusters : one to the west of the River Medway and the other on Blue Bell Hill to the east , with the distance between the two clusters measuring at between 8 and 10 km . The western group includes Coldrum Long Barrow , Addington Long Barrow , and the Chestnuts Long Barrow . The eastern group consists of Kit 's Coty House , Little Kit 's Coty House , the Coffin Stone , and several other stones which might have once been parts of chambered tombs . It is not known if they were all built at the same time , or whether they were constructed in succession , while similarly it is not known if they each served the same function or whether there was a hierarchy in their usage .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.