text
stringlengths 0
3.34M
|
---|
Formal statement is: lemma (in metric_space) metric_Cauchy_iff2: "Cauchy X = (\<forall>j. (\<exists>M. \<forall>m \<ge> M. \<forall>n \<ge> M. dist (X m) (X n) < inverse(real (Suc j))))" Informal statement is: A sequence in a metric space is Cauchy if and only if for every $j$, there exists an $M$ such that for all $m, n \geq M$, we have $d(x_m, x_n) < \frac{1}{j+1}$. |
/* linalg/choleskyc.c
*
* Copyright (C) 2007 Patrick Alken
* Copyright (C) 2010 Huan Wu (gsl_linalg_complex_cholesky_invert)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_errno.h>
/*
* This module contains routines related to the Cholesky decomposition
* of a complex Hermitian positive definite matrix.
*/
static void cholesky_complex_conj_vector(gsl_vector_complex *v);
/*
gsl_linalg_complex_cholesky_decomp()
Perform the Cholesky decomposition on a Hermitian positive definite
matrix. See Golub & Van Loan, "Matrix Computations" (3rd ed),
algorithm 4.2.2.
Inputs: A - (input/output) complex postive definite matrix
Return: success or error
The lower triangle of A is overwritten with the Cholesky decomposition
*/
int
gsl_linalg_complex_cholesky_decomp(gsl_matrix_complex *A)
{
const size_t N = A->size1;
if (N != A->size2)
{
GSL_ERROR("cholesky decomposition requires square matrix", GSL_ENOTSQR);
}
else
{
size_t i, j;
gsl_complex z;
double ajj;
for (j = 0; j < N; ++j)
{
z = gsl_matrix_complex_get(A, j, j);
ajj = GSL_REAL(z);
if (j > 0)
{
gsl_vector_complex_const_view aj =
gsl_matrix_complex_const_subrow(A, j, 0, j);
gsl_blas_zdotc(&aj.vector, &aj.vector, &z);
ajj -= GSL_REAL(z);
}
if (ajj <= 0.0)
{
GSL_ERROR("matrix is not positive definite", GSL_EDOM);
}
ajj = sqrt(ajj);
GSL_SET_COMPLEX(&z, ajj, 0.0);
gsl_matrix_complex_set(A, j, j, z);
if (j < N - 1)
{
gsl_vector_complex_view av =
gsl_matrix_complex_subcolumn(A, j, j + 1, N - j - 1);
if (j > 0)
{
gsl_vector_complex_view aj =
gsl_matrix_complex_subrow(A, j, 0, j);
gsl_matrix_complex_view am =
gsl_matrix_complex_submatrix(A, j + 1, 0, N - j - 1, j);
cholesky_complex_conj_vector(&aj.vector);
gsl_blas_zgemv(CblasNoTrans,
GSL_COMPLEX_NEGONE,
&am.matrix,
&aj.vector,
GSL_COMPLEX_ONE,
&av.vector);
cholesky_complex_conj_vector(&aj.vector);
}
gsl_blas_zdscal(1.0 / ajj, &av.vector);
}
}
/* Now store L^H in upper triangle */
for (i = 1; i < N; ++i)
{
for (j = 0; j < i; ++j)
{
z = gsl_matrix_complex_get(A, i, j);
gsl_matrix_complex_set(A, j, i, gsl_complex_conjugate(z));
}
}
return GSL_SUCCESS;
}
} /* gsl_linalg_complex_cholesky_decomp() */
/*
gsl_linalg_complex_cholesky_solve()
Solve A x = b where A is in cholesky form
*/
int
gsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky,
const gsl_vector_complex * b,
gsl_vector_complex * x)
{
if (cholesky->size1 != cholesky->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (cholesky->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (cholesky->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
gsl_vector_complex_memcpy (x, b);
/* solve for y using forward-substitution, L y = b */
gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x);
/* perform back-substitution, L^H x = y */
gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x);
return GSL_SUCCESS;
}
} /* gsl_linalg_complex_cholesky_solve() */
/*
gsl_linalg_complex_cholesky_svx()
Solve A x = b in place where A is in cholesky form
*/
int
gsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky,
gsl_vector_complex * x)
{
if (cholesky->size1 != cholesky->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (cholesky->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* solve for y using forward-substitution, L y = b */
gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x);
/* perform back-substitution, L^H x = y */
gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x);
return GSL_SUCCESS;
}
} /* gsl_linalg_complex_cholesky_svx() */
/******************************************************************************
gsl_linalg_complex_cholesky_invert()
Compute the inverse of an Hermitian positive definite matrix in
Cholesky form.
Inputs: LLT - matrix in cholesky form on input
A^{-1} = L^{-H} L^{-1} on output
Return: success or error
******************************************************************************/
int
gsl_linalg_complex_cholesky_invert(gsl_matrix_complex * LLT)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else
{
size_t N = LLT->size1;
size_t i, j;
gsl_vector_complex_view v1;
/* invert the lower triangle of LLT */
for (i = 0; i < N; ++i)
{
double ajj;
gsl_complex z;
j = N - i - 1;
{
gsl_complex z0 = gsl_matrix_complex_get(LLT, j, j);
ajj = 1.0 / GSL_REAL(z0);
}
GSL_SET_COMPLEX(&z, ajj, 0.0);
gsl_matrix_complex_set(LLT, j, j, z);
{
gsl_complex z1 = gsl_matrix_complex_get(LLT, j, j);
ajj = -GSL_REAL(z1);
}
if (j < N - 1)
{
gsl_matrix_complex_view m;
m = gsl_matrix_complex_submatrix(LLT, j + 1, j + 1,
N - j - 1, N - j - 1);
v1 = gsl_matrix_complex_subcolumn(LLT, j, j + 1, N - j - 1);
gsl_blas_ztrmv(CblasLower, CblasNoTrans, CblasNonUnit,
&m.matrix, &v1.vector);
gsl_blas_zdscal(ajj, &v1.vector);
}
} /* for (i = 0; i < N; ++i) */
/*
* The lower triangle of LLT now contains L^{-1}. Now compute
* A^{-1} = L^{-H} L^{-1}
*
* The (ij) element of A^{-1} is column i of conj(L^{-1}) dotted into
* column j of L^{-1}
*/
for (i = 0; i < N; ++i)
{
gsl_complex sum;
for (j = i + 1; j < N; ++j)
{
gsl_vector_complex_view v2;
v1 = gsl_matrix_complex_subcolumn(LLT, i, j, N - j);
v2 = gsl_matrix_complex_subcolumn(LLT, j, j, N - j);
/* compute Ainv[i,j] = sum_k{conj(Linv[k,i]) * Linv[k,j]} */
gsl_blas_zdotc(&v1.vector, &v2.vector, &sum);
/* store in upper triangle */
gsl_matrix_complex_set(LLT, i, j, sum);
}
/* now compute the diagonal element */
v1 = gsl_matrix_complex_subcolumn(LLT, i, i, N - i);
gsl_blas_zdotc(&v1.vector, &v1.vector, &sum);
gsl_matrix_complex_set(LLT, i, i, sum);
}
/* copy the Hermitian upper triangle to the lower triangle */
for (j = 1; j < N; j++)
{
for (i = 0; i < j; i++)
{
gsl_complex z = gsl_matrix_complex_get(LLT, i, j);
gsl_matrix_complex_set(LLT, j, i, gsl_complex_conjugate(z));
}
}
return GSL_SUCCESS;
}
} /* gsl_linalg_complex_cholesky_invert() */
/********************************************
* INTERNAL ROUTINES *
********************************************/
static void
cholesky_complex_conj_vector(gsl_vector_complex *v)
{
size_t i;
for (i = 0; i < v->size; ++i)
{
gsl_complex z = gsl_vector_complex_get(v, i);
gsl_vector_complex_set(v, i, gsl_complex_conjugate(z));
}
} /* cholesky_complex_conj_vector() */
|
[STATEMENT]
lemma finvimage_vempty[simp]: "0 -`\<^sub>\<bullet> A = 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. []\<^sub>\<circ> -`\<^sub>\<bullet> A = []\<^sub>\<circ>
[PROOF STEP]
by force |
(**
Definition of binding signatures ([BindingSig]) and translation from from binding signatures to
monads ([BindingSigToMonad]). This is defined in multiple steps:
- Binding signature to a signature with strength ([BindingSigToSignature])
- Construction of initial algebra for a signature with strength ([SignatureInitialAlgebra])
- Signature with strength and initial algebra to a HSS ([SignatureToHSS])
- Construction of a monad from a HSS ([Monad_from_hss] in MonadsFromSubstitutionSystems.v)
- Composition of these maps to get a function from binding signatures to monads ([BindingSigToMonad])
Written by: Anders Mörtberg, 2016
version for simplified notion of HSS by Ralph Matthes (2022, 2023)
the file is identical to the homonymous file in the parent directory, except for importing files from the present directory
*)
Require Import UniMath.Foundations.PartD.
Require Import UniMath.Combinatorics.Lists.
Require Import UniMath.MoreFoundations.Tactics.
Require Import UniMath.CategoryTheory.Core.Categories.
Require Import UniMath.CategoryTheory.Core.Functors.
Require Import UniMath.CategoryTheory.whiskering.
Require Import UniMath.CategoryTheory.limits.graphs.colimits.
Require Import UniMath.CategoryTheory.limits.binproducts.
Require Import UniMath.CategoryTheory.limits.bincoproducts.
Require Import UniMath.CategoryTheory.limits.coproducts.
Require Import UniMath.CategoryTheory.limits.terminal.
Require Import UniMath.CategoryTheory.limits.initial.
Require Import UniMath.CategoryTheory.FunctorAlgebras.
Require Import UniMath.CategoryTheory.FunctorCategory.
Require Import UniMath.CategoryTheory.exponentials.
Require Import UniMath.CategoryTheory.Chains.All.
Require Import UniMath.CategoryTheory.Monads.Monads.
Require Import UniMath.CategoryTheory.categories.HSET.Core.
Require Import UniMath.CategoryTheory.categories.HSET.Limits.
Require Import UniMath.CategoryTheory.categories.HSET.Colimits.
Require Import UniMath.CategoryTheory.categories.HSET.Structures.
Require Import UniMath.SubstitutionSystems.Signatures.
Require Import UniMath.SubstitutionSystems.SignatureExamples.
Require Import UniMath.SubstitutionSystems.SumOfSignatures.
Require Import UniMath.SubstitutionSystems.BinProductOfSignatures.
Require Import UniMath.SubstitutionSystems.SimplifiedHSS.SubstitutionSystems.
Require Import UniMath.SubstitutionSystems.SimplifiedHSS.LiftingInitial_alt.
Require Import UniMath.SubstitutionSystems.SimplifiedHSS.MonadsFromSubstitutionSystems.
Require Import UniMath.SubstitutionSystems.Notation.
Local Open Scope subsys.
Local Open Scope cat.
Local Notation "[ C , D ]" := (functor_category C D).
Local Notation "'chain'" := (diagram nat_graph).
(** * Definition of binding signatures *)
Section BindingSig.
(** A binding signature is a collection of lists of natural numbers indexed by types I *)
Definition BindingSig : UU := ∑ (I : UU) (h : isaset I), I → list nat.
Definition BindingSigIndex : BindingSig -> UU := pr1.
Definition BindingSigIsaset (s : BindingSig) : isaset (BindingSigIndex s) :=
pr1 (pr2 s).
Definition BindingSigMap (s : BindingSig) : BindingSigIndex s -> list nat :=
pr2 (pr2 s).
Definition make_BindingSig {I : UU} (h : isaset I) (f : I -> list nat) : BindingSig := (I,,h,,f).
(** Sum of binding signatures *)
Definition SumBindingSig : BindingSig -> BindingSig -> BindingSig.
Proof.
intros s1 s2.
use tpair.
- apply (BindingSigIndex s1 ⨿ BindingSigIndex s2).
- use tpair.
+ apply (isasetcoprod _ _ (BindingSigIsaset s1) (BindingSigIsaset s2)).
+ induction 1 as [i|i]; [ apply (BindingSigMap s1 i) | apply (BindingSigMap s2 i) ].
Defined.
End BindingSig.
(** * Translation from a binding signature to a monad
<<
S : BindingSig
|-> functor(S) : functor [C,C] [C,C]
|-> Initial (Id + functor(S))
|-> I := Initial (HSS(func(S), θ)
|-> M := Monad_from_HSS(I)
>>
*)
Section BindingSigToMonad.
Context {C : category}.
Local Notation "'[C,C]'" := (functor_category C C).
(** Form "_ o option^n" and return Id if n = 0 *)
Definition precomp_option_iter (BCC : BinCoproducts C) (TC : Terminal C) (n : nat) : functor [C,C] [C,C].
Proof.
induction n as [|n IHn].
- apply functor_identity.
- apply (pre_composition_functor _ _ _ (iter_functor1 _ (option_functor BCC TC) n)).
Defined.
Lemma is_omega_cocont_precomp_option_iter
(BCC : BinCoproducts C) (TC : Terminal C)
(CLC : Colims_of_shape nat_graph C) (n : nat) :
is_omega_cocont (precomp_option_iter BCC TC n).
Proof.
destruct n; simpl.
- apply is_omega_cocont_functor_identity.
- apply is_omega_cocont_pre_composition_functor, CLC.
Defined.
Definition precomp_option_iter_Signature (BCC : BinCoproducts C)
(TC : Terminal C) (n : nat) : Signature C C C.
Proof.
use tpair.
- exact (precomp_option_iter BCC TC n).
- destruct n; simpl.
+ apply θ_functor_identity.
+ exact (pr2 (θ_from_δ_Signature C _ (DL_iter_functor1 C (option_functor BCC TC) (option_DistributiveLaw C TC BCC) n))).
Defined.
(* will not be used, is just a confirmation of proper construction *)
Local Lemma functor_in_precomp_option_iter_Signature_ok (BCC : BinCoproducts C)
(TC : Terminal C) (n : nat) : Signature_Functor (precomp_option_iter_Signature BCC TC n) = precomp_option_iter BCC TC n.
Proof.
apply idpath.
Qed.
(* From here on all constructions need these hypotheses *)
Context (BPC : BinProducts C) (BCC : BinCoproducts C).
(** [nat] to a Signature *)
Definition Arity_to_Signature (TC : Terminal C) (xs : list nat) : Signature C C C:=
foldr1 (BinProduct_of_Signatures _ _ _ BPC)
(ConstConstSignature C C C (TerminalObject TC))
(map (precomp_option_iter_Signature BCC TC) xs).
Let BPC2 BPC := BinProducts_functor_precat C C BPC.
Let constprod_functor1 := constprod_functor1 (BPC2 BPC).
(** The H assumption follows directly if [C,C] has exponentials *)
Lemma is_omega_cocont_Arity_to_Signature
(TC : Terminal C) (CLC : Colims_of_shape nat_graph C)
(H : ∏ (F : [C,C]), is_omega_cocont (constprod_functor1 F))
(xs : list nat) :
is_omega_cocont (Arity_to_Signature TC xs).
Proof.
destruct xs as [[|n] xs].
- destruct xs; apply is_omega_cocont_constant_functor.
- induction n as [|n IHn].
+ destruct xs as [m []]; simpl.
unfold Arity_to_Signature.
apply is_omega_cocont_precomp_option_iter, CLC.
+ destruct xs as [m [k xs]].
apply is_omega_cocont_BinProduct_of_Signatures.
* apply is_omega_cocont_precomp_option_iter, CLC.
* apply (IHn (k,,xs)).
* assumption.
* intro x; apply (H x).
Defined.
(** ** Binding signature to a signature with strength *)
Definition BindingSigToSignature (TC : Terminal C)
(sig : BindingSig) (CC : Coproducts (BindingSigIndex sig) C) :
Signature C C C.
Proof.
apply (Sum_of_Signatures (BindingSigIndex sig)).
- apply CC.
- intro i; apply (Arity_to_Signature TC (BindingSigMap sig i)).
Defined.
Lemma is_omega_cocont_BindingSigToSignature
(TC : Terminal C) (CLC : Colims_of_shape nat_graph C)
(HF : ∏ (F : [C,C]), is_omega_cocont (constprod_functor1 F))
(sig : BindingSig) (CC : Coproducts (BindingSigIndex sig) C) :
is_omega_cocont (BindingSigToSignature TC sig CC).
Proof.
unfold BindingSigToSignature.
apply is_omega_cocont_Sum_of_Signatures.
now intro i; apply is_omega_cocont_Arity_to_Signature, HF.
Defined.
Let Id_H := Id_H C BCC.
(** ** Construction of initial algebra for a signature with strength *)
Definition SignatureInitialAlgebra
(IC : Initial C) (CLC : Colims_of_shape nat_graph C)
(H : Presignature C C C) (Hs : is_omega_cocont H) :
Initial (FunctorAlg (Id_H H)).
Proof.
use colimAlgInitial.
- apply (Initial_functor_precat _ _ IC).
- apply (is_omega_cocont_Id_H _ _ _ Hs).
- apply ColimsFunctorCategory_of_shape, CLC.
Defined.
(** ** Construction of datatype specified by a binding signature *)
Definition DatatypeOfBindingSig
(IC : Initial C) (TC : Terminal C) (CLC : Colims_of_shape nat_graph C)
(HF : ∏ (F : [C,C]), is_omega_cocont (constprod_functor1 F))
(sig : BindingSig) (CC : Coproducts (BindingSigIndex sig) C) :
Initial (FunctorAlg (Id_H (Presignature_Signature(BindingSigToSignature TC sig CC)))).
Proof.
apply SignatureInitialAlgebra; trivial.
now apply is_omega_cocont_BindingSigToSignature.
Defined.
Let HSS := @hss_category C BCC.
(* Redefine this here so that it uses the arguments above *)
Let InitialHSS
(IC : Initial C) (CLC : Colims_of_shape nat_graph C)
(H : Presignature C C C) (Hs : is_omega_cocont H) :
Initial (HSS H).
Proof.
apply InitialHSS; assumption.
Defined.
(** ** Signature with strength and initial algebra to a HSS *)
Definition SignatureToHSS
(IC : Initial C) (CLC : Colims_of_shape nat_graph C)
(H : Presignature C C C) (Hs : is_omega_cocont H) :
HSS H.
Proof.
now apply InitialHSS; assumption.
Defined.
(** The above HSS is initial *)
Definition SignatureToHSSisInitial
(IC : Initial C) (CLC : Colims_of_shape nat_graph C)
(H : Presignature C C C) (Hs : is_omega_cocont H) :
isInitial _ (SignatureToHSS IC CLC H Hs).
Proof.
now unfold SignatureToHSS; destruct InitialHSS.
Qed.
(* Redefine this here so that it uses the arguments above *)
Let Monad_from_hss (H : Signature C C C) : HSS H → Monad C.
Proof.
exact (Monad_from_hss _ BCC H).
Defined.
(** ** Function from binding signatures to monads *)
Definition BindingSigToMonad
(TC : Terminal C) (IC : Initial C) (CLC : Colims_of_shape nat_graph C)
(HF : ∏ (F : [C,C]), is_omega_cocont (constprod_functor1 F))
(sig : BindingSig)
(CC : Coproducts (BindingSigIndex sig) C) :
Monad C.
Proof.
use Monad_from_hss.
- apply (BindingSigToSignature TC sig CC).
- apply (SignatureToHSS IC CLC).
apply (is_omega_cocont_BindingSigToSignature TC CLC HF _ _).
Defined.
End BindingSigToMonad.
(** * Specialized versions of some of the above functions for HSET *)
Section BindingSigToMonadHSET.
(** ** Binding signature to signature with strength for HSET *)
Definition BindingSigToSignatureHSET (sig : BindingSig) : Signature HSET HSET HSET.
Proof.
use BindingSigToSignature.
- apply BinProductsHSET.
- apply BinCoproductsHSET.
- apply TerminalHSET.
- apply sig.
- apply CoproductsHSET, (BindingSigIsaset sig).
Defined.
Lemma is_omega_cocont_BindingSigToSignatureHSET (sig : BindingSig) :
is_omega_cocont (BindingSigToSignatureHSET sig).
Proof.
apply is_omega_cocont_Sum_of_Signatures.
intro i; apply is_omega_cocont_Arity_to_Signature.
+ apply ColimsHSET_of_shape.
+ intros F.
apply is_omega_cocont_constprod_functor1.
apply Exponentials_functor_HSET.
Defined.
(** ** Construction of initial algebra for a signature with strength for HSET *)
Definition SignatureInitialAlgebraHSET (s : Presignature HSET _ _) (Hs : is_omega_cocont s) :
Initial (FunctorAlg (Id_H _ BinCoproductsHSET s)).
Proof.
apply SignatureInitialAlgebra; try assumption.
- apply InitialHSET.
- apply ColimsHSET_of_shape.
Defined.
(** ** Binding signature to a monad for HSET *)
Definition BindingSigToMonadHSET : BindingSig → Monad HSET.
Proof.
intros sig; use (BindingSigToMonad _ _ _ _ _ _ sig).
- apply BinProductsHSET.
- apply BinCoproductsHSET.
- apply TerminalHSET.
- apply InitialHSET.
- apply ColimsHSET_of_shape.
- intros F.
apply is_omega_cocont_constprod_functor1.
apply Exponentials_functor_HSET.
- apply CoproductsHSET.
apply BindingSigIsaset.
Defined.
End BindingSigToMonadHSET.
(* Old code for translation from lists of lists *)
(* (* [[nat]] to Signature *) *)
(* Definition SigToSignature : Sig -> Signature HSET has_homsets_HSET. *)
(* Proof. *)
(* intro xs. *)
(* generalize (map_list Arity_to_Signature xs). *)
(* apply foldr1_list. *)
(* - apply (BinSum_of_Signatures _ _ BinCoproductsHSET). *)
(* - apply IdSignature. *)
(* Defined. *)
(* Lemma is_omega_cocont_SigToSignature (s : Sig) : is_omega_cocont (SigToSignature s). *)
(* Proof. *)
(* destruct s as [n xs]. *)
(* destruct n. *)
(* - destruct xs. *)
(* apply (is_omega_cocont_functor_identity has_homsets_HSET2). *)
(* - induction n. *)
(* + destruct xs as [xs []]; simpl. *)
(* apply is_omega_cocont_Arity_to_Signature. *)
(* + destruct xs as [m xs]. *)
(* generalize (IHn xs). *)
(* destruct xs. *)
(* intro IH. *)
(* apply is_omega_cocont_BinSum_of_Signatures. *)
(* apply is_omega_cocont_Arity_to_Signature. *)
(* apply IH. *)
(* apply BinProductsHSET. *)
(* Defined. *)
|
From Coq Require Import String List ZArith.
From compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.
Local Open Scope Z_scope.
Local Open Scope string_scope.
Module Info.
Definition version := "3.8".
Definition build_number := "".
Definition build_tag := "".
Definition build_branch := "".
Definition arch := "x86".
Definition model := "32sse2".
Definition abi := "standard".
Definition bitsize := 32.
Definition big_endian := false.
Definition source_file := "triang.c".
Definition normalized := true.
End Info.
Definition _Apile_add : ident := 77%positive.
Definition _Apile_count : ident := 78%positive.
Definition _Onepile_add : ident := 74%positive.
Definition _Onepile_count : ident := 75%positive.
Definition _Onepile_init : ident := 73%positive.
Definition _Pile_add : ident := 65%positive.
Definition _Pile_count : ident := 68%positive.
Definition _Pile_free : ident := 70%positive.
Definition _Pile_new : ident := 64%positive.
Definition _Triang_nth : ident := 80%positive.
Definition ___builtin_annot : ident := 22%positive.
Definition ___builtin_annot_intval : ident := 23%positive.
Definition ___builtin_bswap : ident := 7%positive.
Definition ___builtin_bswap16 : ident := 9%positive.
Definition ___builtin_bswap32 : ident := 8%positive.
Definition ___builtin_bswap64 : ident := 6%positive.
Definition ___builtin_clz : ident := 10%positive.
Definition ___builtin_clzl : ident := 11%positive.
Definition ___builtin_clzll : ident := 12%positive.
Definition ___builtin_ctz : ident := 13%positive.
Definition ___builtin_ctzl : ident := 14%positive.
Definition ___builtin_ctzll : ident := 15%positive.
Definition ___builtin_debug : ident := 58%positive.
Definition ___builtin_fabs : ident := 16%positive.
Definition ___builtin_fabsf : ident := 17%positive.
Definition ___builtin_fmadd : ident := 50%positive.
Definition ___builtin_fmax : ident := 48%positive.
Definition ___builtin_fmin : ident := 49%positive.
Definition ___builtin_fmsub : ident := 51%positive.
Definition ___builtin_fnmadd : ident := 52%positive.
Definition ___builtin_fnmsub : ident := 53%positive.
Definition ___builtin_fsqrt : ident := 18%positive.
Definition ___builtin_membar : ident := 24%positive.
Definition ___builtin_memcpy_aligned : ident := 20%positive.
Definition ___builtin_read16_reversed : ident := 54%positive.
Definition ___builtin_read32_reversed : ident := 55%positive.
Definition ___builtin_sel : ident := 21%positive.
Definition ___builtin_sqrt : ident := 19%positive.
Definition ___builtin_va_arg : ident := 26%positive.
Definition ___builtin_va_copy : ident := 27%positive.
Definition ___builtin_va_end : ident := 28%positive.
Definition ___builtin_va_start : ident := 25%positive.
Definition ___builtin_write16_reversed : ident := 56%positive.
Definition ___builtin_write32_reversed : ident := 57%positive.
Definition ___compcert_i64_dtos : ident := 33%positive.
Definition ___compcert_i64_dtou : ident := 34%positive.
Definition ___compcert_i64_sar : ident := 45%positive.
Definition ___compcert_i64_sdiv : ident := 39%positive.
Definition ___compcert_i64_shl : ident := 43%positive.
Definition ___compcert_i64_shr : ident := 44%positive.
Definition ___compcert_i64_smod : ident := 41%positive.
Definition ___compcert_i64_smulh : ident := 46%positive.
Definition ___compcert_i64_stod : ident := 35%positive.
Definition ___compcert_i64_stof : ident := 37%positive.
Definition ___compcert_i64_udiv : ident := 40%positive.
Definition ___compcert_i64_umod : ident := 42%positive.
Definition ___compcert_i64_umulh : ident := 47%positive.
Definition ___compcert_i64_utod : ident := 36%positive.
Definition ___compcert_i64_utof : ident := 38%positive.
Definition ___compcert_va_composite : ident := 32%positive.
Definition ___compcert_va_float64 : ident := 31%positive.
Definition ___compcert_va_int32 : ident := 29%positive.
Definition ___compcert_va_int64 : ident := 30%positive.
Definition _a_pile : ident := 76%positive.
Definition _c : ident := 67%positive.
Definition _exit : ident := 61%positive.
Definition _free : ident := 60%positive.
Definition _head : ident := 4%positive.
Definition _i : ident := 79%positive.
Definition _list : ident := 2%positive.
Definition _main : ident := 71%positive.
Definition _malloc : ident := 59%positive.
Definition _n : ident := 1%positive.
Definition _next : ident := 3%positive.
Definition _p : ident := 62%positive.
Definition _pile : ident := 5%positive.
Definition _q : ident := 66%positive.
Definition _r : ident := 69%positive.
Definition _surely_malloc : ident := 63%positive.
Definition _the_pile : ident := 72%positive.
Definition _t'1 : ident := 81%positive.
Definition _t'2 : ident := 82%positive.
Definition f_Triang_nth := {|
fn_return := tint;
fn_callconv := cc_default;
fn_params := ((_n, tint) :: nil);
fn_vars := nil;
fn_temps := ((_i, tint) :: (_c, tint) ::
(_p, (tptr (Tstruct _pile noattr))) :: (_t'2, tint) ::
(_t'1, (tptr (Tstruct _pile noattr))) :: nil);
fn_body :=
(Ssequence
(Ssequence
(Scall (Some _t'1)
(Evar _Pile_new (Tfunction Tnil (tptr (Tstruct _pile noattr))
cc_default)) nil)
(Sset _p (Etempvar _t'1 (tptr (Tstruct _pile noattr)))))
(Ssequence
(Ssequence
(Sset _i (Econst_int (Int.repr 0) tint))
(Sloop
(Ssequence
(Sifthenelse (Ebinop Olt (Etempvar _i tint) (Etempvar _n tint)
tint)
Sskip
Sbreak)
(Scall None
(Evar _Pile_add (Tfunction
(Tcons (tptr (Tstruct _pile noattr))
(Tcons tint Tnil)) tvoid cc_default))
((Etempvar _p (tptr (Tstruct _pile noattr))) ::
(Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)
tint) :: nil)))
(Sset _i
(Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)
tint))))
(Ssequence
(Ssequence
(Scall (Some _t'2)
(Evar _Pile_count (Tfunction
(Tcons (tptr (Tstruct _pile noattr)) Tnil) tint
cc_default))
((Etempvar _p (tptr (Tstruct _pile noattr))) :: nil))
(Sset _c (Etempvar _t'2 tint)))
(Ssequence
(Scall None
(Evar _Pile_free (Tfunction
(Tcons (tptr (Tstruct _pile noattr)) Tnil) tvoid
cc_default))
((Etempvar _p (tptr (Tstruct _pile noattr))) :: nil))
(Sreturn (Some (Etempvar _c tint)))))))
|}.
Definition composites : list composite_definition :=
nil.
Definition global_definitions : list (ident * globdef fundef type) :=
((___builtin_bswap64,
Gfun(External (EF_builtin "__builtin_bswap64"
(mksignature (AST.Tlong :: nil) AST.Tlong cc_default))
(Tcons tulong Tnil) tulong cc_default)) ::
(___builtin_bswap,
Gfun(External (EF_builtin "__builtin_bswap"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons tuint Tnil) tuint cc_default)) ::
(___builtin_bswap32,
Gfun(External (EF_builtin "__builtin_bswap32"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons tuint Tnil) tuint cc_default)) ::
(___builtin_bswap16,
Gfun(External (EF_builtin "__builtin_bswap16"
(mksignature (AST.Tint :: nil) AST.Tint16unsigned
cc_default)) (Tcons tushort Tnil) tushort cc_default)) ::
(___builtin_clz,
Gfun(External (EF_builtin "__builtin_clz"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons tuint Tnil) tint cc_default)) ::
(___builtin_clzl,
Gfun(External (EF_builtin "__builtin_clzl"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons tuint Tnil) tint cc_default)) ::
(___builtin_clzll,
Gfun(External (EF_builtin "__builtin_clzll"
(mksignature (AST.Tlong :: nil) AST.Tint cc_default))
(Tcons tulong Tnil) tint cc_default)) ::
(___builtin_ctz,
Gfun(External (EF_builtin "__builtin_ctz"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons tuint Tnil) tint cc_default)) ::
(___builtin_ctzl,
Gfun(External (EF_builtin "__builtin_ctzl"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons tuint Tnil) tint cc_default)) ::
(___builtin_ctzll,
Gfun(External (EF_builtin "__builtin_ctzll"
(mksignature (AST.Tlong :: nil) AST.Tint cc_default))
(Tcons tulong Tnil) tint cc_default)) ::
(___builtin_fabs,
Gfun(External (EF_builtin "__builtin_fabs"
(mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))
(Tcons tdouble Tnil) tdouble cc_default)) ::
(___builtin_fabsf,
Gfun(External (EF_builtin "__builtin_fabsf"
(mksignature (AST.Tsingle :: nil) AST.Tsingle cc_default))
(Tcons tfloat Tnil) tfloat cc_default)) ::
(___builtin_fsqrt,
Gfun(External (EF_builtin "__builtin_fsqrt"
(mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))
(Tcons tdouble Tnil) tdouble cc_default)) ::
(___builtin_sqrt,
Gfun(External (EF_builtin "__builtin_sqrt"
(mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))
(Tcons tdouble Tnil) tdouble cc_default)) ::
(___builtin_memcpy_aligned,
Gfun(External (EF_builtin "__builtin_memcpy_aligned"
(mksignature
(AST.Tint :: AST.Tint :: AST.Tint :: AST.Tint :: nil)
AST.Tvoid cc_default))
(Tcons (tptr tvoid)
(Tcons (tptr tvoid) (Tcons tuint (Tcons tuint Tnil)))) tvoid
cc_default)) ::
(___builtin_sel,
Gfun(External (EF_builtin "__builtin_sel"
(mksignature (AST.Tint :: nil) AST.Tvoid
{|cc_vararg:=true; cc_unproto:=false; cc_structret:=false|}))
(Tcons tbool Tnil) tvoid
{|cc_vararg:=true; cc_unproto:=false; cc_structret:=false|})) ::
(___builtin_annot,
Gfun(External (EF_builtin "__builtin_annot"
(mksignature (AST.Tint :: nil) AST.Tvoid
{|cc_vararg:=true; cc_unproto:=false; cc_structret:=false|}))
(Tcons (tptr tschar) Tnil) tvoid
{|cc_vararg:=true; cc_unproto:=false; cc_structret:=false|})) ::
(___builtin_annot_intval,
Gfun(External (EF_builtin "__builtin_annot_intval"
(mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint
cc_default)) (Tcons (tptr tschar) (Tcons tint Tnil))
tint cc_default)) ::
(___builtin_membar,
Gfun(External (EF_builtin "__builtin_membar"
(mksignature nil AST.Tvoid cc_default)) Tnil tvoid
cc_default)) ::
(___builtin_va_start,
Gfun(External (EF_builtin "__builtin_va_start"
(mksignature (AST.Tint :: nil) AST.Tvoid cc_default))
(Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::
(___builtin_va_arg,
Gfun(External (EF_builtin "__builtin_va_arg"
(mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid
cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))
tvoid cc_default)) ::
(___builtin_va_copy,
Gfun(External (EF_builtin "__builtin_va_copy"
(mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid
cc_default))
(Tcons (tptr tvoid) (Tcons (tptr tvoid) Tnil)) tvoid cc_default)) ::
(___builtin_va_end,
Gfun(External (EF_builtin "__builtin_va_end"
(mksignature (AST.Tint :: nil) AST.Tvoid cc_default))
(Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::
(___compcert_va_int32,
Gfun(External (EF_external "__compcert_va_int32"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons (tptr tvoid) Tnil) tuint cc_default)) ::
(___compcert_va_int64,
Gfun(External (EF_external "__compcert_va_int64"
(mksignature (AST.Tint :: nil) AST.Tlong cc_default))
(Tcons (tptr tvoid) Tnil) tulong cc_default)) ::
(___compcert_va_float64,
Gfun(External (EF_external "__compcert_va_float64"
(mksignature (AST.Tint :: nil) AST.Tfloat cc_default))
(Tcons (tptr tvoid) Tnil) tdouble cc_default)) ::
(___compcert_va_composite,
Gfun(External (EF_external "__compcert_va_composite"
(mksignature (AST.Tint :: AST.Tint :: nil) AST.Tint
cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))
(tptr tvoid) cc_default)) ::
(___compcert_i64_dtos,
Gfun(External (EF_runtime "__compcert_i64_dtos"
(mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))
(Tcons tdouble Tnil) tlong cc_default)) ::
(___compcert_i64_dtou,
Gfun(External (EF_runtime "__compcert_i64_dtou"
(mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))
(Tcons tdouble Tnil) tulong cc_default)) ::
(___compcert_i64_stod,
Gfun(External (EF_runtime "__compcert_i64_stod"
(mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))
(Tcons tlong Tnil) tdouble cc_default)) ::
(___compcert_i64_utod,
Gfun(External (EF_runtime "__compcert_i64_utod"
(mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))
(Tcons tulong Tnil) tdouble cc_default)) ::
(___compcert_i64_stof,
Gfun(External (EF_runtime "__compcert_i64_stof"
(mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))
(Tcons tlong Tnil) tfloat cc_default)) ::
(___compcert_i64_utof,
Gfun(External (EF_runtime "__compcert_i64_utof"
(mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))
(Tcons tulong Tnil) tfloat cc_default)) ::
(___compcert_i64_sdiv,
Gfun(External (EF_runtime "__compcert_i64_sdiv"
(mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong
cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong
cc_default)) ::
(___compcert_i64_udiv,
Gfun(External (EF_runtime "__compcert_i64_udiv"
(mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong
cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong
cc_default)) ::
(___compcert_i64_smod,
Gfun(External (EF_runtime "__compcert_i64_smod"
(mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong
cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong
cc_default)) ::
(___compcert_i64_umod,
Gfun(External (EF_runtime "__compcert_i64_umod"
(mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong
cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong
cc_default)) ::
(___compcert_i64_shl,
Gfun(External (EF_runtime "__compcert_i64_shl"
(mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong
cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong
cc_default)) ::
(___compcert_i64_shr,
Gfun(External (EF_runtime "__compcert_i64_shr"
(mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong
cc_default)) (Tcons tulong (Tcons tint Tnil)) tulong
cc_default)) ::
(___compcert_i64_sar,
Gfun(External (EF_runtime "__compcert_i64_sar"
(mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong
cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong
cc_default)) ::
(___compcert_i64_smulh,
Gfun(External (EF_runtime "__compcert_i64_smulh"
(mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong
cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong
cc_default)) ::
(___compcert_i64_umulh,
Gfun(External (EF_runtime "__compcert_i64_umulh"
(mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong
cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong
cc_default)) ::
(___builtin_fmax,
Gfun(External (EF_builtin "__builtin_fmax"
(mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat
cc_default)) (Tcons tdouble (Tcons tdouble Tnil))
tdouble cc_default)) ::
(___builtin_fmin,
Gfun(External (EF_builtin "__builtin_fmin"
(mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat
cc_default)) (Tcons tdouble (Tcons tdouble Tnil))
tdouble cc_default)) ::
(___builtin_fmadd,
Gfun(External (EF_builtin "__builtin_fmadd"
(mksignature
(AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)
AST.Tfloat cc_default))
(Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble
cc_default)) ::
(___builtin_fmsub,
Gfun(External (EF_builtin "__builtin_fmsub"
(mksignature
(AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)
AST.Tfloat cc_default))
(Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble
cc_default)) ::
(___builtin_fnmadd,
Gfun(External (EF_builtin "__builtin_fnmadd"
(mksignature
(AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)
AST.Tfloat cc_default))
(Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble
cc_default)) ::
(___builtin_fnmsub,
Gfun(External (EF_builtin "__builtin_fnmsub"
(mksignature
(AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)
AST.Tfloat cc_default))
(Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble
cc_default)) ::
(___builtin_read16_reversed,
Gfun(External (EF_builtin "__builtin_read16_reversed"
(mksignature (AST.Tint :: nil) AST.Tint16unsigned
cc_default)) (Tcons (tptr tushort) Tnil) tushort
cc_default)) ::
(___builtin_read32_reversed,
Gfun(External (EF_builtin "__builtin_read32_reversed"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons (tptr tuint) Tnil) tuint cc_default)) ::
(___builtin_write16_reversed,
Gfun(External (EF_builtin "__builtin_write16_reversed"
(mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid
cc_default)) (Tcons (tptr tushort) (Tcons tushort Tnil))
tvoid cc_default)) ::
(___builtin_write32_reversed,
Gfun(External (EF_builtin "__builtin_write32_reversed"
(mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid
cc_default)) (Tcons (tptr tuint) (Tcons tuint Tnil))
tvoid cc_default)) ::
(___builtin_debug,
Gfun(External (EF_external "__builtin_debug"
(mksignature (AST.Tint :: nil) AST.Tvoid
{|cc_vararg:=true; cc_unproto:=false; cc_structret:=false|}))
(Tcons tint Tnil) tvoid
{|cc_vararg:=true; cc_unproto:=false; cc_structret:=false|})) ::
(_Pile_new,
Gfun(External (EF_external "Pile_new"
(mksignature nil AST.Tint cc_default)) Tnil
(tptr (Tstruct _pile noattr)) cc_default)) ::
(_Pile_add,
Gfun(External (EF_external "Pile_add"
(mksignature (AST.Tint :: AST.Tint :: nil) AST.Tvoid
cc_default))
(Tcons (tptr (Tstruct _pile noattr)) (Tcons tint Tnil)) tvoid
cc_default)) ::
(_Pile_count,
Gfun(External (EF_external "Pile_count"
(mksignature (AST.Tint :: nil) AST.Tint cc_default))
(Tcons (tptr (Tstruct _pile noattr)) Tnil) tint cc_default)) ::
(_Pile_free,
Gfun(External (EF_external "Pile_free"
(mksignature (AST.Tint :: nil) AST.Tvoid cc_default))
(Tcons (tptr (Tstruct _pile noattr)) Tnil) tvoid cc_default)) ::
(_Triang_nth, Gfun(Internal f_Triang_nth)) :: nil).
Definition public_idents : list ident :=
(_Triang_nth :: _Pile_free :: _Pile_count :: _Pile_add :: _Pile_new ::
___builtin_debug :: ___builtin_write32_reversed ::
___builtin_write16_reversed :: ___builtin_read32_reversed ::
___builtin_read16_reversed :: ___builtin_fnmsub :: ___builtin_fnmadd ::
___builtin_fmsub :: ___builtin_fmadd :: ___builtin_fmin ::
___builtin_fmax :: ___compcert_i64_umulh :: ___compcert_i64_smulh ::
___compcert_i64_sar :: ___compcert_i64_shr :: ___compcert_i64_shl ::
___compcert_i64_umod :: ___compcert_i64_smod :: ___compcert_i64_udiv ::
___compcert_i64_sdiv :: ___compcert_i64_utof :: ___compcert_i64_stof ::
___compcert_i64_utod :: ___compcert_i64_stod :: ___compcert_i64_dtou ::
___compcert_i64_dtos :: ___compcert_va_composite ::
___compcert_va_float64 :: ___compcert_va_int64 :: ___compcert_va_int32 ::
___builtin_va_end :: ___builtin_va_copy :: ___builtin_va_arg ::
___builtin_va_start :: ___builtin_membar :: ___builtin_annot_intval ::
___builtin_annot :: ___builtin_sel :: ___builtin_memcpy_aligned ::
___builtin_sqrt :: ___builtin_fsqrt :: ___builtin_fabsf ::
___builtin_fabs :: ___builtin_ctzll :: ___builtin_ctzl :: ___builtin_ctz ::
___builtin_clzll :: ___builtin_clzl :: ___builtin_clz ::
___builtin_bswap16 :: ___builtin_bswap32 :: ___builtin_bswap ::
___builtin_bswap64 :: nil).
Definition prog : Clight.program :=
mkprogram composites global_definitions public_idents _main Logic.I.
|
module Experiment
using JuMP, COSMO
using Statistics, LinearAlgebra, Random
using Plots
using MATLAB
using FFTW
# Write your package code here.
include("data.jl")
include("position.jl")
include("vector_matrix.jl")
include("solver.jl")
include("basic_function.jl")
include("plot_map.jl")
end
|
function [C,A,G,B] = bekk_parameter_transform(parameters,p,o,q,k,type)
% Parameter transformation for BEKK(p,o,q) multivariate volatility model simulation and estimation
%
% USAGE:
% [C,A,G,B] = bekk_parameter_transform(PARAMETERS,P,O,Q,K,TYPE)
%
% INPUTS:
% PARAMETERS - Vector of parameters governing the dynamics. See BEKK or BEKK_SIMULATE
% P - Positive, scalar integer representing the number of symmetric innovations
% O - Non-negative, scalar integer representing the number of asymmetric innovations
% Q - Non-negative, scalar integer representing the number of conditional covariance lags
% K - Number of assets
% TYPE - Integer indicating type
% 1: Scalar
% 2: Diagonal
% 3: Full
%
% OUTPUTS:
% C - K by K covariance model intercept
% A - K by K by P matrix of symmetric innovation parameters
% G - K by K by O matrix of asymmetric innovation parameters
% B - K by K by Q matrix of smoothing parameters
%
% COMMENTS:
%
% See also BEKK, BEKK_SIMULATE, BEKK_LIKELIHOOD
if type==1
numParams = 1;
elseif type==2
numParams = k;
else
numParams = k*k;
end
k2 = k*(k+1)/2;
C = parameters(1:k2);
C = vec2chol(C);
C = C*C';
offset = k2;
[V,D] = eig(C);
D = diag(D);
if (min(D))<(2*eps*max(D))
D((D/max(D))<eps) = 2*max(D)*eps;
C = V*diag(D)*V';
C=(C+C)/2;
end
m = p+o+q;
temp = zeros(k,k,m);
for j=1:m
tempP = parameters(offset+(1:numParams));
offset = offset+numParams;
if type==1
temp(:,:,j) = tempP*eye(k);
elseif type==2
temp(:,:,j) = diag(tempP);
else
temp(:,:,j) = reshape(tempP,k,k);
end
end
A = temp(:,:,1:p);
G = temp(:,:,p+1:p+o);
B = temp(:,:,p+o+1:p+o+q); |
open import Data.Product using ( ∃ ; _×_ ; _,_ ; proj₁ ; proj₂ )
open import Relation.Unary using ( _∈_ )
open import Web.Semantic.DL.TBox.Interp using ( Δ ; _⊨_≈_ ) renaming
( Interp to Interp′ ; emp to emp′ )
open import Web.Semantic.DL.Signature using ( Signature )
open import Web.Semantic.Util using ( False ; id )
module Web.Semantic.DL.ABox.Interp where
infixr 4 _,_
infixr 5 _*_
{-
An interpretation of a signature Σ (made of concept and role names)
over a set X of individuals consists of
- a Signature interpreation I
- a mapping from X do Δ I, the domain of interpretation of I
Note: In RDF the members of X are sets of IRIs, BNodes or Literals, but
IRIs can also refer to TBox elements.
-}
data Interp (Σ : Signature) (X : Set) : Set₁ where
-- I is a full Interpreation (Interp')
-- The function X → Δ {Σ} I interprets the variables in X
_,_ : ∀ I → (X → Δ {Σ} I) → (Interp Σ X)
-- extract the Signature Interpretation, forgetting the interpretation of variables
⌊_⌋ : ∀ {Σ X} → Interp Σ X → Interp′ Σ
⌊ I , i ⌋ = I
-- return the individuals function for an interpretation
ind : ∀ {Σ X} → (I : Interp Σ X) → X → Δ ⌊ I ⌋
ind (I , i) = i
-- paired individuals function for an interpretation, useful for relations/roles
ind² : ∀ {Σ X} → (I : Interp Σ X) → (X × X) → (Δ ⌊ I ⌋ × Δ ⌊ I ⌋)
ind² I (x , y) = (ind I x , ind I y)
-- why * ?
_*_ : ∀ {Σ X Y} → (Y → X) → Interp Σ X → Interp Σ Y
f * I = (⌊ I ⌋ , λ y → ind I (f y))
-- Empty interpretation
emp : ∀ {Σ} → Interp Σ False
emp = (emp′ , id)
data Surjective {Σ X} (I : Interp Σ X) : Set where
-- y is a variable i.e. y : X
-- (ind I y), x : Δ
-- all elements x of the domain Δ, have a variable y that it is an interpretation of
surj : (∀ x → ∃ λ y → ⌊ I ⌋ ⊨ x ≈ ind I y) → (I ∈ Surjective)
ind⁻¹ : ∀ {Σ X} {I : Interp Σ X} → (I ∈ Surjective) → (Δ ⌊ I ⌋ → X)
ind⁻¹ (surj i) x = proj₁ (i x)
surj✓ : ∀ {Σ X} {I : Interp Σ X} (I∈Surj : I ∈ Surjective) → ∀ x → (⌊ I ⌋ ⊨ x ≈ ind I (ind⁻¹ I∈Surj x))
surj✓ (surj i) x = proj₂ (i x)
|
/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */
/**
* \file boost/numeric/ublasx/operation/mldivide.hpp
*
* \brief Matrix left division.
*
* Inspired by the \c mldivide MATLAB function.
*
* \author Marco Guazzone ([email protected])
*
* <hr/>
*
* Copyright (c) 2012, Marco Guazzone
*
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_NUMERIC_UBLASX_MLDIVIDE_HPP
#define BOOST_NUMERIC_UBLASX_MLDIVIDE_HPP
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublasx/operation/lu.hpp>
namespace boost { namespace numeric { namespace ublasx {
using namespace ::boost::numeric::ublas;
template<typename AMatrixT,
typename BVectorT>
BOOST_UBLAS_INLINE
typename matrix_traits<AMatrixT>::size_type mldivide_inplace(matrix_expression<AMatrixT> const& A,
vector_container<BVectorT>& b)
{
return lu_solve_inplace(A, b);
}
template<typename AMatrixT,
typename BVectorT,
typename XVectorT>
BOOST_UBLAS_INLINE
typename matrix_traits<AMatrixT>::size_type mldivide(matrix_expression<AMatrixT> const& A,
vector_expression<BVectorT> const& b,
vector_container<XVectorT>& x)
{
return lu_solve(A, b, x());
}
template<typename AMatrixT,
typename BMatrixT>
BOOST_UBLAS_INLINE
typename matrix_traits<AMatrixT>::size_type mldivide_inplace(matrix_expression<AMatrixT> const& A,
matrix_container<BMatrixT>& B)
{
return lu_solve_inplace(A, B);
}
template<typename AMatrixT,
typename BMatrixT,
typename XMatrixT>
BOOST_UBLAS_INLINE
typename matrix_traits<AMatrixT>::size_type mldivide(matrix_expression<AMatrixT> const& A,
matrix_expression<BMatrixT> const& B,
matrix_container<XMatrixT>& X)
{
return lu_solve(A, B, X());
}
}}} // Namespace boost::numeric::ublasx
#endif // BOOST_NUMERIC_UBLASX_MLDIVIDE_HPP
|
If $f$ is a function from a vector space to itself such that $f(b_1 + b_2) = f(b_1) + f(b_2)$ and $f(r b) = r f(b)$ for all $b_1, b_2 \in V$ and $r \in \mathbb{R}$, then $f$ is linear. |
#pragma once
#include "rapidjson/pointer.h"
#include "collect_paths_struct.hpp"
#include "collect_paths_json_doc.hpp"
#include "json_doc_converter.hpp"
#include "json_doc_io.hpp"
#include "value_printer.hpp"
#include "JsonValue.hpp"
#include "silver_bullets/fs_ns_workaround.hpp"
#include <map>
#include <boost/optional.hpp>
namespace silver_bullets {
namespace iterate_struct {
class ConfigLoader
{
public:
static std::string findConfigFile(const std::string& name)
{
using namespace std::filesystem;
if (name.empty())
return std::string();
else if (exists(name))
return current_path() / name;
else {
auto searchConfig = [&] (const char *env) {
auto dir = getenv(env);
if (dir) {
auto result = std::string(path(dir) / name);
if (exists(result))
return result;
}
return std::string();
};
auto result = searchConfig("HOME");
if (result.empty())
result = searchConfig("USERPROFILE");
return result;
}
}
template<class Overrider>
ConfigLoader(
std::istream& s,
const std::string& origin,
Overrider configOverrider)
{
load(s, origin);
configOverrider(*this);
}
template<class Overrider>
ConfigLoader(
const std::string& fileName,
Overrider configOverrider)
{
load(fileName);
configOverrider(*this);
}
template<class Overrider>
explicit ConfigLoader(Overrider configOverrider)
{
configOverrider(*this);
}
explicit ConfigLoader(const std::string& fileName)
{
load(fileName);
}
template<class T>
ConfigLoader& setValue(const T& value, const std::string& path, const std::string& origin)
{
auto val = iterate_struct::to_json(value, m_config.GetAllocator());
rapidjson::Pointer(path.c_str()).Create(m_config).Swap(val);
m_configParamOrigin[path] = origin;
return *this;
}
template<class T, class Validator=DefaultValidator<>>
T value(Validator&& validator = Validator{}) const {
return iterate_struct::from_json_doc<T>(m_config, std::move(validator));
}
template<class T>
T valueAt(const std::string& path, const T& defaultValue) const
{
auto val = rapidjson::Pointer(path.c_str()).Get(m_config);
return val? iterate_struct::from_json<T>(*val): defaultValue;
}
template<class T>
T valueAt(const std::string& path) const
{
auto val = rapidjson::Pointer(path.c_str()).Get(m_config);
if (!val)
throw std::runtime_error(std::string("Value at path '") + path + "' is not found");
return iterate_struct::from_json<T>(*val);
}
ConfigLoader& setOptionalString(const boost::optional<std::string>& maybe, const std::string& path, const std::string& origin)
{
if (maybe)
setValue(maybe.get().c_str(), path, origin);
return *this;
}
const rapidjson::Document& config() const {
return m_config;
}
const std::map<std::string, std::string>& configParamOrigin() const {
return m_configParamOrigin;
}
private:
rapidjson::Document m_config;
std::map<std::string, std::string> m_configParamOrigin;
void load(const std::string& fileName)
{
std::ifstream s(fileName);
if (!s.is_open())
throw std::runtime_error(std::string("Failed to open input file '")+fileName+"'");
load(s, fileName);
}
void load(std::istream& s, const std::string& origin)
{
m_config = read_json_doc(s);
for (auto& path : iterate_struct::collect_paths(m_config, true))
m_configParamOrigin[path] = origin;
}
};
} // namespace iterate_struct
} // namespace silver_bullets
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module FEECa.FiniteElementTest where
import Control.Monad ( liftM )
import FEECa.Internal.Form hiding ( inner )
import FEECa.Internal.Spaces
import qualified FEECa.Internal.MultiIndex as MI
import qualified FEECa.Internal.Vector as V
import qualified FEECa.Internal.Simplex as S
import FEECa.Utility.Combinatorics
import FEECa.Utility.Print
import FEECa.Utility.Utility
import FEECa.FiniteElementSpace
import qualified FEECa.Polynomial as P
import qualified FEECa.PolynomialDifferentialForm as DF
import qualified FEECa.Bernstein as B
import FEECa.Utility.Test
import FEECa.Internal.SimplexTest
import qualified Test.QuickCheck as Q
import Test.QuickCheck ( (==>) )
import qualified Numeric.LinearAlgebra.HMatrix as M
--------------------------------------------------------------------------------
-- Random Finite Element Space
--------------------------------------------------------------------------------
max_n = 3
max_r = 3
max_k = 3
arbitraryPL :: (Int -> Int -> Simplex -> FiniteElementSpace)
-> Q.Gen FiniteElementSpace
arbitraryPL cpl = do
[n,r,k] <- mapM Q.choose [(1,max_n), (0,max_r), (0,max_k)]
liftM (cpl r k) (arbitrarySimplex n)
arbitraryPrLk :: Q.Gen FiniteElementSpace
arbitraryPrLk = arbitraryPL PrLk
arbitraryPrmLk :: Q.Gen FiniteElementSpace
arbitraryPrmLk = arbitraryPL PrmLk
instance Q.Arbitrary FiniteElementSpace where
arbitrary = arbitraryPrLk
n = 4
--------------------------------------------------------------------------------
-- Whitney Forms
--------------------------------------------------------------------------------
data WhitneyTest = WhitneyTest Simplex
deriving Show
instance Q.Arbitrary WhitneyTest where
arbitrary = do k <- Q.choose (1,n)
liftM WhitneyTest (arbitrarySubsimplex k n)
prop_whitney_integral :: WhitneyTest -> Bool
prop_whitney_integral (WhitneyTest t) =
abs (DF.integrate t (whitneyForm t [0..k]))
`eqNum` (1 / fromInt (factorial k))
where k = S.topologicalDimension t
--------------------------------------------------------------------------------
-- Psi Forms
--------------------------------------------------------------------------------
data PsiTest = PsiTest Simplex Simplex MI.MultiIndex Vector
deriving Show
instance Q.Arbitrary PsiTest where
arbitrary = do
k <- Q.choose (1,n)
t <- arbitrarySimplex n
f <- Q.elements $ S.subsimplices t k
r <- Q.choose (0,10)
mi <- liftM (MI.extend n (S.sigma f)) (arbitraryMI (k+1) r)
liftM (PsiTest t f mi) (arbitraryVector n)
prop_psi :: PsiTest -> Q.Property
prop_psi (PsiTest t f mi v) =
MI.degree mi > 0 ==> all (eqNum 0.0 . evaluate v) ps
where ps = [DF.apply (psi' t f mi i) [l] | i <- is, l <- axs]
axs = projectionAxes t f mi
is = S.sigma f
k = S.topologicalDimension f
convexCombination :: Simplex -> MI.MultiIndex -> Vector
convexCombination t mi = sumV (zipWith sclV mi' vs)
where vs = S.vertices t
zero = zeroV (head vs)
(l,r) = (MI.toList mi, fromInt $ MI.degree mi)
mi' = [ let i = fromInt (l !! s)
in i / r -- XXX: mulInv???...
| s <- S.sigma t]
projectionAxes :: Simplex -> Simplex -> MI.MultiIndex -> [Vector]
projectionAxes t f mi = map (subV xmi) (S.complement t f)
where xmi = convexCombination f mi
prop_basis :: FiniteElementSpace -> Q.Property
prop_basis s =
length bs > 0 ==> length bs == dim s && linearIndependent DF.inner bs
where bs = basis s
-- XXX: why the normalisation?? ... removed for now, seems unnecessary
-- ==> we use bs instead
--bs' = map (\x -> fmap (sclV (mulInv (sqrt (DF.inner x x)))) x) bs
--n = vspaceDim s
--------------------------------------------------------------------------------
-- PrmLk Form associated to a face.
--------------------------------------------------------------------------------
linearIndependent :: Module v => (v -> v -> Double) -> [v] -> Bool
linearIndependent f bs = M.rank mat == n
where es = M.eigenvaluesSH' mat
-- TODO: changed eigenvaluesSH to eigenvaluesSH' for loading; check!
mat = M.matrix n [ f omega eta | omega <- bs, eta <- bs ]
n = length bs
--------------------------------------------------------------------------------
-- DoFs of PrLk space
--------------------------------------------------------------------------------
prop_dof_basis :: FiniteElementSpace -> Q.Property
prop_dof_basis s = dim s > 0 && degree s > 0 ==> M.rank mat == n
where mat = M.matrix (n) [d b | d <- dofs s, b <- basis s]
n = dim s
prop_ndofs :: FiniteElementSpace -> Q.Property
prop_ndofs s = degree s > 0 ==> length (dofs s) == sum [nDofs s k | k <- [0..n]]
where n = S.topologicalDimension $ simplex s
return []
testFiniteElement = $quickCheckWithAll
space = PrmLk 3 0 (S.referenceSimplex 3)
|
using JuMP, Clp, Ipopt
ROOT=pwd()
include(joinpath(ROOT,"..","src_PowSysMod", "PowSysMod_body.jl"))
"""
get_JuMP_cartesian_model(problem_poly::Problem, mysolver)
Return JuMP cartesian model associated to `mysolver` defined by `problem_poly`, a polynomial problem in complex numbers
# Example
```jldoctest
V1 = Variable("VOLT_1",Complex)
V2 = Variable("VOLT_2",Complex)
p_obj = V1*conj(V2) + (2+im)*abs2(V1) + 1+2im
p_ctr1 = abs2(V1)
p_ctr2 = 3im * V1*conj(V2) + abs2(V1)
problem_poly=Problem()
add_variable!(problem_poly,V1)
add_variable!(problem_poly,V2)
add_constraint!(problem_poly, "ctr1", 0.95^2 << p_ctr1 << 1.05^2)
add_constraint!(problem_poly, "ctr2", p_ctr2==0)
set_objective!(problem_poly, p_obj)
print(problem_poly)
mysolver = ClpSolver()
m = get_JuMP_cartesian_model(problem_poly, mysolver)
print(m)
```
"""
function get_JuMP_cartesian_model(problem_poly::Problem, mysolver)
pb_poly_real = pb_cplx2real(problem_poly)
m = Model(solver = mysolver)
variables_jump = Dict{String, JuMP.Variable}()
for (varname, vartype) in pb_poly_real.variables
if vartype<:Real
variables_jump["$varname"] = @variable(m, varname, basename="$varname")
end
end
ctr_jump = Dict{String,JuMP.ConstraintRef}()
for (ctr, modeler_ctr) in pb_poly_real.constraints
polynome = modeler_ctr.p
lb = modeler_ctr.lb
ub = modeler_ctr.ub
for value in values(polynome)
if imag(value)!=0
error("Polynom coefficients have to be real numbers")
end
end
ctr_jump[ctr] = @NLconstraint(m, lb <= sum(coeff*prod(variables_jump["$var"]^(exp[1]) for (var,exp) in monome) for (monome,coeff) in polynome) <= ub)
end
polynome_obj = pb_poly_real.objective
@NLobjective(m,Min,sum(coeff*prod(variables_jump["$var"]^(exp[1]) for (var,exp) in monome) for (monome,coeff) in polynome_obj))
return m
end
###TEST
# V1 = Variable("VOLT_1",Complex)
# V2 = Variable("VOLT_2",Complex)
# p_obj = V1*conj(V2) + (2+im)*abs2(V1) + 1+2im
# p_ctr1 = abs2(V1)
# p_ctr2 = 3im * V1*conj(V2) + abs2(V1)
#
# problem_poly=Problem()
# add_variable!(problem_poly,V1)
# add_variable!(problem_poly,V2)
# add_constraint!(problem_poly, "ctr1", 0.95^2 << p_ctr1 << 1.05^2)
# add_constraint!(problem_poly, "ctr2", p_ctr2==0)
# set_objective!(problem_poly, p_obj)
# print(problem_poly)
# mysolver = IpoptSolver()
# m = get_JuMP_cartesian_model(problem_poly, mysolver)
# print(m)
"""
get_JuMP_polar_model(pb::Problem, mysolver)
Return JuMP polar model associated to `mysolver` defined by `pb`, a polynomial problem in complex numbers
# Example
```jldoctest
V1 = Variable("VOLT_1",Complex)
V2 = Variable("VOLT_2",Complex)
p_obj = V1*conj(V2) + (2+im)*abs2(V1) + 1+2im
p_ctr1 = abs2(V1)
p_ctr2 = Polynomial((3+4im) * V1*conj(V2))
pb=Problem()
add_variable!(pb,V1)
add_variable!(pb,V2)
add_constraint!(pb, "ctr1", 0 << p_ctr1 << 100)
# add_constraint!(pb, "ctr2", p_ctr2==3+4im)
set_objective!(pb, p_obj)
print(pb)
mysolver = IpoptSolver()
m = get_JuMP_polar_model(pb, mysolver)
print(m)
```
"""
function get_JuMP_polar_model(pb::Problem, mysolver)
m = Model(solver = mysolver)
jump_vars = Dict{String, JuMP.Variable}()
for (varname, vartype) in pb.variables
mod = "ρ_$varname"
jump_vars["ρ_$varname"] = @variable(m, basename="ρ_$varname")
jump_vars["θ_$varname"] = @variable(m, basename="θ_$varname")
end
ctr_jump = Dict{String,JuMP.ConstraintRef}()
for (ctr, modeler_ctr) in pb.constraints
p = modeler_ctr.p
lb = modeler_ctr.lb
ub = modeler_ctr.ub
ps = Dict{Exponent, Tuple{Real, Real}}(exp=>(real(coeff), imag(coeff)) for (exp, coeff) in p)
## Real part of constraint
@NLconstraint(m, real(lb) <= sum( coeff[1] * prod(jump_vars["ρ_$var"]^(exp[1]+exp[2]) for (var,exp) in mon) * cos(sum( (exp[1]-exp[2])*jump_vars["θ_$var"] for (var,exp) in mon))
- coeff[2] * prod(jump_vars["ρ_$var"]^(exp[1]+exp[2]) for (var,exp) in mon) * sin(sum( (exp[1]-exp[2])*jump_vars["θ_$var"] for (var,exp) in mon))
for (mon, coeff) in ps) <= real(ub))
## Imag part of constraint
@NLconstraint(m, imag(lb) <= sum( coeff[2] * prod(jump_vars["ρ_$var"]^(exp[1]+exp[2]) for (var,exp) in mon) * cos(sum( (exp[1]-exp[2])*jump_vars["θ_$var"] for (var,exp) in mon))
+ coeff[1] * prod(jump_vars["ρ_$var"]^(exp[1]+exp[2]) for (var,exp) in mon) * sin(sum( (exp[1]-exp[2])*jump_vars["θ_$var"] for (var,exp) in mon))
for (mon, coeff) in ps) <= imag(ub))
polynome_obj = pb.objective
ps = Dict{Exponent, Tuple{Real, Real}}(exp=>(real(coeff), imag(coeff)) for (exp, coeff) in polynome_obj)
lb_real, ub_real = real(lb), real(ub)
@NLobjective(m, :Min, lb_real <= sum( coeff[1] * prod(jump_vars["ρ_$var"]^(exp[1]+exp[2]) for (var,exp) in mon) * cos(sum( (exp[1]-exp[2])*jump_vars["θ_$var"] for (var,exp) in mon))
- coeff[2] * prod(jump_vars["ρ_$var"]^(exp[1]+exp[2]) for (var,exp) in mon) * sin(sum( (exp[1]-exp[2])*jump_vars["θ_$var"] for (var,exp) in mon))
for (mon, coeff) in ps) <= ub_real)
end
return m
end
####TEST
# V1 = Variable("VOLT_1",Complex)
# V2 = Variable("VOLT_2",Complex)
# p_obj = V1*conj(V2) + (2+im)*abs2(V1) + 1+2im
# p_ctr1 = abs2(V1)
# p_ctr2 = Polynomial((3+4im) * V1*conj(V2))
# pb=Problem()
# add_variable!(pb,V1)
# add_variable!(pb,V2)
# add_constraint!(pb, "ctr1", 0 << p_ctr1 << 100)
# # add_constraint!(pb, "ctr2", p_ctr2==3+4im)
# set_objective!(pb, p_obj)
# print(pb)
# mysolver = IpoptSolver()
# m = get_JuMP_polar_model(pb, mysolver)
# print(m)
|
Formal statement is: lemma complex_mult_cnj: "z * cnj z = complex_of_real ((Re z)\<^sup>2 + (Im z)\<^sup>2)" Informal statement is: The product of a complex number $z$ with its conjugate is equal to the square of the real part of $z$ plus the square of the imaginary part of $z$. |
(*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
theory AbstractFloat
imports artifact_machine.Machine
begin
definition signed_greater_than :: "'a :: len word \<Rightarrow> 'a :: len word \<Rightarrow> bool" ("(_/ >s _)" [50, 51] 50)
where "a >s b \<equiv> a \<noteq> b \<and> \<not>(a <s b)"
declare signed_greater_than_def[symmetric,simp add]
(* Technically already exists as word_sle (<=s) *)
definition signed_le :: "'a :: len word \<Rightarrow> 'a :: len word \<Rightarrow> bool" ("(_/ \<le>s _)" [50, 51] 50)
where "a \<le>s b \<equiv> a = b \<or> a <s b"
declare signed_le_def[symmetric,simp add]
definition signed_ge :: "'a :: len word \<Rightarrow> 'a :: len word \<Rightarrow> bool" ("(_/ \<ge>s _)" [50, 51] 50)
where "a \<ge>s b \<equiv> a = b \<or> a >s b"
declare signed_le_def[symmetric,simp add]
lemma signed_not_le[simp]:
shows "\<not> a \<le>s b \<longleftrightarrow> a >s b"
unfolding signed_le_def signed_greater_than_def
by metis
subsection "Making a float"
text \<open> Make a float from a sign-bit, an exponent and a mantissa. \<close>
fun mk_float :: "bool \<times> nat \<times> nat \<Rightarrow> 64 word"
where "mk_float (s,e,m) = ((if s then 1 else 0) << 63) OR (of_nat e AND mask 11 << 52) OR (of_nat m AND mask 52)"
text \<open> Simplify @{term mk_float} only when it is given concrete values. \<close>
lemmas mk_float_simps_numeral[simp] =
mk_float.simps[of True 0 0]
mk_float.simps[of True 0 1]
mk_float.simps[of True 0 "numeral m"]
mk_float.simps[of True 1 0]
mk_float.simps[of True 1 1]
mk_float.simps[of True 1 "numeral m"]
mk_float.simps[of True "numeral n" 0]
mk_float.simps[of True "numeral n" 1]
mk_float.simps[of True "numeral n" "numeral m"]
mk_float.simps[of False 0 0]
mk_float.simps[of False 0 1]
mk_float.simps[of False 0 "numeral m"]
mk_float.simps[of False 1 0]
mk_float.simps[of False 1 1]
mk_float.simps[of False 1 "numeral m"]
mk_float.simps[of False "numeral n" 0]
mk_float.simps[of False "numeral n" 1]
mk_float.simps[of False "numeral n" "numeral m"]
for n m
declare mk_float.simps[simp del]
text \<open>Constants and Accessor Functions\<close>
definition plus_zero :: "64 word" ("0\<^sup>+")
where "plus_zero \<equiv> mk_float (False,0,0)"
definition minus_zero :: "64 word" ("0\<^sup>-")
where "minus_zero \<equiv> mk_float (True,0,0)"
definition plus_infty :: "64 word" ("\<infinity>\<^sup>+")
where "plus_infty \<equiv> mk_float (False,2^11 - 1,0)"
definition minus_infty :: "64 word" ("\<infinity>\<^sup>-")
where "minus_infty \<equiv> mk_float (True,2^11 - 1,0)"
definition exp :: "64 word \<Rightarrow> 64 word"
where "exp w \<equiv> \<langle>62,52\<rangle>w"
definition mant :: "64 word \<Rightarrow> 64 word"
where "mant w \<equiv> \<langle>51,0\<rangle>w"
definition sign :: "64 word \<Rightarrow> bool"
where "sign \<equiv> msb"
definition isNaN :: "64 word \<Rightarrow> bool"
where "isNaN w \<equiv> exp w = 2^11-1"
definition float_abs :: "'a::len0 word \<Rightarrow> 'a::len0 word" ("\<bar>_\<bar>\<^sup>f")
where "\<bar>w\<bar>\<^sup>f \<equiv> set_bit w (LENGTH('a) - 1) False"
(*
lemma sign_mk_float:
shows "sign (mk_float (s,e,m)) = s"
unfolding sign_def
by (auto simp add: msb_nth mk_float.simps test_bit_of_take_bits word_ao_nth nth_shiftl)
lemma exp_mk_float:
shows "exp (mk_float (s,e,m)) = ((of_nat e)::64 word) AND mask 11"
unfolding exp_def
apply word_bitwise
by (auto simp add: mk_float.simps test_bit_of_take_bits word_ao_nth nth_shiftl)
lemma mant_mk_float:
shows "mant (mk_float (s,e,m)) = ((of_nat m)::64 word) AND mask 52"
unfolding mant_def
apply word_bitwise
apply (auto simp add: mk_float.simps test_bit_of_take_bits word_ao_nth nth_shiftl simp del: take_bits_bitAND)
by (simp only: numeral_2_eq_2)+
*)
datatype float_cmp = Unordered | GT | LT | EQ
text \<open>
For the following functions, we do not yet have an implementation.
We constraint them according the IEEE 754 standard.
\<close>
locale abstract_float =
fixes float_plus :: "64 word \<Rightarrow> 64 word \<Rightarrow> 64 word" (infixl "+\<^sup>f" 65)
and float_minus :: "64 word \<Rightarrow> 64 word \<Rightarrow> 64 word" (infixl "-\<^sup>f" 65)
and float_times:: "64 word \<Rightarrow> 64 word \<Rightarrow> 64 word" (infixl "*\<^sup>f" 65)
and float_div :: "64 word \<Rightarrow> 64 word \<Rightarrow> 64 word" (infixl "div\<^sup>f" 65)
and float_mod :: "64 word \<Rightarrow> 64 word \<Rightarrow> 64 word" (infixl "mod\<^sup>f" 70)
and float_ucmp :: "64 word \<Rightarrow> 64 word \<Rightarrow> float_cmp"
and cvttsd2si :: "64 word \<Rightarrow> 32 word"
and cvtsi2sd :: "32 word \<Rightarrow> 64 word"
assumes plus_plus_zero [simp]: "x +\<^sup>f 0\<^sup>+ = x"
and plus_minus_zero[simp]: "x +\<^sup>f 0\<^sup>- = x"
and isNan_div_0_0: "x \<in> {0\<^sup>-,0\<^sup>+} \<Longrightarrow> y \<in> {0\<^sup>-,0\<^sup>+} \<Longrightarrow> isNaN (x div\<^sup>f y)"
and div_by_plus_zero: "x \<notin> {0\<^sup>-,0\<^sup>+} \<Longrightarrow> x div\<^sup>f 0\<^sup>+ = (if sign x then \<infinity>\<^sup>- else \<infinity>\<^sup>+)"
and div_by_minus_zero: "x \<notin> {0\<^sup>-,0\<^sup>+} \<Longrightarrow> x div\<^sup>f 0\<^sup>- = (if sign x then \<infinity>\<^sup>+ else \<infinity>\<^sup>-)"
and times_by_plus_zero [simp]: "x *\<^sup>f 0\<^sup>+ = (if sign x then 0\<^sup>- else 0\<^sup>+)"
and time_by_neg_zero [simp]: "x *\<^sup>f 0\<^sup>- = (if sign x then 0\<^sup>+ else 0\<^sup>-)"
and times_plus_zero: "0\<^sup>+ *\<^sup>f x = (if sign x then 0\<^sup>- else 0\<^sup>+)"
and times_neg_zero: "0\<^sup>- *\<^sup>f x = (if sign x then 0\<^sup>+ else 0\<^sup>-)"
begin
end
interpretation abstract_float
"\<lambda> x y . x"
"\<lambda> x y . x"
"\<lambda> x y . if y = 0\<^sup>+ then (if sign x then 0\<^sup>- else 0\<^sup>+) else if y = 0\<^sup>- then (if sign x then 0\<^sup>+ else 0\<^sup>-) else
if x = 0\<^sup>+ then (if sign y then 0\<^sup>- else 0\<^sup>+) else if x = 0\<^sup>- then (if sign y then 0\<^sup>+ else 0\<^sup>-)
else x"
"\<lambda> x y . if x \<in> {0\<^sup>-,0\<^sup>+} then mk_float(False,2^11-1,0)
else if x = 0\<^sup>- then 0\<^sup>-
else if y = 0\<^sup>+ then (if sign x then \<infinity>\<^sup>- else \<infinity>\<^sup>+)
else if y = 0\<^sup>- then (if sign x then \<infinity>\<^sup>+ else \<infinity>\<^sup>-)
else 0\<^sup>-"
apply (unfold_locales)
by (auto simp add: isNaN_def exp_def take_bits_def plus_zero_def minus_zero_def sign_def)
lemma bit_AND_bit_pattern_is_float_abs_bit32[simp]:
fixes w :: "32 word"
shows "w AND 2147483647 = \<bar>w\<bar>\<^sup>f"
apply (word_bitwise)
by (auto simp add: word_ao_nth float_abs_def test_bit_set_gen)
lemma bit_AND_bit_pattern_is_float_abs_bit64[simp]:
fixes a :: "64 word"
shows "a AND 9223372036854775807 = \<bar>a\<bar>\<^sup>f"
unfolding float_abs_def
apply word_bitwise
by (auto simp add: test_bit_set_gen del: )
end
|
library(proto)
stack <- proto(expr = {
l <- list()
empty <- function(.) length(.$l) == 0
push <- function(., x)
{
.$l <- c(list(x), .$l)
print(.$l)
invisible()
}
pop <- function(.)
{
if(.$empty()) stop("can't pop from an empty list")
.$l[[1]] <- NULL
print(.$l)
invisible()
}
})
stack$empty()
# [1] TRUE
stack$push(3)
# [[1]]
# [1] 3
stack$push("abc")
# [[1]]
# [1] "abc"
# [[2]]
# [1] 3
stack$push(matrix(1:6, nrow=2))
# [[1]]
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
# [[2]]
# [1] "abc"
# [[3]]
# [1] 3
stack$empty()
# [1] FALSE
stack$pop()
# [[1]]
[1] "abc"
# [[2]]
# [1] 3
stack$pop()
# [[1]]
# [1] 3
stack$pop()
# list()
stack$pop()
# Error in get("pop", env = stack, inherits = TRUE)(stack, ...) :
# can't pop from an empty list
|
program kmc
implicit none
! KMC computes the population vs time of a number of species involved in several dynamical processes
! rate: rate constant of a given processes
! p: population of a given species (p0 is its initial value)
! re (pr): reactant (product) for a given process
! ndisp number of species that dissapear
! ndd species that dissapear
character*80 :: title
integer, parameter :: dp = selected_real_kind(15,307)
integer :: m,nran,nr,nesp,inran,i,j,k,l,mu,ndisp,pd,kk,ijk,totcont
real(dp) :: t,tmax,tprint,tint,a0,r2a0,suma,ptot
real(dp) :: rnd(2)
integer,dimension(:),allocatable :: p,p0,re,pr,n,ndd,cont
real (dp) ,dimension(:),allocatable :: a,rate
read(*,"(a80)") title
print "(t3,a80)",title
read(*,*) m,nesp,nran
allocate(re(m),pr(m),a(m),rate(m),p0(nesp),p(nesp),n(nesp),cont(m))
n=(/ (l,l=1,nesp) /)
do i=1,m
read(*,*) rate(I),re(i),pr(i)
enddo
ptot=0.d0
print*, "at the beginning"
do ijk=1,m
cont(ijk)=0
enddo
do i=1,nesp
read(*,*) p0(i)
print*, "P0(",i,")=",p0(i)
ptot=ptot+p0(i)
enddo
read(*,*) ndisp
allocate(ndd(ndisp))
if(ndisp>0) read(*,*) ndd
read(*,*) tmax,tint
print "(t3,a,i4,/,t3,a,i4,/,t3,a,i4,/)","# of calcs:",nran,"# of procs:",m,"# of specs:",nesp
print "(t3,a,1p,20(e9.2))","Rates:",rate
print "(t3,a,20(i9))","Reacts:",re
print "(t3,a,20(i9))","Prods :",pr
print "(/,t3,a,1p,e10.2,a,/,t3,a,1p,e10.2,a,/)","Total time=",tmax," ps","Step size =",tint," ps"
big: do inran=1,nran
print "(/,t3,a,i4,/,t3,a,500(i7))","Calculation number",inran," Time(ps)",n
p=p0
t=0.d0
tprint=0.d0
do while(tprint<tmax)
do j=1,m
a(j)=rate(j)*p(re(j))
enddo
a0=sum(a)
call random_number(rnd)
t=t-log(rnd(1))/a0
do while (t>=tprint)
print "(e10.4,500(i7))",tprint,p
tprint=tprint+tint
if(tprint>tmax) cycle big
enddo
r2a0=rnd(2)*a0
suma=0.d0
s1: do mu=1,m
suma=suma+a(mu)
if(suma>=r2a0) exit s1
enddo s1
p(re(mu))=p(re(mu))-1
p(pr(mu))=p(pr(mu))+1
cont(mu)=cont(mu)+1
totcont=0
do ijk=1,m
totcont=totcont+cont(ijk)
enddo
if(totcont>=1.d6) cycle big
pd=0
do kk=1,ndisp
pd=pd+p(ndd(kk))
enddo
if(pd<ptot/10000.and.ndisp>0) then
print*, "End+++"
cycle big
endif
enddo
enddo big
print*,"Population of every species"
do i=1,nesp
print "(i6,i7)",i,p(i)
enddo
print*,"counts per process"
do i=1,m
print "(i6,i20,i5,i5)",i,cont(i),re(i),pr(i)
enddo
end program kmc
|
Formal statement is: lemma filterlim_at_top_at_left: fixes f :: "'a::linorder_topology \<Rightarrow> 'b::linorder" assumes mono: "\<And>x y. Q x \<Longrightarrow> Q y \<Longrightarrow> x \<le> y \<Longrightarrow> f x \<le> f y" and bij: "\<And>x. P x \<Longrightarrow> f (g x) = x" "\<And>x. P x \<Longrightarrow> Q (g x)" and Q: "eventually Q (at_left a)" and bound: "\<And>b. Q b \<Longrightarrow> b < a" and P: "eventually P at_top" shows "filterlim f at_top (at_left a)" Informal statement is: If $f$ is a monotone function and $g$ is a bijection such that $f \circ g$ is the identity function, then $f$ is a filter limit at infinity. |
#include "util.h"
#include "parsers/map_parser.h"
#include "parsers/map_parser_tools.h"
#include <istream>
#include <boost/program_options.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
namespace po = boost::program_options;
int main(int argc, char* argv[]) {
std::string infile = "../apps/data_parsing/Saturn_1.5_3D_sm_v1.0.json";
std::string outfile = "../apps/data_parsing/Saturn_map_info.json";
try {
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("infile,i",po::value<std::string>(),"file to parse (string)")
("outfile,o",po::value<std::string>(),"filename for output (string)")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 0;
}
if (vm.count("infile")) {
infile = vm["infile"].as<std::string>();
}
if (vm.count("outfile")) {
outfile = vm["outfile"].as<std::string>();
}
}
catch(std::exception& e) {
std::cerr << "error: " << e.what() << "\n";
return 1;
}
catch(...) {
std::cerr << "Exception of unknown type!\n";
}
std::ifstream i(infile);
json j;
i >> j;
std::vector<std::string> alt_zones = {"sga","ew","cf","kit","lib","llc","sdc","loc_42"};
auto mp = parse_map_from_json(j, alt_zones);
json g;
mp.zones.push_back("UNKNOWN");
mp.graph["llcn"].push_back("UNKNOWN");
mp.graph["UNKNOWN"].push_back("llcn");
mp.graph["r103"].push_back("UNKNOWN");
mp.graph["UNKNOWN"].push_back("r103");
for (auto z : mp.zones) {
g["zones"].push_back(z);
for (auto c : mp.graph[z]) {
g["graph"][z].push_back(c);
}
g["dist_from_change_zone"][z] = shortest_path_BFS(mp.graph,z,"sga");
}
for (auto r : mp.rooms) {
g["rooms"].push_back(r);
}
g["change_zone"] = "sga";
g["no_victim_zones"].push_back("sga");
g["no_victim_zones"].push_back("ew");
g["no_victim_zones"].push_back("UNKNOWN");
g["multi_room_zones"].push_back("cf");
g["multi_room_zones"].push_back("kit");
g["multi_room_zones"].push_back("lib");
g["multi_room_zones"].push_back("llc");
g["multi_room_zones"].push_back("sdc");
std::ofstream o(outfile);
o << std::setw(4) << g << std::endl;
return EXIT_SUCCESS;
}
|
//
// Created by X-ray on 5/30/2021.
//
#pragma once
#include <utility>
#include <iostream>
#include <memory>
#include <boost/beast.hpp>
#include "../../utility/mime.hpp"
#include "../../utility/path_cat.hpp"
#include "response_builder.hpp"
namespace web_server {
namespace session {
namespace handle_request {
namespace beast = boost::beast;
namespace http = beast::http;
struct request {
http::verb method;
std::string url;
std::map<std::string, std::string> parameters;
http::header<true, http::basic_fields<std::allocator<char>>> headers;
};
std::string ErrorResponse(std::string title, std::string what, int error_code);
std::map<std::string, std::string> ParseUrlParameters(std::string url);
class handle_tools {
public:
boost::beast::http::message<false, boost::beast::http::basic_string_body<char>> HandleError(http_status status, std::string error);
using error_handler_t = std::function<boost::beast::http::response<boost::beast::http::string_body>(std::string)>;
void AddErrorHandler(http_status status, error_handler_t handler);
private:
std::map<http_status, error_handler_t> error_handlers;
};
class handle {
public:
handle() {
RegisterErrorHandlers();
}
template<bool isRequest, class Body, class Allocator = std::allocator<char>, class Send>
void run(beast::string_view doc_root, http::message<isRequest, Body, Allocator>&& req, Send&& send) {
try {
request Req{
static_cast<http::verb>(req.method()),
std::string(req.target()),
ParseUrlParameters(std::string(req.target())),
req.base(),
};
// Make sure we can handle the method
if(Req.method != http::verb::get && Req.method != http::verb::head)
return send(tools_.HandleError(http_status::bad_request, "Unknown HTTP-method"));
// Request path must be absolute and not contain "..".
if(Req.url.empty() || req.target()[0] != '/' || Req.url.find("..") != std::string::npos)
return send(tools_.HandleError(http_status::bad_request, "Illegal request-target"));
// Build the path to the requested file
std::string path = utility::path_cat(doc_root, Req.url);
if(Req.url.ends_with('/'))
path.append("index.html");
// Attempt to open the file
beast::error_code ec;
if (path.find('?') != std::string::npos) {
path.erase(path.find('?'));
}
http::file_body::value_type body;
body.open(path.c_str(), beast::file_mode::scan, ec);
// Handle the case where the file doesn't exist
if(ec == beast::errc::no_such_file_or_directory)
return send(tools_.HandleError(http_status::not_found, "The requested url was not found: " + std::string(Req.headers["Host"]) +Req.url));
// Handle an unknown error
if(ec)
return send(tools_.HandleError(http_status::internal_server_error, ec.message()));
if (Req.method == http::verb::head) {
responsebuilder res(http_status::ok, std::string(utility::mime_type(path)));
return send(res.GetStringResponse());
} else if (Req.method == http::verb::get) {
responsebuilder res(http_status::ok, std::string(utility::mime_type(path)), body);
return send(res.GetFileResponse());
}
return send(tools_.HandleError(http_status::internal_server_error, "Request was not handled"));
} catch(std::exception &e) {
return send(tools_.HandleError(http_status::internal_server_error, e.what()));
}
}
private:
handle_tools tools_;
private:
void RegisterErrorHandlers();
};
} // handle_request
} // session
} // web_server
|
open import Data.Product using ( ∃ ; _×_ )
open import FRP.LTL.RSet.Core using ( RSet ; _[_,_] ; ⟦_⟧ )
open import FRP.LTL.RSet.Stateless using ( _⇒_ )
open import FRP.LTL.RSet.Globally using ( □ ; [_] )
open import FRP.LTL.Time using ( _≤_ ; ≤-refl ; _≤-trans_ )
module FRP.LTL.RSet.Causal where
infixr 2 _⊵_
infixr 3 _⋙_
-- A ⊵ B is the causal function space from A to B
_⊵_ : RSet → RSet → RSet
(A ⊵ B) t = ∀ {u} → (t ≤ u) → (A [ t , u ]) → B u
-- Categorical structure
arr : ∀ {A B} → ⟦ □ (A ⇒ B) ⇒ (A ⊵ B) ⟧
arr f s≤t σ = f s≤t (σ s≤t ≤-refl)
identity : ∀ {A} → ⟦ A ⊵ A ⟧
identity {A} = arr [( λ {u} (a : A u) → a )]
_before_ : ∀ {A s u v} → (A [ s , v ]) → (u ≤ v) → (A [ s , u ])
(σ before u≤v) s≤t t≤u = σ s≤t (t≤u ≤-trans u≤v)
_after_ : ∀ {A s t v} → (A [ s , v ]) → (s ≤ t) → (A [ t , v ])
(σ after s≤t) t≤u u≤v = σ (s≤t ≤-trans t≤u) u≤v
_$_ : ∀ {A B s u} → (A ⊵ B) s → (A [ s , u ]) → (B [ s , u ])
(f $ σ) s≤t t≤u = f s≤t (σ before t≤u)
_⋙_ : ∀ {A B C} → ⟦ (A ⊵ B) ⇒ (B ⊵ C) ⇒ (A ⊵ C) ⟧
(f ⋙ g) s≤t σ = g s≤t (f $ σ)
|
-- -------------------------------------------------------------- [ Lens.idr ]
-- Description : Idris port of Control.Lens
-- Copyright : (c) Huw Campbell
-- --------------------------------------------------------------------- [ EOH ]
module Control.Lens.Examples
import Control.Lens
--
-- Examples of interactions available with these Lenses
--
Ex1 : Maybe Int
Ex1 = over mapped (+1) (Just 2)
Ex1Proof : Ex1 = Just 3
Ex1Proof = Refl
Ex2 : (Int, Int)
Ex2 = (2,3) |> over both (+1)
Ex2Proof : Ex2 = (3, 4)
Ex2Proof = Refl
Ex3 : (String, String)
Ex3 = ("Hello",2) |> snd_ .~ "World!"
Ex3Proof : Ex3 = ("Hello","World!")
Ex3Proof = Refl
Ex4 : Either String Int
Ex4 = f (Left "hi")
where f : Either String Int -> Either String Int
f = over right_ (+1)
Ex4Proof : Ex4 = (Left "hi")
Ex4Proof = Refl
Ex5 : Either String Int
Ex5 = f (Right 4)
where f : Either String Int -> Either String Int
f = over right_ (+1)
Ex5Proof : Ex5 = (Right 5)
Ex5Proof = Refl
Ex6 : Either (String, Int) Int
Ex6 = f (Left ("hi", 2))
where f : Either (String,Int) Int -> Either (String,Int) Int
f = over (left_ . snd_) (+1)
Ex6Proof : Ex6 = Left ("hi", 3)
Ex6Proof = Refl
-- Ex7 and Ex8 need to use the PlusNatMonoid named instance and I don't know how to do this yet
[PlusNatSemi] Semigroup Nat where
(<+>) x y = x + y
[PlusNatMonoid] Monoid Nat using PlusNatSemi where
neutral = 0
[PlusNatApplicative] Applicative (Const Nat) using PlusNatMonoid where
pure _ = MkConst neutral
(MkConst f) <*> (MkConst v) = MkConst (f <+> v)
-- f : Either (String, Nat) Int -> Nat
-- f = view @{PlusNatApplicative} (left_ . snd_)
-- Ex7 : Nat
-- Ex7 = f (Left ("hi", 2)) where
-- Ex7Proof : Ex7 = 2
-- Ex7Proof = Refl
-- Ex8 : Nat
-- Ex8 = f (Right 2) where
-- f : Either (String, Additive) Int -> Additive
-- f = view (left_ . snd_)
-- Ex8Proof : Ex8 = 0
-- Ex8Proof = Refl
Ex9 : Maybe String
Ex9 = g ^? right_ . fst_ where
g : Either String (String, Int)
g = Right ("x",2)
Ex9Proof : Ex9 = Just "x"
Ex9Proof = Refl
Ex10 : Maybe ()
Ex10 = Just "x" ^? nothing_
Ex10Proof : Ex10 = Nothing
Ex10Proof = Refl
Ex11 : Maybe ()
Ex11 = n ^? nothing_ where
n : Maybe String
n = Nothing
Ex11Proof : Ex11 = Just ()
Ex11Proof = Refl
Ex12 : Int
Ex12 = view (to fst) (1,2)
Ex12Proof : Ex12 = 1
Ex12Proof = Refl
Ex13 : Either Int String
Ex13 = the (Either Int String) $ left_ # 4
Ex13Proof : Ex13 = Left 4
Ex13Proof = Refl
Ex14 : Either Int String
Ex14 = the (Either Int String) $ 5 ^.re left_
Ex14Proof : Ex14 = Left 5
Ex14Proof = Refl
sansExample : Maybe Int
sansExample = sans () (Just 4)
fusingExample : Maybe (Int, Int)
fusingExample = Just (2,3) |> over ( fusing (just_ . both)) (+1)
confusingExample : Maybe (Int, Int)
confusingExample = Just (2,3) |> over ( confusing (just_ . both)) (+1)
-- --------------------------------------------------------------------- [ EOF ]
|
module Data.List.Extra
%default total
||| Fetches the element at a given position.
||| Returns `Nothing` if the position beyond the list's end.
public export
elemAt : List a -> Nat -> Maybe a
elemAt [] _ = Nothing
elemAt (l :: _) Z = Just l
elemAt (_ :: ls) (S n) = elemAt ls n
|
State Before: α : Type u_3
β : Type u_1
γ : Type u_2
δ : Type ?u.379755
δ' : Type ?u.379758
ι : Sort uι
s✝ t u : Set α
mα : MeasurableSpace α
inst✝¹ : MeasurableSpace β
inst✝ : MeasurableSpace γ
f : α → β
g : β → γ
hg : MeasurableEmbedding g
hf : MeasurableEmbedding f
s : Set α
hs : MeasurableSet s
⊢ MeasurableSet (g ∘ f '' s) State After: no goals Tactic: rwa [image_comp, hg.measurableSet_image, hf.measurableSet_image] |
section \<open>Addition with fixpoint of successor\<close>
theory Ex3
imports "../LCF"
begin
axiomatization
s :: "'a \<Rightarrow> 'a" and
p :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"
where
p_strict: "p(UU) = UU" and
p_s: "p(s(x),y) = s(p(x,y))"
declare p_strict [simp] p_s [simp]
lemma example: "p(FIX(s),y) = FIX(s)"
apply (induct s)
apply simp
apply simp
done
end
|
[STATEMENT]
lemma composition_conseq2l: "(l \<cdot>\<^sub>l \<sigma>\<^sub>1) \<cdot>\<^sub>l \<sigma>\<^sub>2 = l \<cdot>\<^sub>l (\<sigma>\<^sub>1 \<cdot> \<sigma>\<^sub>2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. l \<cdot>\<^sub>l \<sigma>\<^sub>1 \<cdot>\<^sub>l \<sigma>\<^sub>2 = l \<cdot>\<^sub>l (\<sigma>\<^sub>1 \<cdot> \<sigma>\<^sub>2)
[PROOF STEP]
using composition_conseq2t
[PROOF STATE]
proof (prove)
using this:
?t \<cdot>\<^sub>t ?\<sigma>\<^sub>1 \<cdot>\<^sub>t ?\<sigma>\<^sub>2 = ?t \<cdot>\<^sub>t (?\<sigma>\<^sub>1 \<cdot> ?\<sigma>\<^sub>2)
goal (1 subgoal):
1. l \<cdot>\<^sub>l \<sigma>\<^sub>1 \<cdot>\<^sub>l \<sigma>\<^sub>2 = l \<cdot>\<^sub>l (\<sigma>\<^sub>1 \<cdot> \<sigma>\<^sub>2)
[PROOF STEP]
by (cases l) auto |
//F# Compiler for F# 4.1
open System
printfn "Hello, minoJiro!"
|
(* Author: Gertrud Bauer, Tobias Nipkow *)
section \<open>Transitive Closure of Successor List Function\<close>
theory RTranCl
imports Main
begin
text\<open>The reflexive transitive closure of a relation induced by a
function of type @{typ"'a \<Rightarrow> 'a list"}. Instead of defining the closure
again it would have been simpler to take @{term"{(x,y) . y \<in> set(f x)}\<^sup>*"}.\<close>
abbreviation (input)
in_set :: "'a \<Rightarrow> ('a \<Rightarrow> 'b list) \<Rightarrow> 'b \<Rightarrow> bool" ("_ [_]\<rightarrow> _" [55,0,55] 50) where
"g [succs]\<rightarrow> g' == g' \<in> set (succs g)"
inductive_set
RTranCl :: "('a \<Rightarrow> 'a list) \<Rightarrow> ('a * 'a) set"
and in_RTranCl :: "'a \<Rightarrow> ('a \<Rightarrow> 'a list) \<Rightarrow> 'a \<Rightarrow> bool"
("_ [_]\<rightarrow>* _" [55,0,55] 50)
for succs :: "'a \<Rightarrow> 'a list"
where
"g [succs]\<rightarrow>* g' \<equiv> (g,g') \<in> RTranCl succs"
| refl: "g [succs]\<rightarrow>* g"
| succs: "g [succs]\<rightarrow> g' \<Longrightarrow> g' [succs]\<rightarrow>* g'' \<Longrightarrow> g [succs]\<rightarrow>* g''"
inductive_cases RTranCl_elim: "(h,h') : RTranCl succs"
lemma RTranCl_induct(*<*) [induct set: RTranCl, consumes 1, case_names refl succs] (*>*):
"(h, h') \<in> RTranCl succs \<Longrightarrow>
P h \<Longrightarrow>
(\<And>g g'. g' \<in> set (succs g) \<Longrightarrow> P g \<Longrightarrow> P g') \<Longrightarrow>
P h'"
proof -
assume s: "\<And>g g'. g' \<in> set (succs g) \<Longrightarrow> P g \<Longrightarrow> P g'"
assume "(h, h') \<in> RTranCl succs" "P h"
then show "P h'"
proof (induct rule: RTranCl.induct)
fix g assume "P g" then show "P g" .
next
fix g g' g''
assume IH: "P g' \<Longrightarrow> P g''"
assume "g' \<in> set(succs g)" "P g"
then have "P g'" by (rule s)
then show "P g''" by (rule IH)
qed
qed
definition invariant :: "('a \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'a list) \<Rightarrow> bool" where
"invariant P succs \<equiv> \<forall>g g'. g' \<in> set(succs g) \<longrightarrow> P g \<longrightarrow> P g'"
lemma invariantE:
"invariant P succs \<Longrightarrow> g [succs]\<rightarrow> g' \<Longrightarrow> P g \<Longrightarrow> P g'"
by(simp add:invariant_def)
lemma inv_subset:
"invariant P f \<Longrightarrow> (\<And>g. P g \<Longrightarrow> set(f' g) \<subseteq> set(f g)) \<Longrightarrow> invariant P f'"
by(auto simp:invariant_def)
lemma RTranCl_inv:
"invariant P succs \<Longrightarrow> (g,g') \<in> RTranCl succs \<Longrightarrow> P g \<Longrightarrow> P g'"
by (erule RTranCl_induct)(auto simp:invariant_def)
lemma RTranCl_subset2:
assumes a: "(s,g) : RTranCl f"
shows "(\<And>g. (s,g) \<in> RTranCl f \<Longrightarrow> set(f g) \<subseteq> set(h g)) \<Longrightarrow> (s,g) : RTranCl h"
using a
proof (induct rule: RTranCl.induct)
case refl show ?case by(rule RTranCl.intros)
next
case succs thus ?case by(blast intro: RTranCl.intros)
qed
end
|
//fuck
#include <iostream>
#include <boost/filesystem.hpp>
#include <pcl/common/transforms.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/passthrough.h>
int main(int argc, char* argv[]) {
std::string filepath = "/mnt/container-data/ply_data/";
int count=0;
namespace fs = boost::filesystem;
if(!fs::exists(filepath) || !fs::is_directory(filepath)) {
std::cout << "file path misstake !!" << std::endl;
exit(0);
}
fs::directory_iterator last;
for(fs::directory_iterator pos(filepath); pos!=last; ++pos) {
++count;
}
std::cout << "files num : " << std::to_string(count) << std::endl;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
for (int i=0; i<count; i++){
cloud.reset(new pcl::PointCloud<pcl::PointXYZ>);
std::string filename = filepath + std::to_string(i) + ".ply";
std::cout << "READ FILE NAME : " << filename << std::endl;
pcl::io::loadPLYFile(filename, *cloud);
pcl::PassThrough<pcl::PointXYZ> passX;
passX.setInputCloud(cloud);
passX.setFilterFieldName("x");
passX.setFilterLimits(-2.0, 2.0);
passX.setFilterLimitsNegative(false);
passX.filter(*cloud);
pcl::PassThrough<pcl::PointXYZ> passY;
passY.setInputCloud(cloud);
passY.setFilterFieldName("y");
passY.setFilterLimits(0.0, 2.55);
passY.setFilterLimitsNegative(false);
passY.filter(*cloud);
pcl::PassThrough<pcl::PointXYZ> passZ;
passZ.setInputCloud(cloud);
passZ.setFilterFieldName("z");
passZ.setFilterLimits(0.0, 2.0);
passZ.setFilterLimitsNegative(false);
passZ.filter(*cloud);
std::string save_filename = "/mnt/container-data/remove_plane/" + std::to_string(i) + ".ply";
std::cout << "SAVE FILE NAME : " << save_filename << std::endl;
pcl::io::savePLYFileASCII(save_filename, *cloud);
}
return 0;
}
|
(** * Standard finite sets . Vladimir Voevodsky . Apr. - Sep. 2011 .
This file contains main constructions related to the standard finite sets defined as the initial intervals of [ nat ] and their properties . *)
(** ** Preamble *)
(** Imports. *)
Require Export UniMath.Foundations.NaturalNumbers.
Require Import UniMath.MoreFoundations.Tactics.
Require Import UniMath.MoreFoundations.DecidablePropositions.
Require Import UniMath.MoreFoundations.NegativePropositions.
(** ** Standard finite sets [ stn ]. *)
Definition stn ( n : nat ) := ∑ m, m < n.
Definition make_stn n m (l:m<n) := (m,,l) : stn n.
Definition stntonat ( n : nat ) : stn n -> nat := @pr1 _ _ .
Coercion stntonat : stn >-> nat.
Lemma stnlt {n : nat} (i:stn n) : i < n.
Proof.
intros.
exact (pr2 i).
Defined.
(* old way:
Notation " 'stnel' ( i , j ) " :=
( make_stn _ _ ( ctlong natlth isdecrelnatlth j i ( idpath true ) ) )
( at level 70 ). *)
Notation " 'stnpr' j " := (j,,idpath _) ( at level 70 ).
Notation " 'stnel' ( i , j ) " := ( (j,,idpath _) : stn i ) ( at level 70 ).
Declare Scope stn.
Delimit Scope stn with stn.
Notation "⟦ n ⟧" := (stn n) : stn.
(* in agda-mode \[[ n \]] *)
Notation "● i" := (i ,, (idpath _ : natgtb _ _ = _)) (at level 35) : stn.
Lemma isinclstntonat ( n : nat ) : isincl ( stntonat n ).
Proof.
intro.
use isinclpr1.
intro x.
apply ( pr2 ( natlth x n ) ).
Defined.
Definition stntonat_incl n := make_incl (stntonat n) (isinclstntonat n).
Lemma isdecinclstntonat ( n : nat ) : isdecincl ( stntonat n ).
Proof.
intro.
use isdecinclpr1.
intro x.
apply isdecpropif.
use pr2.
apply isdecrelnatgth.
Defined.
Lemma neghfiberstntonat ( n m : nat ) ( is : natgeh m n ) : ¬ ( hfiber ( stntonat n ) m ).
Proof.
intros.
intro h.
destruct h as [ j e ].
destruct j as [ j is' ].
simpl in e.
rewrite e in is'.
apply ( natgehtonegnatlth _ _ is is' ).
Defined.
Lemma iscontrhfiberstntonat ( n m : nat ) ( is : natlth m n ) :
iscontr ( hfiber ( stntonat n ) m ).
Proof.
intros.
apply ( iscontrhfiberofincl ( stntonat n ) ( isinclstntonat n ) ( make_stn n m is ) ).
Defined.
Local Open Scope stn.
Lemma stn_ne_iff_neq {n : nat} (i j: ⟦n⟧ ) : ¬ (i = j) <-> stntonat _ i ≠ stntonat _ j.
Proof.
intros. split.
- intro ne. apply nat_nopath_to_neq. Set Printing Coercions. idtac.
intro e; apply ne; clear ne. apply subtypePath_prop. assumption.
- simpl. intros neq e. apply (nat_neq_to_nopath neq), maponpaths. assumption.
Unset Printing Coercions.
Defined.
Lemma stnneq {n : nat} : neqReln (⟦n⟧).
Proof. (* here we use no axioms *)
intros i j. exists (i ≠ j)%nat. split.
- apply propproperty.
- apply stn_ne_iff_neq.
Defined.
Notation " x ≠ y " := ( stnneq x y ) (at level 70, no associativity) : stn.
Delimit Scope stn with stn.
Local Open Scope stn.
Lemma isisolatedinstn { n : nat } ( x : ⟦n⟧ ) : isisolated _ x.
Proof.
intros.
apply ( isisolatedinclb ( stntonat n ) ( isinclstntonat n ) x ( isisolatedn x ) ).
Defined.
Lemma stnneq_iff_nopath {n : nat} (i j: ⟦n⟧ ) : ¬ (i = j) <-> i ≠ j.
Proof.
intros.
apply negProp_to_iff.
Defined.
Definition stnneq_to_nopath {n : nat} (i j: ⟦n⟧ ) : ¬ (i = j) <- i ≠ j
:= pr2 (stn_ne_iff_neq i j).
Corollary isdeceqstn ( n : nat ) : isdeceq (⟦n⟧).
Proof.
unfold isdeceq.
intros x x'.
apply (isisolatedinstn x x' ).
Defined.
Lemma stn_eq_or_neq {n : nat} (i j: ⟦n⟧ ) : (i=j) ⨿ (i≠j).
Proof.
intros. induction (nat_eq_or_neq i j) as [eq|ne].
- apply ii1, subtypePath_prop. assumption.
- apply ii2. assumption.
Defined.
Definition weqisolatedstntostn ( n : nat ) : ( isolated (⟦n⟧) ) ≃ ⟦n⟧.
Proof.
apply weqpr1.
intro x.
apply iscontraprop1.
apply isapropisisolated.
set ( int := isdeceqstn n x ).
assumption.
Defined.
Corollary isasetstn ( n : nat ) : isaset (⟦n⟧).
Proof.
intro.
apply ( isasetifdeceq _ ( isdeceqstn n ) ).
Defined.
Definition stnset n := make_hSet (⟦n⟧) (isasetstn n).
Definition stn_to_nat n : stnset n -> natset := pr1.
Definition stnposet ( n : nat ) : Poset.
Proof.
unfold Poset.
exists (_,,isasetstn n).
unfold PartialOrder.
exists (λ i j: ⟦n⟧, i ≤ j)%dnat.
unfold isPartialOrder.
split.
- unfold ispreorder.
split.
* intros i j k. apply istransnatleh.
* intros i. apply isreflnatleh.
- intros i j r s. apply (invmaponpathsincl _ ( isinclstntonat _ )).
apply isantisymmnatleh; assumption.
Defined.
Definition lastelement {n : nat} : ⟦S n⟧.
Proof.
split with n.
apply ( natgthsnn n ).
Defined.
Lemma lastelement_ge {n : nat} : ∏ i : ⟦S n⟧, @lastelement n ≥ i.
Proof.
intros.
apply natlthsntoleh.
unfold lastelement.
apply stnlt.
Defined.
Definition firstelement {n : nat} : ⟦S n⟧.
Proof.
exists 0.
apply natgthsn0.
Defined.
Lemma firstelement_le {n : nat} : ∏ i : ⟦S n⟧, @firstelement n ≤ i.
Proof.
intros.
apply idpath.
Defined.
Definition firstValue {X:UU} {n:nat} : (⟦S n⟧ -> X) -> X
:= λ x, x firstelement.
Definition lastValue {X:UU} {n:nat} : (⟦S n⟧ -> X) -> X
:= λ x, x lastelement.
(** Dual of i in stn n, is n - 1 - i *)
Local Lemma dualelement_0_empty {n : nat} (i : ⟦n⟧ ) (e : 0 = n) : empty.
Proof.
induction e.
apply (negnatlthn0 _ (stnlt i)).
Qed.
Local Lemma dualelement_lt (i n : nat) (H : n > 0) : n - 1 - i < n.
Proof.
rewrite natminusminus.
apply (natminuslthn _ _ H).
apply idpath.
Qed.
Definition dualelement {n : nat} (i : ⟦n⟧ ) : ⟦n⟧.
Proof.
induction (natchoice0 n) as [H | H].
- exact (make_stn n (n - 1 - i) (fromempty (dualelement_0_empty i H))).
- exact (make_stn n (n - 1 - i) (dualelement_lt i n H)).
Defined.
Definition stnmtostnn ( m n : nat ) (isnatleh: natleh m n ) : ⟦m⟧ -> ⟦n⟧ :=
λ x : ⟦m⟧, match x with tpair _ i is
=> make_stn _ i ( natlthlehtrans i m n is isnatleh ) end.
Definition stn_left (m n : nat) : ⟦m⟧ -> ⟦m+n⟧.
Proof.
intros i.
exists (pr1 i).
apply (natlthlehtrans (pr1 i) m (m+n) (pr2 i)).
apply natlehnplusnm.
Defined.
Definition stn_right (m n : nat) : ⟦n⟧ -> ⟦m+n⟧.
Proof.
intros i.
exists (m+pr1 i).
apply natlthandplusl.
exact (pr2 i).
Defined.
Definition stn_left_compute (m n : nat) (i: ⟦m⟧ ) : pr1 (stn_left m n i) = i.
Proof.
intros.
apply idpath.
Defined.
Definition stn_right_compute (m n : nat) (i: ⟦n⟧ ) : pr1 (stn_right m n i) = m+i.
Proof.
intros.
apply idpath.
Defined.
Lemma stn_left_0 {m:nat} {i:⟦m⟧} (e: m=m+0) : stn_left m 0 i = transportf stn e i.
Proof.
intros.
apply subtypePath_prop.
induction e.
apply idpath.
Defined.
Definition stn_left' (m n : nat) : m ≤ n -> ⟦m⟧ -> ⟦n⟧.
Proof.
intros le i.
exact (make_stn _ _ (natlthlehtrans _ _ _ (stnlt i) le)).
Defined.
Definition stn_left'' {m n : nat} : m < n -> ⟦m⟧ -> ⟦n⟧.
Proof.
intros le i.
exact (make_stn _ _ (istransnatlth _ _ _ (stnlt i) le)).
Defined.
Lemma stn_left_compare (m n : nat) (r : m ≤ m+n) : stn_left' m (m+n) r = stn_left m n.
Proof.
intros.
apply funextfun; intro i.
apply subtypePath_prop.
apply idpath.
Defined.
(** ** "Boundary" maps [ dni : stn n -> stn ( S n ) ] and their properties. *)
Definition dni {n : nat} ( i : ⟦S n⟧ ) : ⟦n⟧ -> ⟦S n⟧.
Proof. intros x. exists (di i x). unfold di.
induction (natlthorgeh x i) as [lt|ge].
- apply natgthtogths. exact (pr2 x).
- exact (pr2 x).
Defined.
Definition compute_pr1_dni_last (n : nat) (i: ⟦n⟧ ) : pr1 (dni lastelement i) = pr1 i.
Proof.
intros. unfold dni,di; simpl. induction (natlthorgeh i n) as [q|q].
- apply idpath.
- contradicts (pr2 i) (natlehneggth q).
Defined.
Definition compute_pr1_dni_first (n : nat) (i: ⟦n⟧ ) : pr1 (dni firstelement i) = S (pr1 i).
Proof.
intros.
apply idpath.
Defined.
Lemma dni_last {n : nat} (i: ⟦n⟧ ) : pr1 (dni lastelement i) = i.
Proof.
intros.
induction i as [i I].
unfold dni,di. simpl.
induction (natlthorgeh i n) as [g|g].
{ apply idpath. }
simpl.
contradicts (natlehtonegnatgth _ _ g) I.
Defined.
Lemma dni_first {n : nat} (i: ⟦n⟧ ) : pr1 (dni firstelement i) = S i.
Proof.
intros.
apply idpath.
Defined.
Definition dni_firstelement {n : nat} : ⟦n⟧ -> ⟦S n⟧.
(* this definition is simpler than that of [dni n (firstelement n)], since no choice is involved, so it's useful in special situations *)
Proof.
intros h.
exact (S (pr1 h),, pr2 h).
Defined.
Definition replace_dni_first (n : nat) : dni (@firstelement n) = dni_firstelement.
Proof.
intros.
apply funextfun; intros i.
apply subtypePath_prop.
exact (compute_pr1_dni_first n i).
Defined.
Definition dni_lastelement {n : nat} : ⟦n⟧ -> ⟦S n⟧.
(* this definition is simpler than that of [dni lastelement], since no choice is involved, so it's useful in special situations *)
Proof.
intros h.
exists (pr1 h).
exact (natlthtolths _ _ (pr2 h)).
Defined.
Definition replace_dni_last (n : nat) : dni (@lastelement n) = dni_lastelement.
Proof.
intros.
apply funextfun; intros i.
apply subtypePath_prop.
exact (compute_pr1_dni_last n i).
Defined.
Lemma dni_lastelement_ord {n : nat} : ∏ i j: ⟦n⟧, i≤j -> dni_lastelement i ≤ dni_lastelement j.
Proof.
intros ? ? e.
exact e.
Defined.
Definition pr1_dni_lastelement {n : nat} {i: ⟦n⟧ } : pr1 (dni_lastelement i) = pr1 i.
Proof.
intros.
apply idpath.
Defined.
Lemma dni_last_lt {n : nat} (j : ⟦ n ⟧) : dni lastelement j < @lastelement n.
Proof.
intros.
induction j as [j J].
simpl. unfold di.
induction (natlthorgeh j n) as [L|M].
- exact J.
- apply fromempty.
exact (natlthtonegnatgeh _ _ J M).
Defined.
Lemma dnicommsq ( n : nat ) ( i : ⟦S n⟧ ) :
commsqstr( dni i ) ( stntonat ( S n ) ) ( stntonat n ) ( di i ).
Proof.
intros.
intro x.
unfold dni. unfold di.
destruct ( natlthorgeh x i ).
- simpl.
apply idpath.
- simpl.
apply idpath.
Defined.
Theorem dnihfsq ( n : nat ) ( i : ⟦S n⟧ ) :
hfsqstr ( di i ) ( stntonat ( S n ) ) ( stntonat n ) ( dni i ).
Proof.
intros.
apply ( ishfsqweqhfibersgtof' ( di i ) ( stntonat ( S n ) ) ( stntonat n ) ( dni i ) ( dnicommsq _ _ ) ).
intro x.
destruct ( natlthorgeh x n ) as [ g | l ].
- assert ( is1 : iscontr ( hfiber ( stntonat n ) x ) ).
{ apply iscontrhfiberstntonat. assumption. }
assert ( is2 : iscontr ( hfiber ( stntonat ( S n ) ) ( di i x ) ) ).
{ apply iscontrhfiberstntonat.
apply ( natlehlthtrans _ ( S x ) ( S n ) ( natlehdinsn i x ) g ). }
apply isweqcontrcontr.
+ assumption.
+ assumption.
- assert ( is1 : ¬ ( hfiber ( stntonat ( S n ) ) ( di i x ) ) ).
{ apply neghfiberstntonat.
unfold di.
destruct ( natlthorgeh x i ) as [ l'' | g' ].
+ destruct ( natgehchoice2 _ _ l ) as [ g' | e ].
* apply g'.
* rewrite e in l''.
assert ( int := natlthtolehsn _ _ l'' ).
contradicts (natgthnegleh (pr2 i)) int.
+ apply l.
}
apply ( isweqtoempty2 _ is1 ).
Defined.
Lemma dni_neq_i {n : nat} (i : ⟦S n⟧) (j : ⟦n⟧ ) : i ≠ @dni n i j.
Proof.
intros.
simpl.
apply di_neq_i.
Defined.
Lemma weqhfiberdnihfiberdi ( n : nat ) ( i j : ⟦S n⟧ ) :
( hfiber ( dni i ) j ) ≃ ( hfiber ( di i ) j ).
Proof.
intros.
apply ( weqhfibersg'tof _ _ _ _ ( dnihfsq n i ) j ).
Defined.
Lemma neghfiberdni ( n : nat ) ( i : ⟦S n⟧ ) : ¬ ( hfiber ( dni i ) i ).
Proof.
intros.
apply ( negf ( weqhfiberdnihfiberdi n i i ) ( neghfiberdi i ) ).
Defined.
Lemma iscontrhfiberdni ( n : nat ) ( i j : ⟦S n⟧ ) : i ≠ j -> iscontr ( hfiber ( dni i ) j ).
Proof.
intros ne.
exact ( iscontrweqb ( weqhfiberdnihfiberdi n i j ) ( iscontrhfiberdi i j ne ) ).
Defined.
Lemma isdecincldni ( n : nat ) ( i : ⟦S n⟧ ) : isdecincl ( dni i ).
Proof. intros. intro j. induction ( stn_eq_or_neq i j ) as [eq|ne].
- induction eq. apply ( isdecpropfromneg ( neghfiberdni n i ) ).
- exact ( isdecpropfromiscontr (iscontrhfiberdni _ _ _ ne) ).
Defined.
Lemma isincldni ( n : nat ) ( i : ⟦S n⟧ ) : isincl ( dni i ).
Proof.
intros.
exact ( isdecincltoisincl _ ( isdecincldni n i ) ).
Defined.
(** ** The order-preserving functions [ sni n i : stn (S n) -> stn n ] that take the value [i] twice. *)
Definition sni {n : nat} ( i : ⟦n⟧ ) : ⟦n⟧ <- ⟦S n⟧.
Proof.
intros j. exists (si i j). unfold si. induction (natlthorgeh i j) as [lt|ge].
- induction j as [j J]. induction i as [i I]. simpl.
induction j as [|j _].
+ contradicts (negnatlthn0 i) lt.
+ change (S j - 1 < n).
change (S j) with (1 + j).
rewrite natpluscomm.
rewrite plusminusnmm.
exact J.
- induction i as [i I].
exact (natlehlthtrans _ _ _ ge I).
Defined.
(** ** Weak equivalences between standard finite sets and constructions on these sets *)
(** *** The weak equivalence from [ stn n ] to the complement of a point [ j ] in [ stn ( S n ) ] defined by [ dni j ] *)
Definition stn_compl {n : nat} (i: ⟦n⟧ ) := compl_ne _ i (stnneq i).
Definition dnitocompl ( n : nat ) ( i : ⟦S n⟧ ) : ⟦n⟧ -> stn_compl i.
Proof.
intros j.
exists ( dni i j ).
apply dni_neq_i.
Defined.
Lemma isweqdnitocompl ( n : nat ) ( i : ⟦S n⟧ ) : isweq ( dnitocompl n i ).
Proof.
intros jni.
assert ( w := samehfibers ( dnitocompl n i ) _ ( isinclpr1compl_ne _ i _ ) jni ) ;
simpl in w.
apply (iscontrweqb w).
apply iscontrhfiberdni.
exact (pr2 jni).
Defined.
Definition weqdnicompl {n : nat} (i: ⟦S n⟧ ): ⟦n⟧ ≃ stn_compl i.
Proof.
intros.
set (w := weqdicompl (stntonat _ i)).
assert (eq : ∏ j, j < n <-> pr1 (w j) < S n).
{ simpl in w. intros j. unfold w.
change (pr1 ((weqdicompl i) j)) with (di (stntonat _ i) j).
unfold di.
induction (natlthorgeh j i) as [lt|ge].
- split.
+ apply natlthtolths.
+ intros _. exact (natlehlthtrans (S j) i (S n) lt (pr2 i)).
- split; exact (idfun _). }
refine (_ ∘ (weq_subtypes w (λ j, j < n) (λ j, pr1 j < S n) eq))%weq.
use weqtotal2comm12.
Defined.
Definition weqdnicompl_compute {n : nat} (j: ⟦S n⟧ ) (i: ⟦n⟧ ) :
pr1 (weqdnicompl j i) = dni j i.
Proof.
intros.
apply subtypePath_prop.
apply idpath.
Defined.
(** *** Weak equivalence from [ coprod ( stn n ) unit ] to [ stn ( S n ) ] defined by [ dni i ] *)
Definition weqdnicoprod_provisional (n : nat) (j : ⟦S n⟧) : ⟦n⟧ ⨿ unit ≃ ⟦S n⟧.
Proof.
intros.
apply (weqcomp (weqcoprodf (weqdnicompl j) (idweq unit))
(weqrecompl_ne (⟦S n⟧) j (isdeceqstn (S n) j) (stnneq j))).
Defined.
Opaque weqdnicoprod_provisional.
Definition weqdnicoprod_map {n : nat} (j : ⟦S n⟧ ) : ⟦n⟧ ⨿ unit -> ⟦S n⟧.
Proof.
intros x. induction x as [i|t].
- exact (dni j i).
- exact j.
Defined.
Definition weqdnicoprod_compute {n : nat} (j : ⟦S n⟧ ) :
weqdnicoprod_provisional n j ~ weqdnicoprod_map j.
Proof.
intros.
intros i.
induction i as [i|i].
- apply subtypePath_prop. induction i as [i I]. apply idpath.
- apply idpath.
Defined.
Definition weqdnicoprod (n : nat) (j : ⟦S n⟧ ) : ⟦n⟧ ⨿ unit ≃ ⟦S n⟧.
Proof.
intros.
apply (make_weq (weqdnicoprod_map j)).
apply (isweqhomot _ _ (weqdnicoprod_compute _)).
apply weqproperty.
Defined.
Definition weqoverdnicoprod {n : nat} (P: ⟦S n⟧ → UU) :
(∑ i, P i) ≃ (∑ j, P(dni lastelement j)) ⨿ P lastelement.
Proof.
intros.
use (weqcomp (weqtotal2overcoprod' P (weqdnicoprod n lastelement))).
apply weqcoprodf.
- apply idweq.
- apply weqtotal2overunit.
Defined.
Lemma weqoverdnicoprod_eq1 {n : nat} (P: ⟦S n⟧ → UU) j p :
invmap (weqoverdnicoprod P) (ii1 (j,,p)) = ( dni lastelement j ,, p ).
Proof.
intros.
simpl in p.
apply idpath.
Defined.
Lemma weqoverdnicoprod_eq1' {n : nat} (P: ⟦S n⟧ → UU) jp :
invmap (weqoverdnicoprod P) (ii1 jp) = (total2_base_map (dni lastelement) jp).
Proof.
intros.
induction jp.
apply idpath.
Defined.
Lemma weqoverdnicoprod_eq2 {n : nat} (P: ⟦S n⟧→UU) p :
invmap (weqoverdnicoprod P) (ii2 p) = (lastelement ,, p ).
Proof.
intros.
apply idpath.
Defined.
Definition weqdnicoprod_invmap {n : nat} (j : ⟦S n⟧ ) : ⟦n⟧ ⨿ unit <- ⟦S n⟧.
(* perhaps use this to improve weqdnicoprod *)
Proof.
intros i.
induction (isdeceqstn (S n) i j) as [eq|ne].
- exact (ii2 tt).
- apply ii1. induction i as [i I]. induction j as [j J].
choose (i < j)%dnat a a.
+ exists i. exact (natltltSlt _ _ _ a J).
+ exists (i - 1).
induction (natlehchoice _ _ (negnatgthtoleh a)) as [b|b].
* induction (natlehchoice4 _ _ I) as [c|c].
-- apply (natlehlthtrans (i - 1) i n).
++ apply natminuslehn.
++ exact c.
-- induction c. apply natminuslthn.
++ apply (natlehlthtrans _ j _).
** apply natleh0n.
** exact b.
++ apply natlthnsn.
* induction b.
induction (ne (@subtypePath_prop _ _ (make_stn _ j I) (make_stn _ j J) (idpath j))).
Defined.
(** *** Weak equivalences from [ stn n ] for [ n = 0 , 1 , 2 ] to [ empty ] , [ unit ] and [ bool ] ( see also the section on [ nelstruct ] in finitesets.v ). *)
Definition negstn0 : ¬ (⟦0⟧).
Proof.
intro x.
destruct x as [ a b ].
apply ( negnatlthn0 _ b ).
Defined.
Definition weqstn0toempty : ⟦0⟧ ≃ empty.
Proof.
apply weqtoempty.
apply negstn0.
Defined.
Definition weqstn1tounit : ⟦1⟧ ≃ unit.
Proof.
set ( f := λ x : ⟦1⟧, tt ).
apply weqcontrcontr.
- split with lastelement.
intro t.
destruct t as [ t l ].
set ( e := natlth1tois0 _ l ).
apply ( invmaponpathsincl _ ( isinclstntonat 1 ) ( make_stn _ t l ) lastelement e ).
- apply iscontrunit.
Defined.
Corollary iscontrstn1 : iscontr (⟦1⟧).
Proof.
apply iscontrifweqtounit.
apply weqstn1tounit.
Defined.
Corollary isconnectedstn1 : ∏ i1 i2 : ⟦1⟧, i1 = i2.
Proof.
intros i1 i2.
apply (invmaponpathsweq weqstn1tounit).
apply isProofIrrelevantUnit.
Defined.
Lemma isinclfromstn1 { X : UU } ( f : ⟦1⟧ -> X ) ( is : isaset X ) : isincl f.
Proof.
intros.
apply ( isinclbetweensets f ( isasetstn 1 ) is ).
intros x x' e.
apply ( invmaponpathsweq weqstn1tounit x x' ( idpath tt ) ).
Defined.
Definition weqstn2tobool : ⟦2⟧ ≃ bool.
Proof.
set ( f := λ j : ⟦2⟧, match ( isdeceqnat j 0 ) with
ii1 _ => false
| ii2 _ => true
end ).
set ( g := λ b : bool, match b with
false => make_stn 2 0 ( idpath true )
| true => make_stn 2 1 ( idpath true )
end ).
split with f.
assert ( egf : ∏ j : _ , paths ( g ( f j ) ) j ).
{ intro j.
unfold f.
destruct ( isdeceqnat j 0 ) as [ e | ne ].
- apply ( invmaponpathsincl _ ( isinclstntonat 2 ) ).
rewrite e.
apply idpath.
- apply ( invmaponpathsincl _ ( isinclstntonat 2 ) ).
destruct j as [ j l ].
simpl.
set ( l' := natlthtolehsn _ _ l ).
destruct ( natlehchoice _ _ l' ) as [ l'' | e ].
+ simpl in ne.
destruct ( ne ( natlth1tois0 _ l'' ) ).
+ apply ( pathsinv0 ( invmaponpathsS _ _ e ) ).
}
assert ( efg : ∏ b : _ , paths ( f ( g b ) ) b ).
{ intro b.
unfold g.
destruct b.
- apply idpath.
- apply idpath.
}
apply ( isweq_iso _ _ egf efg ).
Defined.
Lemma isinjstntonat (n : nat) : isInjectiveFunction (pr1 : stnset n -> natset).
Proof.
intros i j.
apply subtypePath_prop.
Defined.
(** *** Weak equivalence between the coproduct of [ stn n ] and [ stn m ] and [ stn ( n + m ) ] *)
Definition weqfromcoprodofstn_invmap (n m : nat) : ⟦n + m⟧ -> (⟦n⟧ ⨿ ⟦m⟧).
Proof.
intros i.
induction (natlthorgeh i n) as [i1 | i2].
- exact (ii1 (make_stn n i i1)).
- exact (ii2 (make_stn m (i - n) (nat_split (pr2 i) i2))).
Defined.
Lemma weqfromcoprodofstn_invmap_r0 (n : nat) (i : ⟦n+0⟧ ) :
weqfromcoprodofstn_invmap n 0 i = ii1 (transportf stn (natplusr0 n) i).
Proof.
intros.
unfold weqfromcoprodofstn_invmap.
simpl.
induction (natlthorgeh i n) as [I|J].
- simpl. apply maponpaths. apply subtypePath_prop. simpl.
induction (natplusr0 n). apply idpath.
- simpl. apply fromempty. induction (! natplusr0 n).
exact (natgehtonegnatlth _ _ J (stnlt i)).
Defined.
Definition weqfromcoprodofstn_map (n m : nat) : (⟦n⟧ ⨿ ⟦m⟧) -> ⟦n+m⟧.
Proof.
intros i.
induction i as [i | i].
- apply stn_left. assumption.
- apply stn_right. assumption.
Defined.
Lemma weqfromcoprodofstn_eq1 (n m : nat) :
∏ x : ⟦n⟧ ⨿ ⟦m⟧, weqfromcoprodofstn_invmap n m (weqfromcoprodofstn_map n m x) = x.
Proof.
intros x.
unfold weqfromcoprodofstn_map, weqfromcoprodofstn_invmap. unfold coprod_rect.
induction x as [x | x].
- induction (natlthorgeh (stn_left n m x) n) as [H | H].
+ apply maponpaths. apply isinjstntonat. apply idpath.
+ apply fromempty. apply (natlthtonegnatgeh x n (stnlt x) H).
- induction (natlthorgeh (stn_right n m x) n) as [H | H].
+ apply fromempty.
set (tmp := natlehlthtrans n (n + x) n (natlehnplusnm n x) H).
use (isirrefl_natneq n (natlthtoneq _ _ tmp)).
+ apply maponpaths. apply isinjstntonat. cbn.
rewrite natpluscomm. apply plusminusnmm.
Qed.
Lemma weqfromcoprodofstn_eq2 (n m : nat) :
∏ y : ⟦n+m⟧, weqfromcoprodofstn_map n m (weqfromcoprodofstn_invmap n m y) = y.
Proof.
intros x.
unfold weqfromcoprodofstn_map, weqfromcoprodofstn_invmap. unfold coprod_rect.
induction (natlthorgeh x n) as [H | H].
- apply isinjstntonat. apply idpath.
- induction (natchoice0 m) as [H1 | H1].
+ apply fromempty. induction H1. induction (! (natplusr0 n)).
use (natlthtonegnatgeh x n (stnlt x) H).
+ apply isinjstntonat. cbn. rewrite natpluscomm. apply minusplusnmm. apply H.
Qed.
(** A proof of weqfromcoprodofstn using isweq_iso *)
Theorem weqfromcoprodofstn (n m : nat) : (⟦n⟧ ⨿ ⟦m⟧) ≃ ⟦n+m⟧.
Proof.
use (tpair _ (weqfromcoprodofstn_map n m)).
use (isweq_iso _ (weqfromcoprodofstn_invmap n m)).
- exact (weqfromcoprodofstn_eq1 n m).
- exact (weqfromcoprodofstn_eq2 n m).
Defined.
(** Associativity of [weqfromcoprodofstn] *)
Definition pr1_eqweqmap_stn (m n : nat) (e: m=n) (i: ⟦m⟧ ) :
pr1 (pr1weq (eqweqmap (maponpaths stn e)) i) = pr1 i.
Proof.
intros.
induction e.
apply idpath.
Defined.
Definition coprod_stn_assoc (l m n : nat) : (
eqweqmap (maponpaths stn (natplusassoc l m n))
∘ weqfromcoprodofstn (l+m) n
∘ weqcoprodf (weqfromcoprodofstn l m) (idweq _)
~
weqfromcoprodofstn l (m+n)
∘ weqcoprodf (idweq _) (weqfromcoprodofstn m n)
∘ weqcoprodasstor _ _ _
) %weq.
Proof.
intros.
intros abc.
simpl.
apply (invmaponpathsincl pr1). apply isinclstntonat.
rewrite pr1_eqweqmap_stn.
induction abc as [[a|b]|c].
- simpl. apply idpath.
- simpl. apply idpath.
- simpl. apply natplusassoc.
Defined.
(** *** Weak equivalence from the total space of a family [ stn ( f x ) ] over [ stn n ] to [ stn ( stnsum n f ) ] *)
Definition stnsum {n : nat} (f : ⟦n⟧ -> nat) : nat.
Proof.
revert f.
induction n as [ | n IHn].
- intro. exact 0.
- intro f. exact (IHn (λ i, f (dni lastelement i)) + f lastelement).
Defined.
Lemma stnsum_step {n : nat} (f: ⟦S n⟧ -> nat) :
stnsum f = stnsum (f ∘ (dni lastelement)) + f lastelement.
Proof.
intros.
apply idpath.
Defined.
Lemma stnsum_eq {n : nat} (f g: ⟦n⟧ -> nat) : f ~ g -> stnsum f = stnsum g.
Proof.
intros h.
induction n as [|n IH].
- apply idpath.
- rewrite 2? stnsum_step.
induction (h lastelement).
apply (maponpaths (λ i, i + f lastelement)).
apply IH.
intro x.
apply h.
Defined.
Lemma transport_stnsum {m n : nat} (e: m=n) (g: ⟦n⟧ -> nat) :
stnsum g = stnsum (λ i, g(transportf stn e i)).
Proof.
intros.
induction e.
apply idpath.
Defined.
Lemma stnsum_le {n : nat} (f g: ⟦n⟧ -> nat) : (∏ i, f i ≤ g i) -> stnsum f ≤ stnsum g.
Proof.
intros le.
induction n as [|n IH].
- simpl. apply idpath.
- apply natlehandplus.
+ apply IH. intro i. apply le.
+ apply le.
Defined.
Lemma transport_stn {m n : nat} (e: m=n) (i: ⟦m⟧ ) :
transportf stn e i = make_stn n (pr1 i) (transportf (λ k, pr1 i < k) e (pr2 i)).
Proof.
intros.
induction e.
apply subtypePath_prop.
apply idpath.
Defined.
Lemma stnsum_left_right (m n : nat) (f: ⟦m+n⟧ -> nat) :
stnsum f = stnsum (f ∘ stn_left m n) + stnsum (f ∘ stn_right m n).
Proof.
(* why is this proof so obnoxious and fragile? *)
intros. induction n as [|n IHn].
{ change (stnsum _) with 0 at 3. rewrite natplusr0.
assert (e := ! natplusr0 m).
rewrite (transport_stnsum e). apply stnsum_eq; intro i. simpl.
apply maponpaths. apply pathsinv0. apply stn_left_0. }
rewrite stnsum_step. assert (e : S (m+n) = m + S n).
{ apply pathsinv0. apply natplusnsm. }
rewrite (transport_stnsum e).
rewrite stnsum_step. rewrite <- natplusassoc. apply map_on_two_paths.
{ rewrite IHn; clear IHn. apply map_on_two_paths.
{ apply stnsum_eq; intro i. simpl.
apply maponpaths. apply subtypePath_prop.
rewrite stn_left_compute. induction e.
rewrite idpath_transportf. rewrite dni_last.
apply idpath. }
{ apply stnsum_eq; intro i. simpl.
apply maponpaths. apply subtypePath_prop.
rewrite stn_right_compute. unfold stntonat. induction e.
rewrite idpath_transportf. rewrite 2? dni_last. apply idpath. } }
simpl. apply maponpaths. apply subtypePath_prop.
induction e. apply idpath.
Defined.
Corollary stnsum_left_le (m n : nat) (f: ⟦m+n⟧ -> nat) :
stnsum (f ∘ stn_left m n) ≤ stnsum f.
Proof.
intros.
rewrite stnsum_left_right.
apply natlehnplusnm.
Defined.
Corollary stnsum_left_le' {m n : nat} (f: ⟦n⟧ -> nat) (r:m≤n) :
stnsum (f ∘ stn_left' m n r) ≤ stnsum f.
Proof.
intros.
assert (s := minusplusnmm n m r). rewrite (natpluscomm (n-m) m) in s.
generalize r f; clear r f.
rewrite <- s; clear s.
set (k := n-m).
generalize k; clear k; intros k r f.
induction (natpluscomm m k).
rewrite stn_left_compare.
rewrite stnsum_left_right.
apply natlehnplusnm.
Defined.
Lemma stnsum_dni {n : nat} (f: ⟦S n⟧ -> nat) (j: ⟦S n⟧ ) :
stnsum f = stnsum (f ∘ dni j) + f j.
Proof.
intros.
induction j as [j J].
assert (e2 : j + (n - j) = n).
{ rewrite natpluscomm. apply minusplusnmm. apply natlthsntoleh. exact J. }
assert (e : (S j) + (n - j) = S n).
{ change (S j + (n - j)) with (S (j + (n - j))). apply maponpaths. exact e2. }
intermediate_path (stnsum (λ i, f (transportf stn e i))).
- apply (transport_stnsum e).
- rewrite (stnsum_left_right (S j) (n - j)); unfold funcomp.
apply pathsinv0. rewrite (transport_stnsum e2).
rewrite (stnsum_left_right j (n-j)); unfold funcomp.
rewrite (stnsum_step (λ x, f (transportf stn e _))); unfold funcomp.
apply pathsinv0.
rewrite natplusassoc. rewrite (natpluscomm (f _)). rewrite <- natplusassoc.
apply map_on_two_paths.
+ apply map_on_two_paths.
* apply stnsum_eq; intro i. induction i as [i I].
apply maponpaths. apply subtypePath_prop.
induction e. rewrite idpath_transportf. rewrite stn_left_compute.
unfold dni,di, stntonat; simpl.
induction (natlthorgeh i j) as [R|R].
-- unfold stntonat; simpl; rewrite transport_stn; simpl.
induction (natlthorgeh i j) as [a|b].
++ apply idpath.
++ contradicts R (natlehneggth b).
-- unfold stntonat; simpl; rewrite transport_stn; simpl.
induction (natlthorgeh i j) as [V|V].
++ contradicts I (natlehneggth R).
++ apply idpath.
* apply stnsum_eq; intro i. induction i as [i I]. apply maponpaths.
unfold dni,di, stn_right, stntonat; repeat rewrite transport_stn; simpl.
induction (natlthorgeh (j+i) j) as [X|X].
-- contradicts (negnatlthplusnmn j i) X.
-- apply subtypePath_prop. simpl. apply idpath.
+ apply maponpaths.
rewrite transport_stn; simpl.
apply subtypePath_prop.
apply idpath.
Defined.
Lemma stnsum_pos {n : nat} (f: ⟦n⟧ -> nat) (j: ⟦n⟧ ) : f j ≤ stnsum f.
Proof.
assert (m : 0 < n).
{ apply (natlehlthtrans _ j).
- apply natleh0n.
- exact (pr2 j). }
assert (l : 1 ≤ n). { apply natlthtolehsn. assumption. }
assert (e : n = S (n - 1)).
{ change (S (n - 1)) with (1 + (n - 1)). rewrite natpluscomm.
apply pathsinv0. apply minusplusnmm. assumption. }
rewrite (transport_stnsum (!e) f).
rewrite (stnsum_dni _ (transportf stn e j)).
unfold funcomp.
generalize (stnsum (λ x, f (transportf stn (! e) (dni (transportf stn e j) x)))); intro s.
induction e. apply natlehmplusnm.
Defined.
Corollary stnsum_pos_0 {n : nat} (f: ⟦S n⟧ -> nat) : f firstelement ≤ stnsum f.
Proof.
intros.
exact (stnsum_pos f firstelement).
Defined.
Lemma stnsum_1 (n : nat) : stnsum(λ i: ⟦n⟧, 1) = n.
Proof.
intros.
induction n as [|n IH].
{ apply idpath. }
simpl.
use (natpluscomm _ _ @ _).
apply maponpaths.
exact IH.
Defined.
Lemma stnsum_const {m c : nat} : stnsum (λ i: ⟦m⟧, c) = m*c.
Proof.
intros.
induction m as [|m I].
- apply idpath.
- exact (maponpaths (λ i, i+c) I).
Defined.
Lemma stnsum_last_le {n : nat} (f: ⟦S n⟧ -> nat) : f lastelement ≤ stnsum f.
Proof.
intros. rewrite stnsum_step. apply natlehmplusnm.
Defined.
Lemma stnsum_first_le {n : nat} (f: ⟦S n⟧ -> nat) : f firstelement ≤ stnsum f.
Proof.
intros. induction n as [|n IH].
- apply isreflnatleh.
- rewrite stnsum_step. assert (W := IH (f ∘ dni lastelement)).
change ((f ∘ dni lastelement) firstelement) with (f firstelement) in W.
apply (istransnatleh W); clear W. apply natlehnplusnm.
Defined.
Lemma _c_ {n : nat} {m: ⟦ n ⟧ → nat} (ij : ∑ i : ⟦ n ⟧, ⟦ m i ⟧) :
stnsum (m ∘ stn_left'' (stnlt (pr1 ij))) + pr2 ij < stnsum m.
Proof.
intros.
set (m1 := m ∘ stn_left'' (stnlt (pr1 ij))).
induction ij as [i j].
induction i as [i I].
induction j as [j J].
simpl in m1.
change (stnsum m1 + j < stnsum m).
assert (s := stnsum_left_le' m (I : S i ≤ n)).
use (natlthlehtrans _ _ _ _ s).
clear s.
induction n as [|n _].
- induction (negnatlthn0 _ I).
- assert (t : stnsum m1 + j < stnsum m1 + m (i,,I)).
{ apply natlthandplusl. exact J. }
apply (natlthlehtrans _ _ _ t).
assert (K : ∏ m n, m = n -> m ≤ n).
{ intros a b e. induction e. apply isreflnatleh. }
apply K; clear K.
rewrite stnsum_step.
clear j J t.
unfold m1 ; clear m1.
apply two_arg_paths.
+ apply stnsum_eq. intro l.
simpl. apply maponpaths.
apply subtypePath_prop; simpl.
apply pathsinv0, di_eq1, stnlt.
+ simpl. apply maponpaths. apply subtypePath_prop.
simpl. apply idpath.
Defined.
Local Definition weqstnsum_map { n : nat } (m : ⟦n⟧ -> nat) :
(∑ i, ⟦m i⟧) -> ⟦stnsum m⟧.
Proof.
intros ij.
exact (make_stn _ (stnsum (m ∘ stn_left'' (stnlt (pr1 ij))) + pr2 ij) (_c_ ij)).
Defined.
Local Definition weqstnsum_invmap {n : nat} (m : ⟦n⟧ -> nat) :
⟦stnsum m⟧ -> (∑ i, ⟦m i⟧).
Proof.
revert m.
induction n as [|n IH].
{ intros ? l. apply fromempty, negstn0. assumption. }
intros ? l.
change (⟦ stnsum (m ∘ dni lastelement) + m lastelement ⟧) in l.
(* we are careful to use weqfromcoprodofstn_invmap both here and in concatenate' *)
assert (ls := weqfromcoprodofstn_invmap _ _ l).
induction ls as [j|k].
- exact (total2_base_map (dni lastelement) (IH _ j)).
- exact (lastelement,,k).
Defined.
Definition weqstnsum_invmap_step1 {n : nat} (f : ⟦S n⟧ -> nat)
(j : stn (stnsum (λ x, f (dni lastelement x)))) :
weqstnsum_invmap f
(weqfromcoprodofstn_map (stnsum (λ x, f (dni lastelement x)))
(f lastelement) (ii1 j))
= total2_base_map (dni lastelement) (weqstnsum_invmap (f ∘ dni lastelement) j).
Proof.
intros. unfold weqstnsum_invmap at 1. unfold nat_rect at 1.
rewrite weqfromcoprodofstn_eq1. apply idpath.
Defined.
Definition weqstnsum_invmap_step2 {n : nat} (f : ⟦S n⟧ -> nat)
(k : ⟦f lastelement⟧) :
weqstnsum_invmap f
(weqfromcoprodofstn_map (stnsum (λ x, f (dni lastelement x)))
(f lastelement) (ii2 k))
= (lastelement,,k).
Proof.
intros. unfold weqstnsum_invmap at 1. unfold nat_rect at 1.
rewrite weqfromcoprodofstn_eq1. apply idpath.
Defined.
Lemma partial_sum_prop_aux {n : nat} {m : ⟦n⟧ → nat} :
∏ (i i' : ⟦ n ⟧) (j : ⟦ m i ⟧) (j' : ⟦ m i' ⟧),
i < i' → stnsum (m ∘ stn_left'' (stnlt i)) + j <
stnsum (m ∘ stn_left'' (stnlt i')) + j'.
Proof.
intros ? ? ? ? lt.
apply natlthtolehsn in lt.
pose (ltS := (natlehlthtrans _ _ _ lt (stnlt i'))).
refine (natlthlehtrans _ _ _ _ (natlehnplusnm _ _)).
apply natlthlehtrans with (stnsum (m ∘ stn_left'' ltS)).
- rewrite stnsum_step.
assert (stnsum (m ∘ stn_left'' (stnlt i)) =
stnsum (m ∘ stn_left'' ltS ∘ dni lastelement)) as e. {
apply stnsum_eq.
intros k.
simpl. apply maponpaths.
apply subtypePath_prop. simpl.
apply pathsinv0, di_eq1.
apply (stnlt k).
}
induction e.
apply natlthandplusl.
assert ((m ∘ stn_left'' ltS) lastelement = m i) as e. {
simpl. apply maponpaths.
apply subtypePath_prop, idpath.
}
induction e.
apply (stnlt j).
- assert (stnsum (m ∘ stn_left'' ltS) =
stnsum (m ∘ stn_left'' (stnlt i') ∘ stn_left' _ _ lt)) as e. {
apply stnsum_eq.
intros k.
simpl. apply maponpaths.
apply subtypePath_prop, idpath.
}
rewrite e.
apply stnsum_left_le'.
Defined.
Lemma partial_sum_prop {n : nat} {m : ⟦n⟧ → nat} {l : nat} :
isaprop (∑ (i : ⟦n⟧ ) (j : ⟦m i⟧ ), stnsum (m ∘ stn_left'' (stnlt i)) + j = l).
Proof.
intros.
apply invproofirrelevance.
intros t t'.
induction t as [i je]. induction je as [j e].
induction t' as [i' je']. induction je' as [j' e'].
pose (e'' := e @ !e').
assert (i = i') as p. {
induction (nat_eq_or_neq i i') as [eq | ne].
+ apply subtypePath_prop. assumption.
+ apply fromempty.
generalize e''.
apply nat_neq_to_nopath.
induction (natneqchoice _ _ ne);
[apply natgthtoneq | apply natlthtoneq];
apply partial_sum_prop_aux;
assumption.
}
apply total2_paths_f with p.
- use total2_paths_f.
+ induction p. simpl.
apply subtypePath_prop.
apply (natpluslcan _ _ _ e'').
+ apply isasetnat.
Defined.
Lemma partial_sum_slot {n : nat} {m : ⟦n⟧ → nat} {l : nat} : l < stnsum m ->
∃! (i : ⟦n⟧ ) (j : ⟦m i⟧ ), stnsum (m ∘ stn_left'' (stnlt i)) + j = l.
Proof.
intros lt.
set (len := stnsum m).
induction n as [|n IH].
{ apply fromempty. change (hProptoType(l < 0)) in lt. exact (negnatlthn0 _ lt). }
set (m' := m ∘ dni_lastelement).
set (len' := stnsum m').
induction (natlthorgeh l len') as [I|J].
- assert (IH' := IH m' I); clear IH.
induction IH' as [ijJ Q]. induction ijJ as [i jJ]. induction jJ as [j J].
use tpair.
+ exists (dni_lastelement i). exists j.
abstract (use (_ @ J); apply (maponpaths (λ x, x+j)); apply stnsum_eq; intro r;
unfold m'; simpl; apply maponpaths; apply subtypePath_prop, idpath).
+ intro t.
apply partial_sum_prop.
- clear IH. set (j := l - len').
apply iscontraprop1.
{ apply partial_sum_prop. }
assert (K := minusplusnmm _ _ J). change (l-len') with j in K.
exists lastelement.
use tpair.
* exists j. apply (natlthandpluslinv _ _ len'). rewrite natpluscomm.
induction (!K); clear K J j.
assert(C : len = len' + m lastelement).
{ use (stnsum_step _ @ _). unfold len', m'; clear m' len'.
rewrite replace_dni_last. apply idpath. }
induction C. exact lt.
* simpl. intermediate_path (stnsum m' + j).
-- apply (maponpaths (λ x, x+j)). apply stnsum_eq; intro i.
unfold m'. simpl. apply maponpaths.
apply subtypePath_prop, idpath.
-- rewrite natpluscomm. exact K.
Defined.
Lemma stn_right_first (n i : nat) :
stn_right i (S n) firstelement = make_stn (i + S n) i (natltplusS n i).
Proof.
intros.
apply subtypePath_prop.
simpl.
apply natplusr0.
Defined.
Lemma nat_rect_step (P : nat → UU) (p0 : P 0) (IH : ∏ n, P n → P (S n)) n :
nat_rect P p0 IH (S n) = IH n (nat_rect P p0 IH n).
Proof.
intros.
apply idpath.
Defined.
Definition weqstnsum1_prelim {n : nat} (f : ⟦n⟧ -> nat) :
(∑ i, ⟦f i⟧) ≃ ⟦stnsum f⟧.
Proof.
revert f.
induction n as [ | n' IHn ].
{ intros f. apply weqempty.
- exact (negstn0 ∘ pr1).
- exact negstn0. }
intros f.
change (⟦stnsum f⟧) with (⟦stnsum (f ∘ dni lastelement) + f lastelement⟧).
use (weqcomp _ (weqfromcoprodofstn _ _)).
use (weqcomp (weqoverdnicoprod _) _).
apply weqcoprodf1.
apply IHn.
Defined.
Lemma weqstnsum1_step {n : nat} (f : ⟦S n⟧ -> nat)
: (
weqstnsum1_prelim f
=
weqfromcoprodofstn (stnsum (funcomp (dni lastelement) f)) (f lastelement)
∘ (weqcoprodf1 (weqstnsum1_prelim (λ i, f (dni lastelement i)))
∘ weqoverdnicoprod (λ i, ⟦ f i ⟧))) % weq.
Proof.
intros.
apply idpath.
Defined.
Lemma weqstnsum1_prelim_eq { n : nat } (f : ⟦n⟧ -> nat) :
weqstnsum1_prelim f ~ weqstnsum_map f.
Proof.
revert f.
induction n as [|n I].
- intros f ij. apply fromempty, negstn0. exact (pr1 ij).
- intros f.
rewrite weqstnsum1_step.
intros ij.
rewrite 2 weqcomp_to_funcomp_app.
unfold weqcoprodf1.
change (pr1weq (weqcoprodf (weqstnsum1_prelim (λ i, f (dni lastelement i)))
(idweq (⟦ f lastelement ⟧))))
with (coprodf (weqstnsum1_prelim (λ i, f (dni lastelement i)))
(idfun (⟦ f lastelement ⟧))).
intermediate_path
((weqfromcoprodofstn (stnsum (f ∘ dni lastelement)) (f lastelement))
(coprodf (weqstnsum_map (λ i, f (dni lastelement i)))
(idfun (⟦ f lastelement ⟧)) ((weqoverdnicoprod (λ i, ⟦ f i ⟧)) ij))).
+ apply maponpaths.
apply homotcoprodfhomot.
* apply I.
* intro x. apply idpath.
+ clear I.
apply pathsinv0.
generalize ij ; clear ij.
apply (homotweqinv' (weqstnsum_map f)
(weqoverdnicoprod (λ i : ⟦ S n ⟧, ⟦ f i ⟧))
(λ c, pr1weq (weqfromcoprodofstn (stnsum (f ∘ dni lastelement)) (f lastelement))
(coprodf (weqstnsum_map (λ i, f (dni lastelement i)))
(idfun _) c))
).
intros c.
simpl.
set (P := λ i, ⟦ f i ⟧).
change (pr1weq (weqfromcoprodofstn (stnsum (λ x : ⟦ n ⟧, f (dni lastelement x))) (f lastelement)))
with (weqfromcoprodofstn_map (stnsum (λ x : ⟦ n ⟧, f (dni lastelement x))) (f lastelement)).
induction c as [jk|k].
* unfold coprodf.
induction jk as [j k].
change (invmap (weqoverdnicoprod P) (ii1 (j,,k))) with (tpair P (dni lastelement j) k).
unfold weqfromcoprodofstn_map. unfold coprod_rect. unfold weqstnsum_map.
apply subtypePath_prop.
induction k as [k K]. simpl.
apply (maponpaths (λ x, x+k)). unfold funcomp, stntonat, di.
clear K k.
induction (natlthorgeh _ n) as [G|G'].
-- simpl. apply stnsum_eq; intro k. apply maponpaths.
apply subtypePath_prop. simpl.
apply pathsinv0, di_eq1.
exact (istransnatlth _ _ _ (stnlt k) G).
-- apply fromempty. exact (natlthtonegnatgeh _ _ (stnlt j) G').
* change (invmap (weqoverdnicoprod P) (ii2 k)) with (tpair P lastelement k).
simpl.
unfold weqstnsum_map.
apply subtypePath_prop.
induction k as [k K]. simpl.
apply (maponpaths (λ x, x+k)).
apply maponpaths.
apply funextfun; intro i. induction i as [i I].
simpl. apply maponpaths.
apply subtypePath_prop.
simpl.
apply pathsinv0, di_eq1. assumption.
Defined.
Lemma weqstnsum1_prelim_eq' { n : nat } (f : ⟦n⟧ -> nat) :
invweq (weqstnsum1_prelim f) ~ weqstnsum_invmap f.
Proof.
revert f.
induction n as [|n I].
- intros f k. apply fromempty, negstn0. exact k.
- intros f. rewrite weqstnsum1_step.
intros k. rewrite 2 invweqcomp. rewrite 2 weqcomp_to_funcomp_app. rewrite 3 pr1_invweq.
unfold weqcoprodf1.
change (invmap (weqcoprodf (weqstnsum1_prelim (λ i, f (dni lastelement i))) (idweq (⟦ f lastelement ⟧))))
with (coprodf (invweq (weqstnsum1_prelim (λ i, f (dni lastelement i)))) (idweq (⟦ f lastelement ⟧))).
intermediate_path (invmap (weqoverdnicoprod (λ i : ⟦ S n ⟧, ⟦ f i ⟧))
(coprodf (weqstnsum_invmap (λ i : ⟦ n ⟧, f (dni lastelement i))) (idweq (⟦ f lastelement ⟧))
(invmap (weqfromcoprodofstn (stnsum (f ∘ dni lastelement)) (f lastelement)) k))).
+ apply maponpaths.
change (invmap _ k)
with (invmap (weqfromcoprodofstn (stnsum (f ∘ dni lastelement)) (f lastelement)) k).
generalize (invmap (weqfromcoprodofstn (stnsum (f ∘ dni lastelement)) (f lastelement)) k).
intro c.
apply homotcoprodfhomot.
* apply I.
* apply homotrefl.
+ clear I.
generalize k; clear k.
use (homotweqinv
(λ c, invmap (weqoverdnicoprod (λ i, ⟦ f i ⟧))
(coprodf (weqstnsum_invmap (λ i, f (dni lastelement i)))
(idweq (⟦ f lastelement ⟧))
c))
(weqfromcoprodofstn (stnsum (f ∘ dni lastelement)) (f lastelement))
).
unfold funcomp.
intro c.
induction c as [r|s].
* unfold coprodf.
change (pr1weq (weqfromcoprodofstn (stnsum (λ x, f (dni lastelement x))) (f lastelement)))
with (weqfromcoprodofstn_map (stnsum (λ x, f (dni lastelement x))) (f lastelement)).
set (P := (λ i : ⟦ S n ⟧, ⟦ f i ⟧)).
rewrite weqstnsum_invmap_step1.
change (λ i : ⟦ n ⟧, f (dni lastelement i)) with (f ∘ dni lastelement).
generalize (weqstnsum_invmap (f ∘ dni lastelement) r); intro ij.
induction ij as [i j].
apply idpath.
* unfold coprodf.
change (pr1weq (idweq _) s) with s.
set (P := (λ i : ⟦ S n ⟧, ⟦ f i ⟧)).
change (pr1weq _)
with (weqfromcoprodofstn_map (stnsum (λ x : ⟦ n ⟧, f (dni lastelement x))) (f lastelement)).
rewrite weqstnsum_invmap_step2.
apply idpath.
Defined.
Definition weqstnsum1 {n : nat} (f : ⟦n⟧ -> nat) : (∑ i, ⟦f i⟧) ≃ ⟦stnsum f⟧.
Proof.
intros. use (remakeweqboth (weqstnsum1_prelim_eq _) (weqstnsum1_prelim_eq' _)).
Defined.
Lemma weqstnsum1_eq {n : nat} (f : ⟦n⟧ -> nat) : pr1weq (weqstnsum1 f) = weqstnsum_map f.
Proof.
intros.
apply idpath.
Defined.
Lemma weqstnsum1_eq' {n : nat} (f : ⟦n⟧ -> nat) : invmap (weqstnsum1 f) = weqstnsum_invmap f.
Proof.
intros.
apply idpath.
Defined.
Theorem weqstnsum { n : nat } (P : ⟦n⟧ -> UU) (f : ⟦n⟧ -> nat) :
(∏ i, ⟦f i⟧ ≃ P i) -> total2 P ≃ ⟦stnsum f⟧.
Proof.
intros w.
intermediate_weq (∑ i, ⟦f i⟧).
- apply invweq. apply weqfibtototal. assumption.
- apply weqstnsum1.
Defined.
Corollary weqstnsum2 { X : UU } {n : nat} (f : ⟦n⟧ -> nat) (g : X -> ⟦n⟧ ) :
(∏ i, ⟦f i⟧ ≃ hfiber g i) -> X ≃ ⟦stnsum f⟧.
Proof.
intros w.
use (weqcomp _ (weqstnsum _ _ w)).
apply weqtococonusf.
Defined.
(** lexical enumeration of pairs of natural numbers *)
Definition lexicalEnumeration {n : nat} (m: ⟦n⟧ -> nat) :
⟦stnsum m⟧ ≃ (∑ i : ⟦n⟧, ⟦m i⟧) := invweq (weqstnsum1 m).
Definition inverse_lexicalEnumeration {n : nat} (m: ⟦n⟧ -> nat) :
(∑ i : ⟦n⟧, ⟦m i⟧) ≃ ⟦stnsum m⟧ := weqstnsum1 m.
(** two generalizations of stnsum, potentially useful *)
Definition foldleft {E} (e : E) (m : binop E) {n : nat} (x: ⟦n⟧ -> E) : E.
Proof.
intros.
induction n as [|n foldleft].
+ exact e.
+ exact (m (foldleft (x ∘ (dni lastelement))) (x lastelement)).
Defined.
Definition foldright {E} (m : binop E) (e : E) {n : nat} (x: ⟦n⟧ -> E) : E.
Proof.
intros.
induction n as [|n foldright].
+ exact e.
+ exact (m (x firstelement) (foldright (x ∘ dni firstelement))).
Defined.
(** *** Weak equivalence between the direct product of [ stn n ] and [ stn m ] and [ stn n * m ] *)
Theorem weqfromprodofstn ( n m : nat ) : ⟦n⟧ × ⟦m⟧ ≃ ⟦n*m⟧.
Proof.
intros.
induction ( natgthorleh m 0 ) as [ is | i ].
- assert ( i1 : ∏ i j : nat, i < n -> j < m -> j + i * m < n * m).
+ intros i j li lj.
apply (natlthlehtrans ( j + i * m ) ( ( S i ) * m ) ( n * m )).
* change (S i * m) with (i*m + m).
rewrite natpluscomm.
exact (natgthandplusl m j ( i * m ) lj ).
* exact ( natlehandmultr ( S i ) n m ( natgthtogehsn _ _ li ) ).
+ set ( f := λ ij : ⟦n⟧ × ⟦m⟧,
match ij
with tpair _ i j =>
make_stn ( n * m ) ( j + i * m ) ( i1 i j ( pr2 i ) ( pr2 j ) )
end ).
split with f.
assert ( isinf : isincl f ).
* apply isinclbetweensets.
apply ( isofhleveldirprod 2 _ _ ( isasetstn n ) ( isasetstn m ) ).
apply ( isasetstn ( n * m ) ).
intros ij ij' e. destruct ij as [ i j ]. destruct ij' as [ i' j' ].
destruct i as [ i li ]. destruct i' as [ i' li' ].
destruct j as [ j lj ]. destruct j' as [ j' lj' ].
simpl in e.
assert ( e' := maponpaths ( stntonat ( n * m ) ) e ). simpl in e'.
assert ( eei : i = i' ).
{ apply ( pr1 ( natdivremunique m i j i' j' lj lj' ( maponpaths ( stntonat _ ) e ) ) ). }
set ( eeis := invmaponpathsincl _ ( isinclstntonat _ ) ( make_stn _ i li ) ( make_stn _ i' li' ) eei ).
assert ( eej : j = j' ).
{ apply ( pr2 ( natdivremunique m i j i' j' lj lj' ( maponpaths ( stntonat _ ) e ) ) ). }
set ( eejs := invmaponpathsincl _ ( isinclstntonat _ ) ( make_stn _ j lj ) ( make_stn _ j' lj' ) eej ).
apply ( pathsdirprod eeis eejs ).
* intro xnm.
apply iscontraprop1. apply ( isinf xnm ).
set ( e := pathsinv0 ( natdivremrule xnm m ( natgthtoneq _ _ is ) ) ).
set ( i := natdiv xnm m ). set ( j := natrem xnm m ).
destruct xnm as [ xnm lxnm ].
set ( li := natlthandmultrinv _ _ _ ( natlehlthtrans _ _ _ ( natlehmultnatdiv xnm m ( natgthtoneq _ _ is ) ) lxnm ) ).
set ( lj := lthnatrem xnm m ( natgthtoneq _ _ is ) ).
split with ( make_dirprod ( make_stn n i li ) ( make_stn m j lj ) ).
simpl.
apply ( invmaponpathsincl _ ( isinclstntonat _ ) _ _ ). simpl.
apply e.
- set ( e := natleh0tois0 i ). rewrite e. rewrite ( natmultn0 n ). split with ( @pr2 _ _ ). apply ( isweqtoempty2 _ ( weqstn0toempty ) ).
Defined.
(** *** Weak equivalences between decidable subsets of [ stn n ] and [ stn x ] *)
Theorem weqfromdecsubsetofstn { n : nat } ( f : ⟦n⟧ -> bool ) :
total2 ( λ x : nat, hfiber f true ≃ (⟦x⟧) ).
Proof.
revert f.
induction n as [ | n IHn ].
- intros.
split with 0.
assert ( g : hfiber f true -> (⟦0⟧) ).
{ intro hf.
destruct hf as [ i e ].
destruct ( weqstn0toempty i ).
}
apply ( weqtoempty2 g weqstn0toempty ).
- intro.
set ( g := weqfromcoprodofstn 1 n ).
change ( 1 + n ) with ( S n ) in g.
set ( fl := λ i : ⟦1⟧, f ( g ( ii1 i ) ) ).
set ( fh := λ i : ⟦n⟧, f ( g ( ii2 i ) ) ).
assert ( w : ( hfiber f true ) ≃ ( hfiber ( sumofmaps fl fh ) true ) ).
{ set ( int := invweq ( weqhfibersgwtog g f true ) ).
assert ( h : ∏ x : _ , paths ( f ( g x ) ) ( sumofmaps fl fh x ) ).
{ intro.
destruct x as [ x1 | xn ].
+ apply idpath.
+ apply idpath.
}
apply ( weqcomp int ( weqhfibershomot _ _ h true ) ).
}
set ( w' := weqcomp w ( invweq ( weqhfibersofsumofmaps fl fh true ) ) ).
set ( x0 := pr1 ( IHn fh ) ).
set ( w0 := pr2 ( IHn fh ) ).
simpl in w0.
destruct ( boolchoice ( fl lastelement ) ) as [ i | ni ].
+ split with ( S x0 ).
assert ( wi : hfiber fl true ≃ ⟦1⟧ ).
{ assert ( is : iscontr ( hfiber fl true ) ).
{ apply iscontraprop1.
* apply ( isinclfromstn1 fl isasetbool true ).
* apply ( make_hfiber _ lastelement i ).
}
apply ( weqcontrcontr is iscontrstn1 ).
}
apply ( weqcomp ( weqcomp w' ( weqcoprodf wi w0 ) ) ( weqfromcoprodofstn 1 _ ) ).
+ split with x0.
assert ( g' : ¬ ( hfiber fl true ) ).
{ intro hf.
destruct hf as [ j e ].
assert ( ee : j = lastelement ).
{ apply proofirrelevancecontr, iscontrstn1. }
destruct ( nopathstruetofalse ( pathscomp0 ( pathscomp0 ( pathsinv0 e ) ( maponpaths fl ee ) ) ni ) ).
}
apply ( weqcomp w' ( weqcomp ( invweq ( weqii2withneg _ g' ) ) w0 ) ).
Defined.
(** *** Weak equivalences between hfibers of functions from [ stn n ] over isolated points and [ stn x ] *)
Theorem weqfromhfiberfromstn { n : nat } { X : UU } ( x : X )
( is : isisolated X x ) ( f : ⟦n⟧ -> X ) :
total2 ( λ x0 : nat, hfiber f x ≃ (⟦x0⟧) ).
Proof.
intros.
set ( t := weqfromdecsubsetofstn ( λ i : _, eqbx X x is ( f i ) ) ).
split with ( pr1 t ).
apply ( weqcomp ( weqhfibertobhfiber f x is ) ( pr2 t ) ).
Defined.
(** *** Weak equivalence between [ stn n -> stn m ] and [ stn ( natpower m n ) ] ( uses functional extensionality ) *)
Theorem weqfromfunstntostn ( n m : nat ) : (⟦n⟧ -> ⟦m⟧) ≃ ⟦natpower m n⟧.
Proof.
revert m.
induction n as [ | n IHn ].
- intro m.
apply weqcontrcontr.
+ apply ( iscontrfunfromempty2 _ weqstn0toempty ).
+ apply iscontrstn1.
- intro m.
set ( w1 := weqfromcoprodofstn 1 n ).
assert ( w2 : ( ⟦S n⟧ -> ⟦m⟧ ) ≃ ( (⟦1⟧ ⨿ ⟦n⟧) -> ⟦m⟧ ) ) by apply ( weqbfun _ w1 ).
set ( w3 := weqcomp w2 ( weqfunfromcoprodtoprod (⟦1⟧) (⟦n⟧) (⟦m⟧) ) ).
set ( w4 := weqcomp w3 ( weqdirprodf ( weqfunfromcontr (⟦m⟧) iscontrstn1 ) ( IHn m ) ) ).
apply ( weqcomp w4 ( weqfromprodofstn m ( natpower m n ) ) ).
Defined.
(** *** Weak equivalence from the space of functions of a family [ stn ( f x ) ] over [ stn n ] to [ stn ( stnprod n f ) ] ( uses functional extensionality ) *)
Definition stnprod { n : nat } ( f : ⟦n⟧ -> nat ) : nat.
Proof.
revert f.
induction n as [ | n IHn ].
- intro.
apply 1.
- intro f.
apply ( ( IHn ( λ i : ⟦n⟧, f ( dni lastelement i ) ) ) * f lastelement ).
Defined.
Definition stnprod_step { n : nat } ( f : ⟦S n⟧ -> nat ) :
stnprod f = stnprod (f ∘ dni lastelement) * f lastelement.
Proof.
intros.
apply idpath.
Defined.
Lemma stnprod_eq {n : nat} (f g: ⟦n⟧ -> nat) : f ~ g -> stnprod f = stnprod g.
Proof.
intros h. induction n as [|n IH].
{ apply idpath. }
rewrite 2? stnprod_step. induction (h lastelement).
apply (maponpaths (λ i, i * f lastelement)). apply IH. intro x. apply h.
Defined.
Theorem weqstnprod { n : nat } ( P : ⟦n⟧ -> UU ) ( f : ⟦n⟧ -> nat )
( ww : ∏ i : ⟦n⟧ , ( stn ( f i ) ) ≃ ( P i ) ) :
( ∏ x : ⟦n⟧ , P x ) ≃ stn ( stnprod f ).
Proof.
revert P f ww.
induction n as [ | n IHn ].
- intros. simpl. apply ( weqcontrcontr ).
+ apply ( iscontrsecoverempty2 _ ( negstn0 ) ).
+ apply iscontrstn1.
- intros.
set ( w1 := weqdnicoprod n lastelement ).
assert ( w2 := weqonsecbase P w1 ).
assert ( w3 := weqsecovercoprodtoprod ( λ x : _, P ( w1 x ) ) ).
assert ( w4 := weqcomp w2 w3 ) ; clear w2 w3.
assert ( w5 := IHn ( λ x : ⟦n⟧, P ( w1 ( ii1 x ) ) ) ( λ x : ⟦n⟧, f ( w1 ( ii1 x ) ) ) ( λ i : ⟦n⟧, ww ( w1 ( ii1 i ) ) ) ).
assert ( w6 := weqcomp w4 ( weqdirprodf w5 ( weqsecoverunit _ ) ) ) ; clear w4 w5.
simpl in w6.
assert ( w7 := weqcomp w6 ( weqdirprodf ( idweq _ ) ( invweq ( ww lastelement ) ) ) ).
refine ( _ ∘ w7 )%weq.
unfold w1.
exact (weqfromprodofstn _ _ ).
Defined.
(** *** Weak equivalence between [ ( stn n ) ≃ ( stn n ) ] and [ stn ( factorial n ) ] ( uses functional extensionality ) *)
Theorem weqweqstnsn ( n : nat ) : (⟦S n⟧ ≃ ⟦S n⟧) ≃ ⟦S n⟧ × ( ⟦n⟧ ≃ ⟦n⟧ ).
Proof.
assert ( l := @lastelement n ).
intermediate_weq ( isolated (⟦S n⟧) × (compl _ l ≃ compl _ l) ).
{ apply weqcutonweq. intro i. apply isdeceqstn. }
apply weqdirprodf.
- apply weqisolatedstntostn.
- apply weqweq. apply invweq.
intermediate_weq (compl_ne (⟦S n⟧) l (stnneq l)).
+ apply weqdnicompl.
+ apply compl_weq_compl_ne.
Defined.
Theorem weqfromweqstntostn ( n : nat ) : ( (⟦n⟧) ≃ (⟦n⟧) ) ≃ ⟦factorial n⟧.
Proof.
induction n as [ | n IHn ].
- simpl.
apply ( weqcontrcontr ).
+ apply ( iscontraprop1 ).
* apply ( isapropweqtoempty2 _ ( negstn0 ) ).
* apply idweq.
+ apply iscontrstn1.
- change ( factorial ( S n ) ) with ( ( S n ) * ( factorial n ) ).
set ( w1 := weqweqstnsn n ).
apply ( weqcomp w1 ( weqcomp ( weqdirprodf ( idweq _ ) IHn ) ( weqfromprodofstn _ _ ) ) ).
Defined.
(* End of " weak equivalences between standard finite sets and constructions on these sets ". *)
(** ** Standard finite sets satisfy weak axiom of choice *)
Theorem ischoicebasestn ( n : nat ) : ischoicebase (⟦n⟧).
Proof.
induction n as [ | n IHn ].
- apply ( ischoicebaseempty2 negstn0 ).
- apply ( ischoicebaseweqf ( weqdnicoprod n lastelement )
( ischoicebasecoprod IHn ischoicebaseunit ) ).
Defined.
(** ** Weak equivalence class of [ stn n ] determines [ n ]. *)
Lemma negweqstnsn0 (n : nat) : ¬ (⟦S n⟧ ≃ stn O).
Proof.
unfold neg.
assert (lp: ⟦S n⟧) by apply lastelement.
intro X.
apply weqstn0toempty.
apply (pr1 X lp).
Defined.
Lemma negweqstn0sn (n : nat) : ¬ (stn O ≃ ⟦S n⟧).
Proof.
unfold neg.
assert (lp: ⟦S n⟧) by apply lastelement.
intro X.
apply weqstn0toempty.
apply (pr1 ( invweq X ) lp).
Defined.
Lemma weqcutforstn ( n n' : nat ) : ⟦S n⟧ ≃ ⟦S n'⟧ -> ⟦n⟧ ≃ ⟦n'⟧.
Proof.
intros w. assert ( k := @lastelement n ).
intermediate_weq (stn_compl k).
- apply weqdnicompl.
- intermediate_weq (stn_compl (w k)).
+ apply weqoncompl_ne.
+ apply invweq, weqdnicompl.
Defined.
Theorem weqtoeqstn { n n' : nat } : ⟦n⟧ ≃ ⟦n'⟧ -> n = n'.
Proof. revert n'.
induction n as [ | n IHn ].
- intro. destruct n' as [ | n' ].
+ intros; apply idpath.
+ intro X. apply (fromempty (negweqstn0sn _ X)).
- intro n'. destruct n' as [ | n' ].
+ intro X. apply (fromempty ( negweqstnsn0 n X)).
+ intro X. apply maponpaths. apply IHn.
apply weqcutforstn. assumption.
Defined.
Corollary stnsdnegweqtoeq ( n n' : nat ) ( dw : dneg (⟦n⟧ ≃ ⟦n'⟧) ) : n = n'.
Proof.
apply (eqfromdnegeq nat isdeceqnat _ _ (dnegf (@weqtoeqstn n n') dw)).
Defined.
(** ** Some results on bounded quantification *)
Lemma weqforallnatlehn0 ( F : nat -> hProp ) :
( ∏ n : nat , natleh n 0 -> F n ) ≃ ( F 0 ).
Proof.
intros.
assert ( lg : ( ∏ n : nat , natleh n 0 -> F n ) <-> ( F 0 ) ).
{ split.
- intro f.
apply ( f 0 ( isreflnatleh 0 ) ).
- intros f0 n l.
set ( e := natleh0tois0 l ).
rewrite e.
apply f0.
}
assert ( is1 : isaprop ( ∏ n : nat , natleh n 0 -> F n ) ).
{ apply impred.
intro n.
apply impred.
intro l.
apply ( pr2 ( F n ) ).
}
apply ( weqimplimpl ( pr1 lg ) ( pr2 lg ) is1 ( pr2 ( F 0 ) ) ).
Defined.
Lemma weqforallnatlehnsn' ( n' : nat ) ( F : nat -> hProp ) :
( ∏ n : nat , natleh n ( S n' ) -> F n ) ≃
( ∏ n : nat , natleh n n' -> F n ) × ( F ( S n' ) ).
Proof.
intros.
assert ( lg : ( ∏ n : nat , natleh n ( S n' ) -> F n ) <->
( ∏ n : nat , natleh n n' -> F n ) × ( F ( S n' ) ) ).
{ split.
- intro f.
apply ( make_dirprod ( λ n, λ l, ( f n ( natlehtolehs _ _ l ) ) )
( f ( S n' ) ( isreflnatleh _ ) ) ).
- intro d2.
intro n. intro l.
destruct ( natlehchoice2 _ _ l ) as [ h | e ].
+ simpl in h.
apply ( pr1 d2 n h ).
+ destruct d2 as [ f2 d2 ].
rewrite e.
apply d2.
}
assert ( is1 : isaprop ( ∏ n : nat , natleh n ( S n' ) -> F n ) ).
{ apply impred.
intro n.
apply impred.
intro l.
apply ( pr2 ( F n ) ).
}
assert ( is2 : isaprop ( ( ∏ n : nat , natleh n n' -> F n ) × ( F ( S n' ) ) ) ).
{ apply isapropdirprod.
- apply impred.
intro n.
apply impred.
intro l.
apply ( pr2 ( F n ) ).
- apply ( pr2 ( F ( S n' ) ) ).
}
apply ( weqimplimpl ( pr1 lg ) ( pr2 lg ) is1 is2 ).
Defined.
Lemma weqexistsnatlehn0 ( P : nat -> hProp ) :
( hexists ( λ n : nat, ( natleh n 0 ) × ( P n ) ) ) ≃ P 0.
Proof.
assert ( lg : hexists ( λ n : nat, ( natleh n 0 ) × ( P n ) ) <-> P 0 ).
{ split.
- simpl.
apply ( @hinhuniv _ ( P 0 ) ).
intro t2.
destruct t2 as [ n d2 ].
destruct d2 as [ l p ].
set ( e := natleh0tois0 l ).
clearbody e.
destruct e.
apply p.
- intro p.
apply hinhpr.
split with 0.
split with ( isreflnatleh 0 ).
apply p.
}
apply ( weqimplimpl ( pr1 lg ) ( pr2 lg ) ( pr2 _ ) ( pr2 _ ) ).
Defined.
Lemma weqexistsnatlehnsn' ( n' : nat ) ( P : nat -> hProp ) :
( hexists ( λ n : nat, ( natleh n ( S n' ) ) × ( P n ) ) ) ≃
hdisj ( hexists ( λ n : nat, ( natleh n n' ) × ( P n ) ) ) ( P ( S n' ) ).
Proof.
intros.
assert ( lg : hexists ( λ n : nat, ( natleh n ( S n' ) ) × ( P n ) ) <->
hdisj ( hexists ( λ n : nat, ( natleh n n' ) × ( P n ) ) ) ( P ( S n' ) ) ).
{ split.
- apply hinhfun.
intro t2.
destruct t2 as [ n d2 ].
destruct d2 as [ l p ].
destruct ( natlehchoice2 _ _ l ) as [ h | nh ].
+ simpl in h.
apply ii1.
apply hinhpr.
split with n.
apply ( make_dirprod h p ).
+ destruct nh.
apply ( ii2 p ).
- simpl.
apply ( @hinhuniv _ ( ishinh _ ) ).
intro c.
destruct c as [ t | p ].
+ generalize t.
simpl.
apply hinhfun.
clear t.
intro t.
destruct t as [ n d2 ].
destruct d2 as [ l p ].
split with n.
split with ( natlehtolehs _ _ l ).
apply p.
+ apply hinhpr.
split with ( S n' ).
split with ( isreflnatleh _ ).
apply p.
}
apply ( weqimplimpl ( pr1 lg ) ( pr2 lg ) ( pr2 _ ) ( pr2 _ ) ).
Defined.
Lemma isdecbexists ( n : nat ) ( P : nat -> UU ) ( is : ∏ n' , isdecprop ( P n' ) ) :
isdecprop ( hexists ( λ n', ( natleh n' n ) × ( P n' ) ) ).
Proof.
intros.
set ( P' := λ n' : nat, make_hProp _ ( is n' ) ).
induction n as [ | n IHn ].
- apply ( isdecpropweqb ( weqexistsnatlehn0 P' ) ).
apply ( is 0 ).
- apply ( isdecpropweqb ( weqexistsnatlehnsn' _ P' ) ).
apply isdecprophdisj.
+ apply IHn.
+ apply ( is ( S n ) ).
Defined.
Lemma isdecbforall ( n : nat ) ( P : nat -> UU ) ( is : ∏ n' , isdecprop ( P n' ) ) :
isdecprop ( ∏ n' , natleh n' n -> P n' ).
Proof.
intros.
set ( P' := λ n' : nat, make_hProp _ ( is n' ) ).
induction n as [ | n IHn ].
- apply ( isdecpropweqb ( weqforallnatlehn0 P' ) ).
apply ( is 0 ).
- apply ( isdecpropweqb ( weqforallnatlehnsn' _ P' ) ).
apply isdecpropdirprod.
+ apply IHn.
+ apply ( is ( S n ) ).
Defined.
(** The following lemma finds the largest [ n' ] such that [ neg ( P n' ) ]. It is a stronger form of ( neg ∏ ) -> ( exists neg ) in the case of bounded quantification of decidable propositions. *)
Lemma negbforalldectototal2neg ( n : nat ) ( P : nat -> UU )
( is : ∏ n' : nat , isdecprop ( P n' ) ) :
¬ ( ∏ n' : nat , natleh n' n -> P n' ) ->
total2 ( λ n', ( natleh n' n ) × ¬ ( P n' ) ).
Proof.
set ( P' := λ n' : nat, make_hProp _ ( is n' ) ).
induction n as [ | n IHn ].
- intro nf.
set ( nf0 := negf ( invweq ( weqforallnatlehn0 P' ) ) nf ).
split with 0.
apply ( make_dirprod ( isreflnatleh 0 ) nf0 ).
- intro nf.
set ( nf2 := negf ( invweq ( weqforallnatlehnsn' n P' ) ) nf ).
set ( nf3 := fromneganddecy ( is ( S n ) ) nf2 ).
destruct nf3 as [ f1 | f2 ].
+ set ( int := IHn f1 ).
destruct int as [ n' d2 ].
destruct d2 as [ l np ].
split with n'.
split with ( natlehtolehs _ _ l ).
apply np.
+ split with ( S n ).
split with ( isreflnatleh _ ).
apply f2.
Defined.
(** ** Accessibility - the least element of an inhabited decidable subset of [nat] *)
Definition natdecleast ( F : nat -> UU ) ( is : ∏ n , isdecprop ( F n ) ) :=
total2 ( λ n : nat, ( F n ) × ( ∏ n' : nat , F n' -> natleh n n' ) ).
Lemma isapropnatdecleast ( F : nat -> UU ) ( is : ∏ n , isdecprop ( F n ) ) :
isaprop ( natdecleast F is ).
Proof.
intros.
set ( P := λ n' : nat, make_hProp _ ( is n' ) ).
assert ( int1 : ∏ n : nat, isaprop ( ( F n ) × ( ∏ n' : nat , F n' -> natleh n n' ) ) ).
{ intro n.
apply isapropdirprod.
- apply ( pr2 ( P n ) ).
- apply impred.
intro t.
apply impred.
intro.
apply ( pr2 ( natleh n t ) ).
}
set ( int2 := ( λ n : nat, make_hProp _ ( int1 n ) ) : nat -> hProp ).
change ( isaprop ( total2 int2 ) ).
apply isapropsubtype.
intros x1 x2. intros c1 c2.
simpl in *.
destruct c1 as [ e1 c1 ].
destruct c2 as [ e2 c2 ].
set ( l1 := c1 x2 e2 ).
set ( l2 := c2 x1 e1 ).
apply ( isantisymmnatleh _ _ l1 l2 ).
Defined.
Theorem accth ( F : nat -> UU ) ( is : ∏ n , isdecprop ( F n ) )
( is' : hexists F ) : natdecleast F is.
Proof.
revert is'.
simpl.
apply (@hinhuniv _ ( make_hProp _ ( isapropnatdecleast F is ) ) ).
intro t2.
destruct t2 as [ n l ].
simpl.
set ( F' := λ n' : nat, hexists ( λ n'', ( natleh n'' n' ) × ( F n'' ) ) ).
assert ( X : ∏ n' , F' n' -> natdecleast F is ).
{ intro n'.
induction n' as [ | n' IHn' ].
- apply ( @hinhuniv _ ( make_hProp _ ( isapropnatdecleast F is ) ) ).
intro t2.
destruct t2 as [ n'' is'' ].
destruct is'' as [ l'' d'' ].
split with 0.
split.
+ set ( e := natleh0tois0 l'' ).
clearbody e.
destruct e.
apply d''.
+ apply ( λ n', λ f : _, natleh0n n' ).
- apply ( @hinhuniv _ ( make_hProp _ ( isapropnatdecleast F is ) ) ).
intro t2.
destruct t2 as [ n'' is'' ].
set ( j := natlehchoice2 _ _ ( pr1 is'' ) ).
destruct j as [ jl | je ].
+ simpl.
apply ( IHn' ( hinhpr ( tpair _ n'' ( make_dirprod jl ( pr2 is'' ) ) ) ) ).
+ simpl.
rewrite je in is''.
destruct is'' as [ nn is'' ].
clear nn. clear je. clear n''.
assert ( is' : isdecprop ( F' n' ) ) by apply ( isdecbexists n' F is ).
destruct ( pr1 is' ) as [ f | nf ].
* apply ( IHn' f ).
* split with ( S n' ).
split with is''.
intros n0 fn0.
destruct ( natlthorgeh n0 ( S n' ) ) as [ l' | g' ].
-- set ( i' := natlthtolehsn _ _ l' ).
destruct ( nf ( hinhpr ( tpair _ n0 ( make_dirprod i' fn0 ) ) ) ).
-- apply g'.
}
apply ( X n ( hinhpr ( tpair _ n ( make_dirprod ( isreflnatleh n ) l ) ) ) ).
Defined.
Corollary dni_lastelement_is_inj {n : nat} {i j : ⟦n⟧ }
(e : dni_lastelement i = dni_lastelement j) :
i = j.
Proof.
apply isinjstntonat.
unfold dni_lastelement in e.
apply (maponpaths pr1) in e.
exact e.
Defined.
Corollary dni_lastelement_eq : ∏ (n : nat) (i : ⟦S n⟧ ) (ie : pr1 i < n),
i = dni_lastelement (make_stn n (pr1 i) ie).
Proof.
intros n i ie.
apply isinjstntonat.
apply idpath.
Defined.
Corollary lastelement_eq : ∏ (n : nat) (i : ⟦S n⟧ ) (e : pr1 i = n),
i = lastelement.
Proof.
intros n i e.
unfold lastelement.
apply isinjstntonat.
apply e.
Defined.
(* a tactic for proving things by induction over a finite number of cases *)
Ltac inductive_reflexivity i b :=
(* Here i is a variable natural number and b is a bound on *)
(* i of the form i<k, where k is a numeral. *)
induction i as [|i];
[ try apply isinjstntonat ; apply idpath |
contradicts (negnatlthn0 i) b || inductive_reflexivity i b ].
(** concatenation and flattening of functions *)
Definition concatenate' {X:UU} {m n:nat} (f : ⟦m⟧ -> X) (g : ⟦n⟧ -> X) : ⟦m+n⟧ -> X.
Proof.
intros i.
(* we are careful to use weqfromcoprodofstn_invmap both here and in weqstnsum_invmap *)
induction (weqfromcoprodofstn_invmap _ _ i) as [j | k].
+ exact (f j).
+ exact (g k).
Defined.
Definition concatenate'_r0 {X:UU} {m:nat} (f : ⟦m⟧ -> X) (g : ⟦0⟧ -> X) :
concatenate' f g = transportb (λ n, ⟦n⟧ -> X) (natplusr0 m) f.
Proof.
intros. apply funextfun; intro i. unfold concatenate'.
rewrite weqfromcoprodofstn_invmap_r0; simpl. clear g.
apply transportb_fun'.
Defined.
Definition concatenate'_r0' {X:UU} {m:nat} (f : ⟦m⟧ -> X) (g : ⟦0⟧ -> X) (i : ⟦m+0⟧ ) :
concatenate' f g i = f (transportf stn (natplusr0 m) i).
Proof.
intros.
unfold concatenate'.
rewrite weqfromcoprodofstn_invmap_r0.
apply idpath.
Defined.
Definition flatten' {X:UU} {n:nat} {m: ⟦n⟧ -> nat} :
(∏ (i: ⟦n⟧ ), ⟦m i⟧ -> X) -> ( ⟦stnsum m⟧ -> X).
Proof.
intros g.
exact (uncurry g ∘ invmap (weqstnsum1 m)).
Defined.
Definition stn_predicate {n : nat} (P : ⟦n⟧ -> UU)
(k : nat) (h h' : k < n) :
P (k,,h) -> P (k,,h').
Proof.
intros H.
transparent assert (X : (h = h')).
- apply propproperty.
- exact (transportf (λ x, P (k,,x)) X H).
Defined.
Definition two := ⟦2⟧.
Definition two_rec {A : UU} (a b : A) : ⟦2⟧ -> A.
Proof.
induction 1 as [n p].
induction n as [|n _]; [apply a|].
induction n as [|n _]; [apply b|].
induction (nopathsfalsetotrue p).
Defined.
Definition two_rec_dep (P : two -> UU):
P (● 0) -> P (● 1) -> ∏ n, P n.
Proof.
intros a b n.
induction n as [n p].
induction n as [|n _]. eapply stn_predicate. apply a.
induction n as [|n _]. eapply stn_predicate. apply b.
induction (nopathsfalsetotrue p).
Defined.
Definition three := stn 3.
Definition three_rec {A : UU} (a b c : A) : stn 3 -> A.
Proof.
induction 1 as [n p].
induction n as [|n _]; [apply a|].
induction n as [|n _]; [apply b|].
induction n as [|n _]; [apply c|].
induction (nopathsfalsetotrue p).
Defined.
Definition three_rec_dep (P : three -> UU):
P (● 0) -> P (● 1) -> P (● 2) -> ∏ n, P n.
Proof.
intros a b c n.
induction n as [n p].
induction n as [|n _]. eapply stn_predicate. apply a.
induction n as [|n _]. eapply stn_predicate. apply b.
induction n as [|n _]. eapply stn_predicate. apply c.
induction (nopathsfalsetotrue p).
Defined.
(** ordered bijections are unique *)
Definition is_stn_increasing {m : nat} (f : ⟦m⟧ → nat) :=
∏ (i j: ⟦m⟧ ), i ≤ j → f i ≤ f j.
Definition is_stn_strictly_increasing {m : nat} (f : ⟦m⟧ → nat) :=
∏ (i j: ⟦m⟧ ), i < j → f i < f j.
Lemma is_strincr_impl_incr {m : nat} (f : ⟦m⟧ → nat) :
is_stn_strictly_increasing f -> is_stn_increasing f.
Proof.
intros inc ? ? e. induction (natlehchoice _ _ e) as [I|J]; clear e.
+ apply natlthtoleh. apply inc. exact I.
+ assert (J' : i = j).
{ apply subtypePath_prop. exact J. }
clear J. induction J'. apply isreflnatleh.
Defined.
Lemma is_incr_impl_strincr {m : nat} (f : ⟦m⟧ → nat) :
isincl f -> is_stn_increasing f -> is_stn_strictly_increasing f.
Proof.
intros incl incr i j e.
assert (d : i ≤ j).
{ apply natlthtoleh. assumption. }
assert (c := incr _ _ d); clear d.
assert (b : i != j).
{ intro p. induction p. exact (isirreflnatlth _ e). }
induction (natlehchoice _ _ c) as [T|U].
- exact T.
- apply fromempty.
unfold isincl,isofhlevel,isofhlevelf in incl.
assert (V := invmaponpathsincl f incl i j U).
induction V.
exact (isirreflnatlth _ e).
Defined.
Lemma stnsum_ge1 {m : nat} (f : ⟦m⟧ → nat) : ( ∏ i, f i ≥ 1 ) → stnsum f ≥ m.
Proof.
intros G.
set (g := λ i:⟦m⟧, 1).
assert (E : stnsum g = m).
{ apply stnsum_1. }
assert (F : stnsum g ≤ stnsum f).
{ apply stnsum_le. exact G. }
generalize E F; generalize (stnsum g); clear E F g; intros s e i.
induction e.
exact i.
Defined.
Lemma stnsum_add {m : nat} (f g : ⟦m⟧ → nat) : stnsum (λ i, f i + g i) = stnsum f + stnsum g.
Proof.
intros.
induction m as [|m I].
- apply idpath.
- rewrite 3 stnsum_step.
change ((λ i : ⟦ S m ⟧, f i + g i) ∘ dni lastelement)
with (λ y : ⟦ m ⟧, f (dni lastelement y) + g (dni lastelement y)).
rewrite I. rewrite natplusassoc.
rewrite natplusassoc. simpl. apply maponpaths. rewrite natpluscomm.
rewrite natplusassoc. apply maponpaths. rewrite natpluscomm. apply idpath.
Defined.
Lemma stnsum_lt {m : nat} (f g : ⟦m⟧ → nat) :
( ∏ i, f i < g i ) → stnsum g ≥ stnsum f + m.
Proof.
intros. set (h := λ i, f i + 1).
assert (E : stnsum h = stnsum f + m).
{ unfold h; clear h. rewrite stnsum_add. rewrite stnsum_1. apply idpath. }
rewrite <- E. apply stnsum_le. intros i. unfold h. apply natlthtolehp1. apply X.
Defined.
Local Arguments dni {_} _ _.
Lemma stnsum_diffs {m : nat} (f : ⟦S m⟧ → nat) : is_stn_increasing f ->
stnsum (λ i, f (dni_firstelement i) - f (dni_lastelement i)) =
f lastelement - f firstelement.
Proof.
intros e.
induction m as [|m I].
- change (0 = f firstelement - f firstelement).
apply pathsinv0.
apply minuseq0'.
- rewrite stnsum_step.
change (f (dni_firstelement lastelement)) with (f lastelement).
rewrite natpluscomm.
use (_ @ ! @natdiffplusdiff
(f lastelement)
(f (dni_lastelement lastelement))
(f firstelement) _ _).
+ apply maponpaths.
use (_ @ I (f ∘ dni_lastelement) _ @ _).
* simpl. apply stnsum_eq; intros i.
rewrite replace_dni_last. apply idpath.
* intros i j s. unfold funcomp. apply e. apply s.
* apply idpath.
+ apply e. apply lastelement_ge.
+ apply e. apply firstelement_le.
Defined.
Lemma stn_ord_incl {m : nat} (f : ⟦S m⟧ → nat) :
is_stn_strictly_increasing f → f lastelement ≥ f firstelement + m.
Proof.
intros strinc.
assert (inc := is_strincr_impl_incr _ strinc).
set (d := λ i : ⟦ m ⟧, f (dni_firstelement i) - f (dni_lastelement i)).
assert (E := stnsum_diffs f inc).
change (stnsum d = f lastelement - f firstelement) in E.
assert (F : ∏ i, f (dni_firstelement i) > f (dni_lastelement i)).
{ intros i. apply strinc. change (stntonat _ i < S(stntonat _ i)). apply natlthnsn. }
assert (G : ∏ i, d i ≥ 1).
{ intros i. apply natgthtogehsn. apply minusgth0. apply F. }
clear F.
assert (H := stnsum_ge1 _ G). clear G.
rewrite E in H. clear E d.
assert (I : f lastelement ≥ f firstelement).
{ apply inc. apply idpath. }
assert (J := minusplusnmm _ _ I); clear I.
rewrite <- J; clear J.
rewrite natpluscomm.
apply natgehandplusl.
exact H.
Defined.
Lemma stn_ord_inj {n : nat} (f : incl (⟦n⟧) (⟦n⟧)) :
(∏ (i j: ⟦n⟧ ), i ≤ j → f i ≤ f j) -> ∏ i, f i = i.
Proof.
intros inc ?.
induction n as [|n I].
- apply fromempty. apply negstn0. assumption.
- assert (strincr : is_stn_strictly_increasing (pr1incl _ _ f)).
{ apply is_incr_impl_strincr.
{ use (isinclcomp f (stntonat_incl _)). }
{ exact inc. } }
assert (M : stntonat _ (f lastelement) = n).
{ apply isantisymmnatgeh.
* assert (N : f lastelement ≥ f firstelement + n).
{ exact (stn_ord_incl (pr1incl _ _ f) strincr). }
use (istransnatgeh _ _ _ N).
apply natgehplusnmm.
* exact (stnlt (f lastelement)). }
assert (L : ∏ j, f (dni lastelement j) < n).
{ intros. induction M. apply strincr. apply dni_last_lt. }
(* set (f' := λ j : ⟦n⟧, make_stn n (stntonat _ (f (dni_lastelement j))) (L j)). *)
pose (f'' :=
inclcomp (inclcomp (make_incl _ (isincldni n lastelement)) f)
(make_incl _ (isinclstntonat _))).
pose (f' := λ j : ⟦n⟧, make_stn n (f'' j) (L j)).
assert (J : isincl f').
{ unfold f'. intros x j j'.
apply iscontraprop1.
* apply isaset_hfiber; apply isasetstn.
* use subtypePath.
** intro. apply isasetstn.
** induction j as [j e]. induction j' as [j' e']. simpl.
apply (invmaponpathsincl f'' (pr2 f'')).
apply (base_paths _ _ (e @ !e')). }
assert (F : ∏ j : ⟦n⟧, f' j = j).
{ apply (I (make_incl _ J)).
intros j j' lt. apply inc.
change (pr1 (dni lastelement j) ≤ pr1 (dni lastelement j')).
rewrite 2?dni_last. assumption. }
apply subtypePath_prop.
change (stntonat _ (f i) = i).
induction (natgehchoice _ _ (lastelement_ge i)) as [ge | eq].
+ pose (p := maponpaths (stntonat _) (F (make_stn n i ge))).
simpl in p. induction p.
change (stntonat _ (f i) = f (dni lastelement (make_stn n i ge))).
apply maponpaths, maponpaths, pathsinv0.
apply subtypePath_prop. apply dni_last.
+ apply subtypePath_prop in eq.
rewrite <- eq.
apply M.
Defined.
Lemma stn_ord_bij {n : nat} (f : ⟦ n ⟧ ≃ ⟦ n ⟧) :
(∏ (i j: ⟦n⟧ ), i ≤ j → f i ≤ f j) -> ∏ i, f i = i.
Proof.
apply (stn_ord_inj (weqtoincl f)).
Defined.
|
[STATEMENT]
lemma concI[simp,intro]: "u : A \<Longrightarrow> v : B \<Longrightarrow> u@v : A @@ B"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>u \<in> A; v \<in> B\<rbrakk> \<Longrightarrow> u @ v \<in> A @@ B
[PROOF STEP]
by (auto simp add: conc_def) |
{-# OPTIONS --without-K --safe #-}
module Categories.Category.Dagger.Instance.Rels where
open import Data.Product
open import Function
open import Relation.Binary.PropositionalEquality
open import Level
open import Categories.Category.Dagger
open import Categories.Category.Instance.Rels
RelsHasDagger : ∀ {o ℓ} → HasDagger (Rels o ℓ)
RelsHasDagger = record
{ _† = flip
; †-identity = (lift ∘ sym ∘ lower) , (lift ∘ sym ∘ lower)
; †-homomorphism = (map₂ swap) , (map₂ swap)
; †-resp-≈ = λ p → (proj₁ p) , (proj₂ p) -- it's the implicits that need flipped
; †-involutive = λ _ → id , id
}
RelsDagger : ∀ o ℓ → DaggerCategory (suc o) (suc (o ⊔ ℓ)) (o ⊔ ℓ)
RelsDagger o ℓ = record
{ C = Rels o ℓ
; hasDagger = RelsHasDagger
}
|
State Before: σ : Type u_1
R : Type u_2
inst✝¹ : Semiring R
inst✝ : DecidableEq σ
m n : σ →₀ ℕ
a : R
⊢ ↑(coeff R m) (↑(monomial R n) a) = if m = n then a else 0 State After: σ : Type u_1
R : Type u_2
inst✝¹ : Semiring R
inst✝ : DecidableEq σ
m n : σ →₀ ℕ
a : R
⊢ ↑(LinearMap.stdBasis R (fun x => R) n) a m = if m = n then a else 0 Tactic: rw [coeff, monomial_def, LinearMap.proj_apply] State Before: σ : Type u_1
R : Type u_2
inst✝¹ : Semiring R
inst✝ : DecidableEq σ
m n : σ →₀ ℕ
a : R
⊢ ↑(LinearMap.stdBasis R (fun x => R) n) a m = if m = n then a else 0 State After: σ : Type u_1
R : Type u_2
inst✝¹ : Semiring R
inst✝ : DecidableEq σ
m n : σ →₀ ℕ
a : R
⊢ ↑(LinearMap.stdBasis R (fun x => R) n) a m = if m = n then a else 0 Tactic: dsimp only State Before: σ : Type u_1
R : Type u_2
inst✝¹ : Semiring R
inst✝ : DecidableEq σ
m n : σ →₀ ℕ
a : R
⊢ ↑(LinearMap.stdBasis R (fun x => R) n) a m = if m = n then a else 0 State After: no goals Tactic: rw [LinearMap.stdBasis_apply, Function.update_apply, Pi.zero_apply] |
oh wow AND he was married to rose. (before she was rose.) it was almost like having the doctor in your cafe!! |
function fx = p18_fun ( n, x )
%*****************************************************************************80
%
%% P18_FUN evaluates the integrand for problem 18.
%
% Integral:
%
% Integral ( 0 <= x < +oo ) x^2 * exp ( - x / 2^beta ) dx
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 28 December 2011
%
% Author:
%
% John Burkardt
%
% Reference:
%
% Robert Piessens, Elise de Doncker-Kapenga,
% Christian Ueberhuber, David Kahaner,
% QUADPACK: A Subroutine Package for Automatic Integration,
% Springer, 1983, page 84.
%
% Parameters:
%
% Input, integer N, the number of points.
%
% Input, real X(N), the point at which the integrand
% is to be evaluated.
%
% Output, real FX(N), the value of the integrand at X.
%
beta = 1.0;
fx(1:n) = x(1:n).^2 .* exp ( - x(1:n) / 2^beta );
return
end
|
lemma orthogonal_to_span: assumes a: "a \<in> span S" and x: "\<And>y. y \<in> S \<Longrightarrow> orthogonal x y" shows "orthogonal x a" |
ANAHEIM, Calif. The actual Edmonton Oilers as well as Anaheim Other poultry strategy Online game 7 of the second-round playoff sequence through various viewpoints.
With regard to the majority of the youthful Oilers roster, they’ve waded in to uncharted seas of the shared eradication online game as the Other poultry veterans should solution exactly the same queries regarding their own capability to earn the actual large online game for any 5th consecutive period.
Online game 7 grew to become a real possibility following Edmonton’s 7-1 knocking associated with Anaheim upon Weekend, driven through Leon Draisaitl’s very first profession postseason loath technique. The actual third-year ahead may be easy towards Anaheim, signing up 11 objectives as well as 10 aids within 11 video games from the Other poultry this particular marketing campaign. As the Other poultry possess was missing the protective solution from the bruising German born ahead, Draisaitl is equally as stumped why he’s submitted incredible unpleasant amounts from this challenger.
This is the very first Online game 7 for that business within greater than a 10 years, however this methods this along with small pressure.
The actual Other poultry had been preferred in order to earn the actual sequence, as well as following a remarkable third-period return within Online game 5 by which Anaheim obtained 3 objectives within the last 3: sixteen using their goaltender drawn, the majority of observers believed which Edmonton couldn’t gather upward a large work in order to actually the actual sequence. Whenever the majority of measured all of them away, Edmonton chief Connor McDavid understood their group experienced a minumum of one much more powerful online game in order to perform as well as thinks they are able to duplicate this to maneuver upon. |
##################################################
# Constraints
"""
List of constraints that the model will potentially have
"""
constr_list =
[
:startup_choose,
:startup_restrict,
:segprod_limit,
:segprod_limita,
:segprod_limitb,
:prod_above_def,
:prod_limit,
:str_prod_limit,
:binary_link,
:switch_on_off,
:ramp_up,
:ramp_down,
:str_ramp_up,
:str_ramp_down,
:startstop_limit,
:startup_limit,
:shutdown_limit,
:min_uptime,
:min_downtime,
:power_balance,
:net_injection_def,
:min_reserve
]
|
Require Import Coq.Strings.Ascii.
Require Import ExtLib.Data.Bool.
Require Import ExtLib.Tactics.Consider.
Require Import ExtLib.Core.RelDec.
Set Implicit Arguments.
Set Strict Implicit.
Definition ascii_dec (l r : Ascii.ascii) : bool :=
match l , r with
| Ascii.Ascii l1 l2 l3 l4 l5 l6 l7 l8 ,
Ascii.Ascii r1 r2 r3 r4 r5 r6 r7 r8 =>
if Bool.eqb l1 r1 then
if Bool.eqb l2 r2 then
if Bool.eqb l3 r3 then
if Bool.eqb l4 r4 then
if Bool.eqb l5 r5 then
if Bool.eqb l6 r6 then
if Bool.eqb l7 r7 then
if Bool.eqb l8 r8 then true
else false
else false
else false
else false
else false
else false
else false
else false
end.
Theorem ascii_dec_sound : forall l r,
ascii_dec l r = true <-> l = r.
Proof.
unfold ascii_dec. intros.
destruct l; destruct r.
repeat match goal with
| [ |- (if ?X then _ else _) = true <-> _ ] =>
consider X; intros; subst
end; split; congruence.
Qed.
Global Instance RelDec_ascii : RelDec (@eq Ascii.ascii) :=
{ rel_dec := ascii_dec }.
Global Instance RelDec_Correct_ascii : RelDec_Correct RelDec_ascii.
Proof.
constructor; auto using ascii_dec_sound.
Qed.
Global Instance Reflect_ascii_dec a b : Reflect (ascii_dec a b) (a = b) (a <> b).
Proof.
apply iff_to_reflect; auto using ascii_dec_sound.
Qed.
Definition digit2ascii (n:nat) : Ascii.ascii :=
match n with
| 0 => "0"
| 1 => "1"
| 2 => "2"
| 3 => "3"
| 4 => "4"
| 5 => "5"
| 6 => "6"
| 7 => "7"
| 8 => "8"
| 9 => "9"
| n => ascii_of_nat (n - 10 + nat_of_ascii "A")
end%char.
Definition chr_newline : ascii :=
Eval compute in ascii_of_nat 10.
Export Ascii.
|
[STATEMENT]
lemma is_class_xcpt:
"\<lbrakk> C \<in> sys_xcpts; wf_prog wf_md P \<rbrakk> \<Longrightarrow> is_class P C"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>C \<in> sys_xcpts; wf_prog wf_md P\<rbrakk> \<Longrightarrow> is_class P C
[PROOF STEP]
by(rule wf_syscls_is_class_xcpt[OF _ wf_prog_wf_syscls]) |
function clOut = get_cluster_volume(clIn)
% :Usage:
% ::
%
% clOut = get_cluster_volume(clIn)
%
% Adapted from:
%
% FORMAT clusters = ihb_getClusters
%
% Get cluster information (use [SPM,VOL,xX,xCon,xSDM] = spm_getSPM;)
%
% ..
% 01.03.01 Sergey Pakhomov
% 01.08.01 last modified
%
% Only change is to eliminate stuff in beginning - just update the cluster.
% Tor Wager, 10/18/01
% ..
clOut = clIn;
%----------------------------------------------------------------------------------
% Define default voxel size for canonical image
% This is OK to leave at 1's, because the head plotting utility adjusts
% to millimeters.
%----------------------------------------------------------------------------------
ihbdfl_tal_x_vox = 1;
ihbdfl_tal_y_vox = 1;
ihbdfl_tal_z_vox = 1;
%----------------------------------------------------------------------------------
% Prepare MNI volume data xMNI, yMNI, zMNI, and volMNI
%----------------------------------------------------------------------------------
rMin = min(clOut.XYZmm');
rMax = max(clOut.XYZmm');
voxMNI = clOut.voxSize;
% make all voxMNI positive: Correct bug with negative x voxel size
voxMNI = abs(voxMNI);
[xMNI, yMNI, zMNI] = meshgrid(...
rMin(1) - voxMNI(1) : voxMNI(1) : rMax(1) + voxMNI(1),...
rMin(2) - voxMNI(2) : voxMNI(2) : rMax(2) + voxMNI(2),...
rMin(3) - voxMNI(3) : voxMNI(3) : rMax(3) + voxMNI(3));
volMNI = zeros(size(xMNI));
[x y z] = size(xMNI);
for curVox = 1:clOut.numVox
tmp = clOut.XYZmm(:, curVox);
ind1 = (tmp(1) - rMin(1))/voxMNI(1) + 1;
ind2 = (tmp(2) - rMin(2))/voxMNI(2) + 1;
ind3 = (tmp(3) - rMin(3))/voxMNI(3) + 1;
index = round(x*y*ind3 + x*ind1 + ind2 + 1); % tor changed to avoid rounding error sometimes - 11/13
volMNI(index) = clOut.Z(curVox);
% waitbar stuff too much of a pain.
%nTotalProcessed = nTotalProcessed + 1;
%waitbar(nTotalProcessed/nTotalVox);
end
sizeMNI = size(volMNI);
sizeMNIprod = prod(sizeMNI);
xMNIreshaped = reshape(xMNI, [1 sizeMNIprod]);
yMNIreshaped = reshape(yMNI, [1 sizeMNIprod]);
zMNIreshaped = reshape(zMNI, [1 sizeMNIprod]);
xyzReshaped = [xMNIreshaped; yMNIreshaped; zMNIreshaped];
% tor eliminated this transformation line to keep in MNI space
%xyzTal = ihb_Mni2Tal(xyzReshaped);
xyzTal = xyzReshaped;
xx = reshape(xyzTal(1, :), sizeMNI);
yy = reshape(xyzTal(2, :), sizeMNI);
zz = reshape(xyzTal(3, :), sizeMNI);
clOut.xMin = ihbdfl_tal_x_vox*floor(min(xyzTal(1, :))/ihbdfl_tal_x_vox);
clOut.yMin = ihbdfl_tal_y_vox*floor(min(xyzTal(2, :))/ihbdfl_tal_y_vox);
clOut.zMin = ihbdfl_tal_z_vox*floor(min(xyzTal(3, :))/ihbdfl_tal_z_vox);
clOut.xMax = ihbdfl_tal_x_vox*ceil(max(xyzTal(1, :))/ihbdfl_tal_x_vox);
clOut.yMax = ihbdfl_tal_y_vox*ceil(max(xyzTal(2, :))/ihbdfl_tal_y_vox);
clOut.zMax = ihbdfl_tal_z_vox*ceil(max(xyzTal(3, :))/ihbdfl_tal_z_vox);
[clOut.xTal, clOut.yTal, clOut.zTal] = meshgrid(clOut.xMin:ihbdfl_tal_x_vox:clOut.xMax,...
clOut.yMin:ihbdfl_tal_y_vox:clOut.yMax,...
clOut.zMin:ihbdfl_tal_z_vox:clOut.zMax);
volTal = interp3(xx, yy, zz, volMNI, clOut.xTal, clOut.yTal, clOut.zTal, 'linear');
index = find(isnan(volTal(:,:,:)));
volTal(index) = 0;
clOut.vTal = volTal;
|
#include <petsc.h>
#include "plexview.h"
PetscErrorCode PlexViewFromOptions(DM plex) {
PetscErrorCode ierr;
PetscBool cell_cones = PETSC_FALSE,
closures_coords = PETSC_FALSE,
coords = PETSC_FALSE,
points = PETSC_FALSE,
use_height = PETSC_FALSE,
vertex_supports = PETSC_FALSE;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "plex_view_", "view options for tiny", "");CHKERRQ(ierr);
ierr = PetscOptionsBool("-cell_cones", "print cones of each cell",
"tiny.c", cell_cones, &cell_cones, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-closures_coords", "print vertex and edge (centers) coordinates for each cell",
"tiny.c", closures_coords, &closures_coords, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-coords", "print section and local vec for vertex coordinates",
"tiny.c", coords, &coords, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-points", "print point index ranges for vertices,edges,cells",
"tiny.c", points, &points, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-use_height", "use Height instead of Depth when printing points",
"tiny.c", use_height, &use_height, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-vertex_supports", "print supports of each vertex",
"tiny.c", vertex_supports, &vertex_supports, NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd();
if (points) {
ierr = PlexViewPointRanges(plex,use_height); CHKERRQ(ierr);
}
if (cell_cones) {
ierr = PlexViewFans(plex,2,2,1); CHKERRQ(ierr);
}
if (vertex_supports) {
ierr = PlexViewFans(plex,2,0,1); CHKERRQ(ierr);
}
if (coords) {
ierr = PlexViewCoords(plex); CHKERRQ(ierr);
}
if (closures_coords) {
ierr = PlexViewClosuresCoords(plex); CHKERRQ(ierr);
}
return 0;
}
static const char* stratanames[4][10] =
{{"vertex","", "", ""}, // dim=0 names
{"vertex","cell","", ""}, // dim=1 names
{"vertex","edge","cell",""}, // dim=2 names
{"vertex","edge","face","cell"}}; // dim=3 names
PetscErrorCode PlexViewPointRanges(DM plex, PetscBool use_height) {
PetscErrorCode ierr;
int dim, m, start, end;
const char *plexname;
MPI_Comm comm;
PetscMPIInt rank,size;
ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);
ierr = DMGetDimension(plex,&dim); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(comm,"point ranges for DMPlex %s in %dD:\n",plexname,dim); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(comm," [rank %d]",rank); CHKERRQ(ierr);
}
ierr = DMPlexGetChart(plex,&start,&end); CHKERRQ(ierr);
if (end < 1) { // nothing on this rank
ierr = PetscSynchronizedPrintf(comm,"\n"); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
ierr = PetscSynchronizedPrintf(comm,
" chart points %d,...,%d\n",start,end-1); CHKERRQ(ierr);
for (m = 0; m < dim + 1; m++) {
if (use_height) {
ierr = DMPlexGetHeightStratum(plex,m,&start,&end); CHKERRQ(ierr);
ierr = PetscSynchronizedPrintf(comm,
" height %d of size %d: %d,...,%d (%s)\n",
m,end-start,start,end-1,dim < 4 ? stratanames[dim][2-m] : ""); CHKERRQ(ierr);
} else {
ierr = DMPlexGetDepthStratum(plex,m,&start,&end); CHKERRQ(ierr);
ierr = PetscSynchronizedPrintf(comm,
" depth=dim %d of size %d: %d,...,%d (%s)\n",
m,end-start,start,end-1,dim < 4 ? stratanames[dim][m] : ""); CHKERRQ(ierr);
}
}
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
PetscErrorCode PlexViewFans(DM plex, int dim, int basestrata, int targetstrata) {
PetscErrorCode ierr;
const char *plexname;
const int *targets;
int j, m, start, end, cssize;
MPI_Comm comm;
PetscMPIInt rank,size;
ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(comm,"fans (cones or supports) for DMPlex %s:\n",plexname); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(comm," [rank %d]",rank); CHKERRQ(ierr);
}
ierr = PetscSynchronizedPrintf(comm,
" %s (= %s indices) of each %s\n",
(basestrata > targetstrata) ? "cones" : "supports",
stratanames[dim][targetstrata],stratanames[dim][basestrata]); CHKERRQ(ierr);
ierr = DMPlexGetDepthStratum(plex, basestrata, &start, &end); CHKERRQ(ierr);
for (m = start; m < end; m++) {
if (basestrata > targetstrata) {
ierr = DMPlexGetConeSize(plex,m,&cssize); CHKERRQ(ierr);
ierr = DMPlexGetCone(plex,m,&targets); CHKERRQ(ierr);
} else {
ierr = DMPlexGetSupportSize(plex,m,&cssize); CHKERRQ(ierr);
ierr = DMPlexGetSupport(plex,m,&targets); CHKERRQ(ierr);
}
ierr = PetscSynchronizedPrintf(comm,
" %s %d: ",stratanames[dim][basestrata],m); CHKERRQ(ierr);
for (j = 0; j < cssize-1; j++) {
ierr = PetscSynchronizedPrintf(comm,
"%d,",targets[j]); CHKERRQ(ierr);
}
ierr = PetscSynchronizedPrintf(comm,
"%d\n",targets[cssize-1]); CHKERRQ(ierr);
}
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
PetscErrorCode PlexViewCoords(DM plex) {
PetscErrorCode ierr;
PetscSection coordSection;
Vec coordVec;
const char *plexname;
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,"coordinate PetscSection and Vec for DMPlex %s:\n",plexname); CHKERRQ(ierr);
ierr = DMGetCoordinateSection(plex, &coordSection); CHKERRQ(ierr);
if (coordSection) {
ierr = PetscSectionView(coordSection,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
} else {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"[PlexViewCoords(): vertex coordinates PetscSection has not been set]\n"); CHKERRQ(ierr);
}
ierr = DMGetCoordinatesLocal(plex,&coordVec); CHKERRQ(ierr);
if (coordVec) {
ierr = VecViewLocalStdout(coordVec,PETSC_COMM_WORLD); CHKERRQ(ierr);
} else {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"[PlexViewCoords(): vertex coordinates Vec not been set]\n"); CHKERRQ(ierr);
}
return 0;
}
PetscErrorCode PlexViewClosuresCoords(DM plex) {
PetscErrorCode ierr;
DM cdm;
Vec coords;
double *acoords;
int numpts, *pts = NULL,
j, p, vertexstart, vertexend, edgeend, cellstart, cellend;
MPI_Comm comm;
PetscMPIInt rank,size;
const char *plexname;
ierr = PetscObjectGetComm((PetscObject)plex,&comm); CHKERRQ(ierr);
ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm,&rank); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)plex,&plexname); CHKERRQ(ierr);
ierr = PetscPrintf(comm,
"closure points and coordinates for each cell in DMPlex %s:\n",plexname); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(comm," [rank %d]",rank); CHKERRQ(ierr);
}
ierr = DMPlexGetHeightStratum(plex, 0, &cellstart, &cellend); CHKERRQ(ierr);
if (cellend < 1) { // nothing on this rank
ierr = PetscSynchronizedPrintf(comm,"\n"); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
ierr = DMGetCoordinateDM(plex, &cdm); CHKERRQ(ierr);
ierr = DMGetCoordinatesLocal(plex,&coords); CHKERRQ(ierr);
ierr = DMPlexGetDepthStratum(plex, 0, &vertexstart, &vertexend); CHKERRQ(ierr);
ierr = DMPlexGetDepthStratum(plex, 1, NULL, &edgeend); CHKERRQ(ierr);
ierr = VecGetArray(coords, &acoords); CHKERRQ(ierr);
for (j = cellstart; j < cellend; j++) {
ierr = DMPlexGetTransitiveClosure(plex, j, PETSC_TRUE, &numpts, &pts);
ierr = PetscSynchronizedPrintf(comm," cell %d\n",j); CHKERRQ(ierr);
for (p = 0; p < numpts*2; p += 2) { // omit orientations
if ((pts[p] >= vertexstart) && (pts[p] < edgeend)) { // omit cells in closure
if (pts[p] < vertexend) { // get location from coords
int voff;
voff = pts[p] - vertexstart;
ierr = PetscSynchronizedPrintf(comm,
" vertex %3d at (%g,%g)\n",
pts[p],acoords[2*voff+0],acoords[2*voff+1]); CHKERRQ(ierr);
} else { // assume it is an edge ... compute center
const int *vertices;
int voff[2];
double x,y;
ierr = DMPlexGetCone(plex, pts[p], &vertices); CHKERRQ(ierr);
voff[0] = vertices[0] - vertexstart;
voff[1] = vertices[1] - vertexstart;
x = 0.5 * (acoords[2*voff[0]+0] + acoords[2*voff[1]+0]);
y = 0.5 * (acoords[2*voff[0]+1] + acoords[2*voff[1]+1]);
ierr = PetscSynchronizedPrintf(comm,
" edge %3d at (%g,%g)\n",pts[p],x,y); CHKERRQ(ierr);
}
}
}
ierr = DMPlexRestoreTransitiveClosure(plex, j, PETSC_TRUE, &numpts, &pts); CHKERRQ(ierr);
}
ierr = VecRestoreArray(coords, &acoords); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(comm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
PetscErrorCode VecViewLocalStdout(Vec v, MPI_Comm gcomm) {
PetscErrorCode ierr;
int m,locsize;
PetscMPIInt rank,size;
double *av;
const char *vecname;
ierr = MPI_Comm_size(gcomm,&size);CHKERRQ(ierr);
ierr = MPI_Comm_rank(gcomm,&rank); CHKERRQ(ierr);
ierr = PetscObjectGetName((PetscObject)v,&vecname); CHKERRQ(ierr);
ierr = PetscPrintf(gcomm,"local Vec: %s %d MPI processes\n",
vecname,size); CHKERRQ(ierr);
if (size > 1) {
ierr = PetscSynchronizedPrintf(gcomm,"[rank %d]:\n",rank); CHKERRQ(ierr);
}
ierr = VecGetLocalSize(v,&locsize); CHKERRQ(ierr);
ierr = VecGetArray(v, &av); CHKERRQ(ierr);
for (m = 0; m < locsize; m++) {
ierr = PetscSynchronizedPrintf(gcomm,"%g\n",av[m]); CHKERRQ(ierr);
}
ierr = VecRestoreArray(v, &av); CHKERRQ(ierr);
ierr = PetscSynchronizedFlush(gcomm,PETSC_STDOUT); CHKERRQ(ierr);
return 0;
}
|
wear parts for crushers in cement manufacture whether using cone crushers, hammer crushers, impellor crushers or vertical shaft impact crushers; the group can supply wear parts that offer significant cost benefits when compared to conventionally formulated and manufactured components.
buy stainless steel dust collector equipment, cement mill industrial bag filter from china dust collector equipment for sale of dustfilterbag from china.
cement mill trunnion bearing parts. johnsmachines machines which i have made, am . i have learnt a lot about ball screws in the past few days. contact us.
colombian industry machinery manufacturers colombian manufacturers and suppliers of industry machinery from around the world. panjiva uses over 30 international data sources to help you find qualified vendors of colombian industry machinery.
vertical roller mill parts in cement plants crusher, vertical roller mill parts in cement plants, cement mill,cement raw crusher,cement plant industry, quarry equipment spare parts;, vertical roller mill .
spare parts cement mill, wholesale various high quality spare parts cement mill products from global spare parts cement mill suppliers and spare parts cement mill factory,importer,exporter at alibaba.
types of coal in cement plant mill china . types of coal in cement plant. and is also widely used in mineral grinding mill industry. |
module Prelude.Cast
import Builtin
import Prelude.Basics
import Prelude.Num
import Prelude.Types
%default total
-----------
-- CASTS --
-----------
-- Casts between primitives only here. They might be lossy.
||| Interface for transforming an instance of a data type to another type.
public export
interface Cast from to where
constructor MkCast
||| Perform a (potentially lossy!) cast operation.
||| @ orig The original type
cast : (orig : from) -> to
export
Cast a a where
cast = id
-- To String
export
Cast Int String where
cast = prim__cast_IntString
export
Cast Integer String where
cast = prim__cast_IntegerString
export
Cast Char String where
cast = prim__cast_CharString
export
Cast Double String where
cast = prim__cast_DoubleString
-- To Integer
export
Cast Int Integer where
cast = prim__cast_IntInteger
export
Cast Char Integer where
cast = prim__cast_CharInteger
export
Cast Double Integer where
cast = prim__cast_DoubleInteger
export
Cast String Integer where
cast = prim__cast_StringInteger
export
Cast Nat Integer where
cast = natToInteger
export
Cast Bits8 Integer where
cast = prim__cast_Bits8Integer
export
Cast Bits16 Integer where
cast = prim__cast_Bits16Integer
export
Cast Bits32 Integer where
cast = prim__cast_Bits32Integer
export
Cast Bits64 Integer where
cast = prim__cast_Bits64Integer
-- To Int
export
Cast Integer Int where
cast = prim__cast_IntegerInt
export
Cast Char Int where
cast = prim__cast_CharInt
export
Cast Double Int where
cast = prim__cast_DoubleInt
export
Cast String Int where
cast = prim__cast_StringInt
export
Cast Nat Int where
cast = fromInteger . natToInteger
export
Cast Bits8 Int where
cast = prim__cast_Bits8Int
export
Cast Bits16 Int where
cast = prim__cast_Bits16Int
export
Cast Bits32 Int where
cast = prim__cast_Bits32Int
export
Cast Bits64 Int where
cast = prim__cast_Bits64Int
-- To Char
export
Cast Int Char where
cast = prim__cast_IntChar
-- To Double
export
Cast Int Double where
cast = prim__cast_IntDouble
export
Cast Integer Double where
cast = prim__cast_IntegerDouble
export
Cast String Double where
cast = prim__cast_StringDouble
export
Cast Nat Double where
cast = prim__cast_IntegerDouble . natToInteger
-- To Bits8
export
Cast Int Bits8 where
cast = prim__cast_IntBits8
export
Cast Integer Bits8 where
cast = prim__cast_IntegerBits8
export
Cast Bits16 Bits8 where
cast = prim__cast_Bits16Bits8
export
Cast Bits32 Bits8 where
cast = prim__cast_Bits32Bits8
export
Cast Bits64 Bits8 where
cast = prim__cast_Bits64Bits8
-- To Bits16
export
Cast Int Bits16 where
cast = prim__cast_IntBits16
export
Cast Integer Bits16 where
cast = prim__cast_IntegerBits16
export
Cast Bits8 Bits16 where
cast = prim__cast_Bits8Bits16
export
Cast Bits32 Bits16 where
cast = prim__cast_Bits32Bits16
export
Cast Bits64 Bits16 where
cast = prim__cast_Bits64Bits16
-- To Bits32
export
Cast Int Bits32 where
cast = prim__cast_IntBits32
export
Cast Integer Bits32 where
cast = prim__cast_IntegerBits32
export
Cast Bits8 Bits32 where
cast = prim__cast_Bits8Bits32
export
Cast Bits16 Bits32 where
cast = prim__cast_Bits16Bits32
export
Cast Bits64 Bits32 where
cast = prim__cast_Bits64Bits32
-- To Bits64
export
Cast Int Bits64 where
cast = prim__cast_IntBits64
export
Cast Integer Bits64 where
cast = prim__cast_IntegerBits64
export
Cast Bits8 Bits64 where
cast = prim__cast_Bits8Bits64
export
Cast Bits16 Bits64 where
cast = prim__cast_Bits16Bits64
export
Cast Bits32 Bits64 where
cast = prim__cast_Bits32Bits64
|
!
! this subroutine is used to read some paramters from
! input.dat
! constructed on 4/22/2010 by QS.Wu
subroutine readinput
use wmpi
use para
implicit none
character*12 :: fname='input.dat'
character*25 :: char_temp
character*80 :: inline
logical :: exists
logical :: lfound
real(dp) :: cell_volume
real(dp) :: cell_volume2
integer :: stat
integer :: i, ia, n
integer :: j
integer :: NN
integer :: nwann
real(dp) :: t1, temp
real(dp) :: pos(2)
real(dp) :: k1(2), k2(2)
real(dp) :: kstart(2), kend(2), kstart1, kend1
real(dp) :: R1(2), R2(2)
real(dp), external :: norm
inquire(file=fname,exist=exists)
if (exists)then
if(cpuid==0)write(stdout,*) ' '
if(cpuid==0)write(stdout,*) '>>>Read some paramters from input.dat'
open(unit=1001,file=fname,status='old')
else
if(cpuid==0)write(stdout,*)'file' ,fname, 'dosnot exist'
stop
endif
!> inout file
!read(1001,*)Hrfile
read(1001, TB_FILE, iostat= stat)
if (stat/=0) then
Hrfile='wannier90_hr.dat'
inquire(file='wannier90_hr.dat',exist=exists)
if (.not.exists) stop "TB_FIlE namelist should be given or wannier90_hr.dat should exist"
endif
if(cpuid==0)write(stdout,'(1x, a, a25)')"Tight binding Hamiltonian file: ",Hrfile
BulkBand_calc = .FALSE.
RibbonBand_calc = .FALSE.
SlabSS_calc = .FALSE.
Dos_calc = .FALSE.
FS_calc = .FALSE.
GapPlane_calc = .FALSE.
wanniercenter_calc = .FALSE.
read(1001, CONTROL, iostat=stat)
if (stat/=0) then
write(*, *)"ERROR: namelist CONTROL should be set"
write(*, *)"You should set one of these functions to be T"
write(*, *)"BulkBand_calc,BulkFS_calc,BulkGap_cube_calc,BulkGap_plane_calc"
write(*, *)"RibbonBand_calc,WireBand_calc,SlabSS_calc,SlabArc_calc "
write(*, *)"SlabSpintexture,wanniercenter_calc"
write(*, *)"BerryPhase_calc,BerryCurvature_calc"
write(*, *)"The default Vaule is F"
stop
endif
!> control parameters
if (cpuid==0) then
write(stdout, *) " "
write(stdout, *) ">>>Control parameters: "
write(stdout, *) "BulkBand_calc : ", BulkBand_calc
write(stdout, *) "RibbonBand_calc : ", RibbonBand_calc
write(stdout, *) "SlabSS_calc : ", SlabSS_calc
write(stdout, *) "wanniercenter_calc : ", wanniercenter_calc
endif
!> set system parameters by default
Nslab= 10
Numoccupied = 0
Ntotch = 0
SOC = -1
E_FERMI = 0
Bx = 0
By = 0
Bz = 0
surf_onsite = 0
!> read system parameters from file
read(1001, SYSTEM, iostat=stat)
if (stat/=0) then
write(*, *)"ERROR: namelist SYSTEM is wrong and should be set correctly"
!stop
endif
if (SOC == -1) then
write(*, *)"ERROR: you should set SOC in namelist SYSTEM correctly"
stop
endif
if (Numoccupied == 0) then
write(*, *)"ERROR: you should set Numoccupied in namelist SYSTEM correctly"
stop
endif
if (Ntotch == 0) then
Ntotch = Numoccupied
endif
if (cpuid==0) then
write(stdout, *) " "
write(stdout, *) ">>>System parameters: "
write(stdout, '(1x, a, i6 )')"NumSlabs :", Nslab
write(stdout, '(1x, a, i6)')"Number of Occupied bands:", NumOccupied
write(stdout, '(1x, a, i6)')"Number of total electrons:", Ntotch
write(stdout, '(1x, a, i6)')"With SOC or not in Hrfile:", SOC
write(stdout, '(1x, a, 3f16.6)')"Fermi energy :", E_FERMI
write(stdout, '(1x, a, 3f16.6)')"Bx, By, Bz :", Bx, By, Bz
write(stdout, '(1x, a, 3f16.6)')"surf_onsite :", surf_onsite
endif
!> set up parameters for calculation
E_arc = 0.0d0
Eta_Arc= 0.001d0
OmegaNum = 100
OmegaMin = -1d0
OmegaMax = 1d0
Nk1 = 50
Nk2 = 50
NP = 2
Gap_threshold= 0.01d0
read(1001, PARAMETERS, iostat= stat)
if (cpuid==0) then
write(stdout, *) " "
write(stdout, *) ">>>calculation parameters : "
write(stdout, '(1x, a, f16.5)')'E_arc : ', E_arc
write(stdout, '(1x, a, f16.5)')'Eta_arc : ', Eta_arc
write(stdout, '(1x, a, f16.5)')'Gap_threshold', Gap_threshold
write(stdout, '(1x, a, f16.5)')'OmegaMin : ', OmegaMin
write(stdout, '(1x, a, f16.5)')'OmegaMax : ', OmegaMax
write(stdout, '(1x, a, i6 )')'OmegaNum : ', OmegaNum
write(stdout, '(1x, a, i6 )')'Nk1 : ', Nk1
write(stdout, '(1x, a, i6 )')'Nk2 : ', Nk2
write(stdout, '(1x, a, i6 )')'NP number of principle layers : ', Np
endif
NK = Nk1
!> read lattice information
rewind(1001)
lfound = .false.
do while (.true.)
read(1001, *, end= 100)inline
if (trim(adjustl(inline))=='LATTICE') then
lfound= .true.
if (cpuid==0) write(stdout, *)' '
if (cpuid==0) write(stdout, *)'We found LATTICE card'
exit
endif
enddo
100 continue
if (lfound) then
read(1001, *)inline ! The unit of lattice vector
AngOrBohr=trim(adjustl(inline))
read(1001, *)Rua
read(1001, *)Rub
else
stop 'ERROR: please set lattice information'
endif
if (index(AngOrBohr, 'Bohr')>0) then
Rua= Rua*0.529177d0
Rub= Rub*0.529177d0
endif
!> transform lattice from direct space to reciprocal space
Kua= 0d0
Kub= 0d0
cell_volume=Rua(1)*Rub(2)- Rub(1)*Rua(2)
cell_volume= abs(cell_volume)
cell_volume= 2d0*3.1415926535d0/cell_volume
Kua(1)= cell_volume*Rub(2)
Kua(2)=-cell_volume*Rub(1)
Kub(1)=-cell_volume*Rua(2)
Kub(2)= cell_volume*Rua(1)
if(cpuid==0)write(stdout, '(a)') '>> lattice information (Angstrom)'
if(cpuid==0)write(stdout, '(2f12.6)')Rua
if(cpuid==0)write(stdout, '(2f12.6)')Rub
if(cpuid==0)write(stdout, '(a)') '>> Reciprocal lattice information (1/Angstrom)'
if(cpuid==0)write(stdout, '(2f12.6)')Kua
if(cpuid==0)write(stdout, '(2f12.6)')Kub
!> Read atom positions information
rewind(1001)
lfound = .false.
do while (.true.)
read(1001, *, end= 101)inline
if (trim(adjustl(inline))=='ATOM_POSITIONS') then
lfound= .true.
if (cpuid==0) write(stdout, *)' '
if (cpuid==0) write(stdout, *)'We found ATOM_POSITIONS card'
exit
endif
enddo
101 continue
if (lfound) then
read(1001, *)Num_atoms ! The unit of lattice vector
if(cpuid==0)write(stdout, '(a, i)')'Num_atoms', Num_atoms
allocate(atom_name(Num_atoms))
allocate(Atom_position(2, Num_atoms))
allocate(Atom_position_direct(2, Num_atoms))
read(1001, *)inline ! The unit of lattice vector
DirectOrCart= trim(adjustl(inline))
do i=1, Num_atoms
read(1001, *) atom_name(i), Atom_position(:, i)
if(cpuid==0)write(stdout, '(a4,2f12.6)')atom_name(i), Atom_position(:, i)
if (index(DirectOrCart, "D")>0)then
pos= Atom_position(:, i)
Atom_position(:, i)= pos(1)*Rua+ pos(2)*Rub
endif
enddo
if(cpuid==0)write(stdout,'(a)')'Atom position in cartisen coordinate'
do i=1, Num_atoms
if(cpuid==0)write(stdout, '(a4,2f12.6)')atom_name(i), Atom_position(:, i)
enddo
if(cpuid==0)write(stdout,'(a)')'Atom position in direct coordinate'
do ia=1, Num_atoms
call cart_direct_real(Atom_position(:, ia), Atom_position_direct(:, ia))
if(cpuid==0)write(stdout, '(a4,2f12.6)')atom_name(ia), Atom_position_direct(:, ia)
enddo
else
stop "ERROR: please set atom's positions information"
endif
!> Read projectors information
rewind(1001)
lfound = .false.
do while (.true.)
read(1001, *, end= 102)inline
if (trim(adjustl(inline))=='PROJECTORS'.or.&
trim(adjustl(inline))=='PROJECTOR') then
lfound= .true.
if (cpuid==0) write(stdout, *)' '
if (cpuid==0) write(stdout, *)'We found PROJECTORS card'
exit
endif
enddo
102 continue
if (lfound) then
allocate(nprojs(Num_atoms))
nprojs= 0
read(1001, *)nprojs
if(cpuid==0)write(stdout, '(a, 40i5)')'nprojs', nprojs
max_projs= maxval(nprojs)
allocate(proj_name(max_projs, Num_atoms))
proj_name= ' '
do i=1, Num_atoms
read(1001, *)char_temp, proj_name(1:nprojs(i), i)
if(cpuid==0)write(stdout, '(40a8)') &
char_temp, proj_name(1:nprojs(i), i)
enddo
else
stop "ERROR: please set projectors for Wannier functions information"
endif
!> read edge information
rewind(1001)
lfound = .false.
do while (.true.)
read(1001, *, end= 103)inline
if (trim(adjustl(inline))=='EDGE') then
lfound= .true.
if (cpuid==0) write(stdout, *)' '
if (cpuid==0) write(stdout, *)'We found EDGE card'
exit
endif
enddo
103 continue
if (.not.lfound) then
print *, inline
stop 'ERROR: please set edge information'
endif
!> read information for new lattice
!> in order to get different edge state
!> R1'=U11*R1+U12*R2
!> R2'=U21*R1+U22*R2
read(1001, *)Umatrix(1, :)
read(1001, *)Umatrix(2, :)
if (cpuid==0) then
write(stdout, '(a)')'>> new vectors to define the edge (in unit of lattice vector)'
write(stdout, '(a, 2f12.6)')' The 1st vector on edge :', Umatrix(1, :)
write(stdout, '(a, 2f12.6)')' The 2nd vector on edge :', Umatrix(2, :)
endif
!> check whether Umatrix is right
!> the volume of the new cell should be the same as the old ones
R1= Umatrix(1, 1)*Rua+ Umatrix(1, 2)*Rub
R2= Umatrix(2, 1)*Rua+ Umatrix(2, 2)*Rub
cell_volume2= R1(1)*R2(2)- R1(2)*R2(1)
cell_volume2= 2d0*3.1415926535d0/cell_volume2
if (cell_volume2<0) then
R2=-R2
Umatrix(2, :)= -Umatrix(2, :)
endif
if (abs(abs(cell_volume2)-abs(cell_volume))> 0.001d0.and.cpuid==0) then
write(stdout, *)' ERROR The Umatrix is wrong, the new cell', &
'volume should be the same as the old ones'
write(stdout, '(a,2f10.4)')'cell_volume vs cell_volume-new', cell_volume, cell_volume2
stop
endif
!> read kpath_slab information
rewind(1001)
lfound = .false.
do while (.true.)
read(1001, *, end= 105)inline
if (trim(adjustl(inline))=='KPATH_BULK') then
lfound= .true.
if (cpuid==0) write(stdout, *)' '
if (cpuid==0) write(stdout, *)'We found KPATH_BULK card'
exit
endif
enddo
!> read in k lines for 2D system
k2line_name= ' '
if (cpuid==0) write(stdout, *)'k lines for 2D system'
read(1001, *)nk2lines
if (cpuid==0) write(stdout, *)'No. of k lines for 2D system : ', nk2lines
do i=1, nk2lines
read(1001, *) k2line_name(i), kp(:, i), &
char_temp, ke(:, i)
if(cpuid==0) write(stdout, '(a6, 2f9.5, 4x, a6, 2f9.5)')&
k2line_name(i), kp(:, i), &
char_temp, ke(:, i)
enddo
k2line_name(nk2lines+1) = char_temp
NN= Nk
knv2= NN*nk2lines
allocate( k2_path(knv2, 2))
allocate( k2len (knv2))
k2_path= 0d0
k2len= 0d0
t1=0d0
k2len=0d0
k2line_stop= 0d0
do j=1, nk2lines
do i=1, NN
kstart(1:2)= kp(:, j)
kend(1:2) = ke(:, j)
k1(1:2)= kstart(1)*Kua+ kstart(2)*Kub
k2(1:2)= kend(1)*Kua+ kend(2)*Kub
k2_path(i+(j-1)*NN,:)= kstart(1:2)+ (kend(1:2)-kstart(1:2))*(i-1)/dble(NN-1)
temp= dsqrt((k2(1)- k1(1))**2 &
+(k2(2)- k1(2))**2)/dble(NN-1)
if (i.gt.1) then
t1=t1+temp
endif
k2len(i+(j-1)*NN)= t1
enddo
k2line_stop(j+1)= t1
enddo
105 continue
!> read kpath_ribbon information
rewind(1001)
lfound = .false.
do while (.true.)
read(1001, *, end= 116)inline
if (trim(adjustl(inline))=='KPATH_RIBBON') then
lfound= .true.
if (cpuid==0) write(stdout, *)' '
if (cpuid==0) write(stdout, *)'We found KPATH_RIBBON card'
exit
endif
enddo
!> read in k lines for 1D system
k1line_name= ' '
if (cpuid==0) write(stdout, *)'k lines for 1D system'
read(1001, *)nk1lines
if (cpuid==0) write(stdout, *)'No. of k lines for 1D system : ', nk1lines
do i=1, nk1lines
read(1001, *) k1line_name(i), kp1(i), &
char_temp, ke1(i)
if(cpuid==0) write(stdout, '(a6, 1f9.5, 4x, a6, 1f9.5)')&
k1line_name(i), kp1(i), &
char_temp, ke1(i)
enddo
k1line_name(nk1lines+1) = char_temp
NN= Nk
knv1= NN*nk1lines
allocate( k1_path(knv2))
allocate( k1len (knv2))
k1_path= 0d0
k1len= 0d0
t1=0d0
k1len=0d0
k1line_stop= 0d0
do j=1, nk1lines
do i=1, NN
kstart1= kp1(j)
kend1 = ke1(j)
k1_path(i+(j-1)*NN)= kstart1+ (kend1-kstart1)*(i-1)/dble(NN-1)
temp= abs((kend1- kstart1))/dble(NN-1)
if (i.gt.1) then
t1=t1+temp
endif
k1len(i+(j-1)*NN)= t1
enddo
k1line_stop(j+1)= t1
enddo
116 continue
if (.not.lfound .and.RibbonBand_calc) then
stop 'ERROR: please set KPATH_SLAB for slab band structure calculation'
endif
!> read kplane_slab information
!> default value for KPLANE_SLAB
K2D_start= (/-0.5, -0.5/)
K2D_vec1 = (/ 1.0, 0.0/)
K2D_vec2 = (/ 0.0, 1.0/)
rewind(1001)
lfound = .false.
do while (.true.)
read(1001, *, end= 106)inline
if (trim(adjustl(inline))=='KPLANE_BULK') then
lfound= .true.
if (cpuid==0) write(stdout, *)' '
if (cpuid==0) write(stdout, *)'We found KPLANE_BULK card'
exit
endif
enddo
!> kpoints plane for 2D system--> arcs
read(1001, *)K2D_start
read(1001, *)K2D_vec1
read(1001, *)K2D_vec2
106 continue
if (cpuid==0) write(stdout, *)'>> Kpoints plane for 2D system--> arcs '
if (cpuid==0) write(stdout, '((a, 2f8.4))')'K2D_start:', K2D_start
if (cpuid==0) write(stdout, '((a, 2f8.4))')'The first vector: ', K2D_vec1
if (cpuid==0) write(stdout, '((a, 2f8.4))')'The second vector: ', K2D_vec2
!> close input.dat
close(1001)
eta=(omegamax- omegamin)/omeganum*2d0
if(cpuid==0)write(stdout,*)'<<<Read input.dat file successfully'
return
end subroutine readinput
function norm(R1)
use para, only : dp
implicit none
real(dp), intent(in) :: R1(3)
real(dp) :: norm
norm= sqrt(R1(1)*R1(1)+ R1(2)*R1(2)+ R1(3)*R1(3))
return
end function norm
subroutine cart_direct_real(R1, R2)
use para
implicit none
real(dp), intent(in) :: R1(2)
real(dp), intent(inout) :: R2(2)
real(dp) :: mata(2, 2)
mata(1, :)= Rua
mata(2, :)= Rub
call inv_r(2, mata)
R2= R1(1)*mata(1, :)+ R1(2)*mata(2, :)
return
end subroutine cart_direct_real
subroutine direct_cart_real(R1, R2)
use para
implicit none
real(dp), intent(in) :: R1(2)
real(dp), intent(inout) :: R2(2)
R2= R1(1)*Rua+ R1(2)*Rub
return
end subroutine direct_cart_real
|
#include <bunsan/process/path.hpp>
#include <bunsan/process/error.hpp>
#include <boost/process/search_path.hpp>
namespace bunsan::process {
boost::filesystem::path find_executable_in_path(
const boost::filesystem::path &executable) {
try {
if (executable != executable.filename()) {
BOOST_THROW_EXCEPTION(
non_basename_executable_error()
<< non_basename_executable_error::executable(executable));
}
const boost::filesystem::path path =
boost::process::search_path(executable);
if (path.empty()) {
BOOST_THROW_EXCEPTION(
no_executable_in_path_error()
<< no_executable_in_path_error::executable(executable));
}
return path;
} catch (find_executable_in_path_error &) {
throw;
} catch (std::exception &) {
BOOST_THROW_EXCEPTION(
find_executable_in_path_error()
<< find_executable_in_path_error::executable(executable)
<< enable_nested_current());
}
}
} // namespace bunsan::process
|
/***********************************************************************
This file is part of the librjmcmc project source files.
Copyright : Institut Geographique National (2008-2012)
Contributors : Mathieu Brédif, Olivier Tournaire, Didier Boldo
email : [email protected]
This software is a generic C++ library for stochastic optimization.
This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors have only limited liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.
***********************************************************************/
#ifndef RJMCMC_SIMPLEX_VARIATE_HPP
#define RJMCMC_SIMPLEX_VARIATE_HPP
#include <boost/random/uniform_real.hpp>
namespace rjmcmc {
template<int N> struct factorial { enum { value = factorial<N-1>::value * N };};
template< > struct factorial<0> { enum { value = 1 }; };
struct simplex_variate_log_policy
{
template<int N, typename Engine, typename OutputIterator, typename Rand>
void apply(Engine& e, OutputIterator it, Rand& rand) const
{
double sum = 0;
double x[N+1];
for(unsigned int i=0; i<=N; ++i)
{
x[i] = -log(rand(e));
sum += x[i];
}
for(unsigned int i=0; i<N; ++i, ++it)
{
*it = x[i]/sum;
}
}
};
struct simplex_variate_sort_policy
{
template<int N, typename Engine, typename OutputIterator, typename Rand>
void apply(Engine& e, OutputIterator it, Rand& rand) const
{
double x[N];
for(unsigned int i=0; i<N; ++i) x[i] = rand(e);
std::sort(x,x+N);
double prev = 0;
for(unsigned int i=0; i<N; ++i, ++it)
{
*it = x[i]-prev;
prev = x[i];
}
}
};
struct simplex_variate_power_policy
{
template<int N, typename Engine, typename OutputIterator, typename Rand>
void apply(Engine& e, OutputIterator it, Rand& rand) const
{
static_assert(N>1,"simplex_variate_power_policy is only valid for 2D variates or more !");
double prev = pow(rand(e),1./N);
for(unsigned int i=N-1; i>1; --i)
{
double next = prev*pow(rand(e),1./i);
*it++ = prev-next;
prev = next;
}
double next = prev*rand(e);
*it++ = prev-next;
*it++ = next;
}
};
struct simplex_variate_rejection_policy
{
template<int N, typename Engine, typename OutputIterator, typename Rand>
void apply(Engine& e, OutputIterator it, Rand& rand) const
{
for(;;)
{
double x[N], sum;
for(unsigned int i=0; i<N; ++i)
{
x[i] = rand(e);
sum += x[i];
}
if(sum<=1.)
{
for(unsigned int i=0; i<N; ++i) *it++ = x[i];
return;
}
}
}
};
struct simplex_variate_reflect_policy
{
template<int N, typename Engine, typename OutputIterator, typename Rand>
void apply(Engine& e, OutputIterator it, Rand& rand) const
{
static_assert(N==2,"simplex_variate_reflect_policy is only valid for 2D variates !");
double x = rand(e);
double y = rand(e);
if(x+y>1.)
{
x = 1.-x;
y = 1.-y;
}
*it++ = x;
*it++ = y;
}
};
struct simplex_variate_sqrt_policy
{
template<int N, typename Engine, typename OutputIterator, typename Rand>
void apply(Engine& e, OutputIterator it, Rand& rand) const
{
static_assert(N==2,"simplex_variate_sqrt_policy is only valid for 2D variates, use the generalized simplex_variate_power_policy instead !");
double x = sqrt(rand(e));
double y = x*rand(e);
*it++ = x-y;
*it++ = y;
}
};
template<int N, typename Policy = simplex_variate_power_policy >
class simplex_variate
{
typedef boost::uniform_real<> rand_type;
mutable rand_type m_rand;
const double m_pdf;
Policy m_policy;
public:
typedef double value_type;
enum { dimension = N };
template<typename InputIterator>
inline double pdf(InputIterator it) const {
double sum = 0;
for(unsigned int i=0; i<N; ++i, ++it)
{
if(*it<0) return 0;
sum += *it;
}
return double(sum <= 1.)*m_pdf;
}
template<typename Engine, typename OutputIterator>
inline double operator()(Engine& e, OutputIterator it) const {
m_policy.template apply<N>(e,it,m_rand);
return m_pdf;
}
simplex_variate() : m_rand(0,1), m_pdf(1./factorial<N>::value) {}
};
}; // namespace rjmcmc
#endif // RJMCMC_SIMPLEX_VARIATE_HPP
|
[STATEMENT]
lemma better_LOr2_intro[intro]:
shows "\<lbrakk>y\<sharp>([x1].N1,[x2].N2); b\<sharp>[a].M\<rbrakk>
\<Longrightarrow> Cut <b>.(OrR2 <a>.M b) (y).(OrL (x1).N1 (x2).N2 y) \<longrightarrow>\<^sub>l Cut <a>.M (x2).N2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
assume fs: "y\<sharp>([x1].N1,[x2].N2)" "b\<sharp>[a].M"
[PROOF STATE]
proof (state)
this:
y \<sharp> ([x1].N1, [x2].N2)
b \<sharp> [a].M
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
obtain y'::"name" where f1: "y'\<sharp>(y,M,N1,N2,x1,x2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>y'. y' \<sharp> (y, M, N1, N2, x1, x2) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (rule exists_fresh(1), rule fin_supp, blast)
[PROOF STATE]
proof (state)
this:
y' \<sharp> (y, M, N1, N2, x1, x2)
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
obtain x1'::"name" where f2: "x1'\<sharp>(y,M,N1,N2,x1,x2,y')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>x1'. x1' \<sharp> (y, M, N1, N2, x1, x2, y') \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (rule exists_fresh(1), rule fin_supp, blast)
[PROOF STATE]
proof (state)
this:
x1' \<sharp> (y, M, N1, N2, x1, x2, y')
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
obtain x2'::"name" where f3: "x2'\<sharp>(y,M,N1,N2,x1,x2,y',x1')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>x2'. x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1') \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (rule exists_fresh(1), rule fin_supp, blast)
[PROOF STATE]
proof (state)
this:
x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1')
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
obtain a'::"coname" where f4: "a'\<sharp>(a,N1,N2,M,b)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>a'. a' \<sharp> (a, N1, N2, M, b) \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (rule exists_fresh(2), rule fin_supp, blast)
[PROOF STATE]
proof (state)
this:
a' \<sharp> (a, N1, N2, M, b)
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
obtain b'::"coname" where f5: "b'\<sharp>(a,N1,N2,M,b,a')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>b'. b' \<sharp> (a, N1, N2, M, b, a') \<Longrightarrow> thesis) \<Longrightarrow> thesis
[PROOF STEP]
by (rule exists_fresh(2),rule fin_supp, blast)
[PROOF STATE]
proof (state)
this:
b' \<sharp> (a, N1, N2, M, b, a')
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
have "Cut <b>.(OrR2 <a>.M b) (y).(OrL (x1).N1 (x2).N2 y)
= Cut <b'>.(OrR2 <a>.M b') (y').(OrL (x1).N1 (x2).N2 y')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y = Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y'
[PROOF STEP]
using f1 f2 f3 f4 f5 fs
[PROOF STATE]
proof (prove)
using this:
y' \<sharp> (y, M, N1, N2, x1, x2)
x1' \<sharp> (y, M, N1, N2, x1, x2, y')
x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1')
a' \<sharp> (a, N1, N2, M, b)
b' \<sharp> (a, N1, N2, M, b, a')
y \<sharp> ([x1].N1, [x2].N2)
b \<sharp> [a].M
goal (1 subgoal):
1. Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y = Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y'
[PROOF STEP]
apply(rule_tac sym)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y' = Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y
[PROOF STEP]
apply(perm_simp add: trm.inject alpha calc_atm fresh_prod fresh_left fresh_atm abs_fresh)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>y' \<noteq> y \<and> y' \<sharp> M \<and> y' \<sharp> N1 \<and> y' \<sharp> N2 \<and> y' \<noteq> x1 \<and> y' \<noteq> x2; x1' \<noteq> y \<and> x1' \<sharp> M \<and> x1' \<sharp> N1 \<and> x1' \<sharp> N2 \<and> x1' \<noteq> x1 \<and> x1' \<noteq> x2 \<and> x1' \<noteq> y'; x2' \<noteq> y \<and> x2' \<sharp> M \<and> x2' \<sharp> N1 \<and> x2' \<sharp> N2 \<and> x2' \<noteq> x1 \<and> x2' \<noteq> x2 \<and> x2' \<noteq> y' \<and> x2' \<noteq> x1'; a' \<noteq> a \<and> a' \<sharp> N1 \<and> a' \<sharp> N2 \<and> a' \<sharp> M \<and> a' \<noteq> b; b' \<noteq> a \<and> b' \<sharp> N1 \<and> b' \<sharp> N2 \<and> b' \<sharp> M \<and> b' \<noteq> b \<and> b' \<noteq> a'; (y = x1 \<or> y \<sharp> N1) \<and> (y = x2 \<or> y \<sharp> N2); b = a \<or> b \<sharp> M\<rbrakk> \<Longrightarrow> (x2 = x1 \<longrightarrow> (y = x1 \<longrightarrow> (b = a \<longrightarrow> (a = b' \<and> M = [(b', a)] \<bullet> M \<or> a \<noteq> b') \<and> (x1 = y' \<and> N1 = [(y', x1)] \<bullet> N1 \<or> x1 \<noteq> y') \<and> (x1 = y' \<and> N2 = [(y', x1)] \<bullet> N2 \<or> x1 \<noteq> y')) \<and> (b \<noteq> a \<longrightarrow> M = [(b', b)] \<bullet> M \<and> (x1 = y' \<and> N1 = [(y', x1)] \<bullet> N1 \<or> x1 \<noteq> y') \<and> (x1 = y' \<and> N2 = [(y', x1)] \<bullet> N2 \<or> x1 \<noteq> y'))) \<and> (y \<noteq> x1 \<longrightarrow> (b = a \<longrightarrow> (a = b' \<and> M = [(b', a)] \<bullet> M \<or> a \<noteq> b') \<and> N1 = [(y', y)] \<bullet> N1 \<and> N2 = [(y', y)] \<bullet> N2) \<and> (b \<noteq> a \<longrightarrow> M = [(b', b)] \<bullet> M \<and> N1 = [(y', y)] \<bullet> N1 \<and> N2 = [(y', y)] \<bullet> N2))) \<and> (x2 \<noteq> x1 \<longrightarrow> (y = x1 \<longrightarrow> (b = a \<longrightarrow> (a = b' \<and> M = [(b', a)] \<bullet> M \<or> a \<noteq> b') \<and> (x1 = y' \<and> N1 = [(y', x1)] \<bullet> N1 \<or> x1 \<noteq> y') \<and> N2 = [(y', x1)] \<bullet> N2) \<and> (b \<noteq> a \<longrightarrow> M = [(b', b)] \<bullet> M \<and> (x1 = y' \<and> N1 = [(y', x1)] \<bullet> N1 \<or> x1 \<noteq> y') \<and> N2 = [(y', x1)] \<bullet> N2)) \<and> (y \<noteq> x1 \<longrightarrow> (y = x2 \<longrightarrow> (b = a \<longrightarrow> (a = b' \<and> M = [(b', a)] \<bullet> M \<or> a \<noteq> b') \<and> N1 = [(y', x2)] \<bullet> N1 \<and> (x2 = y' \<and> N2 = [(y', x2)] \<bullet> N2 \<or> x2 \<noteq> y')) \<and> (b \<noteq> a \<longrightarrow> M = [(b', b)] \<bullet> M \<and> N1 = [(y', x2)] \<bullet> N1 \<and> (x2 = y' \<and> N2 = [(y', x2)] \<bullet> N2 \<or> x2 \<noteq> y'))) \<and> (y \<noteq> x2 \<longrightarrow> (b = a \<longrightarrow> (a = b' \<and> M = [(b', a)] \<bullet> M \<or> a \<noteq> b') \<and> N1 = [(y', y)] \<bullet> N1 \<and> N2 = [(y', y)] \<bullet> N2) \<and> (b \<noteq> a \<longrightarrow> M = [(b', b)] \<bullet> M \<and> N1 = [(y', y)] \<bullet> N1 \<and> N2 = [(y', y)] \<bullet> N2))))
[PROOF STEP]
apply(auto simp add: perm_fresh_fresh)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y = Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y'
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y = Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y'
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
have "\<dots> = Cut <b'>.(OrR2 <a'>.([(a',a)]\<bullet>M) b')
(y').(OrL (x1').([(x1',x1)]\<bullet>N1) (x2').([(x2',x2)]\<bullet>N2) y')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y' = Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y'
[PROOF STEP]
using f1 f2 f3 f4 f5 fs
[PROOF STATE]
proof (prove)
using this:
y' \<sharp> (y, M, N1, N2, x1, x2)
x1' \<sharp> (y, M, N1, N2, x1, x2, y')
x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1')
a' \<sharp> (a, N1, N2, M, b)
b' \<sharp> (a, N1, N2, M, b, a')
y \<sharp> ([x1].N1, [x2].N2)
b \<sharp> [a].M
goal (1 subgoal):
1. Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y' = Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y'
[PROOF STEP]
apply(rule_tac sym)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y' = Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y'
[PROOF STEP]
apply(perm_simp add: trm.inject alpha calc_atm fresh_prod fresh_left fresh_atm abs_fresh)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y' = Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y'
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
Cut <b'>.OrR2 <a>.M b' y'.OrL x1.N1 x2.N2 y' = Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y'
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
have "\<dots> \<longrightarrow>\<^sub>l Cut <a'>.([(a',a)]\<bullet>M) (x2').([(x2',x2)]\<bullet>N2)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y' \<longrightarrow>\<^sub>l Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2)
[PROOF STEP]
using f1 f2 f3 f4 f5 fs
[PROOF STATE]
proof (prove)
using this:
y' \<sharp> (y, M, N1, N2, x1, x2)
x1' \<sharp> (y, M, N1, N2, x1, x2, y')
x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1')
a' \<sharp> (a, N1, N2, M, b)
b' \<sharp> (a, N1, N2, M, b, a')
y \<sharp> ([x1].N1, [x2].N2)
b \<sharp> [a].M
goal (1 subgoal):
1. Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y' \<longrightarrow>\<^sub>l Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2)
[PROOF STEP]
apply -
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y' \<longrightarrow>\<^sub>l Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2)
[PROOF STEP]
apply(rule l_redu.intros)
[PROOF STATE]
proof (prove)
goal (6 subgoals):
1. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> b' \<sharp> ([a'].([(a', a)] \<bullet> M), [(x1', x1)] \<bullet> N1, [(x2', x2)] \<bullet> N2, a')
2. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> y' \<sharp> ([x1'].([(x1', x1)] \<bullet> N1), [x2'].([(x2', x2)] \<bullet> N2), [(a', a)] \<bullet> M, x1', x2')
3. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> x1' \<sharp> ([(a', a)] \<bullet> M, [(x2', x2)] \<bullet> N2)
4. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> x2' \<sharp> ([(a', a)] \<bullet> M, [(x1', x1)] \<bullet> N1)
5. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> a' \<sharp> ([(x1', x1)] \<bullet> N1, [(x2', x2)] \<bullet> N2)
6. \<lbrakk>y' \<sharp> (y, M, N1, N2, x1, x2); x1' \<sharp> (y, M, N1, N2, x1, x2, y'); x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1'); a' \<sharp> (a, N1, N2, M, b); b' \<sharp> (a, N1, N2, M, b, a'); y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> x1' \<noteq> x2'
[PROOF STEP]
apply(auto simp add: abs_fresh fresh_prod fresh_left calc_atm fresh_atm)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done
[PROOF STATE]
proof (state)
this:
Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y' \<longrightarrow>\<^sub>l Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2)
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
Cut <b'>.OrR2 <a'>.([(a', a)] \<bullet> M) b' y'.OrL x1'.([(x1', x1)] \<bullet> N1) x2'.([(x2', x2)] \<bullet> N2) y' \<longrightarrow>\<^sub>l Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2)
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
have "\<dots> = Cut <a>.M (x2).N2"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2) = Cut <a>.M x2.N2
[PROOF STEP]
using f1 f2 f3 f4 f5 fs
[PROOF STATE]
proof (prove)
using this:
y' \<sharp> (y, M, N1, N2, x1, x2)
x1' \<sharp> (y, M, N1, N2, x1, x2, y')
x2' \<sharp> (y, M, N1, N2, x1, x2, y', x1')
a' \<sharp> (a, N1, N2, M, b)
b' \<sharp> (a, N1, N2, M, b, a')
y \<sharp> ([x1].N1, [x2].N2)
b \<sharp> [a].M
goal (1 subgoal):
1. Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2) = Cut <a>.M x2.N2
[PROOF STEP]
by (auto simp add: trm.inject alpha fresh_atm fresh_prod calc_atm)
[PROOF STATE]
proof (state)
this:
Cut <a'>.([(a', a)] \<bullet> M) x2'.([(x2', x2)] \<bullet> N2) = Cut <a>.M x2.N2
goal (1 subgoal):
1. \<lbrakk>y \<sharp> ([x1].N1, [x2].N2); b \<sharp> [a].M\<rbrakk> \<Longrightarrow> Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
goal (1 subgoal):
1. Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
Cut <b>.OrR2 <a>.M b y.OrL x1.N1 x2.N2 y \<longrightarrow>\<^sub>l Cut <a>.M x2.N2
goal:
No subgoals!
[PROOF STEP]
qed |
{-# OPTIONS --safe #-}
module Cubical.Algebra.CommAlgebra.Instances.Initial where
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.HLevels
open import Cubical.Foundations.Isomorphism
open import Cubical.Data.Unit
open import Cubical.Data.Sigma.Properties using (Σ≡Prop)
open import Cubical.Algebra.CommRing
open import Cubical.Algebra.Ring
open import Cubical.Algebra.Algebra.Base using (IsAlgebraHom)
open import Cubical.Algebra.CommAlgebra.Base
private
variable
ℓ : Level
module _ ((R , str) : CommRing ℓ) where
initialCAlg : CommAlgebra (R , str) ℓ
initialCAlg =
let open CommRingStr str
in (R , commalgebrastr _ _ _ _ _ (λ r x → r · x)
(makeIsCommAlgebra (isSetRing (CommRing→Ring (R , str)))
+Assoc +Rid +Rinv +Comm
·Assoc ·Lid
·Ldist+ ·Comm
(λ x y z → sym (·Assoc x y z)) ·Ldist+ ·Rdist+ ·Lid
λ x y z → sym (·Assoc x y z)))
module _ (A : CommAlgebra (R , str) ℓ) where
open CommAlgebraStr ⦃... ⦄
private
instance
_ : CommAlgebraStr (R , str) (fst A)
_ = snd A
_ : CommAlgebraStr (R , str) R
_ = snd initialCAlg
_*_ : R → (fst A) → (fst A)
r * a = CommAlgebraStr._⋆_ (snd A) r a
initialMap : CommAlgebraHom initialCAlg A
initialMap =
makeCommAlgebraHom {M = initialCAlg} {N = A}
(λ r → r * 1a)
(⋆-lid _)
(λ x y → ⋆-ldist x y 1a)
(λ x y → (x · y) * 1a ≡⟨ ⋆-assoc _ _ _ ⟩
x * (y * 1a) ≡[ i ]⟨ x * (·Lid (y * 1a) (~ i)) ⟩
x * (1a · (y * 1a)) ≡⟨ sym (⋆-lassoc _ _ _) ⟩
(x * 1a) · (y * 1a) ∎)
(λ r x → (r · x) * 1a ≡⟨ ⋆-assoc _ _ _ ⟩
(r * (x * 1a)) ∎)
initialMapEq : (f : CommAlgebraHom initialCAlg A)
→ f ≡ initialMap
initialMapEq f =
let open IsAlgebraHom (snd f)
in Σ≡Prop
(isPropIsCommAlgebraHom {M = initialCAlg} {N = A})
λ i x →
((fst f) x ≡⟨ cong (fst f) (sym (·Rid _)) ⟩
fst f (x · 1a) ≡⟨ pres⋆ x 1a ⟩
CommAlgebraStr._⋆_ (snd A) x (fst f 1a) ≡⟨ cong
(λ u → (snd A CommAlgebraStr.⋆ x) u)
pres1 ⟩
(CommAlgebraStr._⋆_ (snd A) x 1a) ∎) i
initialityIso : Iso (CommAlgebraHom initialCAlg A) (Unit* {ℓ = ℓ})
initialityIso = iso (λ _ → tt*)
(λ _ → initialMap)
(λ {tt*x → refl})
λ f → sym (initialMapEq f)
initialityPath : CommAlgebraHom initialCAlg A ≡ Unit*
initialityPath = isoToPath initialityIso
|
The identity function is Lebesgue measurable. |
Make sure you remove `raise NotImplementedError()` and fill in any place that says `# YOUR CODE HERE`, as well as your `NAME`, `ID`, and `LAB_SECTION` below:
```python
NAME = "FAHMID BIN KIBRIA"
ID = "19201063"
LAB_SECTION = "02"
```
---
# Part 1: Hermite Interpolation
---
Hermite Interpolation is an example of a variant of the interpolation problem, where the interpolant matches one or more **derivatives of $f$** at each of the nodes, in addition to the function values.
## Importing the necessary libraries
```python
import numpy as np
import matplotlib.pyplot as plt
from itertools import combinations
from numpy.polynomial import Polynomial
```
## Creating the components for Hermite interpolation
For the case of Hermite Interpolation, we look for a polynomial that matches both $f'(x_i)$ and $f(x_i)$ at the nodes $x_i = x_0,\dots,x_n$. Say you have $n+1$ data points, $(x_0, y_0), (x_1, y_1), x_2, y_2), \dots, (x_n, y_n)$ and you happen to know the first-order derivative at all of these points, namely, $(x_0, y_0 ^\prime ), (x_1, y_1 ^\prime ), x_2, y_2 ^\prime ), \dots ,(x_n, y_n ^\prime )$. According to hermite interpolation, since there are $2n + 2$ conditions; $n+1$ for $f(x_i)$ plus $n+1$ for $f'(x_i)$; you can fit a polynomial of order $2n+1$.
General form of a $2n+1$ degree Hermite polynomial:
$$p_{2n+1} = \sum_{k=0}^{n} \left(f(x_k)h_k(x) + f'(x_k)\hat{h}_k(x)\right), \tag{1}$$
where $h_k$ and $\hat{h}_k$ are defined using Lagrange basis functions by the following equations:
$$h_k(x) = (1-2(x-x_k)l^\prime_k(x_k))l^2_k(x_k), \tag{2}$$
and
$$\hat{h}_k(x) = (x-x_k)l^2_k(x_k), \tag{3}$$
where the Lagrange basis function being:
$$l_k(x) = \prod_{j=0, j\neq k}^{n} \frac{x-x_j}{x_k-x_j}. \tag{4}$$
**Note** that, we can rewrite Equation $(2)$ in this way,
\begin{align}
h_k(x) &= \left(1-2(x-x_k)l^\prime_k(x_k) \right)l^2_k(x_k) \\
&= \left(1 - 2xl^\prime_k(x_k) + 2x_kl^\prime_k(x_k) \right)l^2_k(x_k) \\
&= \left(1 + 2x_kl^\prime_k(x_k) - 2l'_k(x_k)x \right) l^2_k(x_k) \tag{5}
\end{align}
Replacing $l^\prime_k(x_k)$ with $m$, we get:
$$h_k(x) = (1 - 2xm + 2x_km)l^2_k(x_k). \tag{6}$$
# Tasks:
* The functions: `l(k, x)`, `h(k, x)` and `h_hat(k, x)` calculate the corresponding $l_k$, $h_k$, and $\hat{h}_k$, respectively.
* Function `l(k, x)` has already been defined for you. Your task is to complete the `h(k, x)`, `h_hat(k, x)`, and `hermit(x, y, y_prime)` functions.
* Later we will draw some plots to check if the code is working.
---
### Part 1: Calculate $l_k$
This function uses the following equation to calculate $l_k(x)$ and returns a polynomial:
$$l_k(x) = \prod_{j=0, j\neq k}^{n} \frac{x-x_j}{x_k-x_j}.$$
```python
# Already written for you.
def l(k, x):
n = len(x)
assert (k < len(x))
x_k = x[k]
x_copy = np.delete(x, k)
denominator = np.prod(x_copy - x_k)
coeff = []
for i in range(n):
coeff.append(sum([np.prod(x) for x in combinations(x_copy, i)]) * (-1)**(i) / denominator)
coeff.reverse()
return Polynomial(coeff)
```
### Part 2: Calculate $h_k$
This function calculates $h_k(x)$ using the following equation:
$$h_k(x) = \left(1 + 2x_kl^\prime_k(x_k) - 2l'_k(x_k)x \right) l^2_k(x_k).$$
This equation is basically a multiplication of two polynomials.
First polynomial: $1 + 2x_kl^\prime_k(x_k) - 2l'_k(x_k)x$.
Second polynomial: $l^2_k(x_k)$.
The `coeff` variable should contain a python list of coefficient values for the **first** polynomial of the equation. These coefficient values are used to create a polynomial `p`.
```python
def h(k, x):
# initialize with None. Replace with appropriate values/function calls
# initialize with None. Replace with appropriate values/function calls
l_k = None
l_k_sqr = None
l_k_prime = None
coeff = None
p = None
# --------------------------------------------
# YOUR CODE HERE
l_k = l(k,x)
l_k_sqr = l_k**2
l_k_prime = l_k.deriv()
coeff = [ 1 + 2*x[k]*l_k_prime(x[k]) , -2*l_k_prime(x[k])]
p = Polynomial(coeff)
# --------------------------------------------
return p * l_k_sqr
```
```python
# Test case for the h(k, x) function
x = [3, 5, 7, 9]
k = 2
h_test = h(k, [3, 5, 7, 9])
h_result = Polynomial([-2.5, 0.5]) * (l(k, x) ** 2)
```
### Part 3: Calculate $\hat{h}_k$
This function calculates $\hat{h}_k(x)$ using the following equation:
$$\hat{h}_k(x) = (x-x_k)l^2_k(x_k).$$
This equation is also a multiplication of two polynomials.
First polynomial: $x-x_k$.
Second polynomial: $l^2_k(x_k)$.
The `coeff` variable should contain a python list of coefficient values for the **first** polynomial of the equation. These coefficient values are used to create a polynomial `p`.
```python
def h_hat(k, x):
# Initialize with none
l_k = None
l_k_sqr = None
coeff = None
p = None
# --------------------------------------------
# YOUR CODE HERE
l_k = l(k,x)
l_k_sqr = l_k**2
coeff = [-x[k] , 1]
p = Polynomial(coeff)
# --------------------------------------------
return p * l_k_sqr
```
```python
# Test case for the h(k, x) function
x = [3, 5, 7, 9]
k = 2
h_test = h_hat(k, [3, 5, 7, 9])
h_result = Polynomial([-7, 1]) * (l(k, x) ** 2)
```
### Part 4: The Hermite Polynomial
This function uses the following equation:
$$p_{2n+1} = \sum_{k=0}^{n} \left(f(x_k)h_k(x) + f'(x_k)\hat{h}_k(x)\right).$$
The polynomial denoted by the equation is calculated by the variable `f`.
```python
def hermit(x, y, y_prime):
assert len(x) == len(y)
assert len(y) == len(y_prime)
f = 0
# --------------------------------------------
# YOUR CODE HERE
for i in range(len(y)):
f += y[i]*h(i,x) + y_prime[i]*h_hat(i,x)
print(f)
# --------------------------------------------
return f
```
## Testing our methods by plotting graphs.
**Note:**
* For each of the 5 plots, there will be 2 curves plotted: one being the original function, and the other being the interpolated curve.
* The original functions are displayed in orange color, while the hermite interpolated curves are in blue.
* `x`, `y`, and `y_prime` contain $x_i$, $f(x_i)$, and $f'(x_i)$ of the given nodes of the original function $f$.
Upon calling the `hermit()` function, it returns a polynomial `f`. For example, for plot 1, it is called `f3`.
In general, a polynomial may look like the following: $f = 1 + 2x + 3x^2$. Next, we pass in a number of $x$ values to the polynomial by calling the `.linspace()` function on the polynomial object using `f.linspace()`. This function outputs a tuple, which is stored in a variable called `data`. First element of `data` contains a 1D numpy array of $x_i$ values generated by `linspace()`, and the second element of `data` contains a 1D numpy array of the corresponding $y_i$ values outputted by our example polynomial:
$f = 1 + 2x + 3x^2$.
Using `test_x`, we generate a range of $x_i$ values to plot the original function, and `test_y` contains the corresponding $y_i$ values of the original function. For the first plot, our original function is the *sine curve*.
For all the plots:
`plt.plot(test_x, test_y)` plots the original function.
`plt.plot(data[0], data[1])` plots the interpolated polynomial.
```python
pi = np.pi
x = np.array([0.0, pi/2.0, pi, 3.0*pi/2.0])
y = np.array([0.0, 1.0, 0.0, -1.0])
y_prime = np.array([1.0, 0.0, 1.0, 0.0])
```
**Plot 1:** trying to interpolate a sine curve (`np.sin()`) using first 2 nodes in `x` and `y`, and their corresponding derivative in `y_prime`.
```python
n = 1
f3 = hermit(x[:(n+1)], y[:(n+1)], y_prime[:(n+1)])
data = f3.linspace(n=50, domain=[-3, 3])
test_x = np.linspace(-3, 3, 50, endpoint=True)
test_y = np.sin(test_x)
plt.plot(data[0], data[1])
plt.plot(test_x, test_y)
plt.show()
```
**Plot 2:** trying to interpolate a sine curve (`np.sin()`) using first 3 nodes in `x` and `y` and their corresponding derivative in `y_prime`.
```python
n = 2
f5 = hermit(x[:(n+1)], y[:(n+1)], y_prime[:(n+1)])
data = f5.linspace(n=50, domain=[-0.7, 3])
test_x = np.linspace(-2*pi, 2*pi, 50, endpoint=True)
test_y = np.sin(test_x)
plt.plot(test_x, test_y) # 25-
plt.plot(data[0], data[1]) # 10-33
plt.show()
```
**Plot 3:** trying to interpolate a sine curve (`np.sin()`) using first 4 nodes in `x` and `y` and their corresponding derivative in `y_prime`.
```python
n = 3
f7 = hermit(x[:(n+1)], y[:(n+1)], y_prime[:(n+1)])
data = f7.linspace(n=50, domain=[-0.3, 3])
test_x = np.linspace(-2*pi, 2*pi, 50, endpoint=True)
test_y = np.sin(test_x)
plt.plot(data[0], data[1])
plt.plot(test_x, test_y)
plt.show()
```
**Plot 4:** trying to interpolate an exponential curve (`np.exp()`) using all nodes in `x` and `y` and their corresponding derivatives in `y_prime`.
```python
#defining new set of given node information: x, y and y'
x = np.array([0.0, 1.0, 2.0 ])
y = np.array([1.0, 2.71828183, 54.59815003])
y_prime = np.array([0.0, 5.43656366, 218.39260013])
f7 = hermit( x, y, y_prime)
data = f7.linspace(n=50, domain=[-0.5, 2.2])
test_x = np.linspace(-0.5, 2.2, 50, endpoint=True)
test_y = np.exp(test_x**2)
plt.plot(data[0], data[1])
plt.plot(test_x, test_y)
plt.show()
```
**Plot 5:** trying to interpolate $y = (x-3)^2 + 1$ using all nodes in `x` and `y` and their corresponding derivatives in `y_prime`.
For this plot you might be able to see only one curve due to the two curves overlapping. This means that our polynomial is accurately interpolating the original function.
```python
#defining new set of given node information: x, y and y'
x = np.array([1.0, 3.0, 5.0])
y = np.array([5.0, 1.0, 5.0])
y_prime = np.array([-4.0, 0.0, 4.0])
f7 = hermit( x, y, y_prime)
data = f7.linspace(n=50, domain=[-10, 10])
test_x = np.linspace(-10, 10, 50, endpoint=True)
test_y = (test_x-3)**2 + 1
plt.plot(data[0], data[1])
plt.plot(test_x, test_y)
plt.show()
```
## Part 2: Polynomial Interpolation Using Newton's Divided Difference Form
---
### Newton's Divided Difference Form
Newton form of a $n$ degree polynomial:
$$p_n(x) = \sum_{k=0}^{n} a_kn_k(x),$$
where the basis is:
$$n_k(x) = \prod_{j=0}^{k-1}(x-x_j),$$
$$ n_0(x)=1,$$
and the coefficients are: $$a_k = f[x_0, x_1, ..., x_k],$$
where the notation $f[x_0, x_1,\dots,x_k]$ denotes the divided difference.
By expanding the Newton form, we get:
$$p(x) = f [x_0] + (x-x_0) f[x_0,x_1] + (x-x_0) (x-x_1) f[x_0,x_1,x_2] + \dots + (x-x_0) (x-x_1) \dots (x-x_{k-1}) f[x_0, x_1, \dots, x_k]$$
### Tasks:
1. Complete the `calc_div_diff(x,y)` function which takes input `x` and `y`, and calculates all the divided differences. You may use the lambda function `difference()` inside the `calc_div_diff(x,y)` function to calculate the divided differences.
2. Complete the `__call__()` function which takes an input `x`, and calculates `y` using all the difference coefficients. `x` can be a single value or a numpy. In this case, it is a numpy array.
`res` variable must contain all results (corresponding y for x).
```python
class Newtons_Divided_Differences:
def __init__(self, differences):
self.differences = differences
def __call__(self, x):
'''
this function is for calculating y from given x using all the difference coefficients
x can be a single value or a numpy
the formula being used:
f(x) = f [x0] + (x-x0) f[x0,x1] + (x-x0) (x-x1) f[x0,x1,x2] + . . . + (x-x0) (x-x1) . . . (x-xk-1) f[x0, x1, . . ., xk]
work on this after implementing 'calc_div_diff'. Then you should have
f[x0], f[x0,x1]. . . . . ., f[x0, x1, . . ., xk] stored in self.differences
'res' variable must return all the results (corresponding y for x)
'''
res = np.zeros(len(x)) #Initialization to avoid runtime error. You can change this line if you wish
#----------------------------------------------
# YOUR CODE HERE
for k in range(0, len(x)):
res[k]=self.differences[0]
for i in range(1, len(self.differences)):
product = 1
for j in range(i):
product = product * (x[k] - data_x[j])
res[k] = res[k] + product * self.differences[i]
#----------------------------------------------
return res
```
```python
# basic rule for calculating the difference, implanted in the lambda function.
# You may use it if you wish
difference = lambda y2, y1, x2, x1: (y2-y1)/(x2-x1)
def calc_div_diff(x,y):
assert(len(x)==len(y))
#write this function to calculate all the divided differences in the list 'b'
b = [] #initializing
#----------------------------------------------
# YOUR CODE HERE
table=np.array([[0.000000000]*len(y)]*len(y))
for i in range(0,len(y)-1):
table[i, 0]=y[i]
for i in range(1, len(y)):
for j in range(len(y) - i):
table[j, i] = difference(table[j, i - 1], table[j + 1, i - 1], x[j], x[i + j])
b = [0.0000000]*len(table)
for i in range(0,len(table)):
b[i]=table[0, i]
#----------------------------------------------
return b
```
```python
# Test case for the calc_div_diff(x,y) function.
data_x = [-3.,-2.,-1.,0.,1.,3.,4.]
data_y = [-60.,-80.,6.,1.,45.,30.,16.]
test = calc_div_diff(data_x, data_y)
assert len(test) == len(data_x)
```
### Plotting the polynomial
* `data_x` and `data_y` are the coordinates of the given nodes.
* `differences` is a list which contains the divided differences as each of its elements: $f[x_0], f[x_0,x_1], f[x_0,x_1,x_2], \dots$
* `obj` is an object of type `Newtons_Divided_Differences`. Creating the object runs the constructor of the class where the `difference` are stored in `self.differences`.
* `X` contains $x_i$ values through which we want to plot our polynomial.
* Calling the object using `obj(X)` executes the `__call__()` function of the class, which returns a numpy array containing the corresponding $y_i$ values, and storing them in variable `F`.
* Using `plt.plot(X,F)`, we plot the $(x_i, y_i)$ pairs of the polynomial.
```python
import numpy as np
import matplotlib.pyplot as plt
data_x = np.array([-3.,-2.,-1.,0.,1.,3.,4.])
data_y = np.array([-60.,-80.,6.,1.,45.,30.,16.])
differences = calc_div_diff(list(data_x), list(data_y))
p = Newtons_Divided_Differences(list(differences))
test_x = np.linspace(-3, 4, 50, endpoint=True)
test_y = p(test_x)
#generating 50 points from -3 to 4 in order to create a smooth line
plt.plot(test_x, test_y)
plt.plot(data_x, data_y, 'ro')
plt.show()
```
```python
```
|
lemma pole_theorem: assumes holg: "g holomorphic_on S" and a: "a \<in> interior S" and eq: "\<And>z. z \<in> S - {a} \<Longrightarrow> g z = (z - a) * f z" shows "(\<lambda>z. if z = a then deriv g a else f z - g a/(z - a)) holomorphic_on S" |
# Cases must include `case_name` and `scm_suffix`. If `case_name`=="LES_driven_SCM", must also include `y_dir`.
struct ScmTest end
function get_reference_config(::ScmTest)
config = Dict()
# amip4K data: April
cfsite_numbers = (13, 21, 23)
les_kwargs = (forcing_model = "HadGEM2-A", month = 4, experiment = "amip4K")
ref_dirs = [get_cfsite_les_dir(cfsite_number; les_kwargs...) for cfsite_number in cfsite_numbers]
suffixes = [get_gcm_les_uuid(cfsite_number; les_kwargs...) for cfsite_number in cfsite_numbers]
n_repeat = length(ref_dirs)
config["case_name"] = repeat(["LES_driven_SCM"], n_repeat)
config["y_dir"] = ref_dirs
config["scm_suffix"] = suffixes
return config
end
|
"""
mineral_specs(mineral::Symbol)
Reads and returns the spectral data of a chosen mineral.
Available `mineral` types:
* `:augite`
* `:goethite`
* `:hematite`
* `:pigeonite`
"""
function mineral_specs(mineral::Symbol)
mineral == :augite ? filename = "Augite.spec" :
mineral == :goethite ? filename = "Goethite.spec" :
mineral == :hematite ? filename = "Hematite.spec" :
mineral == :pigeonite ? filename = "Pigeonite.spec" : nothing
fp=@__DIR__
cd(fp)
cd("..\\spectra")
sfile=readlines(filename)
map(x->parse(Float64, x), sfile)
end
"""
mineral(mineral::Symbol, spectable = mineral_specs(mineral))
Returns reflectance spectrum of chosen mineral.
Allowed names for `mineral`: `:augite`, `:goethite`, `:hematite`, `:pigeonite`
"""
function mineral(mineral::Symbol, spectable = mineral_specs(mineral))
len = div(length(spectable), 2)
0 < idx < 1270 ? (i = (idx - 1) * n + 1) : (throw(DomainError(idx, "Index is outside the range of 1 ≤ idx ≤ 1269.")))
reflectance_spec(list[map(n -> n * 2 - 1, 1:len)], list[map(n -> n * 2, 1:len)])
end |
module Main
import Objects.User
main : IO ()
main = putStrLn "hello IdrisVKAPI!"
|
section \<open> Enumeration Extras \<close>
theory Enum_extra
imports "HOL-Library.Code_Cardinality"
begin
subsection \<open> First Index Function \<close>
text \<open> The following function extracts the index of the first occurrence of an element in a list,
assuming it is indeed an element. \<close>
fun first_ind :: "'a list \<Rightarrow> 'a \<Rightarrow> nat \<Rightarrow> nat" where
"first_ind [] y i = undefined" |
"first_ind (x # xs) y i = (if (x = y) then i else first_ind xs y (Suc i))"
lemma first_ind_length:
"x \<in> set(xs) \<Longrightarrow> first_ind xs x i < length(xs) + i"
by (induct xs arbitrary: i, auto, metis add_Suc_right)
lemma nth_first_ind:
"\<lbrakk> distinct xs; x \<in> set(xs) \<rbrakk> \<Longrightarrow> xs ! (first_ind xs x i - i) = x"
apply (induct xs arbitrary: i)
apply (auto)
apply (metis One_nat_def add.right_neutral add_Suc_right add_diff_cancel_left' diff_diff_left empty_iff first_ind.simps(2) list.set(1) nat.simps(3) neq_Nil_conv nth_Cons' zero_diff)
done
lemma first_ind_nth:
"\<lbrakk> distinct xs; i < length xs \<rbrakk> \<Longrightarrow> first_ind xs (xs ! i) j = i + j"
apply (induct xs arbitrary: i j)
apply (auto)
apply (metis less_Suc_eq_le nth_equal_first_eq)
using less_Suc_eq_0_disj apply auto
done
subsection \<open> Enumeration Indices \<close>
syntax
"_ENUM" :: "type \<Rightarrow> logic" ("ENUM'(_')")
translations
"ENUM('a)" => "CONST Enum.enum :: ('a::enum) list"
text \<open> Extract a unique natural number associated with an enumerated value by using its index
in the characteristic list \<^term>\<open>ENUM('a)\<close>. \<close>
definition enum_ind :: "'a::enum \<Rightarrow> nat" where
"enum_ind (x :: 'a::enum) = first_ind ENUM('a) x 0"
lemma length_enum_CARD: "length ENUM('a) = CARD('a)"
by (simp add: UNIV_enum distinct_card enum_distinct)
lemma CARD_length_enum: "CARD('a) = length ENUM('a)"
by (simp add: length_enum_CARD)
lemma enum_ind_less_CARD [simp]: "enum_ind (x :: 'a::enum) < CARD('a)"
using first_ind_length[of x, OF in_enum, of 0] by (simp add: enum_ind_def CARD_length_enum)
lemma enum_nth_ind [simp]: "Enum.enum ! (enum_ind x) = x"
using nth_first_ind[of Enum.enum x 0, OF enum_distinct in_enum] by (simp add: enum_ind_def)
lemma enum_distinct_conv_nth:
assumes "i < CARD('a)" "j < CARD('a)" "ENUM('a) ! i = ENUM('a) ! j"
shows "i = j"
proof -
have "(\<forall>i<length ENUM('a). \<forall>j<length ENUM('a). i \<noteq> j \<longrightarrow> ENUM('a) ! i \<noteq> ENUM('a) ! j)"
using distinct_conv_nth[of "ENUM('a)", THEN sym] by (simp add: enum_distinct)
with assms show ?thesis
by (auto simp add: CARD_length_enum)
qed
lemma enum_ind_nth [simp]:
assumes "i < CARD('a::enum)"
shows "enum_ind (ENUM('a) ! i) = i"
using assms first_ind_nth[of "ENUM('a)" i 0, OF enum_distinct]
by (simp add: enum_ind_def CARD_length_enum)
lemma enum_ind_spec:
"enum_ind (x :: 'a::enum) = (THE i. i < CARD('a) \<and> Enum.enum ! i = x)"
proof (rule sym, rule the_equality, safe)
show "enum_ind x < CARD('a)"
by (simp add: enum_ind_less_CARD[of x])
show "enum_class.enum ! enum_ind x = x"
by simp
show "\<And>i. i < CARD('a) \<Longrightarrow> x = ENUM('a) ! i \<Longrightarrow> i = enum_ind (ENUM('a) ! i)"
by (simp add: enum_ind_nth)
qed
lemma enum_ind_inj: "inj (enum_ind :: 'a::enum \<Rightarrow> nat)"
by (rule inj_on_inverseI[of _ "\<lambda> i. ENUM('a) ! i"], simp)
lemma enum_ind_neq [simp]: "x \<noteq> y \<Longrightarrow> enum_ind x \<noteq> enum_ind y"
by (simp add: enum_ind_inj inj_eq)
end |
from numpy import sqrt
print("You have an equation ax^2+bx+c = 0")
print("Enter the coefficients for a, b, c")
while 1:
try:
a=int(raw_input("a = "))
break
except ValueError:
print("Enter a number")
continue
while 1:
try:
b=int(raw_input("b = "))
break
except ValueError:
print("Enter a number")
continue
while 1:
try:
c=int(raw_input("c = "))
break
except ValueError:
print("Enter a number")
continue
if a==0:
print("Not a quadratic equation")
if b==0:
print("There is no x")
else:
x1=-b/c
print("x1 = "+str(x1))
else:
if b**2-4*a*c<0:
print("No Real Roots")
else:
x1=(-b+sqrt(b**2-4*a*c))/(2*a)
x2=(-b-sqrt(b**2-4*a*c))/(2*a)
print("x1 = "+str(x1))
print("x2 = "+str(x2))
|
\documentclass[11pt]{article}
\textheight 22cm
\textwidth 16cm
\hoffset= -0.6in
\voffset= -0.5in
\setlength{\parindent}{0cm}
\setlength{\parskip}{10pt plus 2pt minus 2pt}
\pagenumbering{roman}
\setcounter{page}{-9}
\newcommand{\be}{\begin{equation}}
\newcommand{\ee}{\end{equation}}
\newcommand{\bd}{\begin{displaymath}}
\newcommand{\ed}{\end{displaymath}}
\begin{document}
\title{Astrophysics II: Laboratory 3}
\author{\Large Binary Stars and Stellar Masses}
\maketitle
\setlength{\parindent}{0.2pt}
\setlength{\parskip}{2ex}
\section{{\bf Objectives:}}
\begin{itemize}
\item Continue learning functionality of MATLAB.\\
- Visualize data.\\
- Use visualization in aid of fitting function to data.
\item Use Spectroscopic measurements of a stellar absorption line to determine binary masses.\\
\end{itemize}
\section{{\bf Introduction}}
Our sun appears to be a rarity in space. Approximately two-thirds of all solar-type field stars are members of binary systems, and recent studies suggest that virtually all stars begin life as members of multiple systems. Consequently, many of the stars you see at night are actually binaries, comprised of two stars gravitationally bound in orbit with one another. These binary systems are important astrophysical laboratories because they allow us to deduce the properties of the constituent stars more accurately than we can with single stars. The physics that governs how stars orbit one another was developed by Newton and Kepler over three hundred years ago, and can be summarized by the equation
\be
P^{2}=\frac{4\pi^{2}}{G(M_{P}+M_{S})}a^{3}
\ee
where P is the period of orbit, G is the gravitational constant, $M_{P}$ and $M_{S}$ are the masses of the primary and secondary stars respectively, and $a$ is the semi-major axes of the two orbits $a=a_{P}+a_{S}$. In mks units, $G = 6.67 \times 10^{-11}$ but these units are not the units of choice. If masses are measured in solar masses, distances in astronomical units, and periods in years, then the application of Newton's law to the Earth-Sun system gives $4\pi^{2}/G=1$.
Binary stars fall into several categories, depending on their observed properties: optical doubles, visual binaries, composite spectrum binaries, astrometric binaries, spectroscopic binaries, and eclipsing binaries (photometric binaries). Here we focus on the case of spectroscopic binaries in the case where the spectrum from the binary system exhibits a doublet of the same HI absorption line.
Your primary task in this lab is to measure the wavelength of the H$\alpha$ line vs time in a series of stellar spectra. This can be done simply by plotting the spectra in matlab and then calculating roughly by sight the shift in wavelength corresponding to doppler shift in the low velocity limit. We assume here that the components of the binary in question are assumed to follow circular orbits. This is not true for all binaries, but for the present system it is valid. This means that the orbital eccentricity is zero and that the orbital velocities are constant at all times.
\section{{\bf Procedure}}
\begin{enumerate}
\item Open MATLAB.
\item Download the seven data files at www.astro.umd.edu/$\sim$mavara/lab3-121/ and save them into the MATLAB directory.
\item Type the following commands at the matlab command line to load the data in each of these files into matlab:\\
$<<$ load(`binary1.dat')\\
$<<$ load(`binary2.dat')\\
etc.....
\item Note that these data files each contain a matrix of two columns, the first signifying wavelength in angstroms and the second a normalized flux.
\item Plot a few of these spectra to get a feel for what they're showing.
\item The primary absorption feature in these plots is a doubling of the HI$\alpha$ line. Notice that there are two strong absorption features in each spectrum and they are of unequal depths. What does that different signify in a normalized spectrum?
\item Use the equation
\be
\frac{\lambda_{0}}{\lambda}=\frac{v}{c}
\ee
to determine the corresponding radial velocities of both components of the binary system for each spectrum
\item The Spectra, in order, were taken on the Julian Dates given in Table 1.
\begin{table}[ht]
\caption{Dates of Observations}
\centering
\begin{tabular}{c c}
\hline \hline
Filename & Julian Date\\ [0.5ex]
\hline
binary1.dat & 2441578.831 \\
binary2.dat & 2441579.581 \\
binary3.dat & 2441580.742 \\
binary4.dat & 2441581.943 \\
binary5.dat & 2441582.670 \\
binary6.dat & 2441582.982 \\
binary7.dat & 2441583.960 \\
\hline
\end{tabular}
\end{table}
\item Plot the radial velocity from the absorption feature of each contributing star vs date, plotting both sets of data on the same plot.
\item Estimate the period, amplitude, etc, and plot a sin function over the data to confirm your estimations.
\item Note: In general, primary refers to the brighter or more massive star in a binary system.
\item Use our assumptions about this particular stellar binary system and the velocities to measure the semi-major axis of the orbit.
\item Use the simplified (units of stellar mass, etc.) version of Equation 1 to calculate the combined mass.
\item What are the masses of the two components in solar masses?\\
(Recall, from the definition of center of mass, $a_{S}M_{S} = a_{P}M_{P}$. Your measurement demonstrates the importance of studying binary stars. Virtually everything we know about stellar masses comes from analyzing their motions.)
\end{enumerate}
\section{{\bf Questions}}
{\it Now let's think about the usefulness of what we've learned.}
What is the primary problem with the measurements of masses of the primary and secondary we obtained?
How might we go about solving this problem?
What additional information about the binary system have we acquired with the spectroscopic information?
Can we be sure that the primary absorption features in the spectrum represent the same line? What else can particular lines tell us?
What would the spectrum of a triple system look like?
\\
\\
\\
* Note that this lab has borrowed heavily from Dr. Christopher Palma's Lab 4 of Astro 293, spring 2003.
http://www.astro.psu.edu/$\sim$cpalma/astro293/
\end{document}
|
# Copyright (c) 2018-2021, Carnegie Mellon University
# See LICENSE for details
saveComment := function(r, fld)
local str, last;
str := CommentBuffer();
last := Position(List(str), "");
ClearCommentBuffer();
r.(fld) := str{[3..last-3]};
end;
Declare(AsmX86Unparser);
Unparse := function(code, unparser, i, is)
local o, res;
# D($(..)) magic allows to deal with functions that do not return a value.
# In this case res := D(_bag_0) without gap complaining.
# We need this so that cx_leave runs before the function returns
if not IsBound(unparser.cx) then unparser := WithBases(unparser, rec(cx := empty_cx())); fi;
if IsRec(code) then
cx_enter(unparser.cx, code);
o := ObjId(code);
if IsBound(unparser.(o.name)) then
res := D($(unparser.(o.name)(code, i, is)));
elif IsBound(o.unparse) and IsBound(unparser.(o.unparse)) then
res := D($(unparser.(o.unparse)(code, i, is)));
else return Error("Cannot unparse <o>. Unparser ", unparser, " does not have field '",
o.name, "'", When(IsBound(o.unparse), Concat(" or ",o.unparse), ""));
fi;
else
res := D($(unparser.atomic(code, i, is)));
fi;
cx_leave(unparser.cx, code);
return $res;
end;
Class(Unparser, rec(
gen := meth(self, subname, o, opts)
local oo;
# using WithBases prevents mem leaks, by avoiding of keeping extra state around
self := WithBases(self, rec(opts := opts, cx := empty_cx()));
oo := self.preprocess(o);
Print(
self.header(subname, oo),
Unparse(oo, self, 4, 2),
self.footer(subname, oo)
);
end,
__call__ := (self, o, i, is) >> Unparse(o,self,i,is),
fileinfo := (self,opts) >> Print(""),
# str = format string with $n for arguments ($1 = first argument)
# list of arguments , arguments are printed using this unparser
printf := (self, str, args) >> ApplyFunc(PrintEvalF, Concatenation([str],
List(args, a ->
Cond(IsFunc(a), a,
() -> Cond(IsType(a), self.declare(a, [], 0, 0), self(a, 0, 0)))))),
# printf with initial indentation
indprintf := (self, i, is, str, args) >> Print(Blanks(i),
ApplyFunc(PrintEvalF, Concatenation([str],
List(args, a-> Cond(IsFunc(a), a,
() -> Cond(IsType(a), self.declare(a, [], i+is, is), self(a, i+is, is))))))),
prefix := meth(self, f, lst)
local first, c;
Print(f, "(");
first := true;
for c in lst do
if first then first := false; else Print(", "); fi;
self(c,0,4);
od;
Print(")");
end,
infixbreak := 8,
#F infix(<lst>, <sep>, <i>)
#F infix takes 2 - 3 arguments. the 3rd argument specifies the number of spaces to indent, otherwise 0
#F
infix := meth(arg)
local self, lst, sep, i, count, c, first;
if not Length(arg) in [3, 4] then
Error("Usage: infix(<lst>, <sep>, [<i>])\n");
fi;
if Length(arg)=3 then
[self, lst, sep] := arg;
i := 0;
else
[self, lst, sep, i] := arg;
fi;
count := 0;
first := true;
for c in lst do
if (count > 0) then
if ((count mod self.infixbreak) = 0) then
Print(sep, "\n",Blanks(i+4));
first := true;
fi;
if not first then
Print(sep);
fi;
fi;
count := count + 1;
self(c,0,4);
first := false;
od;
end,
# finfix( <list>, <func>, <separator> ) - applying <func> to each element of <list>
# and printing <separator> in between.
finfix := meth(self, lst, func, sep)
local first, c;
first := true;
for c in lst do
if first then first := false; else Print(sep); fi;
func(c);
od;
end,
# pinfix(<lst>, <sep>), similar to infix, but parenthesizes the expression
pinfix := meth(self, lst, sep)
Print("(");
self.finfix(lst, c -> self(c, 0, 4), sep);
Print(")");
end,
# ppinfix(<lst>, <sep>), similar to infix, but parenthesizes inside the expression
ppinfix := meth(self, lst, sep)
Print("(");
self.finfix(lst, c -> Print("(", self(c, 0, 4), ")"), sep);
Print(")");
end,
# condinfix(<lst>, <sep>), for conditions like leq.
# condinfix([a,b,c], " sep1 ", " sep2 ") unparses to
# (a sep1 b) sep2 (b sep1 c)
#
condinfix := meth(self, lst, sep1, sep2)
local first, c, i;
Print("(");
for i in [1..Length(lst)-1] do
if i<>1 then Print(sep2); fi;
self.pinfix([lst[i], lst[i+1]], sep1);
od;
Print(")");
end,
));
#F LayeredUnparser(<unparser-class1>, <unparser-class2>, ...)
#F
#F This creates an unnamed class with superclasses listed in arguments.
#F unparser-class1 takes priority over 2, etc.
#F
Class(LayeredUnparser, rec(
__call__ := arg >> Checked(Length(arg)>1, ForAll(Drop(arg, 1), IsClass),
WithBases(arg, rec(operations := PrintOps, __call__ := Unparser.__call__))),
print := self >> Print("LayeredUnparser(", PrintCS(Drop(self.__bases__,1)), ")")
));
Loc.unparse := "Loc";
Exp.unparse := "Exp";
Command.unparse := "Command";
Class(CUnparserBase, Unparser, rec(
preprocess := (self, o) >> o,
preprocess_init := (self, o) >> o,
# example: includes := [ "<math.h>" ]
includes := [],
generated_by := Concat("\
/*\
* This code was generated by Spiral ", SpiralVersion, ", www.spiral.net\
*/\
\n"),
extraHeader := "",
header_top := meth(self, subname, o)
local precomputed_data;
Print(self.generated_by);
self.fileinfo(self.opts);
DoForAll(Concatenation(self.includes, self.opts.includes),
inc -> Print("#include ", inc, "\n"));
if IsBound(o.dimensions) then Print("/* ", o.dimensions, " */\n"); fi;
if IsBound(o.runtime_data) then
DoForAll(o.runtime_data, x->Print(self.opts.arrayDataModifier, " ",
self.declare(x.t, x, 0, 4), ";\n"));
Print("\n");
fi;
precomputed_data := List(Collect(o, data), x->[x.var, x.value]);
DoForAll(precomputed_data, d -> When(IsArrayT(d[1].t), self.genData(d[1], d[2])));
end,
header_func := meth(self, subname, o)
local loopvars;
Print("void ", self.opts.funcModifier, " ", subname, "(",
self.declare(Y.t, Y, 0, 0), ", ", self.declare(X.t, X, 0, 0));
if IsBound(self.opts.sig) then
DoForAll(self.opts.sig, p -> Print(", ", self.declare(p.t, p, 0, 0)));
fi;
Print(") {\n");
loopvars := Set(List(Collect(o, @(1).cond(IsLoop)), x->x.var));
if loopvars <> [] then Print(Blanks(4), "int ", PrintCS(loopvars), ";\n"); fi;
end,
header := meth(self, subname, o)
self.header_top(subname, o);
self.header_func(subname, o);
end,
footer := meth(self, subname, o)
local init, loopvars;
Print("}\n");
Print("void init_", subname, "() {\n");
if IsBound(o.runtime_init) then # unparse initialization code
loopvars := Union(List(o.runtime_init, cc -> List(Collect(cc, @(1).cond(IsLoop)), x->x.var)));
if loopvars <> [ ] then
Print(Blanks(4), "int ", PrintCS(loopvars), ";\n"); fi;
for init in o.runtime_init do
init := self.preprocess_init(init);
self(SReduce(init, o), 4, 4);
od;
fi;
Print(" }\n");
end,
genData := (self, v, val) >> Print(
When(IsArrayT(val.t), self.opts.arrayDataModifier, self.opts.scalarDataModifier), " ",
self.declare(val.t, v, 0, 4), " = ", self(val,2,2), ";\n",
When(IsArrayT(val.t), "\n", "")),
####################
## General
####################
atomic := (self,o,i,is) >> Print(o),
param := (self,o,i,is) >> Print(o.id),
var := (self,o,i,is) >> Print(o.id),
Loc := (self,o,i,is) >> o.cprint(),
####################
## Commands
####################
asmvolatile := (self,o,i,is) >> AsmX86Unparser.asmvolatile(o.asm),
skip := (self,o,i,is) >> Print(Blanks(i), "/* skip */\n"),
noUnparse :=(self,o,i,is) >> Print(o.str),
assign := (self,o,i,is) >> Print(Blanks(i), self(o.loc,i,is), " = ", self(o.exp,i,is), ";\n"),
assign_acc := (self,o,i,is) >> Print(Blanks(i), self(o.loc,i,is), " += ", self(o.exp,i,is), ";\n"),
chain := (self,o,i,is) >> DoForAll(o.cmds, c -> self(c, i, is)),
brackets := (self,o,i,is) >> self.printf("($1)", [o.args[1]]),
unparseChain := (self,o,i,is) >> DoForAll(o.cmds, c -> self(c, i, is)),
kern := (self, o, i, is) >> When( IsBound(self.opts.SimFlexKernelFlag) and IsBound(o.bbnum),
Print(
"#if !defined(KERN) || defined(KERN", String(o.bbnum), ")\n",
self(o.cmd, i, is),
"#endif\n"
),
self(o.cmd, i, is)
),
unroll_cmd := ~.chain,
# all datas are handled in the header, just proceed to children
data := (self,o,i,is) >> Print(
When(not IsArrayT(o.var.t), Print(Blanks(i), self.genData(o.var, o.value))),
self(o.cmd, i, is)
),
_lt := " <= ",
loop := (self,o,i,is) >> Checked(IsRange(o.range),
let(v := o.var, lo := o.range[1], hi := Last(o.range),
Print(Blanks(i), "for(", v, " = ", lo, "; ", v, self._lt, hi, "; ", v, "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}\n"))),
loopn := (self,o,i,is) >>
let(v := o.var, n := o.range,
Print(Blanks(i), "for(", v, " = ", 0, "; ", v, self._lt, self(n-1,i,is), "; ", v, "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}\n")),
doloop := (self,o,i,is) >>
let(v := o.var, n := o.range,
Print(Blanks(i), "do {\n",
self(o.cmd,i+is,is),
Blanks(i), "} while( ", self(v,i,is), "<", self(n,i,is), " );\n")),
loopn := (self, o, i, is) >> self.loop(o, i, is),
IF := (self,o,i,is) >> Print(Blanks(i),
"if (", self(o.cond,i,is), ") {\n", self(o.then_cmd,i+is,is), Blanks(i), "}",
When(o.else_cmd = skip(),
"\n",
Print(" else {\n", self(o.else_cmd,i+is,is), Blanks(i), "}\n"))),
DOWHILE := (self,o,i,is) >> Print(Blanks(i),
"do \n", Blanks(i), "{\n", self(o.then_cmd,i+is,is), Blanks(i), "}",
"while (", self(o.cond,i,is), ");\n" ),
WHILE := (self,o,i,is) >> Print(Blanks(i),
"while (", self(o.cond,i,is), ")\n" ,
Blanks(i), "{\n", self(o.then_cmd,i+is,is), Blanks(i), "}\n"),
PRINT := (self,o, i, is) >> Print(Blanks(i),
"printf(\"", o.fmt, "\"",
When(o.vars <> [],
Print(", ",
DoForAll( DropLast(o.vars,1),
e -> Print(self(e,i,is), ", ")
),
self(Last(o.vars),i,is)
),
Print("")
),
");\n"
),
multi_if := meth(self,o,i,is)
local j, conds;
conds := o.args { [1..Int(Length(o.args)/2)]*2 - 1 };
# degenerate case, no conditions, else branch only
if Length(o.args)=1 then
self(o.args[1], i, is);
# generate switch stmt
elif ForAll(conds, c -> ObjId(c)=eq and ObjId(c.args[1]) in [var,param] and c.args[1]=conds[1].args[1] and IsValue(c.args[2])) then
Print(Blanks(i), "switch(", self(conds[1].args[1], i, is), ") { \n");
j := 1;
while j < Length(o.args) do
Print(Blanks(i+Int(is/2)), "case ", self(o.args[j].args[2], i, is), ": ");
Cond(ObjId(o.args[j+1])=ret,
Print(self(o.args[j+1],0,is), Blanks(i+is), "break;\n "),
Print("{\n", self(o.args[j+1],i+is,is), Blanks(i+is), "break; }\n"));
j := j+2;
od;
# Print out the else branch if it exists (j=Length)
if j = Length(o.args) then
Print(Blanks(i+Int(is/2)), "default: ");
Cond(ObjId(o.args[j])=ret,
Print(self(o.args[j], 0, is)),
Print("{\n", self(o.args[j], i+is, is), Blanks(i+Int(is/2)), "}\n"));
fi;
Print(Blanks(i), "}\n");
# general IF cascade
else
j := 1;
while j < Length(o.args) do
Print(Blanks(i), When(j<>1, "else "), "if (",
self(o.args[j], i+is,is), ") {\n",
self(o.args[j+1],i+is,is), Blanks(i), "}\n");
j := j+2;
od;
# Print out the else branch if it exists (j=Length)
if j = Length(o.args) then
Print(Blanks(i), "else {\n",
self(o.args[j], i+is, is), Blanks(i), "}\n");
fi;
fi;
end,
zallocate := (self, o, i, is) >> Print(
self(allocate(o.loc,o.exp),i,is),
Blanks(i),"memset(",self(o.loc, i, is)," ,'\\0', sizeof(",
self.declare(o.exp.t,[],0,0), ") * ", self(o.exp.size,i,is), ");\n"),
# Blanks(i),"for(int iinit = 0; iinit < ",self(o.exp.size,i,is),"; iinit++)\n",
# Blanks(i)," ", self(o.loc, i, is),"[iinit]=0;\n"),
####################
## Expressions
####################
RewritableObjectExp := (self,o,i,is) >> Print(o.name, self.pinfix(o.rChildren(), ", ")),
Exp := (self,o,i,is) >> Print(o.name, self.pinfix(o.args, ", ")),
ExpCommand := (self,o,i,is) >> Print(Blanks(i), o.name, self.pinfix(o.args, ", "), ";\n"),
Command := (self,o,i,is) >> Print(Blanks(i), o.name, self.pinfix(o.rChildren(), ", "), ";\n"),
call := (self,o,i,is) >> Print(Blanks(i), self(o.args[1],i,is), self.pinfix(Drop(o.args,1), ", "), ";\n"),
errExp := (self, o, i, is) >> self(o.t.zero(), i, is),
eq := (self, o, i, is) >> self.condinfix(o.args, " == ", " && "),
neq := (self, o, i, is) >> self.condinfix(o.args, " != ", " && "),
geq := (self, o, i, is) >> self.condinfix(o.args, " >= ", " && "),
leq := (self, o, i, is) >> self.condinfix(o.args, " <= ", " && "),
gt := (self, o, i, is) >> self.condinfix(o.args, " > ", " && "),
lt := (self, o, i, is) >> self.condinfix(o.args, " < ", " && "),
nth := (self,o,i,is) >> Print(self(o.loc,i,is), "[", self(o.idx,i,is), "]"),
deref := (self,o,i,is) >> Print("*(", self(o.loc,i,is), ")"),
addrof := (self,o,i,is) >> Print("&(", self(o.loc,i,is), ")"),
fdiv := (self,o,i,is) >> Print("(((", self.declare(TReal, [],i,is), ")",
self(o.args[1],i,is), ") / ", self(o.args[2],i,is), ")"),
add := (self,o,i,is) >> self.pinfix(o.args, " + "),
logic_and := (self,o,i,is) >> self.ppinfix(o.args, " && "),
logic_or := (self,o,i,is) >> self.ppinfix(o.args, " || "),
logic_neg := (self,o,i,is) >> Print("( !(",self(o.args[1],i,is), ") )"),
sub := (self,o,i,is) >> self.pinfix(o.args, " - "),
neg := (self,o,i,is) >> Print("-(", self(o.args[1],i,is), ")"),
mul := (self,o,i,is) >> self.pinfix(o.args, "*"),
div := (self,o,i,is) >> self.pinfix(o.args, " / "),
idiv := (self,o,i,is) >> self.pinfix(o.args, " / "),
imod := (self,o,i,is) >> self.pinfix(List(o.args, x -> When(IsPtrT(x.t), tcast(TSym("size_t"),x) ,x)), " % "),
no_mod := (self,o,i,is) >> self(o.args[1],i,is),
re := (self,o,i,is) >> self.printf("creal($1)", [o.args[1]]),
im := (self,o,i,is) >> self.printf("cimag($1)", [o.args[1]]),
cxpack := (self,o,i,is) >> self.printf("($1) + _Complex_I*($2)", [o.args[1], o.args[2]]),
bin_and := (self,o,i,is) >> Print("((", self.pinfix(List(o.args, x -> When(IsPtrT(x.t), tcast(TSym("size_t"),x) ,x)), ")&("), "))"),
bin_or := (self,o,i,is) >> Print("((", self.pinfix(List(o.args, x -> When(IsPtrT(x.t), tcast(TSym("size_t"),x) ,x)), ")|("), "))"),
bin_xor := (self,o,i,is) >> Print("((", self(o.args[1],i,is), ")^(", self(o.args[2],i,is),"))"),
abs := (self,o,i,is) >> Print("abs(", self(o.args[1],i,is), ")"),
floor := (self,o,i,is) >> Print("((int)(", self(o.args[1],i,is), "))"),
lShift := (self,o,i,is) >> Cond(IsBound(o.args[3]),
Error("non implemented"),
Print("((",self(o.args[1],i,is),") << (",self(o.args[2],i,is), "))")),
rShift := (self,o,i,is) >> Cond(IsBound(o.args[3]),
Error("non implemented"),
Print("((",self(o.args[1],i,is),") >> (",self(o.args[2],i,is), "))")),
arith_shr := (self, o, i, is) >> Cond( o.t.isSigned(), self.printf("(($1) >> ($2))", [o.args[1], o.args[2]]),
Error("implement arith_shr for unsigned data type")),
arith_shl := (self, o, i, is) >> Cond( o.t.isSigned(), self.printf("(($1) \<\< ($2))", [o.args[1], o.args[2]]),
Error("implement arith_shl for unsigned data type")),
xor := meth(self,o,i,is)
Print("((", self(o.args[1],i,is));
DoForAll(o.args{[2..Length(o.args)]}, e -> Print(")^(", self(e,i,is)));
Print("))");
end,
max := (self,o,i,is) >> self(cond(geq(o.args[1],o.args[2]),o.args[1],o.args[2]),i,is),
min := (self,o,i,is) >> self(cond(leq(o.args[1],o.args[2]),o.args[1],o.args[2]),i,is),
log := (self,o,i,is) >> Cond( Length(o.args)=1,
Cond( o.t = T_Real(32) or (IsBound(self.opts.TRealCtype) and self.opts.TRealCtype = "float"),
self.printf("logf($1)", [o.args[1]]),
# else
self.printf("log((double)($1))", [o.args[1]])),
Cond( o.t = T_Real(32) or (IsBound(self.opts.TRealCtype) and self.opts.TRealCtype = "float"),
self.printf("logf($1)/logf($2)", [o.args[1], o.args[2]]),
# else
self.printf("log((double)($1))/log((double)($2))", [o.args[1], o.args[2]]))),
pow := (self,o,i,is) >> Cond(
o.args[2]=2,
self(mul(o.args[1], o.args[1]), i, is),
# else
Error("Implement pow()")),
sqrt := (self,o,i,is) >> self.printf("sqrt($1)", [o.args[1]]),
rsqrt := (self,o,i,is) >> self.printf("$1/sqrt($2)", [o.t.one(), o.args[1]]),
cond := (self,o,i,is) >> Cond(
Length(o.args)=3,
Cond(ObjId(o.args[3]) = errExp,
self(o.args[2], i, is),
Print("((",self(o.args[1],i,is),") ? (",self(o.args[2],i,is),") : (",self(o.args[3],i,is),"))")),
# NOTE: no else case here, maybe just leave it like this?
Length(o.args)=2,
self(o.args[2],i,is),
# more than 3 args: do a binsplit trick
Print("((",self(o.args[1],i,is),") ? (",self(o.args[2],i,is),") : ",
self(ApplyFunc(cond, Drop(o.args, 2)), i,is),")")),
_decval :=(self, v) >> let(pf := When(IsBound(self.opts.valuePostfix), self.opts.valuePostfix, ""),
Print(v, pf)),
Value := (self,o,i,is) >>
Cond(
o.t = TComplex, let(c:=Complex(o.v), re:=ReComplex(c), im:=ImComplex(c),
Cond(re=0 and im=1, Print(self.opts.c99.I),
re=0 and im=-1, Print("(- ", self.opts.c99.I, ")"),
im=0, Print(self._decval(re)),
re=0, Print("(", self._decval(im), " * ", self.opts.c99.I, ")"),
im < 0, Print("(", self._decval(re), " - ", self.opts.c99.I, " * ", self._decval(-im), ")"),
Print("(", self._decval(re), " + ", self.opts.c99.I, " * ", self._decval(im), ")"))),
o.t = TReal, let(
v := Cond(IsCyc(o.v), ReComplex(Complex(o.v)), o.v),
Cond(v < 0,
Print("(", self._decval(v), ")"),
Print(self._decval(v)))),
IsArray(o.t), Print("{", WithBases(self, rec(infixbreak:=4)).infix(o.v, ", ", i), "}"),
o.v < 0, Print("(", o.v, ")"),
o.t = TBool, When(o.v in [true, 1], Print("1"), Print("0")),
o.t = TUInt, Print(o.v, "u"),
Print(o.v)
),
##########################
## Types and declarations
##########################
# This function unparses the standard decl(var, value, code) Command.
# First, we unparse array variables then group variables by their type,
# and then call CUnparserBase.declare on each group
decl := meth(self,o,i,is)
local arrays, other, l, arri, myMem;
[arrays, other] := SplitBy(o.vars, x->IsArray(x.t));
DoForAll(arrays, v -> Print(Blanks(i),
When(self.opts.arrayBufModifier <> "", self.opts.arrayBufModifier::" ", ""),
self.declare(v.t, v, i, is), ";\n"));
if (Length(other)>0) then
other:=SortRecordList(other,x->x.t);
for l in other do
Sort(l, (a,b)->a.id < b.id);
Print(Blanks(i), self.declare(l[1].t, l, i, is), ";\n");
od;
fi;
self(o.cmd, i, is);
#Pop arena for this decl
if IsBound(self.opts.useMemoryArena) and self.opts.useMemoryArena and Length(arrays) > 0 and arrays[1].id[1] <> 'D' then
myMem := 0;
for arri in arrays do
# Account for vector allocations in memory arena (which is scalar)
myMem := myMem + (arri.t.size * When(IsBound(arri.t.t) and ObjId(arri.t.t)=TVect, arri.t.t.size, 1));
od;
if ObjId(myMem) = Value then myMem := myMem.v; fi;
Print(Blanks(i));
Print("arenalevel += ", myMem, ";\n" );
fi;
end,
# defines a struct
define := meth(self, o, i, is)
local e, ee;
for e in o.types do
Print(Blanks(i), "typedef struct {\n");
for ee in e.getVars() do
Print(Blanks(i+is));
Print(self.declare(ee.t, [ee], i, is), ";\n");
od;
Print(Blanks(i), "} ", e.getName(), ";\n");
od;
end,
tcast := (self, o, i, is) >> Print("((", self.declare(o.args[1], [], i, is), ") ", self(o.args[2],i,is), ")"),
sizeof := (self, o, i, is) >> Print("sizeof(", self.declare(o.args[1], [], i, is), ")"),
declare := (self, t, vars, i, is) >> When(
IsBound(self.(t.name)),
self.(t.name)(t, When(IsList(vars), vars, [vars]), i, is),
Error("Can't declare ", vars, " no method '", t.name, "' in ", self)),
TVect := (self, t, vars, i, is) >> Print("__m128 ", self.infix(vars, ", ", i+is)),
TComplex := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TComplexCtype), self.opts.TComplexCtype, "complex_t "), " ",
self.infix(vars, ", ",i+is)),
T_Complex := (self, t, vars, i, is) >> Print("_Complex ", self.declare(t.params[1], vars, i, is)),
T_Real := (self, t, vars, i, is) >> Print(Cond(
t.params[1] = 128, "long double",
t.params[1] = 80, "long double", #x86 specific
t.params[1] = 64, "double",
t.params[1] = 32, "float",
Error("Type is not supported")
)," ",self.infix(vars, ", ",i+is)),
T_Int := (self, t, vars, i, is) >> Print(Cond(
t.params[1] = 64, "__int64",
t.params[1] = 32, "__int32",
t.params[1] = 16, "__int16",
t.params[1] = 8, "__int8",
Error("Type is not supported")
), " ", self.infix(vars, ", ",i+is)),
T_UInt := (self, t, vars, i, is) >> Print("unsigned ", Cond(
t.params[1] = 64, "__int64",
t.params[1] = 32, "__int32",
t.params[1] = 16, "__int16",
t.params[1] = 8, "__int8",
t.params[1] = 1, "__bit",
Error("Type is not supported")
), " ", self.infix(vars, ", ",i+is)),
T_Struct := (self, t, vars, i, is) >> Print(
t.getName(), " ", self.infix(vars, ", ", i+is)
),
TReal := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TRealCtype), self.opts.TRealCtype, TReal.ctype), " ",
self.infix(vars, ", ",i+is)),
TInt := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TIntCtype), self.opts.TIntCtype, TInt.ctype), " ",
self.infix(vars, ", ",i+is)),
TDummy := ~.TInt,
TBool := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TIntCtype), self.opts.TIntCtype, TInt.ctype), " ",
self.infix(vars, ", ",i+is)),
TUInt := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TUIntCtype), self.opts.TUIntCtype, TUInt.ctype), " ",
self.infix(vars, ", ",i+is)),
TULongLong := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TULongLongCtype), self.opts.TULongLongCtype, TULongLong.ctype), " ",
self.infix(vars, ", ",i+is)),
TChar := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TCharCtype), self.opts.TCharCtype, TChar.ctype), " ",
self.infix(vars, ", ",i+is)),
TUChar := (self, t, vars, i, is) >> Print(
When(IsBound(self.opts.TUCharCtype), self.opts.TUCharCtype, TUChar.ctype), " ",
self.infix(vars, ", ",i+is)),
TVoid := (self, t, vars, i, is) >> Print("void ", self.infix(vars, ", ",i+is)),
_restrict := (self, t) >> let(opts := self.opts, rst := Concat(When(IsBound(opts.restrict),
opts.restrict(), "restrict"), " "), When(t._restrict, rst, "")),
TPtr := (self, t, vars, i, is) >>
Print(Cond(not IsBound(t.qualifiers) or t.qualifiers=[], "", Print(self.infix(t.qualifiers, " "), " ")),
Cond(vars=[],
Print(self.declare(t.t, [], i, is), " *", self._restrict(t)),
Print(self.declare(t.t, [], i, is),
Print(" *", self._restrict(t) ),
self.infix(vars, Concatenation(", *", self._restrict(t)), i+is)))),
TSym := (self, t, vars, i, is) >> Print(t.id, " ", self.infix(vars, ", ")),
_TFunc_args := (self, t, i, is) >> let(params := DropLast(t.params, 1),
Print(
DoForAllButLast(params, p -> Print(self.declare(p, [], i, is), ", ")),
self.declare(Last(params), [], i, is))),
TFunc := (self, t, vars, i, is) >>
Cond(Length(vars) in [0,1],
PrintEvalF("$1 (*$2)($3)",
() -> self.declare(Last(t.params), [], i, is),
When(vars=[], "", vars[1].id),
() -> self._TFunc_args(t, i, is)),
Print(
DoForAllButLast(vars, v -> Print(self.declare(t, v, i, is), ", ")),
self.declare(t, [Last(vars)], i, is))),
TArray := meth(self,t,vars,i,is)
local dims, elt, v, ptype, vsize;
if Length(vars) > 1 then DoForAll(vars, v->Print(self.TArray(t, [v], i, is), "; "));
elif Length(vars) = 0 then
Print(self.declare(t.t, [], i, is), " *");
else
# at this point Length(vars)=1
v := When(IsList(vars), vars[1], vars);
dims := []; elt := t;
while IsArray(elt) do Add(dims, elt.size); elt := elt.t; od;
#NOTE: Ignoring twiddles by looking for "D" in .id
# Better way: look for func.name="init" in parent/context
if IsBound(self.opts.useMemoryArena) and self.opts.useMemoryArena and v.id[1] <> 'D' then
#NOTE: Arena currently doesn't handle multiple dims.
#NOTE: Slightly ugly hack to get this to be a pointer
# To handle vectors. Arena is declared only for scalars. For
# vectors, we must manually scale the allocation by vector length.
vsize := 1; if ObjId(elt)=TVect then vsize := elt.size; fi;
# ptype := Concatenation(elt.name, "Pointer");
# self.(ptype)(elt, [v], i, is);
self.TPtr(TPtr(elt), [v], i, is);
Print(" = &(ARENA[ (arenalevel-=",self(dims[1]*vsize,i,is),") ])");
else
self.(elt.name)(elt, [v], i, is);
DoForAll(dims, d->Print("[",self(d,i,is),"]"));
fi;
fi;
end,
# comments embedded in code
comment := (self, o, i, is) >> When(Length(o.exp) = 0,
PrintLine(),
PrintLine(Blanks(i), "/* ", o.exp, " */")
),
quote := (self, o, i, is) >> Print("\"", self(o.cmd,i,is), "\"")
));
# Locate instances of assign(loc, Value), where types of Value and loc
# do not match. Fix the value to be of correct type.
# Note: For linear transforms the only possible Value is 0 (otherwise
# transform is not linear)
FixAssign0 := c -> SubstTopDownNR(c, [assign, @(1), @(2,Value,e->e.t <> @(1).val.t)],
e -> assign(@(1).val,
When(@(2).val.v = 0, @(1).val.t.zero(),
@(1).val.t.value(@(2).val.v))));
Class(CMacroUnparser, CUnparserBase, rec(
preprocess := (self, c) >> FixAssign0(PropagateTypes(c)),
preprocess_init := (self, c) >> FixAssign0(PropagateTypes(c)),
# Split non-binary "+" into nested binary ops
add := (self,o,i,is) >> Cond(
o.t=TInt or IsPtrT(o.t), Inherited(o, i, is),
Length(o.args)=2, self.prefixTT("ADD", o.args[1].t, o.args[2].t, o.args),
let(rem := ApplyFunc(add, Drop(o.args, 1)),
self.prefixTT("ADD", o.args[1].t, rem.t, [o.args[1], rem]))),
sub := (self,o,i,is) >> Cond(o.t=TInt or IsPtrT(o.t), Inherited(o, i, is),
self.prefixTT("SUB", o.args[1].t, o.args[2].t, o.args)),
nth := (self,o,i,is) >> Cond(o.t=TInt or IsPtrT(o.t), Inherited(o, i, is), self.prefixT("NTH", o.t, [o.loc, o.idx])),
neg := (self,o,i,is) >> Cond(o.t=TInt or IsPtrT(o.t), Inherited(o, i, is), self.prefixT("NEG", o.t, o.args)),
bin_and := (self, o, i, is) >> Cond(o.t=TInt or ObjId(o.t) in [T_Int, T_UInt], Inherited(o, i, is), self.prefixT("AND", o.t, o.args)),
bin_xor := (self, o, i, is) >> Cond(o.t=TInt or ObjId(o.t) in [T_Int, T_UInt], Inherited(o, i, is), self.prefixT("XOR", o.t, o.args)),
div := (self,o,i,is) >> Cond(o.t=TInt, Inherited(o, i, is), self.prefixTT("DIV", o.args[1].t, o.args[2].t, o.args)),
imod := (self,o,i,is) >> self.prefixT("IMOD", o.t, o.args),
max := (self,o,i,is) >> self.prefixTT("MAX", o.args[1].t, o.args[2].t, o.args),
min := (self,o,i,is) >> self.prefixTT("MIN", o.args[1].t, o.args[2].t, o.args),
idiv := (self,o,i,is) >> Cond(o.t=TInt and ForAll(o.args,x->x.t=TInt), Inherited(o, i, is),
self.prefixT("IDIV", o.t, o.args)),
fdiv := (self,o,i,is) >> self.prefixTT("FDIV", o.args[1].t, o.args[2].t, o.args),
re := (self,o,i,is) >> self.prefixT("RE", o.args[1].t, o.args),
im := (self,o,i,is) >> self.prefixT("IM", o.args[1].t, o.args),
cxpack := (self,o,i,is) >> self.prefixT("C", o.t, o.args),
no_mod := (self,o,i,is) >> self(o.args[1],i,is),
Value := (self, o, i, is) >> Cond(
IsArray(o.t), Print("{", self.infix(o.v, ", "), "}"),
let(fmt := self._const(o),
pfx := Cond(self.cx.isInside(data), "CD_", "C_"),
Cond(fmt[2]=[], Print(pfx, fmt[1]),
fmt[1]="INT", Print(fmt[2][1]),
self.prefix(Concat(pfx, fmt[1]), fmt[2])))),
# mults by different constants are unparsed differently
# Split non-binary "*" into nested binary ops
mul := (self,o,i,is) >> Cond(
o.t=TInt, Inherited(o, i, is),
Length(o.args)<>2, self(mul(o.args[1], ApplyFunc(mul, Drop(o.args, 1))), i, is),
let(
# check if constant ended up in slot #2
a := When(IsValue(o.args[2]), o.args[2], o.args[1]),
b := When(IsValue(o.args[2]), o.args[1], o.args[2]),
When(not (IsValue(a) or (IsVar(a) and IsBound(a.value))),
# <a> is not a constant
self.prefix(Concat("MUL_", self._pfx(a.t), "_", self._pfx(b.t)), [a,b]),
# <a> is a constant
let(fmt := self._const( When(IsValue(a), a, a.value) ),
self.prefix(Concat("MUL_", fmt[1], "_", self._pfx(b.t)),
# check if constant is special, and does not go into MUL args
# for example fmt[1]="I" denotes sqrt(-1), one such constant
When(fmt[2]=[], [b], [a, b])))))),
prefixT := (self, funcname, t, args) >>
self.prefix(Concat(funcname, "_", self._pfx(t)), args),
prefixTT := (self, funcname, t1, t2, args) >>
self.prefix(Concat(funcname, "_", self._pfx(t1), "_", self._pfx(t2)), args),
prefixTTT := (self, funcname, t1, t2, t3, args) >>
self.prefix(Concat(funcname, "_", self._pfx(t1), "_", self._pfx(t2), "_", self._pfx(t3)), args),
# this is getting really ugly
prefixTTTT := (self, funcname, t1, t2, t3, t4, args) >>
self.prefix(Concat(funcname, "_", self._pfx(t1), "_", self._pfx(t2), "_", self._pfx(t3), "_", self._pfx(t4)), args),
prefix_T := (self, funcname, args) >>
self.prefix(funcname :: ConcatList(args, a -> "_" :: self._pfx(a.t)), args),
_pfx := (self, t) >> Cond(
IsComplexT(t), "CPX",
IsRealT(t), "FLT",
IsOrdT(t), "INT",
t = TUnknown, "UNK",
ObjId(t) = TSym, "SYM",
IsPtrT(t), "P" :: self._pfx(t.t),
IsArrayT(t), "A" :: self._pfx(t.t),
IsVecT(t), Cond(
IsComplexT(t.t), "FC" :: StringInt(t.size),
IsRealT(t.t), "FV" :: StringInt(t.size),
IsOrdT(t.t), "IV" :: StringInt(t.size),
Error("Can't handle type ", t)
),
Error("Can't handle type ", t)),
# returns a tuple [suffix, args], where suffix is used for MUL_XXX or C_XXX,
# and args are additional parameters into C_XXX
_const := (self,o) >> Cond(
# we assume here that complex constants with 0 imaginary parts have
# been converted to TReal already
o.t = TComplex, let(c:=Complex(o.v), re:=ReComplex(c), im:=ImComplex(c),
Cond(re=0 and im=1, ["I", []],
re=0 and im=-1, ["NI", []],
re=0, ["IM", [im]],
im < 0, ["CPXN", [re, -im]],
["CPX", [re, im]])),
ObjId(o.t) = T_Complex, let(c:=Complex(o.v), re:=ReComplex(c), im:=ImComplex(c),
Cond(re=0 and im=1, ["I", []],
re=0 and im=-1, ["NI", []],
re=0, ["IM", [im]],
im < 0, ["CPXN", [re, -im]],
["CPX", [re, im]])),
o.t = TReal and IsCyc(o.v), ["FLT", [ReComplex(Complex(o.v))]],
o.t = TReal, ["FLT", [o.v]],
o.t = TInt, ["INT", [o.v]],
o.t = TUnknown, ["INT", [o.v]], # NOTE: there is a bug that creates V(0) with TUnknown
o.t = TString, ["STR", [o.v]],
o.t = TBool, ["INT", [When(o.v in [true, 1], 1, 0)]],
IsVecT(o.t), Cond(
o.t.t = TReal, [Concat("FV",StringInt(o.t.size)), List(o.v, x->x.v)],
o.t.t = TComplex, [Concat("FC",StringInt(o.t.size)), List(o.v, x->x.v)],
o.t.t = TInt, [Concat("IV",StringInt(o.t.size)), List(o.v, x->x.v)],
Error("Don't know how to handle constant of type ", o.t)
),
Error("Don't know how to handle constant of type ", o.t)
),
tcast := (self, o, i, is) >> Print("((", self.declare(o.args[1], [], i, is), ") ", self(o.args[2],i,is), ")"),
TVect := (self, t, vars, i, is) >> Print(self._pfx(t), " ", self.infix(vars, ", ")),
TComplex := (self, t, vars, i, is) >> Print(self._pfx(t), " ", self.infix(vars, ", ")),
TReal := (self, t, vars, i, is) >> Print(self._pfx(t), " ", self.infix(vars, ", ")),
TInt := (self, t, vars, i, is) >> Print("int ", self.infix(vars, ", ")),
gen := meth(self, subname, o, opts)
local oo;
self.opts := CopyFields(opts, rec(subName := subname));
oo := self.preprocess(o);
Print(self.header(subname, oo), Unparse(oo, self, 0, 4), self.footer(subname, oo));
end,
fld := (self, o, i, is) >> Print(self(o.loc, i, is), When(IsPtrT(o.loc.t), "->", "."), o.id),
ufld := ~.fld,
header := (self, subname, o) >> Print(
self.generated_by,
self.extraHeader,
self.fileinfo(self.opts),
DoForAll(self.includes, inc -> Print("#include ", inc, "\n")),
DoForAll(self.opts.includes, inc -> Print("#include ", inc, "\n"))
),
footer := Ignore,
data := (self,o,i,is) >> Print(Blanks(i), self.genData(o.var, o.value), self(o.cmd, i, is)),
func := (self, o, i, is) >> let(
parameters:=Flat(o.params),
id := Cond(o.id="transform" and IsBound(self.opts.subName),
self.opts.subName,
o.id="init" and IsBound(self.opts.subName),
Concat("init_",self.opts.subName),
o.id="destroy" and IsBound(self.opts.subName),
Concat("destroy_",self.opts.subName),
o.id),
Print("\n", Blanks(i),
When(IsBound(o.inline) and o.inline,"inline ",""),
self.opts.funcModifier, self.declare(o.ret, var(id, o.ret), i, is), "(",
DoForAllButLast(parameters, p->Print(self.declare(p.t, p,i,is), ", ")),
When(Length(parameters)>0, self.declare(Last(parameters).t, Last(parameters),i,is), ""), ") ",
"{\n",
self(o.cmd, i+is, is),
Blanks(i),
"}\n")),
# C99 style, loop var declared inside
# - needed for correct operation of OpenMP
# - simplifies function declarations (no need to worry about declaring loop vars)
loop := (self, o, i, is) >> let(v := o.var, lo := o.range[1], hi := Last(o.range),
Print(Blanks(i), "for(int ", v, " = ", lo, "; ", v, " <= ", hi, "; ", v, "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}\n")),
loopn := (self, o, i, is) >> let(v := o.var, lo := 0, hi := o.range, #NOTE: YSV what is the right thing here?
Print(Blanks(i), "for(int ", self(v, i, is), " = ", self(lo, i, is), "; ", self(v, i, is), " < ", self(hi, i, is), "; ", self(v, i, is), "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}\n")),
program := (self,o,i,is) >> DoForAll(o.cmds, c -> self(c,i,is)),
allocate := (self, o, i, is) >> Print(Blanks(i),
self(o.loc, i, is), " = (", self.declare(o.exp.t, [],0,0), "*) MALLOC(sizeof(",
self.declare(o.exp.t,[],0,0), ") * ", self(o.exp.size,i,is), ");\n"),
# Blanks(i),"for(int iinit = 0; iinit < ",self(o.exp.size,i,is),"; iinit++)\n",
# Blanks(i)," ", self(o.loc, i, is),"[iinit]=0;\n"),
deallocate := (self, o, i, is) >> Print(
Blanks(i),
"FREE(",
self(o.loc, i, is),
");\n"
),
ret := (self, o, i, is) >> Print(Blanks(i), "return ", self(o.args[1], i+is, is), ";\n"),
tcvt := (self, o, i, is) >> self.printf("(($1)($2))", [ o.args[1], o.args[2] ])
));
# can handle program/func, etc
#
Class(CUnparser, CUnparserBase, rec(
gen := meth(self, subname, o, opts)
local oo;
self.opts := CopyFields(opts, rec(subName := subname));
oo := self.preprocess(o);
self.checkPrintRuleTree(o, opts);
Print(self.header(subname, oo), Unparse(oo, self, 0, 4), self.footer(subname, oo));
end,
fld := (self, o, i, is) >> Print(self(o.loc, i, is), When(IsPtrT(o.loc.t), "->", "."), o.id),
ufld := ~.fld,
header := (self, subname, o) >> Print(
self.generated_by,
self.extraHeader,
self.fileinfo(self.opts),
DoForAll(self.includes, inc -> Print("#include ", inc, "\n")),
DoForAll(self.opts.includes, inc -> Print("#include ", inc, "\n"))
),
checkPrintRuleTree := meth(self, o, opts)
if IsBound(opts.printRuleTree) and opts.printRuleTree and IsBound(o.ruletree) then
Print("/* RuleTree:\nrt :=\n");
Print(o.ruletree);
Print("\n;\n*/\n\n");
fi;
end,
footer := Ignore,
data := (self,o,i,is) >> Print(Blanks(i), self.genData(o.var, o.value), self(o.cmd, i, is)),
func := (self, o, i, is) >> let(
parameters:=Flat(o.params),
id := Cond(o.id="transform" and IsBound(self.opts.subName),
self.opts.subName,
o.id="init" and IsBound(self.opts.subName),
Concat("init_",self.opts.subName),
o.id="destroy" and IsBound(self.opts.subName),
Concat("destroy_",self.opts.subName),
o.id),
Print("\n", Blanks(i),
self.opts.funcModifier, self.declare(o.ret, var(id, o.ret), i, is), "(",
DoForAllButLast(parameters, p->Print(self.declare(p.t, p,i,is), ", ")),
When(Length(parameters)>0, self.declare(Last(parameters).t, Last(parameters),i,is), ""), ") ",
"{\n",
When(IsBound(self.opts.postalign), DoForAll(parameters, p->self.opts.postalign(p,i+is,is))),
self(o.cmd, i+is, is),
Blanks(i),
"}\n")),
# C99 style, loop var declared inside
loop := (self, o, i, is) >> let(v := o.var, lo := o.range[1], hi := Last(o.range),
Print(When(IsBound(self.opts.looppragma), self.opts.looppragma(o,i,is)),
Blanks(i), "for(int ", v, " = ", lo, "; ", v, " <= ", hi, "; ", v, "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}\n")),
loopn := (self, o, i, is) >> let(v := o.var.id, lo := 0, hi := o.range,
Print(Blanks(i), "for(int ", v, " = ", lo, "; ", v, " < ", self(hi,i,is), "; ", v, "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}\n")),
program := (self,o,i,is) >> DoForAll(o.cmds, c -> self(c,i,is)),
allocate := (self, o, i, is) >> Print(Blanks(i),
self(o.loc, i, is), " = (", self.declare(o.exp.t, [],0,0),
"*) calloc(", self(o.exp.size,i,is), ", sizeof(", self.declare(o.exp.t,[],0,0), "));\n"),
deallocate := (self, o, i, is) >> Print(
Blanks(i),
"free(",
self(o.loc, i, is),
");\n"
),
ret := (self, o, i, is) >> Print(Blanks(i), "return ", self(o.args[1], i+is, is), ";\n"),
call := (self, o, i, is) >> Print(Blanks(i), o.args[1].id, self.pinfix(Drop(o.args, 1), ", "), ";\n"),
fcall := (self, o, i, is) >> Print(self(o.args[1],0,0), "(", self.infix(Drop(o.args, 1), ", "), ")"),
# structure definition
struct := (self, o, i, is) >> Print(
Blanks(i), "typedef struct {\n",
DoForAll(o.fields, f ->
Print(Blanks(i+is), self.declare(f.t, f, i+is, is), ";\n")
),
Blanks(i), "} ", o.id, ";\n\n"
)
));
# old style variable declarations. this is for older/stricter compilers (like gcc-2.5.2 used by simplescalar)
# {int v; for(v=0; .... rather than for(int v=0; ...
# and
# { double x; .... rather than double x
Class(C89Unparser, CUnparser, rec(
loop := (self, o, i, is) >> let(v := o.var, lo := o.range[1], hi := Last(o.range),
Print(Blanks(i), "{int ", v, "; for(", v, " = ", lo, "; ", v, " <= ", hi, "; ", v, "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}}\n")),
loopn := (self, o, i, is) >> let(v := o.var.id, lo := 0, hi := o.range,
Print(Blanks(i), "{int ", v, "; for(", v, " = ", lo, "; ", v, " < ", self(hi,i,is), "; ", v, "++) {\n",
self(o.cmd,i+is,is),
Blanks(i), "}}\n")),
# exactly like the normal decl except wrapped in {}
# decl := meth(self,o,i,is)
# local arrays, other, l;
# Print("{");
# [arrays, other] := SplitBy(o.vars, x->IsArray(x.t));
# DoForAll(arrays, v -> Print(Blanks(i), self.opts.arrayBufModifier, " ", self.declare(v.t, v, i, is), ";\n"));
# if (Length(other)>0) then
# other:=SortRecordList(other,x->x.t);
# for l in other do
# Sort(l, (a,b)->a.id < b.id);
# Print(Blanks(i), self.declare(l[1].t, l, i, is), ";\n");
# od;
# fi;
# self(o.cmd, i, is);
# Print("}");
# end,
));
# FFTX: Temporary to handle idiv(imod()).
CUnparser.("idivmod") := (self,o,i,is) >> self(imod(idiv(o.args[1], o.args[3]), o.args[2]), i, is);
#
# NOTE: These are obsolete names
#
CUnparserProg := CUnparser;
CMacroUnparserProg := CMacroUnparser;
C89UnparserProg := C89Unparser;
|
#' Download a gzipped csv file of a dataset.
#'
#' @export
#'
#' @template key-curl
#' @param dataset Dataset name. Required.
#' @param select (character) Vector of columns to be returned with each row.
#' Default is to return all columns.
#' @param conjunction one of "and" or "or". Only applicable when more than one
#' \code{search} or \code{where} parameter is provided. Default: "and"
#' @param sort (character) Sort rows by a particular column in a given
#' direction. + denotes ascending order, - denotes descending. See examples.
#' @param where (character) Filter results with a SQL-style "where" clause.
#' Only applies to numerical columns - use the \code{search} parameter for
#' strings. Valid operators are >, < and =. Only one \code{where} clause per
#' request is currently supported.
#' @param search (character) Filter results by only returning rows that match
#' a search query. By default this searches the entire table for matching text.
#' To search particular fields only, use the query format "@@fieldname query".
#' To match multiple queries, the | (or) operator can be used
#' eg. "query1|query2".
#' @param path File name and path of output zip file. Defaults to write a zip
#' file to your home directory with name of the dataset, and file extension
#' \code{.csv.gz}.
#' @param poll_sleep (integer) Time to sleep between polling events to fetch
#' data. For very large datasets, it could take a while to be ready. By
#' default, we poll continuously. If you are requesting a large dataset and/or
#' have not much left on your allowed requests with Enigam (see
#' \code{\link{rate_limit}}) you may want to insert some sleep time between
#' pollings.
#'
#' @details Note that \code{\link[enigma]{enigma_fetch}} downloads the file,
#' and gives back a path to the file. In a separte function,
#' \code{\link[enigma]{enigma_read}}, you can read in the data.
#' \code{\link[enigma]{enigma_fetch}} doesn't read in data in case the file
#' is very large which may make your R session crash or slow down
#' significantly.
#'
#' This function makes a request to ask Enigma to get a download ready. We
#' then poll the provided URL from Enigma until it is ready. Once ready we
#' fetch it and write it to disk.
#'
#' If file exists already, we overwrite it.
#'
#' @references \url{https://app.enigma.io/api#exporting}
#'
#' @return A (character) path to the file on your machine
#'
#' @examples \dontrun{
#' ## After obtaining an API key from Enigma's website, pass in your key to
#' ## the function call or set in your options (see above instructions for the
#' ## key parameter) If you pass in your key to the function call use the
#' ## key parameter
#'
#' # Fetch a dataset
#' res <- enigma_fetch(dataset = 'edu.umd.start.gtd')
#' enigma_read(res)
#'
#' # Use the select parameter to limit fields returned
#' res <- enigma_fetch(dataset = 'edu.umd.start.gtd',
#' select = c("country_txt", "resolution", "attacktype1"))
#' enigma_read(res)
#'
#' # Use the search parameter to query entire table or particular fields
#' res <- enigma_fetch(dataset = 'edu.umd.start.gtd', search = "armed")
#' enigma_read(res)
#'
#' # Use the search parameter to query entire table or particular fields
#' res <- enigma_fetch(dataset = 'edu.umd.start.gtd',
#' where = "nkill > 0", select = c("country_txt", "attacktype1", "nkill"))
#' enigma_read(res)
#' }
enigma_fetch <- function(dataset = NULL, select = NULL, search = NULL,
where = NULL, conjunction = NULL, sort = NULL, path = NULL,
key = NULL, poll_sleep = 0, ...) {
if (!class(poll_sleep) %in% c('numeric', 'integer')) {
stop("poll_sleep must be integer or numeric", call. = FALSE)
}
url <- sprintf('%s/export/%s/%s', en_base(), check_key(key),
check_dataset(dataset))
sw <- proc_search_where(search, where)
if (!is.null(select)) select <- paste(select, collapse = ",")
args <- list(select = select, conjunction = conjunction, sort = sort)
args <- as.list(unlist(ec(c(sw, args))))
if (length(args) == 0) args <- NULL
cli <- crul::HttpClient$new(url = url)
res <- cli$get(query = args, ...)
json <- error_handler(res)
if (is.null(path)) {
path <- file.path(Sys.getenv('HOME'),
basename(strsplit(json$export_url, "\\?")[[1]][1]))
}
not_ready <- TRUE
while (not_ready) {
Sys.sleep(poll_sleep)
bincli <- crul::HttpClient$new(url = json$export_url)
bin <- bincli$get(disk = path)
if (bin$status_code == 200) not_ready <- FALSE
}
if (bin$status_code > 201) {
if (grepl("xml", bin$headers$`content-type`)) {
x <- bin$parse("UTF-8")
xml <- xml2::read_xml(x)
mssg <- unlist(xml2::as_list(xml), FALSE)
stop("\n ",
paste(names(mssg), unname(mssg), sep = ": ", collapse = "\n "),
call. = FALSE)
} else {
bin$raise_for_status()
}
}
message(sprintf("On disk at %s", bin$content))
structure(path, class = "enigma_fetch", dataset = dataset)
}
#' @export
print.enigma_fetch <- function(x, ...) {
stopifnot(inherits(x, 'enigma_fetch'))
cat("<<enigma download>>", "\n", sep = "")
cat(" Dataset: ", attr(x, "dataset"), "\n", sep = "")
cat(" Path: ", x, "\n", sep = "")
cat(" see enigma_read()")
}
#' @export
#' @param input The output from \code{enigma_fetch} or a path to a file d
#' ownloaded from Enigma.io
#' @rdname enigma_fetch
enigma_read <- function(input) {
input <- as.enigma_fetch(input)
tibble::as_tibble(
utils::read.delim(input[[1]], header = TRUE, sep = ",",
stringsAsFactors = FALSE)
)
}
as.enigma_fetch <- function(x) UseMethod("as.enigma_fetch")
as.enigma_fetch.enigma_fetch <- function(x) x
as.enigma_fetch.character <- function(x) structure(x, class = 'enigma_fetch',
dataset = NA)
|
[STATEMENT]
lemma powr_mono:
fixes x :: real
assumes "a \<le> b" and "1 \<le> x" shows "x powr a \<le> x powr b"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x powr a \<le> x powr b
[PROOF STEP]
using assms less_eq_real_def
[PROOF STATE]
proof (prove)
using this:
a \<le> b
1 \<le> x
(?x \<le> ?y) = (?x < ?y \<or> ?x = ?y)
goal (1 subgoal):
1. x powr a \<le> x powr b
[PROOF STEP]
by auto |
[STATEMENT]
lemma spec_cond_dist: "(P \<Rightarrow> (Q \<triangleleft> b \<triangleright> R)) = ((P \<Rightarrow> Q) \<triangleleft> b \<triangleright> (P \<Rightarrow> R))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (P \<Rightarrow> Q \<triangleleft> b \<triangleright> R) = (P \<Rightarrow> Q) \<triangleleft> b \<triangleright> (P \<Rightarrow> R)
[PROOF STEP]
by (pred_auto) |
/-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import logic.equiv.fin
import topology.dense_embedding
import topology.support
/-!
# Homeomorphisms
This file defines homeomorphisms between two topological spaces. They are bijections with both
directions continuous. We denote homeomorphisms with the notation `≃ₜ`.
# Main definitions
* `homeomorph α β`: The type of homeomorphisms from `α` to `β`.
This type can be denoted using the following notation: `α ≃ₜ β`.
# Main results
* Pretty much every topological property is preserved under homeomorphisms.
* `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is
an open map is a homeomorphism.
-/
open set filter
open_locale topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Homeomorphism between `α` and `β`, also called topological isomorphism -/
@[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ₜ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm
initialize_simps_projections homeomorph
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
@[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl
@[simp] lemma coe_symm_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv.symm = h.symm := rfl
lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
/-- Identity map as a homeomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma trans_apply (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun
@[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
@[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma inducing (h : α ≃ₜ β) : inducing h :=
inducing_of_inducing_compose h.continuous h.symm.continuous $
by simp only [symm_comp_self, inducing_id]
lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $
by simp only [self_comp_symm, quotient_map.id]
lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› :=
h.quotient_map.2.symm
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.inducing, h.injective⟩
/-- Homeomorphism given an embedding. -/
noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) :=
{ continuous_to_fun := continuous_subtype_mk _ hf.continuous,
continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe],
.. equiv.of_injective f hf.inj }
protected lemma second_countable_topology [topological_space.second_countable_topology β]
(h : α ≃ₜ β) :
topological_space.second_countable_topology α :=
h.inducing.second_countable_topology
lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.is_compact_iff_is_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.compact_image
@[simp] lemma comap_cocompact (h : α ≃ₜ β) : comap h (cocompact β) = cocompact α :=
(comap_cocompact_le h.continuous).antisymm $
(has_basis_cocompact.le_basis_iff (has_basis_cocompact.comap h)).2 $ λ K hK,
⟨h ⁻¹' K, h.compact_preimage.2 hK, subset.rfl⟩
@[simp] lemma map_cocompact (h : α ≃ₜ β) : map h (cocompact α) = cocompact β :=
by rw [← h.comap_cocompact, map_comap_of_surjective h.surjective]
protected lemma compact_space [compact_space α] (h : α ≃ₜ β) : compact_space β :=
{ compact_univ := by { rw [← image_univ_of_surjective h.surjective, h.compact_image],
apply compact_space.compact_univ } }
protected lemma t0_space [t0_space α] (h : α ≃ₜ β) : t0_space β :=
h.symm.embedding.t0_space
protected lemma t1_space [t1_space α] (h : α ≃ₜ β) : t1_space β :=
h.symm.embedding.t1_space
protected lemma t2_space [t2_space α] (h : α ≃ₜ β) : t2_space β :=
h.symm.embedding.t2_space
protected lemma regular_space [regular_space α] (h : α ≃ₜ β) : regular_space β :=
h.symm.embedding.regular_space
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := h.surjective.dense_range,
.. h.embedding }
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
h.quotient_map.is_open_preimage
@[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s :=
by rw [← preimage_symm, is_open_preimage]
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2
@[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s :=
by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage]
@[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s :=
by rw [← preimage_symm, is_closed_preimage]
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2
protected lemma open_embedding (h : α ≃ₜ β) : open_embedding h :=
open_embedding_of_embedding_open h.embedding h.is_open_map
protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h :=
closed_embedding_of_embedding_closed h.embedding h.is_closed_map
protected lemma normal_space [normal_space α] (h : α ≃ₜ β) : normal_space β :=
h.symm.closed_embedding.normal_space
lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) :=
h.is_open_map.preimage_closure_eq_closure_preimage h.continuous _
lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) :=
by rw [← preimage_symm, preimage_closure]
lemma image_interior (h : α ≃ₜ β) (s : set α) : h '' (interior s) = interior (h '' s) :=
by rw [← preimage_symm, preimage_interior]
lemma preimage_frontier (h : α ≃ₜ β) (s : set β) : h ⁻¹' (frontier s) = frontier (h ⁻¹' s) :=
h.is_open_map.preimage_frontier_eq_frontier_preimage h.continuous _
@[to_additive]
lemma _root_.has_compact_mul_support.comp_homeomorph {M} [has_one M] {f : β → M}
(hf : has_compact_mul_support f) (φ : α ≃ₜ β) : has_compact_mul_support (f ∘ φ) :=
hf.comp_closed_embedding φ.closed_embedding
@[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) :=
h.embedding.map_nhds_of_mem _ (by simp)
lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x :=
by rw [h.symm.map_nhds_eq, h.symm_apply_apply]
lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) :=
h.embedding.to_inducing.nhds_eq_comap x
@[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) :=
by rw [h.nhds_eq_comap, h.apply_symm_apply]
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
rw continuous_def,
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
to_equiv := e }
@[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.inducing.continuous_on_iff.symm
@[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.inducing.continuous_iff.symm
@[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.quotient_map.continuous_iff.symm
lemma comp_continuous_at_iff (h : α ≃ₜ β) (f : γ → α) (x : γ) :
continuous_at (h ∘ f) x ↔ continuous_at f x :=
h.inducing.continuous_at_iff.symm
lemma comp_continuous_at_iff' (h : α ≃ₜ β) (f : β → γ) (x : α) :
continuous_at (f ∘ h) x ↔ continuous_at f (h x) :=
h.inducing.continuous_at_iff' (by simp)
lemma comp_continuous_within_at_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) (x : γ) :
continuous_within_at f s x ↔ continuous_within_at (h ∘ f) s x :=
h.inducing.continuous_within_at_iff
@[simp] lemma comp_is_open_map_iff (h : α ≃ₜ β) {f : γ → α} :
is_open_map (h ∘ f) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, h.is_open_map.comp hf⟩,
intros hf,
rw [← function.comp.left_id f, ← h.symm_comp_self, function.comp.assoc],
exact h.symm.is_open_map.comp hf,
end
@[simp] lemma comp_is_open_map_iff' (h : α ≃ₜ β) {f : β → γ} :
is_open_map (f ∘ h) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, hf.comp h.is_open_map⟩,
intros hf,
rw [← function.comp.right_id f, ← h.self_comp_symm, ← function.comp.assoc],
exact hf.comp h.symm.is_open_map,
end
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
to_equiv := equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.continuous)
(continuous_inr.comp h₂.continuous),
ext x, cases x; refl,
end,
continuous_inv_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.symm.continuous)
(continuous_inr.comp h₂.symm.continuous),
ext x, cases x; refl
end,
to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk
(h₂.continuous.comp continuous_snd),
continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk
(h₂.symm.continuous.comp continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous_snd.prod_mk continuous_fst,
continuous_inv_fun := continuous_snd.prod_mk continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk
((continuous_snd.comp continuous_fst).prod_mk continuous_snd),
continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk
(continuous_snd.comp continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is homeomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ₜ α :=
{ to_equiv := equiv.prod_punit α,
continuous_to_fun := continuous_fst,
continuous_inv_fun := continuous_id.prod_mk continuous_const }
/-- `{*} × α` is homeomorphic to `α`. -/
def punit_prod : punit × α ≃ₜ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
to_equiv := equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
begin
refine (homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm _ _).symm,
{ convert continuous_sum_rec
((continuous_inl.comp continuous_fst).prod_mk continuous_snd)
((continuous_inr.comp continuous_fst).prod_mk continuous_snd),
ext1 x, cases x; refl, },
{ exact (is_open_map_sum
(open_embedding_inl.prod open_embedding_id).is_open_map
(open_embedding_inr.prod open_embedding_id).is_open_map) }
end
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
(continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding_sigma_mk.prod open_embedding_id).is_open_map)
end distrib
/-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def fun_unique (ι α : Type*) [unique ι] [topological_space α] : (ι → α) ≃ₜ α :=
{ to_equiv := equiv.fun_unique ι α,
continuous_to_fun := continuous_apply _,
continuous_inv_fun := continuous_pi (λ _, continuous_id) }
/-- Homeomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/
@[simps { fully_applied := ff }]
def {u} pi_fin_two (α : fin 2 → Type u) [Π i, topological_space (α i)] : (Π i, α i) ≃ₜ α 0 × α 1 :=
{ to_equiv := pi_fin_two_equiv α,
continuous_to_fun := (continuous_apply 0).prod_mk (continuous_apply 1),
continuous_inv_fun := continuous_pi $ fin.forall_fin_two.2 ⟨continuous_fst, continuous_snd⟩ }
/-- Homeomorphism between `α² = fin 2 → α` and `α × α`. -/
@[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ₜ α × α :=
{ to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) }
/--
A subset of a topological space is homeomorphic to its image under a homeomorphism.
-/
@[simps] def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s :=
{ continuous_to_fun := by continuity!,
continuous_inv_fun := by continuity!,
to_equiv := e.to_equiv.image s, }
/-- `set.univ α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def set.univ (α : Type*) [topological_space α] : (univ : set α) ≃ₜ α :=
{ to_equiv := equiv.set.univ α,
continuous_to_fun := continuous_subtype_coe,
continuous_inv_fun := continuous_subtype_mk _ continuous_id }
end homeomorph
/-- An inducing equiv between topological spaces is a homeomorphism. -/
@[simps] def equiv.to_homeomorph_of_inducing [topological_space α] [topological_space β] (f : α ≃ β)
(hf : inducing f) :
α ≃ₜ β :=
{ continuous_to_fun := hf.continuous,
continuous_inv_fun := hf.continuous_iff.2 $ by simpa using continuous_id,
.. f }
namespace continuous
variables [topological_space α] [topological_space β]
lemma continuous_symm_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : continuous f.symm :=
begin
rw continuous_iff_is_closed,
intros C hC,
have hC' : is_closed (f '' C) := (hC.is_compact.image hf).is_closed,
rwa equiv.image_eq_preimage at hC',
end
/-- Continuous equivalences from a compact space to a T2 space are homeomorphisms.
This is not true when T2 is weakened to T1
(see `continuous.homeo_of_equiv_compact_to_t2.t1_counterexample`). -/
@[simps]
def homeo_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : α ≃ₜ β :=
{ continuous_to_fun := hf,
continuous_inv_fun := hf.continuous_symm_of_equiv_compact_to_t2,
..f }
end continuous
|
If $n > 1$, then the sum of all the $n$th roots of unity is zero. |
/- Lecture 1.1: Basics — Specifications -/
/- Natural numbers -/
namespace my_nat
inductive nat
| zero : nat
| succ : nat → nat
#check nat
#check nat.zero
#check nat.succ
#print nat
def add : nat → nat → nat
| m nat.zero := m
| m (nat.succ n) := nat.succ (add m n)
#reduce add (nat.succ nat.zero) (nat.succ nat.zero)
lemma add_comm (m n : nat) : add m n = add n m :=
_
lemma add_assoc (l m n : nat) : add (add l m) n = add l (add m n) :=
_
def mul : nat → nat → nat
| _ nat.zero := nat.zero
| m (nat.succ n) := add m (mul m n)
#reduce mul (nat.succ (nat.succ nat.zero)) (nat.succ (nat.succ nat.zero))
lemma mul_comm (m n : nat) : mul m n = mul n m :=
begin
induction n,
simp[mul],
induction m,
simp[mul],
rw[m_ih],
end
lemma mul_assoc (l m n : nat) : mul (mul l m) n = mul l (mul m n) :=
_
lemma mul_add (l m n : nat) : mul l (add m n) = add (mul l m) (mul l n) :=
_
#print mul
#print mul._main
-- illegal
def evil : nat → nat
| n := nat.succ (evil n)
end my_nat
def power : ℕ → ℕ → ℕ
| _ 0 := 1
| m (nat.succ n) := m * power m n
#reduce power 2 5
def power' (m : ℕ) : ℕ → ℕ
| 0 := 1
| (nat.succ n) := m * power' n
#reduce power' 2 5
def iter (α : Type) (z : α) (f : α → α) : ℕ → α
| 0 := z
| (nat.succ n) := f (iter n)
#check iter
def power'' (m n : ℕ) :=
iter _ 1 (λl, m * l) n
#reduce power'' 2 5
/- Lists -/
namespace my_list
inductive list (α : Type)
| nil : list
| cons : α → list → list
#check list.nil
#check list.cons
#check @list.cons
def append (α : Type) : list α → list α → list α
| (list.nil _) ys := ys
| (list.cons x xs) ys := list.cons x (append xs ys)
#check append
#reduce append _ (list.cons 1 (list.nil _)) (list.cons 2 (list.nil _))
def append' {α : Type} : list α → list α → list α
| (list.nil _) ys := ys
| (list.cons x xs) ys := list.cons x (append' xs ys)
#check append'
#reduce append' (list.cons 1 (list.nil _)) (list.cons 2 (list.nil _))
end my_list
#print list
def reverse {α : Type} : list α → list α
| [] := []
| (x :: xs) := reverse xs ++ [x]
lemma reverse_reverse {α : Type} (xs : list α) : reverse (reverse xs) = xs :=
begin
induction xs,
refl,
rw[<-xs_ih],
simp[list.append_assoc]
end
lemma reverse_concat {α: Type} {β: Type} (xs : list α) (ls : list α): reverse (append xs ls) = append (reverse xs) (reverse ls) :=
begin
simp[append],
simp
end
/- Some basic types -/
#print bool
#reduce ff || tt
#print prod
#print sum
#print empty
#check (ℕ → ℕ) → list ℕ → list ℕ
#check Πα β, (α → β) → list α → list β
/- RGB values -/
structure rgb :=
(red green blue : ℕ)
structure rgba extends rgb :=
(alpha : ℕ)
#print rgb
#print rgba
#reduce rgb.mk 0xff 0xcc 0xff
#reduce ({red := 0xff, green := 0xcc, blue := 0xff} : rgb)
#reduce ({red := 0xff, green := 0xcc, blue := 0xff, alpha := 0x7f} : rgba)
def red : rgb := {red := 0xff, green := 0x00, blue := 0x00}
def semitransparent_red : rgba := {alpha := 0x7f, ..red}
def green : rgb := ⟨0x00, 0xff, 0x00⟩
#print red
#print semitransparent_red
#print green
def shuffle (c : rgb) : rgb :=
{red := c.green, green := c.blue, blue := c.red}
lemma shuffle_shuffle_shuffle (c : rgb) : shuffle (shuffle (shuffle c)) = c :=
by cases c; refl
|
{-# OPTIONS --without-K #-}
module PiLevel1Alternative where
open import Relation.Binary.PropositionalEquality
open import Data.Nat
open import Data.Vec
open import FinVec
open F
open import ConcretePermutation
------------------------------------------------------------------------------
-- Equivalences between permutations
-- Objects are level 0 permutations ⟷
-- Morphisms are equivalences between these permutations
factorial : ℕ → ℕ
factorial 0 = 1
factorial (suc n) = n * factorial n
record EquivBetweenPerm {values : ℕ} {size : ℕ} (p₁ p₂ : CPerm values size) : Set where
constructor ebp
module p₁ = CPerm p₁
module p₂ = CPerm p₂
field
-- first we have a permutation on the underlying finite sets
π : FinVec values size
πᵒ : FinVec size values
αp : π ∘̂ πᵒ ≡ F.1C
βp : πᵒ ∘̂ π ≡ F.1C
-- then we have a permutation on these maps are consistent with p₁.π, p₂.π, etc.
ππ : Vec (FinVec values size) (factorial size) -- ??? NO
-- and so on
-- and apply
{--
Ex: the two underlying permutations p₁ and p₂ are:
values = {A,B,C}
size = 3
p₁.π = { A <=> C, B <=> A, C <=> B } represented as {C,A,B}
p₂.π = { A <=> C, B <=> A, C <=> B } represented as {C,A,B}
one equivalence between these permutations is 'id'; another has:
π = { A <=> B, B <=> C, C <=> A }
ππ = { (A <=> C) <=> (B <=> A),
(B <=> A) <=> (C <=> B),
(C <=> B) <=> (A <=> C) }
represented as p₁.πᵒ ???
--}
------------------------------------------------------------------------------
|
/*******************************************************************************
Copyright(c) 2015-2021 Parker Hannifin Corp. All rights reserved.
MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License.
*******************************************************************************/
#include "stdafx.h"
#include "MipFieldParser_Displacement.h"
#include <boost/date_time/posix_time/ptime.hpp>
#include "mscl/MicroStrain/MIP/Packets/MipDataPacket.h"
#include "mscl/MicroStrain/DataBuffer.h"
#include "mscl/Types.h"
namespace mscl
{
//the classes in this file do not get referenced anywhere, therefore the
//linker will not include this compilation unit when statically
//linking to an executable. Defining this variable, and then using it
//elsewhere, will force this file to be included
bool _forceLibraryToIncludeCompilationUnit_Displacement;
//=====================================================================================================================================================
// FieldParser_RawPosition
const MipTypes::ChannelField FieldParser_RawPosition::FIELD_TYPE = MipTypes::CH_FIELD_DISP_DISPLACEMENT_RAW;
const bool FieldParser_RawPosition::REGISTERED = FieldParser_RawPosition::registerParser(); //register the parser immediately
void FieldParser_RawPosition::parse(const MipDataField& field, MipDataPoints& result) const
{
DataBuffer bytes(field.fieldData());
uint32 adcCount = bytes.read_uint32();
result.push_back(MipDataPoint(FIELD_TYPE, MipTypes::CH_DISPLACEMENT, valueType_uint32, anyType(adcCount)));
}
bool FieldParser_RawPosition::registerParser()
{
static FieldParser_RawPosition p;
return MipFieldParser::registerParser(FIELD_TYPE, &p);
}
//=====================================================================================================================================================
//=====================================================================================================================================================
// FieldParser_Position
const MipTypes::ChannelField FieldParser_Position::FIELD_TYPE = MipTypes::CH_FIELD_DISP_DISPLACEMENT_MM;
const bool FieldParser_Position::REGISTERED = FieldParser_Position::registerParser(); //register the parser immediately
void FieldParser_Position::parse(const MipDataField& field, MipDataPoints& result) const
{
DataBuffer bytes(field.fieldData());
float position = bytes.read_float();
result.push_back(MipDataPoint(FIELD_TYPE, MipTypes::CH_DISPLACEMENT, valueType_float, anyType(position)));
}
bool FieldParser_Position::registerParser()
{
static FieldParser_Position p;
return MipFieldParser::registerParser(FIELD_TYPE, &p);
}
//=====================================================================================================================================================
} |
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
! This file was ported from Lean 3 source module topology.sets.order
! leanprover-community/mathlib commit dc6c365e751e34d100e80fe6e314c3c3e0fd2988
! Please do not edit these lines, except to modify the commit id
! if you have ported upstream changes.
-/
import Mathlib.Order.UpperLower.Basic
import Mathlib.Topology.Sets.Closeds
/-!
# Clopen upper sets
In this file we define the type of clopen upper sets.
-/
open Set TopologicalSpace
variable {α β : Type _} [TopologicalSpace α] [LE α] [TopologicalSpace β] [LE β]
/-! ### Compact open sets -/
/-- The type of clopen upper sets of a topological space. -/
structure ClopenUpperSet (α : Type _) [TopologicalSpace α] [LE α] extends Clopens α where
upper' : IsUpperSet carrier
#align clopen_upper_set ClopenUpperSet
namespace ClopenUpperSet
instance : SetLike (ClopenUpperSet α) α where
coe s := s.carrier
coe_injective' s t h := by
obtain ⟨⟨_, _⟩, _⟩ := s
obtain ⟨⟨_, _⟩, _⟩ := t
congr
/-- See Note [custom simps projection]. -/
def Simps.coe (s : ClopenUpperSet α) : Set α := s
initialize_simps_projections ClopenUpperSet (carrier → coe)
theorem upper (s : ClopenUpperSet α) : IsUpperSet (s : Set α) :=
s.upper'
#align clopen_upper_set.upper ClopenUpperSet.upper
theorem clopen (s : ClopenUpperSet α) : IsClopen (s : Set α) :=
s.clopen'
#align clopen_upper_set.clopen ClopenUpperSet.clopen
/-- Reinterpret a upper clopen as an upper set. -/
@[simps]
def toUpperSet (s : ClopenUpperSet α) : UpperSet α :=
⟨s, s.upper⟩
#align clopen_upper_set.to_upper_set ClopenUpperSet.toUpperSet
@[ext]
protected theorem ext {s t : ClopenUpperSet α} (h : (s : Set α) = t) : s = t :=
SetLike.ext' h
#align clopen_upper_set.ext ClopenUpperSet.ext
@[simp]
instance : Sup (ClopenUpperSet α) :=
⟨fun s t => ⟨s.toClopens ⊔ t.toClopens, s.upper.union t.upper⟩⟩
instance : Inf (ClopenUpperSet α) :=
⟨fun s t => ⟨s.toClopens ⊓ t.toClopens, s.upper.inter t.upper⟩⟩
instance : Top (ClopenUpperSet α) :=
⟨⟨⊤, isUpperSet_univ⟩⟩
instance : Bot (ClopenUpperSet α) :=
⟨⟨⊥, isUpperSet_empty⟩⟩
instance : Lattice (ClopenUpperSet α) :=
SetLike.coe_injective.lattice _ (fun _ _ => rfl) fun _ _ => rfl
instance : BoundedOrder (ClopenUpperSet α) :=
BoundedOrder.lift ((↑) : _ → Set α) (fun _ _ => id) rfl rfl
@[simp]
theorem coe_sup (s t : ClopenUpperSet α) : (↑(s ⊔ t) : Set α) = ↑s ∪ ↑t :=
rfl
#align clopen_upper_set.coe_sup ClopenUpperSet.coe_sup
@[simp]
theorem coe_inf (s t : ClopenUpperSet α) : (↑(s ⊓ t) : Set α) = ↑s ∩ ↑t :=
rfl
#align clopen_upper_set.coe_inf ClopenUpperSet.coe_inf
@[simp]
theorem coe_top : (↑(⊤ : ClopenUpperSet α) : Set α) = univ :=
rfl
#align clopen_upper_set.coe_top ClopenUpperSet.coe_top
@[simp]
theorem coe_bot : (↑(⊥ : ClopenUpperSet α) : Set α) = ∅ :=
rfl
#align clopen_upper_set.coe_bot ClopenUpperSet.coe_bot
instance : Inhabited (ClopenUpperSet α) :=
⟨⊥⟩
end ClopenUpperSet
|
theory Source_Code
imports "~~/src/HOL/Probability/Information"
begin
(*
AIM: Formalize Shannon's theorems
*)
section{* Basic types *}
type_synonym bit = bool
type_synonym bword = "bit list"
type_synonym letter = nat
type_synonym 'b word = "'b list"
type_synonym 'b encoder = "'b word \<Rightarrow> bword"
type_synonym 'b decoder = "bword \<Rightarrow> 'b word option"
type_synonym 'b code = "'b encoder * 'b decoder"
type_synonym 'b prob = "'b \<Rightarrow> real"
section{* First locale, generic to both Shannon's theorems *}
(*
X is the input, Y is the output.
They are not independent (if they are, all of this serves no purpose)
We fix N, N' the measures (TODO: should I? Can we have two different bit measures?)
The input is only correlated to the corresponding output.
From a code, we consider:
_its extension: the code obtained when we encode each
letter and concatenate the result (and fortunately decode it if it has some good
properties).
_its block code, with a natural parameter, that takes mentioned number of
letters, consider it as a single character (of a new alphabet), and encode it.
*)
(* locale generic to both theorems *)
locale source_code = information_space +
(* information source *)
fixes fi :: "'b \<Rightarrow> real"
fixes X::"'a \<Rightarrow> 'b"
assumes distr_i: "simple_distributed M X fi"
(*
According to RAHM, this should be a rat: my impression is that they aim for a code that can achieve
precisely this rate, however the gist is that we can achieve a rate equal OR better than H + \<epsilon>, so
in my mind it is not that important. In the Shannon's original paper it is not clear to me either.
*)
fixes H::real
(*
The entropy depends on the value of b, which is the cardinal of the set of available
output symbols.
*)
(*
I have tried to use statements that do not use the value of b explicitly, using b_gt_1 whenever
possible. However it is not possible to avoid using this value altogether, since it is encoded in
the output type of the code (which is a bword, a word of bits). This is one of the shortcomings of
Isabelle vs Coq/SSreflect, where dependent parameter types are available.
*)
assumes b_val: "b = 2"
assumes entropy_defi: "H = \<H>(X)"
fixes L :: "'b set"
assumes fin_L: "finite L"
assumes emp_L: "L \<noteq> {}"
(*
TLDR: technicality
The assumption boils down to say that for all letter l in L, there is a "omega" such that X(omega) =
l. Even with that, we can still have P(X=l) = 0, if only by modifying X for one value in the
(continuous) probability space but keeping the same distribution.
*)
assumes bounded_input: "X ` space M = L"
fixes c::"'b code"
assumes real_code : "((\<forall>x. snd c (fst c x) = Some x) \<and>
(\<forall>w. (fst c) w = [] \<longleftrightarrow> w = []) \<and>
(\<forall>x. x \<noteq> [] \<longrightarrow> fst c x = (fst c) [(hd x)] @ (fst c) (tl x)))"
(*
TODO: Have some predicates to allow reasonings about codes. Keep the input_block_size that limits
the size of the input, and use it.
*)
(*
We will generalize the type "code" to any input by splitting the input in piece of length below a
constant.
*)
section{* Source coding theorem, direct: the entropy is a lower bound *}
context source_code
begin
subsection{* Codes and words *}
abbreviation real_word :: "'b word \<Rightarrow> bool" where
"real_word w \<equiv> (set w \<subseteq> L)"
abbreviation k_words :: "nat \<Rightarrow> ('b word) set" where
"k_words k \<equiv> {w. length w = k \<and> real_word w}"
lemma rw_tail:
assumes "real_word w"
shows "w = [] \<or> real_word (tl w)"
by (meson assms list.set_sel(2) subset_code(1))
(*
length of the codeword associated with the letter
*)
definition code_word_length :: "'e code \<Rightarrow> 'e \<Rightarrow> nat" where
"code_word_length co l = length ((fst co) [l])"
abbreviation cw_len :: "'b \<Rightarrow> nat" where
"cw_len l \<equiv> code_word_length c l"
(*
The code rate is the expectation of the length of the code taken on all inputs (which is a finite
set, the set of letters).
*)
definition code_rate :: "'e code \<Rightarrow> ('a \<Rightarrow> 'e) \<Rightarrow> real" where
"code_rate co Xo = expectation (\<lambda>a. (code_word_length co ((Xo) a)))"
abbreviation cr :: "real" where
"cr \<equiv> code_rate c X"
lemma fi_pos: "i\<in> L \<Longrightarrow> 0 \<le> fi i"
using simple_distributed_nonneg[OF distr_i] bounded_input by auto
(*
Proof by Johannes Hölzl
*)
lemma (in prob_space) simp_exp_composed:
assumes X: "simple_distributed M X Px"
shows "expectation (\<lambda>a. f (X a)) = (\<Sum>x \<in> X`space M. f x * Px x)"
using distributed_integral[OF simple_distributed[OF X], of f]
by (simp add: lebesgue_integral_count_space_finite[OF simple_distributed_finite[OF X]] ac_simps)
lemma cr_rw:
"cr = (\<Sum>i \<in> X ` space M. fi i * cw_len i)" unfolding code_rate_def
using simp_exp_composed[OF distr_i, of "cw_len"]
by (simp add: mult.commute)
abbreviation cw_len_concat :: "'b word \<Rightarrow> nat" where
"cw_len_concat w \<equiv> foldr (\<lambda>x s. (cw_len x) + s) w 0"
lemma cw_len_length: "cw_len_concat w = length (fst c w)"
proof (induction w)
case Nil
show ?case using real_code by simp
case (Cons a w)
have "cw_len_concat (a # w) = cw_len a + cw_len_concat w" by simp
thus ?case using code_word_length_def real_code Cons
by (metis length_append list.distinct(1) list.sel(1) list.sel(3))
qed
lemma maj_fold:
assumes "\<And>l. l\<in>L \<Longrightarrow> f l \<le> bound"
assumes "real_word w"
shows "foldr (\<lambda>x s. f x + s) w 0 \<le> length w * bound"
using assms
by(induction w) (simp,fastforce)
definition max_len :: "nat" where
"max_len = Max ((\<lambda>x. cw_len x) ` L)"
lemma max_cw:
"l \<in> L \<Longrightarrow> cw_len l \<le> max_len"
by (simp add: max_len_def fin_L)
subsection{* Related to the Kraft theorem *}
definition kraft_sum :: "real" where
"kraft_sum = (\<Sum>i\<in>L. 1 / b ^ (cw_len i))"
lemma pos_cw_len: "0 < 1 / b ^ cw_len i" using b_gt_1 by simp
lemma kraft_sum_nonnull: "0 < kraft_sum"
using emp_L fin_L pos_cw_len setsum_pos kraft_sum_def
by metis
lemma kraft_sum_powr: "kraft_sum = (\<Sum>i\<in>L. 1 / b powr (cw_len i))"
using powr_realpow b_gt_1
by (simp add: kraft_sum_def)
definition kraft_inequality :: "bool" where
"kraft_inequality = (kraft_sum \<le> 1)"
lemma k_words_rel:
"k_words (Suc k) = {w. (hd w \<in> L \<and> tl w \<in> k_words k \<and> w \<noteq> [])}"
proof
fix k
show "k_words (Suc k) \<subseteq> {w. (hd w \<in> L \<and> tl w \<in> k_words k \<and> w \<noteq> [] )}" (is "?l \<subseteq> ?r")
proof
fix w
assume w_kw: "w \<in> k_words (Suc k)"
hence "real_word w" by simp
hence "hd w \<in> L"
by (metis (mono_tags) w_kw hd_in_set list.size(3) mem_Collect_eq nat.distinct(1) subset_code(1))
moreover have "length w = Suc k" using w_kw by simp
moreover hence "w \<noteq> []" by auto
moreover have "real_word (tl w)" using \<open>real_word w\<close> calculation(3) rw_tail by auto
ultimately show "w \<in> ?r" using w_kw by simp
qed
next
fix k
show "k_words (Suc k) \<supseteq> {w. (hd w \<in> L \<and> tl w \<in> k_words k \<and> w \<noteq> [])}"
proof
fix w
assume asm: "w \<in> {w. hd w \<in> L \<and> tl w \<in> {w. length w = k \<and> real_word w} \<and> w \<noteq> []}"
hence "hd w \<in> L \<and> length (tl w) = k \<and> real_word (tl w)" by simp
hence "real_word w"
by (metis empty_iff insert_subset list.collapse list.set(1) set_simps(2) subsetI)
moreover hence "length w = Suc k" using asm by auto
ultimately show "w \<in> k_words (Suc k)" by simp
qed
qed
lemma bij_k_words:
shows "bij_betw (\<lambda>wi. Cons (fst wi) (snd wi)) (L \<times> (k_words k)) (k_words (Suc k))"
unfolding bij_betw_def
proof
fix k
let ?f = "(\<lambda>wi. Cons (fst wi) (snd wi))"
let ?S = "L \<times> (k_words k)"
let ?T = "k_words (Suc k)"
show "inj_on ?f ?S" by (simp add: inj_on_def)
show "?f`?S = ?T"
proof (rule ccontr)
assume "?f ` ?S \<noteq> ?T"
hence "\<exists>w. w\<in> ?T \<and> w \<notin> ?f`?S" by auto
then obtain w where asm: "w\<in> ?T \<and> w \<notin> ?f`?S" by blast
hence "w = ?f ((hd w),(tl w))" using k_words_rel by simp
moreover have "((hd w),(tl w)) \<in> ?S" using k_words_rel asm by simp
ultimately have "w \<in> ?f`?S" by blast
thus "False" using asm by simp
qed
qed
lemma finite_k_words: "finite (k_words k)"
proof (induct k)
case 0
show ?case by simp
case (Suc n)
thus ?case using bij_k_words bij_betw_finite fin_L by blast
qed
lemma cartesian_product:
fixes f::"('c \<Rightarrow> real)"
fixes g::"('d \<Rightarrow> real)"
assumes "finite A"
assumes "finite B"
shows "(\<Sum>b\<in>B. g b)* (\<Sum>a\<in>A. f a) = (\<Sum>ab\<in>A\<times>B. f (fst ab) * g (snd ab))"
using bilinear_times bilinear_setsum[where h="(\<lambda>x y. x * y)" and f="f" and g="g"] assms
by (metis (erased, lifting) setsum.cong split_beta' Groups.ab_semigroup_mult_class.mult.commute)
lemma kraft_sum_power :
shows "kraft_sum ^k = (\<Sum>w \<in> (k_words k). 1 / b^(cw_len_concat w))"
proof (induct k)
case 0
have "k_words 0 = {[]}" by auto
thus ?case by simp
next
case (Suc n)
have "kraft_sum ^Suc n = kraft_sum ^n * kraft_sum " by simp
also have "\<dots> =
(\<Sum>w \<in> k_words n. 1 / b^cw_len_concat w) * (\<Sum>i\<in>L. 1 / b^cw_len i)"
using Suc.hyps kraft_sum_def by auto
also have
"\<dots> =
(\<Sum>wi \<in> L \<times> k_words n. 1/b^cw_len (fst wi) * (1 / b^cw_len_concat (snd wi)))"
using fin_L finite_k_words cartesian_product
by blast
also have "\<dots> =
(\<Sum>wi \<in> L \<times> k_words n. 1 / b^(cw_len_concat (snd wi) + cw_len (fst wi)))"
by (metis (no_types, lifting) power_add add.commute power_one_over)
also have "\<dots> =
(\<Sum>wi \<in> L \<times> k_words n. 1 / b^cw_len_concat (fst wi # snd wi))"
by (metis (erased, lifting) add.commute comp_apply foldr.simps(2))
also have "\<dots> = (\<Sum>w \<in> (k_words (Suc n)). 1 / b^(cw_len_concat w))"
using bij_k_words setsum.reindex_bij_betw by fastforce
finally show ?case by simp
qed
lemma bound_len_concat:
shows "\<And>w. w \<in> k_words k \<Longrightarrow> cw_len_concat w \<le> k * max_len"
using max_cw maj_fold by blast
subsection{* Inequality of the kraft sum (source coding theorem, direct) *}
subsubsection{* Sum manipulation lemmas and McMillan theorem *}
lemma real_plus_one:
shows "real ((n::nat) + 1) * r = (n * r + r)"
by (simp add: semiring_normalization_rules(2))
lemma sum_vimage_proof:
fixes g::"nat \<Rightarrow> real"
assumes "\<And>w. f w < bd"
shows "finite S \<Longrightarrow> (\<Sum>w\<in>S. g (f w)) = (\<Sum> m=0..<bd. (card ((f-`{m}) \<inter> S) )* g m)"
(is "_ \<Longrightarrow> _ = (\<Sum> m=0..<bd. ?ff m S)")
proof (induct S rule: finite_induct)
case empty
show ?case by simp
next
case (insert x F)
let ?rr = "(\<Sum>m = 0..<bd. ?ff m (insert x F))"
(* focusing of the right hand term *)
have "(f x) \<in> {0..<bd}" using assms by simp
hence "\<And>h::(nat \<Rightarrow> real). (\<Sum>m=0..<bd. h m) = (\<Sum>y\<in>({0..<bd} - {f x}).h y) + h (f x)"
by (metis diff_add_cancel finite_atLeastLessThan setsum_diff1_ring)
moreover hence
"(\<Sum>m = 0..<bd. ?ff m (insert x F))
= (\<Sum>m\<in>{0..<bd} - {f x}. ?ff m (insert x F)) + card (f -` {f x} \<inter> F) * g (f x) + g (f x)"
using insert real_plus_one by fastforce
ultimately have "(\<Sum>m = 0..<bd. ?ff m (insert x F)) = (\<Sum>m\<in>{0..<bd}. ?ff m F) + g (f x)"
by fastforce
thus ?case using insert by simp
qed
lemma sum_vimage:
fixes g::"nat \<Rightarrow> real"
assumes bounded: "\<And>w. w \<in> S \<Longrightarrow> f w < bd" and "0 < bd"
assumes finite: "finite S"
shows "(\<Sum>w\<in>S. g (f w)) = (\<Sum> m=0..<bd. (card ((f-`{m}) \<inter> S) ) * g m)"
(is "?s1 = ?s2")
proof -
let ?ff = "(\<lambda>x. if x\<in>S then f x else 0)"
let ?ss1 = "(\<Sum>w\<in>S. g (?ff w))"
let ?ss2 = "(\<Sum> m=0..<bd. (card ((?ff-`{m}) \<inter> S) ) * g m)"
have "?s1 =?ss1" by simp
moreover have"\<And>m. ?ff -`{m} \<inter> S = f-`{m} \<inter> S" by auto
moreover hence "?s2 = ?ss2" by simp
moreover have "\<And>w . ?ff w < bd" using assms by simp
moreover hence "?ss1 = ?ss2" using sum_vimage_proof[of "?ff"] finite by blast
ultimately show "?s1 = ?s2" by metis
qed
(*
5.54
*)
lemma kraft_sum_rewrite :
"(\<Sum>w \<in> (k_words k). 1 / b^(cw_len_concat w)) = (\<Sum>m=0..<Suc (k*max_len). card (k_words k \<inter>
((cw_len_concat) -` {m})) * (1 / b^m))" (is "?L = ?R")
proof -
have "\<And>w. w \<in> k_words k \<Longrightarrow> cw_len_concat w < Suc ( k * max_len)"
by (simp add: bound_len_concat le_imp_less_Suc)
moreover have
"?R = (\<Sum>m = 0..<Suc (k * max_len).
(card (cw_len_concat -` {m} \<inter> k_words k)) * (1 / b ^ m))"
by (metis Int_commute)
moreover have "0 < Suc (k*max_len)" by simp
ultimately show ?thesis
using finite_k_words
sum_vimage[where f="cw_len_concat" and g = "\<lambda>i. 1/ (b^i)"]
by fastforce
qed
definition set_of_k_words_length_m :: "nat \<Rightarrow> nat \<Rightarrow> 'b word set" where
"set_of_k_words_length_m k m = {xk. xk \<in> k_words k} \<inter> (cw_len_concat)-`{m}"
lemma am_inj_code :
shows "inj_on (fst c) ((cw_len_concat)-`{m})" (is "inj_on ?enc ?s")
proof -
fix x y
let ?dec = "snd c"
have "x \<in> ?s \<and> y \<in> ?s \<and> ?enc x = ?enc y \<longrightarrow> ?dec (?enc x) = ?dec (?enc y)" by auto
moreover have "(\<forall>x. snd c (fst c x) = Some x)" using real_code by blast
ultimately show ?thesis using inj_on_def[of "?enc" "?s"] by (metis option.inject)
qed
lemma img_inc:
shows "(fst c)`(cw_len_concat)-`{m} \<subseteq> {bl. length bl = m}"
proof
fix y
assume "y \<in>(fst c)`(cw_len_concat)-`{m}"
then obtain x where "y = fst c x" "x\<in>(cw_len_concat)-`{m}" by auto
thus "y \<in> {bl. length bl = m}" using cw_len_length by simp
qed
lemma bool_list_fin:
"finite {bl::bool list. length bl = m}"
proof -
have "{bl. set bl \<subseteq> {True, False} \<and> length bl = m} = {bl. length bl= m}" by auto
moreover have "finite {bl. set bl \<subseteq> {True, False} \<and> length bl = m}"
by (simp add: finite_lists_length_eq)
ultimately show ?thesis by simp
qed
lemma bool_lists_card:
shows "card {bl::bool list. length bl = m} = b^m"
proof -
have "card {b. set b \<subseteq> {True,False} \<and> length b = m} = card {True,False}^m"
using card_lists_length_eq[of "{True,False}"] by simp
moreover have "card {True, False} = b" using b_val by simp
moreover have "\<And>d. d \<in> {c::(bool list). True} \<longleftrightarrow> set d \<subseteq> {True, False}" by auto
ultimately show ?thesis by simp
qed
lemma img_card:
assumes "real_code c"
shows "card (fst c`cw_len_concat-`{m}) \<le> b^m"
proof -
have "card ((fst c)` (cw_len_concat)-`{m}) \<le> card {b::(bool list). length b = m}"
by (metis (mono_tags) bool_list_fin img_inc card_mono)
thus ?thesis by (metis bool_lists_card of_nat_le_iff)
qed
lemma am_maj_aux2:
shows "finite ((cw_len_concat)-`{m}) \<and> (card ((cw_len_concat)-`{m})) \<le> b^m"
by (metis (no_types, lifting) am_inj_code bool_list_fin bool_lists_card card.infinite card_0_eq
card_image card_mono empty_iff finite_subset img_inc inf_img_fin_dom of_nat_le_iff)
lemma am_maj:
shows "card (set_of_k_words_length_m k m)\<le> b^m" (is "?c \<le> ?b")
proof -
have "set_of_k_words_length_m k m \<subseteq> (cw_len_concat)-`{m}"
using set_of_k_words_length_m_def by simp
hence "card (set_of_k_words_length_m k m) \<le> card ((cw_len_concat)-`{m})"
using assms am_maj_aux2 card_mono by blast
thus ?thesis using real_code am_maj_aux2[of m] by simp
qed
lemma empty_set_k_words:
assumes "0 < k"
shows "set_of_k_words_length_m k 0 = {}"
proof (rule ccontr)
assume "\<not> set_of_k_words_length_m k 0 = {}"
hence "\<exists>x. x \<in> set_of_k_words_length_m k 0" by auto
then obtain x where x_def: "x \<in> set_of_k_words_length_m k 0" by auto
hence "x \<noteq> []" unfolding set_of_k_words_length_m_def using assms by auto
moreover have "cw_len_concat (hd x#tl x) = cw_len_concat (tl x) + cw_len (hd x)"
by (metis add.commute comp_apply foldr.simps(2))
moreover have "(fst c) [(hd x)] \<noteq> []" using assms real_code by blast
moreover hence "0 < cw_len (hd x)" unfolding code_word_length_def by simp
ultimately have "x \<notin> set_of_k_words_length_m k 0" by (simp add:set_of_k_words_length_m_def)
thus "False" using x_def by simp
qed
lemma kraft_sum_rewrite2:
assumes "0 < k"
shows "(\<Sum>m=0..<Suc (k*max_len). (card (set_of_k_words_length_m k m))/ b^m) \<le> (k * max_len)"
proof -
have
"(\<Sum>m=1..<Suc (k*max_len). (card (set_of_k_words_length_m k m) / b^m))
\<le> (\<Sum>m=1..<Suc(k * max_len). b^m / b^m)"
using am_maj b_val
Groups_Big.setsum_mono[of "{1..<Suc(k*max_len)}"
"(\<lambda>m. (card (set_of_k_words_length_m k m))/b^m)" "\<lambda>m. b^m /b^m"]
by simp
moreover have"(\<Sum>m=1..<Suc(k * max_len). b^m / b^m) = (\<Sum>m=1..<Suc(k *max_len). 1)"
using b_gt_1 by simp
moreover have "(\<Sum>m=1..<Suc(k*max_len). 1) =(k * max_len)"
by simp
ultimately have
"(\<Sum>m = 1..<Suc (k * max_len). (card (set_of_k_words_length_m k m)) / b ^ m) \<le>(k * max_len)"
by (metis One_nat_def card_atLeastLessThan card_eq_setsum diff_Suc_Suc real_of_card)
thus ?thesis using empty_set_k_words assms
by (simp add: setsum_shift_lb_Suc0_0_upt split: split_if_asm)
qed
lemma kraft_sum_power_bound :
assumes "0 < k"
shows "kraft_sum^k \<le> (k * max_len)"
using assms kraft_sum_power kraft_sum_rewrite kraft_sum_rewrite2
by (simp add: set_of_k_words_length_m_def)
theorem McMillan :
shows "kraft_inequality"
proof -
have ineq: "\<And>k. 0 < k \<Longrightarrow> (kraft_sum) \<le> root k k * root k (max_len)"
using kraft_sum_nonnull kraft_sum_power_bound
by (metis (no_types, hide_lams) not_less of_nat_0_le_iff of_nat_mult power_strict_mono real_root_mult real_root_pos_pos_le real_root_pos_unique real_root_power)
hence "0 < max_len \<Longrightarrow> (\<lambda>k. root k k * root k (max_len)) \<longlonglongrightarrow> 1"
using LIMSEQ_root LIMSEQ_root_const tendsto_mult
by fastforce
moreover have "\<forall>n\<ge>1. kraft_sum \<le> root n n * root n (max_len)"
using ineq by simp
moreover have "max_len = 0 \<Longrightarrow> kraft_sum \<le> 1" using ineq by fastforce
ultimately have "kraft_sum \<le> 1" using LIMSEQ_le_const by blast
thus "kraft_inequality" unfolding kraft_inequality_def by simp
qed
lemma entropy_rewrite: "H = -(\<Sum>i \<in> L. fi i * log b (fi i))"
using entropy_simple_distributed[OF distr_i] bounded_input
by (simp add: entropy_defi)
lemma log_mult_ext_not_0:
"0 < x \<Longrightarrow> 0 < y \<Longrightarrow> 0 < z \<Longrightarrow> x * log b (x*z*y) = x * log b (x*z) + x * log b y"
using b_gt_1 distrib_left log_mult by simp
lemma log_mult_ext_3:
" 0 \<le> x \<Longrightarrow> 0 < y \<Longrightarrow> 0 < z \<Longrightarrow> x * log b (x*z*y) = x * log b (x*z) + x * log b y"
using log_mult_ext_not_0[of x] mult_zero_left[of "log b (0 * z * y)"] by fastforce
lemma log_mult_ext2: "0 \<le> x \<Longrightarrow> 0 < y \<Longrightarrow> x * log b (x*y) = x * log b (x) + x * log b y"
by (metis (no_types) log_mult_ext_3 mult.right_neutral zero_less_one)
subsubsection {* KL divergence and properties *}
(*
TODO (eventually): I use a custom definition of the KL_divergence, as it is far simpler for me to
use. It'd be better if in the end I can use the real def definition KL_div.
*)
definition KL_div ::"'b set \<Rightarrow> ('b \<Rightarrow> real) \<Rightarrow> ('b \<Rightarrow> real) \<Rightarrow> real" where
"KL_div S a d = (\<Sum> i \<in> S. a i * log b (a i / d i))"
lemma KL_div_mul:
assumes "0 < d" "d \<le> 1"
assumes "\<And>i. i\<in>S \<Longrightarrow> 0 \<le> a i" "\<And>i. i\<in>S \<Longrightarrow> 0 < e i"
shows "KL_div S a e \<ge> KL_div S a (\<lambda>i. e i / d)"
unfolding KL_div_def
proof -
{
fix i
assume "i\<in>S"
hence "(a i / ((e i) / d)) \<le> (a i / e i)" using assms
by (metis (no_types) divide_1 frac_le less_imp_triv not_less)
hence "log b (a i / (e i / d)) \<le> log b (a i / e i)" using assms(1)
by (metis (full_types) b_gt_1 divide_divide_eq_left inverse_divide le_less_linear log_le
log_neg_const order_refl times_divide_eq_right zero_less_mult_iff)
}
thus "(\<Sum>i\<in>S. a i * log b (a i / (e i / d))) \<le> (\<Sum>i\<in>S. a i * log b (a i / e i))"
by (meson mult_left_mono assms setsum_mono)
qed
lemma KL_div_pos:
fixes a e::"'b \<Rightarrow> real"
assumes fin: "finite S"
assumes nemp: "S \<noteq> {}"
assumes non_null: "\<And>i. i\<in>S \<Longrightarrow> 0 < a i" "\<And>i. i\<in> S \<Longrightarrow> 0 < e i"
assumes sum_a_one: "(\<Sum> i \<in> S. a i) = 1"
assumes sum_c_one: "(\<Sum> i \<in> S. e i) = 1"
shows "0 \<le> KL_div S a e"
unfolding KL_div_def
proof -
let ?f = "\<lambda>i. e i / a i"
have f_pos: "\<And>i. i\<in>S \<Longrightarrow> 0 < ?f i"
using non_null
by simp
have a_pos: "\<And>i. i\<in> S \<Longrightarrow> 0 \<le> a i"
using non_null
by (simp add: order.strict_implies_order)
have "- log b (\<Sum>i\<in>S. a i * e i / a i) \<le> (\<Sum>i\<in>S. a i * - log b (e i / a i))"
using convex_on_setsum[
OF fin,
OF nemp,OF minus_log_convex[OF b_gt_1],
OF convex_real_interval(3),
OF sum_a_one,
OF a_pos
]
f_pos
by fastforce
also have "- log b (\<Sum>i\<in>S. a i * e i / a i) = -log b (\<Sum>i\<in>S. e i)"
proof -
from non_null(1) have "\<And>i. i \<in> S \<Longrightarrow> a i * e i / a i = e i" by force
thus ?thesis by simp
qed
finally have "0 \<le> (\<Sum>i\<in>S. a i * - log b (e i / a i))"
using sum_c_one
by simp
thus "0 \<le> (\<Sum>i\<in>S. a i * log b (a i / e i))"
using b_gt_1 log_divide non_null
by simp
qed
lemma KL_div_pos_emp:
"0 \<le> KL_div {} a e" unfolding KL_div_def by simp
lemma KL_div_pos_gen:
fixes a d::"'b \<Rightarrow> real"
assumes fin: "finite S"
assumes non_null: "\<And>i. i\<in>S \<Longrightarrow> 0 < a i" "\<And>i. i\<in> S \<Longrightarrow> 0 < d i"
assumes sum_a_one: "(\<Sum> i \<in> S. a i) = 1"
assumes sum_d_one: "(\<Sum> i \<in> S. d i) = 1"
shows "0 \<le> KL_div S a d"
using KL_div_pos KL_div_pos_emp assms by metis
theorem KL_div_pos2:
fixes a d::"'b \<Rightarrow> real"
assumes fin: "finite S"
assumes non_null: "\<And>i. i\<in>S \<Longrightarrow> 0 \<le> a i" "\<And>i. i\<in> S \<Longrightarrow> 0 < d i"
assumes sum_a_one: "(\<Sum> i \<in> S. a i) = 1"
assumes sum_c_one: "(\<Sum> i \<in> S. d i) = 1"
shows "0 \<le> KL_div S a d"
proof -
have "S = (S \<inter> {i. 0 < a i}) \<union> (S \<inter> {i. 0 = a i})" using non_null(1)
by fastforce
moreover have "(S \<inter> {i. 0 < a i}) \<inter> (S \<inter> {i. 0 = a i}) = {}" by auto
ultimately have
eq: "KL_div S a d = KL_div (S \<inter> {i. 0 < a i}) a d + KL_div (S \<inter> {i. 0 = a i}) a d"
unfolding KL_div_def
by (metis (mono_tags, lifting) fin finite_Un setsum.union_disjoint)
have "KL_div (S \<inter> {i. 0 = a i}) a d = 0" unfolding KL_div_def by simp
hence "KL_div S a d = KL_div (S \<inter> {i. 0 < a i}) a d" using eq by simp
moreover have "0 \<le> KL_div (S \<inter> {i. 0 < a i}) a d"
proof(cases "(S \<inter> {i. 0 < a i}) = {}")
case True
thus ?thesis unfolding KL_div_def by simp
next
case False
let ?c = "\<lambda>i. d i / (\<Sum>j \<in>(S \<inter> {i. 0 < a i}). d j)"
(* a pos *)
have 1: "(\<And>i. i \<in> S \<inter> {i. 0 < a i} \<Longrightarrow> 0 < a i)" by simp
(* ?c pos *)
have 2: "(\<And>i. i \<in> S \<inter> {i. 0 < a i} \<Longrightarrow> 0 < ?c i)"
by (metis False IntD1 divide_pos_pos fin finite_Int non_null(2) setsum_pos)
(* sum a equals to 1 *)
have 3: "setsum a (S \<inter> {i. 0 < a i}) = 1"
using setsum.cong[of S, of S, of "(\<lambda>x. if x \<in> {i. 0 < a i} then a x else 0)", of a]
setsum.inter_restrict[OF fin, of a] non_null(1) sum_a_one
by fastforce
have "(\<Sum>i\<in>S \<inter> {j. 0 < a j}. ?c i) = (\<Sum>i\<in>S \<inter> {j. 0 < a j}. d i) / (\<Sum>i\<in>S \<inter> {j. 0 < a j}. d i)"
by (metis setsum_divide_distrib)
(* sum ?c equals to 1 *)
hence 5: "(\<Sum>i\<in>S \<inter> {j. 0 < a j}. ?c i) = 1"
using 2 False by force
hence "0 \<le> KL_div (S \<inter> {j. 0 < a j}) a ?c" using
KL_div_pos_gen[
OF finite_Int[OF disjI1, of S, of "{j. 0 < a j}"], of a, of ?c
] 1 2 3
by (metis fin)
have fstdb: "0 < setsum d (S \<inter> {i. 0 < a i})" using non_null(2) False
by (metis Int_Collect fin finite_Int setsum_pos)
have "(\<And>i. i \<in> S \<inter> {i. 0 < a i} \<Longrightarrow> 0 < a i) \<Longrightarrow>
(\<And>i. i \<in> S \<inter> {i. 0 < a i} \<Longrightarrow> 0 < d i / setsum d (S \<inter> {i. 0 < a i})) \<Longrightarrow>
setsum a (S \<inter> {i. 0 < a i}) = 1 \<Longrightarrow>
(\<Sum>i\<in>S \<inter> {i. 0 < a i}. d i / setsum d (S \<inter> {i. 0 < a i})) = 1 \<Longrightarrow>
0 \<le> KL_div (S \<inter> {i. 0 < a i}) a (\<lambda>i. d i / setsum d (S \<inter> {i. 0 < a i}))"
using KL_div_pos_gen[
OF finite_Int[OF disjI1, OF fin], of "{i. 0 < a i}", of "a", of "?c"
] by simp
hence 6: "
0 \<le> KL_div (S \<inter> {i. 0 < a i}) a (\<lambda>i. d i / setsum d (S \<inter> {i. 0 < a i}))"
using 2 3 5
by simp
have
"(\<And>i. i \<in> S \<inter> {j. 0 < a j} \<Longrightarrow> 0 < d i) \<Longrightarrow>
0 < setsum d (S \<inter> {i. 0 < a i}) \<Longrightarrow>
setsum d (S \<inter> {i. 0 < a i}) \<le> 1 \<Longrightarrow>
(\<And>i. i \<in> S \<inter> {j. 0 < a j} \<Longrightarrow> 0 \<le> a i) \<Longrightarrow>
KL_div (S \<inter> {j. 0 < a j}) a
(\<lambda>i. d i / setsum d (S \<inter> {i. 0 < a i}))
\<le> KL_div (S \<inter> {j. 0 < a j}) a d"
using KL_div_mul
by fastforce
hence "setsum d (S \<inter> {i. 0 < a i}) \<le> 1 \<Longrightarrow>
(\<And>i. i \<in> S \<inter> {j. 0 < a j} \<Longrightarrow> 0 \<le> a i) \<Longrightarrow>
KL_div (S \<inter> {j. 0 < a j}) a
(\<lambda>i. d i / setsum d (S \<inter> {i. 0 < a i}))
\<le> KL_div (S \<inter> {j. 0 < a j}) a d" using non_null(2) fstdb
by simp
hence
"(\<And>i. i \<in> S \<inter> {j. 0 < a j} \<Longrightarrow> 0 \<le> a i) \<Longrightarrow> KL_div (S \<inter> {j. 0 < a j}) a
(\<lambda>i. d i / setsum d (S \<inter> {i. 0 < a i}))
\<le> KL_div (S \<inter> {j. 0 < a j}) a d" using setsum.inter_restrict[OF fin, of d, of "{i. 0 < a i}"]
setsum_mono[of S, of "(\<lambda>x. if x \<in> {i. 0 < a i} then d x else 0)", of d] non_null(2) sum_c_one
by force
hence
"KL_div (S \<inter> {j. 0 < a j}) a (\<lambda>i. d i / setsum d (S \<inter> {i. 0 < a i})) \<le> KL_div (S \<inter> {j. 0 < a j}) a d"
using non_null by simp
moreover have "0 \<le> KL_div (S \<inter> {j. 0 < a j}) a (\<lambda>i. d i / setsum d (S \<inter> {i. 0 < a i}))"
using KL_div_pos_gen[ OF finite_Int[OF disjI1, OF fin]] using 2 3 5 by fastforce
ultimately show "0 \<le> KL_div (S \<inter> {j. 0 < a j}) a d" by simp
qed
ultimately show ?thesis by simp
qed
(* Used in many theorems... *)
lemma sum_div_1:
fixes f::"'b \<Rightarrow> 'c::field"
assumes "(\<Sum>i\<in>A. f i) \<noteq> 0"
defines "S \<equiv> \<Sum>i\<in>A. f i"
shows "(\<Sum>i\<in>A. f i / S) = 1"
by (metis (no_types) S_def assms right_inverse_eq setsum_divide_distrib)
(*
_Kraft inequality for real codes using the McMillan theorem
*)
theorem rate_lower_bound :
defines "l \<equiv> (\<lambda>i. cw_len i)"
defines "LL \<equiv> L - {i. fi i = 0}"
defines "F \<equiv> (X ` space M)"
shows "H \<le> cr"
proof -
let ?c = "kraft_sum"
let ?r = "(\<lambda>i. 1 / ((b powr l i) * ?c))"
{
fix i
assume "i \<in> L"
hence "0 \<le> fi i" using simple_distributed_nonneg[OF distr_i] bounded_input by blast
} hence pos_pi: "\<And>i. i \<in> L \<Longrightarrow> 0 \<le> fi i" by simp
{
fix i
assume iL: "i \<in> L"
hence
"fi i * (log b (1 / (1 / b powr (l i))) + log b (fi i))
= fi i * log b (fi i / (1 / b powr (l i)))"
using log_mult_ext2[OF pos_pi] b_gt_1
by (simp add:
`\<And>y i. \<lbrakk>i \<in> L; 0 < y\<rbrakk> \<Longrightarrow> fi i * log b (fi i * y) = fi i * log b (fi i) + fi i * log b y`
linordered_field_class.sign_simps(36))
}
hence eqpi:
"\<And>i. i\<in> L \<Longrightarrow> fi i * (log b (1 / (1 / b powr (l i))) + log b (fi i))
= fi i * log b (fi i / (1 / b powr (l i)))"
by simp
have sum_one: "(\<Sum> i \<in> F. fi i) = 1"
using simple_distributed_setsum_space[OF distr_i] F_def by simp
hence sum_one_L: "(\<Sum> i \<in> L. fi i) = 1" using bounded_input F_def by simp
{
fix i
assume iL: "i \<in> L"
have
"fi i * log b (fi i * ?c / (1/b powr l i) * (inverse kraft_sum)) =
fi i * log b (fi i * ?c / (1/b powr l i)) + fi i * log b (inverse kraft_sum)"
using log_mult_ext_3[OF pos_pi[OF iL]
positive_imp_inverse_positive[OF kraft_sum_nonnull],
of "kraft_sum / (1 / b powr (l i))"] divide_pos_pos[OF kraft_sum_nonnull] powr_gt_zero[of b]
Orderings.order_class.order.strict_implies_not_eq[
OF Orderings.order_class.order.strict_trans[OF zero_less_one, OF b_gt_1]
]
by (metis (no_types) divide_1 inverse_divide inverse_positive_iff_positive times_divide_eq_right)
} hence big_eq:
"\<And>i. i \<in> L \<Longrightarrow> fi i * log b (fi i * ?c / (1/b powr l i) * (1 / kraft_sum)) =
fi i * log b (fi i * ?c / (1/b powr l i)) + fi i * log b (1 / kraft_sum)"
by (simp add: inverse_eq_divide)
have 1: "cr - H = (\<Sum>i \<in> L. fi i * l i) + (\<Sum>i \<in> L. fi i * log b (fi i))"
using kraft_sum_def entropy_rewrite cr_rw bounded_input l_def by simp
also have 2: "(\<Sum>i\<in>L. fi i * l i) = (\<Sum>i \<in> L. fi i * (-log b (1/(b powr (l i)))))"
using b_gt_1 log_divide by simp
also have "\<dots> = -1 * (\<Sum>i \<in> L. fi i * (log b (1/(b powr (l i)))))"
using setsum_right_distrib[of "-1" "(\<lambda>i. fi i * (- 1 * log b (1 / b powr (l i))))" L]
by simp
finally have
"cr - H = -(\<Sum>i \<in> L. fi i * log b (1/b powr l i)) + (\<Sum>i \<in> L. fi i * log b (fi i))"
by simp
have "cr - H = (\<Sum>i \<in> L. fi i * ((log b (1/ (1/(b powr (l i))))) +log b (fi i)))"
using b_gt_1 1
by (simp add: distrib_left setsum.distrib)
also have "\<dots> = (\<Sum>i \<in> L. fi i *((log b (fi i / (1/(b powr (l i)))))))"
using Cartesian_Euclidean_Space.setsum_cong_aux[OF eqpi] by simp
also from big_eq have
"\<dots> = (\<Sum>i\<in>L. fi i * (log b (fi i * ?c / (1 / b powr (l i))))) + (\<Sum>i \<in> L. fi i) * log b (1/ ?c)"
using kraft_sum_nonnull
by (simp add: setsum_left_distrib setsum.distrib)
also have "\<dots> = (\<Sum>i\<in>L. fi i * (log b (fi i * ?c / (1 / b powr (l i))))) - log b (?c)"
using kraft_sum_nonnull
by (simp add: log_inverse_eq divide_inverse sum_one_L)
also have "\<dots> = (\<Sum> i \<in> L. fi i * log b (fi i / ?r i)) - log b (?c)"
by (metis (mono_tags, hide_lams) divide_divide_eq_left divide_divide_eq_right)
also have "\<dots> = KL_div L fi ?r + log b (inverse ?c)"
using b_gt_1 kraft_sum_nonnull by (simp add: log_inverse KL_div_def)
finally have code_ent_kl_log: "cr - H = KL_div L fi ?r + log b (inverse ?c)" by simp
have "setsum ?r L = 1"
using sum_div_1[of "\<lambda>i. 1 / (b powr (l i))"] kraft_sum_nonnull l_def kraft_sum_powr
by simp
moreover have "\<And>i. 0 < ?r i" using b_gt_1 kraft_sum_nonnull by simp
moreover have "(\<Sum>i\<in>L. fi i) = 1" using sum_one_L by simp
ultimately have "0 \<le> KL_div L fi ?r"
using KL_div_pos2[OF fin_L fi_pos] by simp
hence "log b (inverse ?c) \<le> cr - H" using code_ent_kl_log by simp
hence "log b (inverse (kraft_sum)) \<le> cr - H" by simp
moreover from McMillan assms have "0 \<le> log b (inverse (kraft_sum))"
using kraft_sum_nonnull unfolding kraft_inequality_def
by (simp add: b_gt_1 log_inverse_eq)
ultimately show ?thesis by simp
qed
end
end
|
Formal statement is: lemma (in bounded_linear) isCont: "isCont g a \<Longrightarrow> isCont (\<lambda>x. f (g x)) a" Informal statement is: If $g$ is a continuous function, then $f \circ g$ is continuous. |
# Rectangular Plate Bending Element
This derivation follows the procedure given in Chapter 12 of "A First Course in the Finite Element Method, 4th Edition" by Daryl L. Logan. Logan's method has been improved upon to allow for orthotropic behavior. Closed form solutions for stiffness and load matrices are provided.
We'll start by importing a few Python libraries that are useful for symbolic math, and initializing "pretty" printing.
```python
from sympy import symbols, Matrix, diff, integrate, simplify, factor, latex, init_printing
from IPython.display import display, Math
init_printing()
```
The plate width will be defined as $2b$, and the height will be $2c$ to be consistent with Figure 12-1. We'll set up some Sympy symbols to represent $b$ and $c$.
```python
b, c = symbols('b, c')
```
The plate is defined by four nodes specified in counter-clockwise order: i, j, m, and n. The local x-axis runs from node i toward node j, and the local y-axis runs from node i toward node n. Next we'll define the element's local displacement vector, $[d]$, at each node. There are 3 degrees of freedom at each node: $w$, $\theta_x$, and $\theta_y$.
```python
wi, theta_xi, theta_yi = symbols('w_i, theta_x_i, theta_yi')
wj, theta_xj, theta_yj = symbols('w_j, theta_xj, theta_yj')
wm, theta_xm, theta_ym = symbols('w_m, theta_xm, theta_ym')
wn, theta_xn, theta_yn = symbols('w_n, theta_xn, theta_yn')
d = Matrix([wi, theta_xi, theta_yi, wj, theta_xj, theta_yj, wm, theta_xm, theta_ym, wn, theta_xn, theta_yn])
display(Math('[d] = ' + latex(d)))
```
$\displaystyle [d] = \left[\begin{matrix}w_{i}\\\theta_{x i}\\\theta_{yi}\\w_{j}\\\theta_{xj}\\\theta_{yj}\\w_{m}\\\theta_{xm}\\\theta_{ym}\\w_{n}\\\theta_{xn}\\\theta_{yn}\end{matrix}\right]$
A 12-term polynomial displacement function will be assumed to define the out-of-plane displacement, w, at any point (x, y) in the plate's local coordinate system. The rotations about each axis are derivatives of this displacement:
```python
a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = symbols('a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9, a_10, a_11, a_12')
x, y, w, theta_x, theta_y = symbols('x, y, w, theta_x, theta_y')
w = a1 + a2*x + a3*y + a4*x**2 + a5*x*y + a6*y**2 + a7*x**3 + a8*x**2*y + a9*x*y**2 + a10*y**3 + a11*x**3*y + a12*x*y**3
theta_x = diff(w, y)
theta_y = -diff(w, x)
display(Math('w = ' + latex(w)))
display(Math('\\theta_x = ' + latex(theta_x)))
display(Math('\\theta_y = ' + latex(theta_y)))
```
$\displaystyle w = a_{1} + a_{10} y^{3} + a_{11} x^{3} y + a_{12} x y^{3} + a_{2} x + a_{3} y + a_{4} x^{2} + a_{5} x y + a_{6} y^{2} + a_{7} x^{3} + a_{8} x^{2} y + a_{9} x y^{2}$
$\displaystyle \theta_x = 3 a_{10} y^{2} + a_{11} x^{3} + 3 a_{12} x y^{2} + a_{3} + a_{5} x + 2 a_{6} y + a_{8} x^{2} + 2 a_{9} x y$
$\displaystyle \theta_y = - 3 a_{11} x^{2} y - a_{12} y^{3} - a_{2} - 2 a_{4} x - a_{5} y - 3 a_{7} x^{2} - 2 a_{8} x y - a_{9} y^{2}$
The negative sign on $\frac{dw}{dx}$ is required to be consistent with the right hand rule. These equations can be rewritten in matrix form as follows:
$[\psi] = [P][a]$
where $[\psi]$ is shorthand for $\begin{bmatrix} w \\ \theta_x \\ \theta_y \end{bmatrix}$ and $[P]$ is defined as follows:
```python
P = Matrix([[1, x, y, x**2, x*y, y**2, x**3, x**2*y, x*y**2, y**3, x**3*y, x*y**3],
[0, 0, 1, 0, x, 2*y, 0, x**2, 2*x*y, 3*y**2, x**3, 3*x*y**2],
[0, -1, 0, -2*x, -y, 0, -3*x**2, -2*x*y, -y**2, 0, -3*x**2*y, -y**3]])
display(Math('P = ' + latex(P)))
```
$\displaystyle P = \left[\begin{array}{cccccccccccc}1 & x & y & x^{2} & x y & y^{2} & x^{3} & x^{2} y & x y^{2} & y^{3} & x^{3} y & x y^{3}\\0 & 0 & 1 & 0 & x & 2 y & 0 & x^{2} & 2 x y & 3 y^{2} & x^{3} & 3 x y^{2}\\0 & -1 & 0 & - 2 x & - y & 0 & - 3 x^{2} & - 2 x y & - y^{2} & 0 & - 3 x^{2} y & - y^{3}\end{array}\right]$
This general equation for $[P]$ will be evaluated at each node to give us a larger set of equations:
$[d] = [C][a]$
where $[C]$ is merely $[P]$ evaluated at each node, and $[d]$ is correpsondingly $[\psi]$ at each node. Knowing that the plate width is $2b$ and the plate height is $2c$, we can obtain the matrix $[C]$.
```python
C = Matrix([P, P, P, P])
C[0:3, 0:12] = C[0:3, 0:12].subs(x, 0).subs(y, 0) # i-node @ x = 0, y = 0
C[3:6, 0:12] = C[3:6, 0:12].subs(x, 2*b).subs(y, 0) # j-node @ x = 2b, y = 0
C[6:9, 0:12] = C[6:9, 0:12].subs(x, 2*b).subs(y, 2*c) # m-node @ x = 2b, y = 2c
C[9:12, 0:12] = C[9:12, 0:12].subs(x, 0).subs(y, 2*c) # n-node @ x = 0, y = 2c
display(Math('[C] = ' + latex(C)))
print(C)
```
$\displaystyle [C] = \left[\begin{array}{cccccccccccc}1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\1 & 2 b & 0 & 4 b^{2} & 0 & 0 & 8 b^{3} & 0 & 0 & 0 & 0 & 0\\0 & 0 & 1 & 0 & 2 b & 0 & 0 & 4 b^{2} & 0 & 0 & 8 b^{3} & 0\\0 & -1 & 0 & - 4 b & 0 & 0 & - 12 b^{2} & 0 & 0 & 0 & 0 & 0\\1 & 2 b & 2 c & 4 b^{2} & 4 b c & 4 c^{2} & 8 b^{3} & 8 b^{2} c & 8 b c^{2} & 8 c^{3} & 16 b^{3} c & 16 b c^{3}\\0 & 0 & 1 & 0 & 2 b & 4 c & 0 & 4 b^{2} & 8 b c & 12 c^{2} & 8 b^{3} & 24 b c^{2}\\0 & -1 & 0 & - 4 b & - 2 c & 0 & - 12 b^{2} & - 8 b c & - 4 c^{2} & 0 & - 24 b^{2} c & - 8 c^{3}\\1 & 0 & 2 c & 0 & 0 & 4 c^{2} & 0 & 0 & 0 & 8 c^{3} & 0 & 0\\0 & 0 & 1 & 0 & 0 & 4 c & 0 & 0 & 0 & 12 c^{2} & 0 & 0\\0 & -1 & 0 & 0 & - 2 c & 0 & 0 & 0 & - 4 c^{2} & 0 & 0 & - 8 c^{3}\end{array}\right]$
Matrix([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2*b, 0, 4*b**2, 0, 0, 8*b**3, 0, 0, 0, 0, 0], [0, 0, 1, 0, 2*b, 0, 0, 4*b**2, 0, 0, 8*b**3, 0], [0, -1, 0, -4*b, 0, 0, -12*b**2, 0, 0, 0, 0, 0], [1, 2*b, 2*c, 4*b**2, 4*b*c, 4*c**2, 8*b**3, 8*b**2*c, 8*b*c**2, 8*c**3, 16*b**3*c, 16*b*c**3], [0, 0, 1, 0, 2*b, 4*c, 0, 4*b**2, 8*b*c, 12*c**2, 8*b**3, 24*b*c**2], [0, -1, 0, -4*b, -2*c, 0, -12*b**2, -8*b*c, -4*c**2, 0, -24*b**2*c, -8*c**3], [1, 0, 2*c, 0, 0, 4*c**2, 0, 0, 0, 8*c**3, 0, 0], [0, 0, 1, 0, 0, 4*c, 0, 0, 0, 12*c**2, 0, 0], [0, -1, 0, 0, -2*c, 0, 0, 0, -4*c**2, 0, 0, -8*c**3]])
An important matrix that we will come back to later is the shape function matrix $[N]$, defined as:
$[N] = [P][C]^{-1}$
The closed form solution of $[N]$ for a rectangular plate is:
```python
N = P*C.inv()
display(Math('[N] = ' + latex(simplify(N))))
```
$\displaystyle [N] = \left[\begin{array}{cccccccccccc}1 - \frac{3 y^{2}}{4 c^{2}} + \frac{y^{3}}{4 c^{3}} - \frac{x y}{4 b c} + \frac{3 x y^{2}}{8 b c^{2}} - \frac{x y^{3}}{8 b c^{3}} - \frac{3 x^{2}}{4 b^{2}} + \frac{3 x^{2} y}{8 b^{2} c} + \frac{x^{3}}{4 b^{3}} - \frac{x^{3} y}{8 b^{3} c} & y - \frac{y^{2}}{c} + \frac{y^{3}}{4 c^{2}} - \frac{x y}{2 b} + \frac{x y^{2}}{2 b c} - \frac{x y^{3}}{8 b c^{2}} & - x + \frac{x y}{2 c} + \frac{x^{2}}{b} - \frac{x^{2} y}{2 b c} - \frac{x^{3}}{4 b^{2}} + \frac{x^{3} y}{8 b^{2} c} & \frac{x \left(2 b^{2} c^{2} y - 3 b^{2} c y^{2} + b^{2} y^{3} + 6 b c^{3} x - 3 b c^{2} x y - 2 c^{3} x^{2} + c^{2} x^{2} y\right)}{8 b^{3} c^{3}} & \frac{x y \left(4 c^{2} - 4 c y + y^{2}\right)}{8 b c^{2}} & \frac{x^{2} \left(4 b c - 2 b y - 2 c x + x y\right)}{8 b^{2} c} & \frac{x y \left(- 2 b^{2} c^{2} + 3 b^{2} c y - b^{2} y^{2} + 3 b c^{2} x - c^{2} x^{2}\right)}{8 b^{3} c^{3}} & \frac{x y^{2} \left(- 2 c + y\right)}{8 b c^{2}} & \frac{x^{2} y \left(2 b - x\right)}{8 b^{2} c} & \frac{y \left(6 b^{3} c y - 2 b^{3} y^{2} + 2 b^{2} c^{2} x - 3 b^{2} c x y + b^{2} x y^{2} - 3 b c^{2} x^{2} + c^{2} x^{3}\right)}{8 b^{3} c^{3}} & \frac{y^{2} \left(- 4 b c + 2 b y + 2 c x - x y\right)}{8 b c^{2}} & \frac{x y \left(- 4 b^{2} + 4 b x - x^{2}\right)}{8 b^{2} c}\\\frac{- 12 b^{3} c y + 6 b^{3} y^{2} - 2 b^{2} c^{2} x + 6 b^{2} c x y - 3 b^{2} x y^{2} + 3 b c^{2} x^{2} - c^{2} x^{3}}{8 b^{3} c^{3}} & 1 - \frac{2 y}{c} + \frac{3 y^{2}}{4 c^{2}} - \frac{x}{2 b} + \frac{x y}{b c} - \frac{3 x y^{2}}{8 b c^{2}} & \frac{x \left(4 b^{2} - 4 b x + x^{2}\right)}{8 b^{2} c} & \frac{x \left(2 b^{2} c^{2} - 6 b^{2} c y + 3 b^{2} y^{2} - 3 b c^{2} x + c^{2} x^{2}\right)}{8 b^{3} c^{3}} & \frac{x \left(4 c^{2} - 8 c y + 3 y^{2}\right)}{8 b c^{2}} & \frac{x^{2} \left(- 2 b + x\right)}{8 b^{2} c} & \frac{x \left(- 2 b^{2} c^{2} + 6 b^{2} c y - 3 b^{2} y^{2} + 3 b c^{2} x - c^{2} x^{2}\right)}{8 b^{3} c^{3}} & \frac{x y \left(- 4 c + 3 y\right)}{8 b c^{2}} & \frac{x^{2} \left(2 b - x\right)}{8 b^{2} c} & \frac{12 b^{3} c y - 6 b^{3} y^{2} + 2 b^{2} c^{2} x - 6 b^{2} c x y + 3 b^{2} x y^{2} - 3 b c^{2} x^{2} + c^{2} x^{3}}{8 b^{3} c^{3}} & \frac{y \left(- 8 b c + 6 b y + 4 c x - 3 x y\right)}{8 b c^{2}} & \frac{x \left(- 4 b^{2} + 4 b x - x^{2}\right)}{8 b^{2} c}\\\frac{2 b^{2} c^{2} y - 3 b^{2} c y^{2} + b^{2} y^{3} + 12 b c^{3} x - 6 b c^{2} x y - 6 c^{3} x^{2} + 3 c^{2} x^{2} y}{8 b^{3} c^{3}} & \frac{y \left(4 c^{2} - 4 c y + y^{2}\right)}{8 b c^{2}} & 1 - \frac{y}{2 c} - \frac{2 x}{b} + \frac{x y}{b c} + \frac{3 x^{2}}{4 b^{2}} - \frac{3 x^{2} y}{8 b^{2} c} & \frac{- 2 b^{2} c^{2} y + 3 b^{2} c y^{2} - b^{2} y^{3} - 12 b c^{3} x + 6 b c^{2} x y + 6 c^{3} x^{2} - 3 c^{2} x^{2} y}{8 b^{3} c^{3}} & \frac{y \left(- 4 c^{2} + 4 c y - y^{2}\right)}{8 b c^{2}} & \frac{x \left(- 8 b c + 4 b y + 6 c x - 3 x y\right)}{8 b^{2} c} & \frac{y \left(2 b^{2} c^{2} - 3 b^{2} c y + b^{2} y^{2} - 6 b c^{2} x + 3 c^{2} x^{2}\right)}{8 b^{3} c^{3}} & \frac{y^{2} \left(2 c - y\right)}{8 b c^{2}} & \frac{x y \left(- 4 b + 3 x\right)}{8 b^{2} c} & \frac{y \left(- 2 b^{2} c^{2} + 3 b^{2} c y - b^{2} y^{2} + 6 b c^{2} x - 3 c^{2} x^{2}\right)}{8 b^{3} c^{3}} & \frac{y^{2} \left(- 2 c + y\right)}{8 b c^{2}} & \frac{y \left(4 b^{2} - 8 b x + 3 x^{2}\right)}{8 b^{2} c}\end{array}\right]$
We can now solve for the $[a]$ matrix in terms of the nodal displacements:
```python
a = simplify(C.inv()*d)
display(Math('[a] = ' + latex(a)))
```
$\displaystyle [a] = \left[\begin{matrix}w_{i}\\- \theta_{yi}\\\theta_{x i}\\\frac{2 b \left(2 \theta_{yi} + \theta_{yj}\right) - 3 w_{i} + 3 w_{j}}{4 b^{2}}\\\frac{2 b \left(\theta_{yi} - \theta_{yn}\right) + 2 c \left(- \theta_{x i} + \theta_{xj}\right) - w_{i} + w_{j} - w_{m} + w_{n}}{4 b c}\\\frac{- 2 c \left(2 \theta_{x i} + \theta_{xn}\right) - 3 w_{i} + 3 w_{n}}{4 c^{2}}\\\frac{- b \left(\theta_{yi} + \theta_{yj}\right) + w_{i} - w_{j}}{4 b^{3}}\\\frac{2 b \left(- 2 \theta_{yi} - \theta_{yj} + \theta_{ym} + 2 \theta_{yn}\right) + 3 w_{i} - 3 w_{j} + 3 w_{m} - 3 w_{n}}{8 b^{2} c}\\\frac{2 c \left(2 \theta_{x i} - 2 \theta_{xj} - \theta_{xm} + \theta_{xn}\right) + 3 w_{i} - 3 w_{j} + 3 w_{m} - 3 w_{n}}{8 b c^{2}}\\\frac{c \left(\theta_{x i} + \theta_{xn}\right) + w_{i} - w_{n}}{4 c^{3}}\\\frac{b \left(\theta_{yi} + \theta_{yj} - \theta_{ym} - \theta_{yn}\right) - w_{i} + w_{j} - w_{m} + w_{n}}{8 b^{3} c}\\\frac{c \left(- \theta_{x i} + \theta_{xj} + \theta_{xm} - \theta_{xn}\right) - w_{i} + w_{j} - w_{m} + w_{n}}{8 b c^{3}}\end{matrix}\right]$
The next step is to define the curvature matrix:
$[\kappa] = \begin{bmatrix} -\frac{d^2w}{dx^2} \\ -\frac{d^2w}{dy^2} \\ -\frac{2d^2w}{dxdy} \end{bmatrix} = [Q][a]$
It should be recognized that $w/[a]$ is simply the first row of our $[P]$ matrix. Evaluating the derivatives in this expression gives $[Q]$ as follows:
```python
Q = Matrix([-diff(diff(P[0, :], x), x),
-diff(diff(P[0, :], y), y),
-2*diff(diff(P[0, :], x), y)])
display(Math('[Q] = ' + latex(Q)))
print(Q)
```
$\displaystyle [Q] = \left[\begin{array}{cccccccccccc}0 & 0 & 0 & -2 & 0 & 0 & - 6 x & - 2 y & 0 & 0 & - 6 x y & 0\\0 & 0 & 0 & 0 & 0 & -2 & 0 & 0 & - 2 x & - 6 y & 0 & - 6 x y\\0 & 0 & 0 & 0 & -2 & 0 & 0 & - 4 x & - 4 y & 0 & - 6 x^{2} & - 6 y^{2}\end{array}\right]$
Matrix([[0, 0, 0, -2, 0, 0, -6*x, -2*y, 0, 0, -6*x*y, 0], [0, 0, 0, 0, 0, -2, 0, 0, -2*x, -6*y, 0, -6*x*y], [0, 0, 0, 0, -2, 0, 0, -4*x, -4*y, 0, -6*x**2, -6*y**2]])
With $[Q]$ in hand we can now solve for the $[B]$ matrix which is essential for formulating the stiffness matrix $[k]$
```python
B = simplify(Q*C.inv())
display(Math('[B] = ' + latex(B)))
```
$\displaystyle [B] = \left[\begin{array}{cccccccccccc}\frac{3 \left(2 b c - b y - 2 c x + x y\right)}{4 b^{3} c} & 0 & \frac{- 8 b c + 4 b y + 6 c x - 3 x y}{4 b^{2} c} & \frac{3 \left(- 2 b c + b y + 2 c x - x y\right)}{4 b^{3} c} & 0 & \frac{- 4 b c + 2 b y + 6 c x - 3 x y}{4 b^{2} c} & \frac{3 y \left(- b + x\right)}{4 b^{3} c} & 0 & \frac{y \left(- 2 b + 3 x\right)}{4 b^{2} c} & \frac{3 y \left(b - x\right)}{4 b^{3} c} & 0 & \frac{y \left(- 4 b + 3 x\right)}{4 b^{2} c}\\\frac{3 \left(2 b c - 2 b y - c x + x y\right)}{4 b c^{3}} & \frac{8 b c - 6 b y - 4 c x + 3 x y}{4 b c^{2}} & 0 & \frac{3 x \left(c - y\right)}{4 b c^{3}} & \frac{x \left(4 c - 3 y\right)}{4 b c^{2}} & 0 & \frac{3 x \left(- c + y\right)}{4 b c^{3}} & \frac{x \left(2 c - 3 y\right)}{4 b c^{2}} & 0 & \frac{3 \left(- 2 b c + 2 b y + c x - x y\right)}{4 b c^{3}} & \frac{4 b c - 6 b y - 2 c x + 3 x y}{4 b c^{2}} & 0\\\frac{2 b^{2} c^{2} - 6 b^{2} c y + 3 b^{2} y^{2} - 6 b c^{2} x + 3 c^{2} x^{2}}{4 b^{3} c^{3}} & \frac{c^{2} - 2 c y + \frac{3 y^{2}}{4}}{b c^{2}} & \frac{- b^{2} + 2 b x - \frac{3 x^{2}}{4}}{b^{2} c} & \frac{- 2 b^{2} c^{2} + 6 b^{2} c y - 3 b^{2} y^{2} + 6 b c^{2} x - 3 c^{2} x^{2}}{4 b^{3} c^{3}} & \frac{- c^{2} + 2 c y - \frac{3 y^{2}}{4}}{b c^{2}} & \frac{x \left(4 b - 3 x\right)}{4 b^{2} c} & \frac{2 b^{2} c^{2} - 6 b^{2} c y + 3 b^{2} y^{2} - 6 b c^{2} x + 3 c^{2} x^{2}}{4 b^{3} c^{3}} & \frac{y \left(4 c - 3 y\right)}{4 b c^{2}} & \frac{x \left(- 4 b + 3 x\right)}{4 b^{2} c} & \frac{- 2 b^{2} c^{2} + 6 b^{2} c y - 3 b^{2} y^{2} + 6 b c^{2} x - 3 c^{2} x^{2}}{4 b^{3} c^{3}} & \frac{y \left(- 4 c + 3 y\right)}{4 b c^{2}} & \frac{b^{2} - 2 b x + \frac{3 x^{2}}{4}}{b^{2} c}\end{array}\right]$
Now we form the constitutive matrix for orthotropic materials, [D]. This matrix is analagous to the flexural stiffness of a beam EI.
```python
Ex, Ey, nu_xy, nu_yx, G, t = symbols('E_x, E_y, \\nu_{xy}, \\nu_{yx}, G, t')
D = 1/(1 - nu_xy*nu_yx)*Matrix([[ Ex, nu_yx*Ex, 0 ],
[nu_xy*Ey, Ey, 0 ],
[ 0, 0, (1 - nu_xy*nu_yx)*G]])
display(Math('[D] = \\frac{t^3}{12}' + latex(D)))
print(t**3/12*D)
```
$\displaystyle [D] = \frac{t^3}{12}\left[\begin{matrix}\frac{E_{x}}{- \nu_{xy} \nu_{yx} + 1} & \frac{E_{x} \nu_{yx}}{- \nu_{xy} \nu_{yx} + 1} & 0\\\frac{E_{y} \nu_{xy}}{- \nu_{xy} \nu_{yx} + 1} & \frac{E_{y}}{- \nu_{xy} \nu_{yx} + 1} & 0\\0 & 0 & G\end{matrix}\right]$
Matrix([[E_x*t**3/(12*(-\nu_{xy}*\nu_{yx} + 1)), E_x*\nu_{yx}*t**3/(12*(-\nu_{xy}*\nu_{yx} + 1)), 0], [E_y*\nu_{xy}*t**3/(12*(-\nu_{xy}*\nu_{yx} + 1)), E_y*t**3/(12*(-\nu_{xy}*\nu_{yx} + 1)), 0], [0, 0, G*t**3/12]])
Now we can calculate the stiffness matrix:
$[k] = \int_0^{2c} \int_0^{2b} [B]^T[D][B] dx dy$
```python
k = simplify(integrate(integrate(B.T*D*B, (x, 0, 2*b)), (y, 0, 2*c)))
display(Math('[k] = \\frac{t^3}{12}' + latex(k)))
# Uncomment the line below for a version that can be copied/pasted
# Be sure to multiply by t**3/12
print(k)
```
$\displaystyle [k] = \frac{t^3}{12}\left[\begin{array}{cccccccccccc}\frac{- \frac{E_{x} \nu_{yx} b^{2} c^{2}}{4} - E_{x} c^{4} - \frac{E_{y} \nu_{xy} b^{2} c^{2}}{4} - E_{y} b^{4} + \frac{7 G \nu_{xy} \nu_{yx} b^{2} c^{2}}{5} - \frac{7 G b^{2} c^{2}}{5}}{b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} c^{2}}{2} - E_{y} b^{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{x} c^{2} + \frac{E_{y} \nu_{xy} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} + \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} \nu_{yx} b^{2} c^{2} + 20 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} - 10 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} \nu_{yx} c^{2}}{2} - \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} c^{2} - G \nu_{xy} \nu_{yx} b^{2} + G b^{2}}{5 b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{x} \nu_{yx} b^{2} c^{2} + 10 E_{x} c^{4} - 5 E_{y} \nu_{xy} b^{2} c^{2} + 10 E_{y} b^{4} + 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} - 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} \nu_{yx} b^{2} c^{2} - 10 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} + 20 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{y} b^{2} + G \nu_{xy} \nu_{yx} c^{2} - G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} c^{2}}{2} - \frac{E_{y} \nu_{xy} b^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)}\\\frac{- \frac{E_{y} \nu_{xy} c^{2}}{2} - E_{y} b^{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{4 \left(- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{y} \nu_{xy}}{\nu_{xy} \nu_{yx} - 1} & \frac{\frac{E_{y} \nu_{xy} c^{2}}{2} - \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - 4 G \nu_{xy} \nu_{yx} c^{2} + 4 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{\frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0\\\frac{\frac{E_{x} \nu_{yx} b^{2}}{2} + E_{x} c^{2} - \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} + \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{x} \nu_{yx}}{\nu_{xy} \nu_{yx} - 1} & \frac{4 \left(- 5 E_{x} c^{2} + 2 G \nu_{xy} \nu_{yx} b^{2} - 2 G b^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{x} c^{2} + G \nu_{xy} \nu_{yx} b^{2} - G b^{2}}{5 b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{2 \left(- 5 E_{x} c^{2} - G \nu_{xy} \nu_{yx} b^{2} + G b^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- 5 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} b^{2}}{2} + \frac{E_{x} c^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} - \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & - \frac{10 E_{x} c^{2} + 8 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)}\\\frac{5 E_{x} \nu_{yx} b^{2} c^{2} + 20 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} - 10 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} \nu_{yx} c^{2}}{2} - \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{x} c^{2} + G \nu_{xy} \nu_{yx} b^{2} - G b^{2}}{5 b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} b^{2} c^{2}}{4} - E_{x} c^{4} - \frac{E_{y} \nu_{xy} b^{2} c^{2}}{4} - E_{y} b^{4} + \frac{7 G \nu_{xy} \nu_{yx} b^{2} c^{2}}{5} - \frac{7 G b^{2} c^{2}}{5}}{b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} c^{2}}{2} - E_{y} b^{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- E_{x} c^{2} - \frac{E_{y} \nu_{xy} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} - \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} \nu_{yx} b^{2} c^{2} - 10 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} + 20 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{y} b^{2} + G \nu_{xy} \nu_{yx} c^{2} - G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} c^{2}}{2} + \frac{E_{y} \nu_{xy} b^{2}}{2} - \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{x} \nu_{yx} b^{2} c^{2} + 10 E_{x} c^{4} - 5 E_{y} \nu_{xy} b^{2} c^{2} + 10 E_{y} b^{4} + 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} - 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)}\\\frac{\frac{E_{y} \nu_{xy} c^{2}}{2} - \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - 4 G \nu_{xy} \nu_{yx} c^{2} + 4 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- \frac{E_{y} \nu_{xy} c^{2}}{2} - E_{y} b^{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{4 \left(- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{E_{y} \nu_{xy}}{\nu_{xy} \nu_{yx} - 1} & \frac{5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{\frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0\\\frac{5 E_{x} c^{2} - G \nu_{xy} \nu_{yx} b^{2} + G b^{2}}{5 b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{2 \left(- 5 E_{x} c^{2} - G \nu_{xy} \nu_{yx} b^{2} + G b^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} b^{2}}{2} - E_{x} c^{2} + \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} - \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{E_{x} \nu_{yx}}{\nu_{xy} \nu_{yx} - 1} & \frac{4 \left(- 5 E_{x} c^{2} + 2 G \nu_{xy} \nu_{yx} b^{2} - 2 G b^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} \nu_{yx} b^{2}}{2} - \frac{E_{x} c^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} + \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & - \frac{10 E_{x} c^{2} + 8 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- 5 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)}\\\frac{- 5 E_{x} \nu_{yx} b^{2} c^{2} + 10 E_{x} c^{4} - 5 E_{y} \nu_{xy} b^{2} c^{2} + 10 E_{y} b^{4} + 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} - 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} \nu_{yx} b^{2} c^{2} - 10 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} + 20 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{x} c^{2} - 25 E_{y} \nu_{xy} b^{2} + 2 b^{2} \left(15 E_{y} \nu_{xy} - G \nu_{xy} \nu_{yx} + G\right)}{10 b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} b^{2} c^{2}}{4} - E_{x} c^{4} - \frac{E_{y} \nu_{xy} b^{2} c^{2}}{4} - E_{y} b^{4} + \frac{7 G \nu_{xy} \nu_{yx} b^{2} c^{2}}{5} - \frac{7 G b^{2} c^{2}}{5}}{b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} \nu_{yx} c^{2}}{2} + E_{y} b^{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- E_{x} c^{2} - \frac{E_{y} \nu_{xy} b^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} \nu_{yx} b^{2} c^{2} + 20 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} - 10 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} c^{2}}{2} + \frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- E_{x} c^{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)}\\\frac{- \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- 5 E_{y} b^{2} + G \nu_{xy} \nu_{yx} c^{2} - G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{\frac{E_{y} \nu_{xy} c^{2}}{2} + E_{y} b^{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{4 \left(- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{y} \nu_{xy}}{\nu_{xy} \nu_{yx} - 1} & \frac{- \frac{E_{y} \nu_{xy} c^{2}}{2} + \frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - 4 G \nu_{xy} \nu_{yx} c^{2} + 4 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0\\\frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- 5 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} \nu_{yx} b^{2}}{2} - \frac{E_{x} c^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} + \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & - \frac{10 E_{x} c^{2} + 8 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} b^{2}}{2} - E_{x} c^{2} + \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} - \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{x} \nu_{yx}}{\nu_{xy} \nu_{yx} - 1} & \frac{4 \left(- 5 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{x} c^{2} - \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & - \frac{10 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)}\\\frac{5 E_{x} \nu_{yx} b^{2} c^{2} - 10 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} + 20 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} c^{2} + 25 E_{y} \nu_{xy} b^{2} - 2 b^{2} \left(15 E_{y} \nu_{xy} - G \nu_{xy} \nu_{yx} + G\right)}{10 b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{x} \nu_{yx} b^{2} c^{2} + 10 E_{x} c^{4} - 5 E_{y} \nu_{xy} b^{2} c^{2} + 10 E_{y} b^{4} + 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} - 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{5 E_{x} \nu_{yx} b^{2} c^{2} + 20 E_{x} c^{4} + 5 E_{y} \nu_{xy} b^{2} c^{2} - 10 E_{y} b^{4} - 28 G \nu_{xy} \nu_{yx} b^{2} c^{2} + 28 G b^{2} c^{2}}{20 b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} c^{2}}{2} + \frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{x} c^{2} - \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- \frac{E_{x} \nu_{yx} b^{2} c^{2}}{4} - E_{x} c^{4} - \frac{E_{y} \nu_{xy} b^{2} c^{2}}{4} - E_{y} b^{4} + \frac{7 G \nu_{xy} \nu_{yx} b^{2} c^{2}}{5} - \frac{7 G b^{2} c^{2}}{5}}{b^{3} c^{3} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} \nu_{yx} c^{2}}{2} + E_{y} b^{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{E_{x} c^{2} + \frac{E_{y} \nu_{xy} b^{2}}{2} - \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)}\\\frac{- 5 E_{y} b^{2} + G \nu_{xy} \nu_{yx} c^{2} - G c^{2}}{5 b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - G \nu_{xy} \nu_{yx} c^{2} + G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- \frac{E_{y} b^{2}}{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- \frac{E_{y} \nu_{xy} c^{2}}{2} + \frac{E_{y} b^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} - \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{2 \left(- 5 E_{y} b^{2} - 4 G \nu_{xy} \nu_{yx} c^{2} + 4 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{\frac{E_{y} \nu_{xy} c^{2}}{2} + E_{y} b^{2} - \frac{G \nu_{xy} \nu_{yx} c^{2}}{5} + \frac{G c^{2}}{5}}{b c^{2} \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{4 \left(- 5 E_{y} b^{2} + 2 G \nu_{xy} \nu_{yx} c^{2} - 2 G c^{2}\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{E_{y} \nu_{xy}}{\nu_{xy} \nu_{yx} - 1}\\\frac{- \frac{E_{x} \nu_{yx} b^{2}}{2} + \frac{E_{x} c^{2}}{2} + \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} - \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & - \frac{10 E_{x} c^{2} + 8 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{\frac{E_{x} c^{2}}{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & \frac{- 5 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{- E_{x} c^{2} + \frac{G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & 0 & - \frac{10 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)} & \frac{\frac{E_{x} \nu_{yx} b^{2}}{2} + E_{x} c^{2} - \frac{G \nu_{xy} \nu_{yx} b^{2}}{5} + \frac{G b^{2}}{5}}{b^{2} c \left(\nu_{xy} \nu_{yx} - 1\right)} & - \frac{E_{x} \nu_{yx}}{\nu_{xy} \nu_{yx} - 1} & \frac{4 \left(- 5 E_{x} c^{2} + 2 G b^{2} \left(\nu_{xy} \nu_{yx} - 1\right)\right)}{15 b c \left(\nu_{xy} \nu_{yx} - 1\right)}\end{array}\right]$
Matrix([[(-E_x*\nu_{yx}*b**2*c**2/4 - E_x*c**4 - E_y*\nu_{xy}*b**2*c**2/4 - E_y*b**4 + 7*G*\nu_{xy}*\nu_{yx}*b**2*c**2/5 - 7*G*b**2*c**2/5)/(b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*c**2/2 - E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2 + E_y*\nu_{xy}*b**2/2 - G*\nu_{xy}*\nu_{yx}*b**2/5 + G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*\nu_{yx}*b**2*c**2 + 20*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 - 10*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (E_x*\nu_{yx}*c**2/2 - E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*c**2 - G*\nu_{xy}*\nu_{yx}*b**2 + G*b**2)/(5*b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_x*\nu_{yx}*b**2*c**2 + 10*E_x*c**4 - 5*E_y*\nu_{xy}*b**2*c**2 + 10*E_y*b**4 + 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 - 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*\nu_{yx}*b**2*c**2 - 10*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 + 20*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2 - G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2/2 - E_y*\nu_{xy}*b**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1))], [(-E_y*\nu_{xy}*c**2/2 - E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 4*(-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), E_y*\nu_{xy}/(\nu_{xy}*\nu_{yx} - 1), (E_y*\nu_{xy}*c**2/2 - E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - 4*G*\nu_{xy}*\nu_{yx}*c**2 + 4*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0], [(E_x*\nu_{yx}*b**2/2 + E_x*c**2 - G*\nu_{xy}*\nu_{yx}*b**2/5 + G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), E_x*\nu_{yx}/(\nu_{xy}*\nu_{yx} - 1), 4*(-5*E_x*c**2 + 2*G*\nu_{xy}*\nu_{yx}*b**2 - 2*G*b**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_x*c**2 + G*\nu_{xy}*\nu_{yx}*b**2 - G*b**2)/(5*b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, 2*(-5*E_x*c**2 - G*\nu_{xy}*\nu_{yx}*b**2 + G*b**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), -(E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-5*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*b**2/2 + E_x*c**2/2 + G*\nu_{xy}*\nu_{yx}*b**2/5 - G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, -(10*E_x*c**2 + 8*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1))], [(5*E_x*\nu_{yx}*b**2*c**2 + 20*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 - 10*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (E_x*\nu_{yx}*c**2/2 - E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_x*c**2 + G*\nu_{xy}*\nu_{yx}*b**2 - G*b**2)/(5*b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*b**2*c**2/4 - E_x*c**4 - E_y*\nu_{xy}*b**2*c**2/4 - E_y*b**4 + 7*G*\nu_{xy}*\nu_{yx}*b**2*c**2/5 - 7*G*b**2*c**2/5)/(b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*c**2/2 - E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*c**2 - E_y*\nu_{xy}*b**2/2 + G*\nu_{xy}*\nu_{yx}*b**2/5 - G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*\nu_{yx}*b**2*c**2 - 10*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 + 20*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2 - G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*c**2/2 + E_y*\nu_{xy}*b**2/2 - G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_x*\nu_{yx}*b**2*c**2 + 10*E_x*c**4 - 5*E_y*\nu_{xy}*b**2*c**2 + 10*E_y*b**4 + 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 - 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), -(E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1))], [(E_y*\nu_{xy}*c**2/2 - E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - 4*G*\nu_{xy}*\nu_{yx}*c**2 + 4*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-E_y*\nu_{xy}*c**2/2 - E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 4*(-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), -E_y*\nu_{xy}/(\nu_{xy}*\nu_{yx} - 1), (5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0], [(5*E_x*c**2 - G*\nu_{xy}*\nu_{yx}*b**2 + G*b**2)/(5*b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, 2*(-5*E_x*c**2 - G*\nu_{xy}*\nu_{yx}*b**2 + G*b**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*b**2/2 - E_x*c**2 + G*\nu_{xy}*\nu_{yx}*b**2/5 - G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), -E_x*\nu_{yx}/(\nu_{xy}*\nu_{yx} - 1), 4*(-5*E_x*c**2 + 2*G*\nu_{xy}*\nu_{yx}*b**2 - 2*G*b**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (E_x*\nu_{yx}*b**2/2 - E_x*c**2/2 - G*\nu_{xy}*\nu_{yx}*b**2/5 + G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, -(10*E_x*c**2 + 8*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-5*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1))], [(-5*E_x*\nu_{yx}*b**2*c**2 + 10*E_x*c**4 - 5*E_y*\nu_{xy}*b**2*c**2 + 10*E_y*b**4 + 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 - 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), -(E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*\nu_{yx}*b**2*c**2 - 10*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 + 20*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_x*c**2 - 25*E_y*\nu_{xy}*b**2 + 2*b**2*(15*E_y*\nu_{xy} - G*\nu_{xy}*\nu_{yx} + G))/(10*b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*b**2*c**2/4 - E_x*c**4 - E_y*\nu_{xy}*b**2*c**2/4 - E_y*b**4 + 7*G*\nu_{xy}*\nu_{yx}*b**2*c**2/5 - 7*G*b**2*c**2/5)/(b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (E_x*\nu_{yx}*c**2/2 + E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*c**2 - E_y*\nu_{xy}*b**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*\nu_{yx}*b**2*c**2 + 20*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 - 10*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*c**2/2 + E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*c**2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1))], [(-E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-5*E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2 - G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (E_y*\nu_{xy}*c**2/2 + E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 4*(-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), E_y*\nu_{xy}/(\nu_{xy}*\nu_{yx} - 1), (-E_y*\nu_{xy}*c**2/2 + E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - 4*G*\nu_{xy}*\nu_{yx}*c**2 + 4*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0], [(E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-5*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (E_x*\nu_{yx}*b**2/2 - E_x*c**2/2 - G*\nu_{xy}*\nu_{yx}*b**2/5 + G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, -(10*E_x*c**2 + 8*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*b**2/2 - E_x*c**2 + G*\nu_{xy}*\nu_{yx}*b**2/5 - G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), E_x*\nu_{yx}/(\nu_{xy}*\nu_{yx} - 1), 4*(-5*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2 - G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, -(10*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1))], [(5*E_x*\nu_{yx}*b**2*c**2 - 10*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 + 20*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*c**2 + 25*E_y*\nu_{xy}*b**2 - 2*b**2*(15*E_y*\nu_{xy} - G*\nu_{xy}*\nu_{yx} + G))/(10*b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_x*\nu_{yx}*b**2*c**2 + 10*E_x*c**4 - 5*E_y*\nu_{xy}*b**2*c**2 + 10*E_y*b**4 + 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 - 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (5*E_x*\nu_{yx}*b**2*c**2 + 20*E_x*c**4 + 5*E_y*\nu_{xy}*b**2*c**2 - 10*E_y*b**4 - 28*G*\nu_{xy}*\nu_{yx}*b**2*c**2 + 28*G*b**2*c**2)/(20*b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*c**2/2 + E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2 - G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*\nu_{yx}*b**2*c**2/4 - E_x*c**4 - E_y*\nu_{xy}*b**2*c**2/4 - E_y*b**4 + 7*G*\nu_{xy}*\nu_{yx}*b**2*c**2/5 - 7*G*b**2*c**2/5)/(b**3*c**3*(\nu_{xy}*\nu_{yx} - 1)), (E_x*\nu_{yx}*c**2/2 + E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (E_x*c**2 + E_y*\nu_{xy}*b**2/2 - G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1))], [(-5*E_y*b**2 + G*\nu_{xy}*\nu_{yx}*c**2 - G*c**2)/(5*b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2 + G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-E_y*b**2/2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), (-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-E_y*\nu_{xy}*c**2/2 + E_y*b**2/2 + G*\nu_{xy}*\nu_{yx}*c**2/5 - G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 2*(-5*E_y*b**2 - 4*G*\nu_{xy}*\nu_{yx}*c**2 + 4*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (E_y*\nu_{xy}*c**2/2 + E_y*b**2 - G*\nu_{xy}*\nu_{yx}*c**2/5 + G*c**2/5)/(b*c**2*(\nu_{xy}*\nu_{yx} - 1)), 4*(-5*E_y*b**2 + 2*G*\nu_{xy}*\nu_{yx}*c**2 - 2*G*c**2)/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), -E_y*\nu_{xy}/(\nu_{xy}*\nu_{yx} - 1)], [(-E_x*\nu_{yx}*b**2/2 + E_x*c**2/2 + G*\nu_{xy}*\nu_{yx}*b**2/5 - G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, -(10*E_x*c**2 + 8*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), -(E_x*c**2/2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, (-5*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (-E_x*c**2 + G*b**2*(\nu_{xy}*\nu_{yx} - 1)/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), 0, -(10*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1)), (E_x*\nu_{yx}*b**2/2 + E_x*c**2 - G*\nu_{xy}*\nu_{yx}*b**2/5 + G*b**2/5)/(b**2*c*(\nu_{xy}*\nu_{yx} - 1)), -E_x*\nu_{yx}/(\nu_{xy}*\nu_{yx} - 1), 4*(-5*E_x*c**2 + 2*G*b**2*(\nu_{xy}*\nu_{yx} - 1))/(15*b*c*(\nu_{xy}*\nu_{yx} - 1))]])
The surface force matrix $[F_s]$ can be obtained from the shape function matrix. Since we're interested in the surface force matrix for uniform pressures in the direction of w,
```python
q = symbols('q')
Fs = integrate(integrate(N[0, :].T*q, (x, 0, 2*b)), (y, 0, 2*c))
display(Math('[F_s] = 4qcb' + latex(Fs/(4*q*c*b))))
# Uncomment the line below for a version that can be copied/pasted
print(Fs)
```
$\displaystyle [F_s] = 4qcb\left[\begin{matrix}\frac{1}{4}\\\frac{c}{12}\\- \frac{b}{12}\\\frac{1}{4}\\\frac{c}{12}\\\frac{b}{12}\\\frac{1}{4}\\- \frac{c}{12}\\\frac{b}{12}\\\frac{1}{4}\\- \frac{c}{12}\\- \frac{b}{12}\end{matrix}\right]$
Matrix([[b*c*q], [b*c**2*q/3], [-b**2*c*q/3], [b*c*q], [b*c**2*q/3], [b**2*c*q/3], [b*c*q], [-b*c**2*q/3], [b**2*c*q/3], [b*c*q], [-b*c**2*q/3], [-b**2*c*q/3]])
## Membrane Action
### Shape Functions
```python
from sympy import factor, symbols
r, s = symbols('r, s')
h1 = factor(1/4*(1-r)*(1-s))
h2 = factor(1/4*(1+r)*(1-s))
h3 = factor(1/4*(1+r)*(1+s))
h4 = factor(1/4*(1-r)*(1+s))
```
```python
x1, y1, x2, y2, x3, y3, x4, y4 = symbols('x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4')
x = h1*x1 + h2*x2 + h3*x3 + h4*x4
y = h1*y1 + h2*y2 + h3*y3 + h4*y4
```
```python
J = Matrix([[diff(x, r), diff(y, r)],
[diff(x, s), diff(y, s)]])
display(Math('J = (1/4)' + latex(factor(J*4))))
print(J*4)
```
$\displaystyle J = (1/4)\left[\begin{matrix}x_{1} \left(s - 1\right) - 1.0 x_{2} \left(s - 1\right) + x_{3} \left(s + 1\right) - 1.0 x_{4} \left(s + 1\right) & y_{1} \left(s - 1\right) - 1.0 y_{2} \left(s - 1\right) + y_{3} \left(s + 1\right) - 1.0 y_{4} \left(s + 1\right)\\x_{1} \left(r - 1\right) - 1.0 x_{2} \left(r + 1\right) + x_{3} \left(r + 1\right) - 1.0 x_{4} \left(r - 1\right) & y_{1} \left(r - 1\right) - 1.0 y_{2} \left(r + 1\right) + y_{3} \left(r + 1\right) - 1.0 y_{4} \left(r - 1\right)\end{matrix}\right]$
Matrix([[x_1*(s - 1) - 1.0*x_2*(s - 1) + x_3*(s + 1) - 1.0*x_4*(s + 1), y_1*(s - 1) - 1.0*y_2*(s - 1) + y_3*(s + 1) - 1.0*y_4*(s + 1)], [x_1*(r - 1) - 1.0*x_2*(r + 1) + x_3*(r + 1) - 1.0*x_4*(r - 1), y_1*(r - 1) - 1.0*y_2*(r + 1) + y_3*(r + 1) - 1.0*y_4*(r - 1)]])
```python
print(4*diff(h1, r))
print(4*diff(h2, r))
print(4*diff(h3, r))
print(4*diff(h4, r))
```
s - 1.0
1.0 - 1.0*s
s + 1.0
-1.0*s - 1.0
```python
```
|
\section{Limitations \& Future Work}
|
function t_om_solve_qps(quiet)
%T_OM_SOLVE_QPS Tests of QP solvers via OM.SOLVE().
% MP-Opt-Model
% Copyright (c) 2010-2020, Power Systems Engineering Research Center (PSERC)
% by Ray Zimmerman, PSERC Cornell
%
% This file is part of MP-Opt-Model.
% Covered by the 3-clause BSD License (see LICENSE file for details).
% See https://github.com/MATPOWER/mp-opt-model for more info.
if nargin < 1
quiet = 0;
end
algs = {'DEFAULT', 'BPMPD', 'MIPS', 250, 'IPOPT', 'OT', 'CPLEX', 'MOSEK', 'GUROBI', 'CLP', 'GLPK', 'OSQP'};
names = {'DEFAULT', 'BPMPD_MEX', 'MIPS', 'sc-MIPS', 'IPOPT', 'linprog/quadprog', 'CPLEX', 'MOSEK', 'Gurobi', 'CLP', 'glpk', 'OSQP'};
check = {[], 'bpmpd', [], [], 'ipopt', 'quadprog', 'cplex', 'mosek', 'gurobi', 'clp', 'glpk', 'osqp'};
does_qp = [1 1 1 1 1 1 1 1 1 1 0 1];
n = 30;
nqp = 21;
t_begin(27+n*length(algs), quiet);
diff_alg_warn_id = 'optim:linprog:WillRunDiffAlg';
if have_feature('quadprog') && have_feature('quadprog', 'vnum') == 7.005
s1 = warning('query', diff_alg_warn_id);
warning('off', diff_alg_warn_id);
end
for k = 1:length(algs)
if ~isempty(check{k}) && ~have_feature(check{k})
t_skip(n, sprintf('%s not installed', names{k}));
else
opt = struct('verbose', 0, 'alg', algs{k});
mpopt = struct( ...
'verbose', 0, ...
'opf', struct( ...
'violation', 5e-6 ), ...
'cplex', struct( ...
'lpmethod', 0, ...
'qpmethod', 0, ...
'opt', 0 ), ...
'mosek', struct( ...
'lp_alg', 0, ...
'max_it', 0, ...
'gap_tol', 0, ...
'max_time', 0, ...
'num_threads', 0, ...
'opt', 0 ) ...
);
switch names{k}
case {'DEFAULT', 'MIPS', 'sc-MIPS'}
opt.mips_opt.comptol = 1e-8;
% case 'linprog/quadprog'
% opt.verbose = 2;
% opt.linprog_opt.Algorithm = 'interior-point';
% opt.linprog_opt.Algorithm = 'active-set';
% opt.linprog_opt.Algorithm = 'simplex';
% opt.linprog_opt.Algorithm = 'dual-simplex';
% end
case 'CPLEX'
% alg = 0; %% default uses barrier method with NaN bug in lower lim multipliers
alg = 2; %% use dual simplex
mpopt.cplex.lpmethod = alg;
mpopt.cplex.qpmethod = min([4 alg]);
opt.cplex_opt = cplex_options([], mpopt);
case 'MOSEK'
% sc = mosek_symbcon;
% alg = sc.MSK_OPTIMIZER_DUAL_SIMPLEX; %% use dual simplex
% alg = sc.MSK_OPTIMIZER_INTPNT; %% use interior point
% mpopt.mosek.lp_alg = alg;
mpopt.mosek.gap_tol = 1e-10;
% mpopt.mosek.opts.MSK_DPAR_INTPNT_TOL_PFEAS = 1e-10;
% mpopt.mosek.opts.MSK_DPAR_INTPNT_TOL_DFEAS = 1e-10;
% mpopt.mosek.opts.MSK_DPAR_INTPNT_TOL_INFEAS = 1e-10;
% mpopt.mosek.opts.MSK_DPAR_INTPNT_TOL_REL_GAP = 1e-10;
vnum = have_feature('mosek', 'vnum');
if vnum >= 8
% mpopt.mosek.opts.MSK_DPAR_INTPNT_QO_TOL_PFEAS = 1e-10;
% mpopt.mosek.opts.MSK_DPAR_INTPNT_QO_TOL_DFEAS = 1e-10;
% mpopt.mosek.opts.MSK_DPAR_INTPNT_QO_TOL_INFEAS = 1e-10;
% mpopt.mosek.opts.MSK_DPAR_INTPNT_QO_TOL_MU_RED = 1e-10;
mpopt.mosek.opts.MSK_DPAR_INTPNT_QO_TOL_REL_GAP = 1e-10;
end
% opt.verbose = 3;
opt.mosek_opt = mosek_options([], mpopt);
case 'OSQP'
opt.osqp_opt.polish = 1;
% opt.osqp_opt.alpha = 1;
% opt.osqp_opt.eps_abs = 1e-8;
% opt.osqp_opt.eps_rel = 1e-10;
% opt.osqp_opt.eps_prim_inf = 1e-8;
% opt.osqp_opt.eps_dual_inf = 1e-8;
end
t = sprintf('%s - 3-d LP : ', names{k});
%% based on example from 'doc linprog'
c = [-5; -4; -6];
A = [1 -1 1;
-3 -2 -4;
3 2 0];
l = [-Inf; -42; -Inf];
u = [20; Inf; 30];
xmin = [0; 0; 0];
x0 = [];
om = opt_model;
om.add_var('x', 3, x0, xmin);
om.add_quad_cost('c', [], c);
om.add_lin_constraint('Ax', A, l, u);
[x, f, s, out, lam] = om.solve(opt);
t_is(s, 1, 12, [t 'success']);
t_is(x, [0; 15; 3], 6, [t 'x']);
t_is(f, -78, 6, [t 'f']);
t_is(lam.mu_l, [0;1.5;0], 9, [t 'lam.mu_l']);
t_is(lam.mu_u, [0;0;0.5], 9, [t 'lam.mu_u']);
if strcmp(algs{k}, 'CLP') && ~have_feature('opti_clp')
t_skip(2, [t 'lam.lower/upper : MEXCLP does not return multipliers on var bounds']);
else
t_is(lam.lower, [1;0;0], 9, [t 'lam.lower']);
t_is(lam.upper, zeros(size(x)), 9, [t 'lam.upper']);
end
t_ok(~isfield(om.soln, 'var'), [t 'no parse_soln() outputs']);
if does_qp(k)
t = sprintf('%s - unconstrained 3-d quadratic : ', names{k});
%% from http://www.akiti.ca/QuadProgEx0Constr.html
H = [5 -2 -1; -2 4 3; -1 3 5];
c = [2; -35; -47];
x0 = [0; 0; 0];
om = opt_model;
om.add_var('x', 3, x0);
om.add_quad_cost('c', H, c);
[x, f, s, out, lam] = om.solve(opt);
t_is(s, 1, 12, [t 'success']);
t_is(x, [3; 5; 7], 7, [t 'x']);
t_is(f, -249, 11, [t 'f']);
t_ok(isempty(lam.mu_l), [t 'lam.mu_l']);
t_ok(isempty(lam.mu_u), [t 'lam.mu_u']);
t_is(lam.lower, zeros(size(x)), 13, [t 'lam.lower']);
t_is(lam.upper, zeros(size(x)), 13, [t 'lam.upper']);
t = sprintf('%s - constrained 2-d QP : ', names{k});
%% example from 'doc quadprog'
H = [ 1 -1;
-1 2 ];
c = [-2; -6];
A = [ 1 1;
-1 2;
2 1 ];
l = [];
u = [2; 2; 3];
xmin = [0; 0];
x0 = [];
om = opt_model;
om.add_var('x', 2, x0, xmin);
om.add_quad_cost('c', H, c);
om.add_lin_constraint('Ax', A, l, u);
[x, f, s, out, lam] = om.solve(opt);
t_is(s, 1, 12, [t 'success']);
t_is(x, [2; 4]/3, 7, [t 'x']);
t_is(f, -74/9, 6, [t 'f']);
t_is(lam.mu_l, [0;0;0], 13, [t 'lam.mu_l']);
t_is(lam.mu_u, [28;4;0]/9, 4, [t 'lam.mu_u']);
if strcmp(algs{k}, 'CLP') && ~have_feature('opti_clp')
t_skip(2, [t 'lam.lower/upper : MEXCLP does not return multipliers on var bounds']);
else
t_is(lam.lower, zeros(size(x)), 7, [t 'lam.lower']);
t_is(lam.upper, zeros(size(x)), 13, [t 'lam.upper']);
end
t = sprintf('%s - constrained 4-d QP : ', names{k});
%% from https://v8doc.sas.com/sashtml/iml/chap8/sect12.htm
H = [ 1003.1 4.3 6.3 5.9;
4.3 2.2 2.1 3.9;
6.3 2.1 3.5 4.8;
5.9 3.9 4.8 10 ];
c = zeros(4,1);
A = [ 1 1 1 1;
0.17 0.11 0.10 0.18 ];
l = [1; 0.10];
u = [1; Inf];
xmin = zeros(4,1);
x0 = [1; 0; 0; 1];
om = opt_model;
om.add_var('x', 4, x0, xmin);
om.add_quad_cost('c', H, c);
om.add_lin_constraint('Ax', A, l, u);
[x, f, s, out, lam] = om.solve(opt);
t_is(s, 1, 12, [t 'success']);
t_is(x, [0; 2.8; 0.2; 0]/3, 5, [t 'x']);
t_is(f, 3.29/3, 6, [t 'f']);
t_is(lam.mu_l, [6.58;0]/3, 6, [t 'lam.mu_l']);
t_is(lam.mu_u, [0;0], 13, [t 'lam.mu_u']);
if strcmp(algs{k}, 'CLP') && ~have_feature('opti_clp')
t_skip(2, [t 'lam.lower/upper : MEXCLP does not return multipliers on var bounds']);
else
t_is(lam.lower, [2.24;0;0;1.7667], 4, [t 'lam.lower']);
t_is(lam.upper, zeros(size(x)), 13, [t 'lam.upper']);
end
else
t_skip(nqp, sprintf('%s does not handle QP problems', names{k}));
end
t = sprintf('%s - infeasible LP : ', names{k});
p = struct('A', sparse([1 1]), 'c', [1;1], 'u', -1, 'xmin', [0;0], 'opt', opt);
[x, f, s, out, lam] = qps_master(p);
t_ok(s <= 0, [t 'no success']);
end
end
t = 'om.soln.';
opt.alg = 'DEFAULT';
%% from https://v8doc.sas.com/sashtml/iml/chap8/sect12.htm
H = [ 1003.1 4.3 6.3 5.9;
4.3 2.2 2.1 3.9;
6.3 2.1 3.5 4.8;
5.9 3.9 4.8 10 ];
c = zeros(4,1);
A = [ 1 1 1 1;
0.17 0.11 0.10 0.18 ];
l = [1; 0.10];
u = [1; Inf];
xmin = zeros(4,1);
x0 = [1; 0; 0; 1];
om = opt_model;
om.add_var('x', 4, x0, xmin);
om.add_quad_cost('c', H, c);
om.add_lin_constraint('Ax', A, l, u);
opt.parse_soln = 1;
[x, f, s, out, lam] = om.solve(opt);
t_is(om.soln.x, x, 14, [t 'x']);
t_is(om.soln.f, f, 14, [t 'f']);
t_is(om.soln.eflag, s, 14, [t 'eflag']);
t_str_match(om.soln.output.alg, out.alg, [t 'output.alg']);
t_is(om.soln.lambda.lower, lam.lower, 14, [t 'om.soln.lambda.lower']);
t_is(om.soln.lambda.upper, lam.upper, 14, [t 'om.soln.lambda.upper']);
t_is(om.soln.lambda.mu_l, lam.mu_l, 14, [t 'om.soln.lambda.mu_l']);
t_is(om.soln.lambda.mu_u, lam.mu_u, 14, [t 'om.soln.lambda.mu_u']);
t = 'om.get_soln(''var'', ''x'') : ';
[x1, mu_l, mu_u] = om.get_soln('var', 'x');
t_is(x1, x, 14, [t 'x']);
t_is(mu_l, lam.lower, 14, [t 'mu_l']);
t_is(mu_u, lam.upper, 14, [t 'mu_u']);
t = 'om.get_soln(''var'', ''mu_l'', ''x'') : ';
t_is(om.get_soln('var', 'mu_l', 'x'), lam.lower, 14, [t 'mu_l']);
t = 'om.get_soln(''lin'', ''Ax'') : ';
[g, mu_l] = om.get_soln('lin', 'Ax');
t_is(g{1}, A*x-u, 14, [t 'A * x - u']);
t_is(g{2}, l-A*x, 14, [t 'l - A * x']);
t_is(mu_l, lam.mu_l, 14, [t 'mu_l']);
t = 'om.get_soln(''lin'', {''mu_u'', ''mu_l'', ''Ax_u''}, ''Ax'') : ';
[mu_u, mu_l, g] = om.get_soln('lin', {'mu_u', 'mu_l', 'Ax_u'}, 'Ax');
t_is(g, A*x-u, 14, [t 'A * x - u']);
t_is(mu_l, lam.mu_l, 14, [t 'mu_l']);
t_is(mu_u, lam.mu_u, 14, [t 'mu_u']);
t = 'om.get_soln(''qdc'', ''c'') : ';
[f1, df, d2f] = om.get_soln('qdc', 'c');
t_is(f1, f, 14, [t 'f']);
t_is(df, H*x+c, 14, [t 'df']);
t_is(d2f, H, 14, [t 'd2f']);
t = 'om.get_soln(''qdc'', ''df'', ''c'') : ';
df = om.get_soln('qdc', 'df', 'c');
t_is(df, H*x+c, 14, [t 'df']);
t = 'parse_soln : ';
t_is(om.soln.var.val.x, om.get_soln('var', 'x'), 14, [t 'var.val.x']);
t_is(om.soln.var.mu_l.x, om.get_soln('var', 'mu_l', 'x'), 14, [t 'var.mu_l.x']);
t_is(om.soln.var.mu_u.x, om.get_soln('var', 'mu_u', 'x'), 14, [t 'var.mu_u.x']);
t_is(om.soln.lin.mu_l.Ax, om.get_soln('lin', 'mu_l', 'Ax'), 14, [t 'lin.mu_l.Ax']);
t_is(om.soln.lin.mu_u.Ax, om.get_soln('lin', 'mu_u', 'Ax'), 14, [t 'lin.mu_u.Ax']);
if have_feature('quadprog') && have_feature('quadprog', 'vnum') == 7.005
warning(s1.state, diff_alg_warn_id);
end
t_end;
|
(* *********************************************************************)
(* *)
(* The Compcert verified compiler *)
(* *)
(* Xavier Leroy, INRIA Paris-Rocquencourt *)
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
(* Automatique. All rights reserved. This file is distributed *)
(* under the terms of the INRIA Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(** Proof of type preservation for Reload and of
correctness of computation of stack bounds for Linear. *)
Require Import Coqlib.
Require Import AST.
Require Import Op.
Require Import Locations.
Require Import LTLin.
Require Import LTLintyping.
Require Import Linear.
Require Import Lineartyping.
Require Import Conventions.
Require Import Parallelmove.
Require Import Reload.
Require Import Reloadproof.
(** * Typing Linear constructors *)
(** We show that the Linear constructor functions defined in [Reload]
generate well-typed instruction sequences,
given sufficient typing and well-formedness hypotheses over the locations involved. *)
Hint Constructors wt_instr: reloadty.
Remark wt_code_cons:
forall f i c, wt_instr f i -> wt_code f c -> wt_code f (i :: c).
Proof.
intros; red; simpl; intros. elim H1; intro.
subst i; auto. auto.
Qed.
Hint Resolve wt_code_cons: reloadty.
Definition loc_valid (f: function) (l: loc) :=
match l with R _ => True | S s => slot_valid f s end.
Lemma loc_acceptable_valid:
forall f l, loc_acceptable l -> loc_valid f l.
Proof.
destruct l; simpl; intro. auto.
destruct s; simpl. omega. tauto. tauto.
Qed.
Definition loc_writable (l: loc) :=
match l with R _ => True | S s => slot_writable s end.
Lemma loc_acceptable_writable:
forall l, loc_acceptable l -> loc_writable l.
Proof.
destruct l; simpl; intro. auto.
destruct s; simpl; tauto.
Qed.
Hint Resolve loc_acceptable_valid loc_acceptable_writable: reloadty.
Definition locs_valid (f: function) (ll: list loc) :=
forall l, In l ll -> loc_valid f l.
Definition locs_writable (ll: list loc) :=
forall l, In l ll -> loc_writable l.
Lemma locs_acceptable_valid:
forall f ll, locs_acceptable ll -> locs_valid f ll.
Proof.
unfold locs_acceptable, locs_valid. auto with reloadty.
Qed.
Lemma locs_acceptable_writable:
forall ll, locs_acceptable ll -> locs_writable ll.
Proof.
unfold locs_acceptable, locs_writable. auto with reloadty.
Qed.
Hint Resolve locs_acceptable_valid locs_acceptable_writable: reloadty.
Lemma wt_add_reload:
forall f src dst k,
loc_valid f src -> Loc.type src = mreg_type dst ->
wt_code f k -> wt_code f (add_reload src dst k).
Proof.
intros; unfold add_reload.
destruct src; eauto with reloadty.
destruct (mreg_eq m dst); eauto with reloadty.
Qed.
Hint Resolve wt_add_reload: reloadty.
Lemma wt_add_reloads:
forall f srcs dsts k,
locs_valid f srcs -> map Loc.type srcs = map mreg_type dsts ->
wt_code f k -> wt_code f (add_reloads srcs dsts k).
Proof.
induction srcs; destruct dsts; simpl; intros; try congruence.
auto. inv H0. apply wt_add_reload; auto with coqlib reloadty.
apply IHsrcs; auto. red; intros; auto with coqlib.
Qed.
Hint Resolve wt_add_reloads: reloadty.
Lemma wt_add_spill:
forall f src dst k,
loc_valid f dst -> loc_writable dst -> Loc.type dst = mreg_type src ->
wt_code f k -> wt_code f (add_spill src dst k).
Proof.
intros; unfold add_spill.
destruct dst; eauto with reloadty.
destruct (mreg_eq src m); eauto with reloadty.
Qed.
Hint Resolve wt_add_spill: reloadty.
Lemma wt_add_move:
forall f src dst k,
loc_valid f src -> loc_valid f dst -> loc_writable dst ->
Loc.type dst = Loc.type src ->
wt_code f k -> wt_code f (add_move src dst k).
Proof.
intros. unfold add_move.
destruct (Loc.eq src dst); auto.
destruct src; auto with reloadty.
destruct dst; auto with reloadty.
set (tmp := match slot_type s with
| Tint => IT1
| Tfloat => FT1
end).
assert (mreg_type tmp = Loc.type (S s)).
simpl. destruct (slot_type s); reflexivity.
apply wt_add_reload; auto with reloadty.
apply wt_add_spill; auto. congruence.
Qed.
Hint Resolve wt_add_move: reloadty.
Lemma wt_add_moves:
forall f b moves,
(forall s d, In (s, d) moves ->
loc_valid f s /\ loc_valid f d /\ loc_writable d /\ Loc.type s = Loc.type d) ->
wt_code f b ->
wt_code f
(List.fold_right (fun p k => add_move (fst p) (snd p) k) b moves).
Proof.
induction moves; simpl; intros.
auto.
destruct a as [s d]. simpl.
destruct (H s d) as [A [B [C D]]]. auto.
auto with reloadty.
Qed.
Theorem wt_parallel_move:
forall f srcs dsts b,
List.map Loc.type srcs = List.map Loc.type dsts ->
locs_valid f srcs -> locs_valid f dsts -> locs_writable dsts ->
wt_code f b -> wt_code f (parallel_move srcs dsts b).
Proof.
intros. unfold parallel_move. apply wt_add_moves; auto.
intros.
elim (parmove_prop_2 _ _ _ _ H4); intros A B.
split. destruct A as [C|[C|C]]; auto; subst s; exact I.
split. destruct B as [C|[C|C]]; auto; subst d; exact I.
split. destruct B as [C|[C|C]]; auto; subst d; exact I.
eapply parmove_prop_3; eauto.
Qed.
Hint Resolve wt_parallel_move: reloadty.
Lemma wt_reg_for:
forall l, mreg_type (reg_for l) = Loc.type l.
Proof.
intros. destruct l; simpl. auto.
case (slot_type s); reflexivity.
Qed.
Hint Resolve wt_reg_for: reloadty.
Lemma wt_regs_for_rec:
forall locs itmps ftmps,
enough_temporaries_rec locs itmps ftmps = true ->
(forall r, In r itmps -> mreg_type r = Tint) ->
(forall r, In r ftmps -> mreg_type r = Tfloat) ->
List.map mreg_type (regs_for_rec locs itmps ftmps) = List.map Loc.type locs.
Proof.
induction locs; intros.
simpl. auto.
simpl in H. simpl.
destruct a.
simpl. decEq. eauto.
caseEq (slot_type s); intro SLOTTYPE; rewrite SLOTTYPE in H.
destruct itmps. discriminate.
simpl. decEq.
rewrite SLOTTYPE. auto with coqlib.
apply IHlocs; auto with coqlib.
destruct ftmps. discriminate. simpl. decEq.
rewrite SLOTTYPE. auto with coqlib.
apply IHlocs; auto with coqlib.
Qed.
Lemma wt_regs_for:
forall locs,
enough_temporaries locs = true ->
List.map mreg_type (regs_for locs) = List.map Loc.type locs.
Proof.
intros. unfold regs_for. apply wt_regs_for_rec.
auto.
simpl; intros; intuition; subst r; reflexivity.
simpl; intros; intuition; subst r; reflexivity.
Qed.
Hint Resolve wt_regs_for: reloadty.
Hint Resolve enough_temporaries_op_args enough_temporaries_cond enough_temporaries_addr: reloadty.
Hint Extern 4 (_ = _) => congruence : reloadty.
Lemma wt_transf_instr:
forall f instr k,
LTLintyping.wt_instr (LTLin.fn_sig f) instr ->
wt_code (transf_function f) k ->
wt_code (transf_function f) (transf_instr f instr k).
Proof.
Opaque reg_for regs_for.
intros. inv H; simpl; auto with reloadty.
caseEq (is_move_operation op args); intros.
destruct (is_move_operation_correct _ _ H). congruence.
assert (map mreg_type (regs_for args) = map Loc.type args).
eauto with reloadty.
assert (mreg_type (reg_for res) = Loc.type res). eauto with reloadty.
auto with reloadty.
assert (map mreg_type (regs_for args) = map Loc.type args).
eauto with reloadty.
assert (mreg_type (reg_for dst) = Loc.type dst). eauto with reloadty.
auto with reloadty.
caseEq (enough_temporaries (src :: args)); intro ENOUGH.
caseEq (regs_for (src :: args)); intros. auto.
assert (map mreg_type (regs_for (src :: args)) = map Loc.type (src :: args)).
apply wt_regs_for. auto.
rewrite H in H5. injection H5; intros.
auto with reloadty.
apply wt_add_reloads; auto with reloadty.
symmetry. apply wt_regs_for. eauto with reloadty.
assert (op_for_binary_addressing addr <> Omove).
unfold op_for_binary_addressing; destruct addr; congruence.
assert (type_of_operation (op_for_binary_addressing addr) = (type_of_addressing addr, Tint)).
apply type_op_for_binary_addressing.
rewrite <- H1. rewrite list_length_map.
eapply not_enough_temporaries_length; eauto.
apply wt_code_cons.
constructor; auto. rewrite H5. decEq. rewrite <- H1. eauto with reloadty.
apply wt_add_reload; auto with reloadty.
apply wt_code_cons; auto. constructor. reflexivity.
rewrite <- H2. eauto with reloadty.
assert (locs_valid (transf_function f) (loc_arguments sig)).
red; intros. generalize (loc_arguments_acceptable sig l H).
destruct l; simpl; auto. destruct s; simpl; intuition.
assert (locs_writable (loc_arguments sig)).
red; intros. generalize (loc_arguments_acceptable sig l H6).
destruct l; simpl; auto. destruct s; simpl; intuition.
assert (map Loc.type args = map Loc.type (loc_arguments sig)).
rewrite loc_arguments_type; auto.
assert (Loc.type res = mreg_type (loc_result sig)).
rewrite H2. unfold loc_result. unfold proj_sig_res.
destruct (sig_res sig); auto. destruct t; auto.
destruct ros.
destruct H3 as [A [B C]].
apply wt_parallel_move; eauto with reloadty.
apply wt_add_reload; eauto with reloadty.
apply wt_code_cons; eauto with reloadty.
constructor. rewrite <- A. auto with reloadty.
auto with reloadty.
assert (locs_valid (transf_function f) (loc_arguments sig)).
red; intros. generalize (loc_arguments_acceptable sig l H).
destruct l; simpl; auto. destruct s; simpl; intuition.
assert (locs_writable (loc_arguments sig)).
red; intros. generalize (loc_arguments_acceptable sig l H6).
destruct l; simpl; auto. destruct s; simpl; intuition.
assert (map Loc.type args = map Loc.type (loc_arguments sig)).
rewrite loc_arguments_type; auto.
destruct ros. destruct H2 as [A [B C]]. auto 10 with reloadty.
auto 10 with reloadty.
destruct (ef_reloads ef) eqn:?.
assert (arity_ok (sig_args (ef_sig ef)) = true) by intuition congruence.
assert (map mreg_type (regs_for args) = map Loc.type args).
apply wt_regs_for. apply arity_ok_enough. congruence.
assert (mreg_type (reg_for res) = Loc.type res). eauto with reloadty.
auto 10 with reloadty.
auto with reloadty.
assert (map mreg_type (regs_for args) = map Loc.type args).
eauto with reloadty.
auto with reloadty.
assert (mreg_type (reg_for arg) = Loc.type arg).
eauto with reloadty.
auto with reloadty.
destruct optres; simpl in *; auto with reloadty.
apply wt_add_reload; auto with reloadty.
unfold loc_result. rewrite <- H1.
destruct (Loc.type l); reflexivity.
Qed.
Lemma wt_transf_code:
forall f c,
LTLintyping.wt_code (LTLin.fn_sig f) c ->
Lineartyping.wt_code (transf_function f) (transf_code f c).
Proof.
induction c; simpl; intros.
red; simpl; tauto.
apply wt_transf_instr; auto with coqlib.
apply IHc. red; auto with coqlib.
Qed.
Lemma wt_transf_fundef:
forall fd,
LTLintyping.wt_fundef fd ->
Lineartyping.wt_fundef (transf_fundef fd).
Proof.
intros. destruct fd; simpl.
inv H. inv H1. constructor. unfold wt_function. simpl.
apply wt_parallel_move; auto with reloadty.
rewrite loc_parameters_type. auto.
red; intros.
destruct (list_in_map_inv _ _ _ H) as [r [A B]].
generalize (loc_arguments_acceptable _ _ B).
destruct r; intro.
rewrite A. simpl. auto.
red in H0. destruct s; try tauto.
simpl in A. subst l. simpl. auto.
apply wt_transf_code; auto.
constructor.
Qed.
Lemma program_typing_preserved:
forall p,
LTLintyping.wt_program p ->
Lineartyping.wt_program (transf_program p).
Proof.
intros; red; intros.
destruct (transform_program_function _ _ _ _ H0) as [f0 [A B]].
subst f; apply wt_transf_fundef. eauto.
Qed.
|
\chapter{Switch}
\section{Operation}
\subsection{Switch boot sequence}
After a Cisco switch is powered on, it goes through the following boot sequence:
\begin{enumerate}
\item The switch loads a power-on self-test (POST) program stored in ROM.
\item Boot loader software is loaded.
\item The boot loader initializes the CPU registers.
\item The boot loader initializes the flash file system.
\item The boot loader loads IOS image into RAM and gives control of the switch to the IOS.
\item The IOS initializes the startup-config file, which is stored in NVRAM.
\end{enumerate}
The boot loader software finds the Cisco IOS image using \emph{Boot environment variables}. If this variable is not set, the switch attempts to load and execute the first executable file it finds. Use the command \code{show boot} to see content of the the variable and what the current IOS boot file is set to.
\begin{sexylisting}{Setting boot environment variable}
boot system flash:/c2960-lanbasek9-mz.150-2.SE/c2960-lanbasek9-mz.150-2.SE.bin
\end{sexylisting}
\subsection{MAC address table}
A Layer 2 Ethernet switch uses MAC addresses to make forwarding decisions. It consults a MAC address table to make a forwarding decision for each frame. By default, most Ethernet switches keep an entry in the MAC address table for 5 minutes.
\paragraph{Learning MAC Address:} The switch dynamically builds the MAC address table by examining the source MAC address of the frames received on a port. Every frame that enters a switch is checked for new information to learn. If the source MAC address does not exist, it is added to the table along with the incoming port number. If the source MAC address does exist, the switch updates the refresh timer for that entry. If the source MAC address does exist in the table but on a different port, the switch treats this as a new entry.
\paragraph{Forwarding MAC Address:} Next, if the destination MAC address is a unicast address, the switch will look for a match between the destination MAC address of the frame and an entry in its MAC address table. If the destination MAC address is in the table, it will forward the frame out the specified port. If the destination MAC address is not in the table, the switch will forward the frame out all ports except the incoming port. If the destination MAC address is a broadcast or a multicast, the frame is also flooded out all ports except the incoming port.\\
A switch can have multiple MAC addresses associated with a single port. This is common when the switch is connected to another switch.
\subsection{Frame forwarding method}
A switch makes a decision on frame forwarding based on two criteria: \textbf{Ingress port} and \textbf{Destination address}. Switches use one of the following forwarding methods: Store-and-forward switching and Cut-through switching.
\paragraph{Store-and-forward switching:} has two primary characteristics that distinguish it from cut-through: \textbf{error checking} and \textbf{automatic buffering}. When the switch receives the frame, it stores the data in buffers until the complete frame has been received. In this process, the switch also performs an error checking using the CRC trailer portion of the Ethernet frame. When an error is detected in a frame, the switch discards the frame. Discarding frames with errors reduces the amount of bandwidth consumed by corrupt data. Store-and-forward switching is required for Quality of Service (QoS).
\paragraph{Cut-through switching:} There are two primary characteristics of cut-through switching: \textbf{rapid frame forwarding} and \textbf{fragment free}. The switch buffers just enough of the frame to read the destination MAC address (first 6 bytes) so that it can determine to which port to forward the data. No error detection is performed. There are two variants of cut-through switching:
\begin{itemize}
\item \textbf{Fast-forward switching:} the switch immediately forwards a packet after reading the destination address. It offers the lowest level of latency.
\item \textbf{Fragment-free switching} the switch waits for the collision window (64 bytes) to pass before forwarding the frame. The reason is that most network errors and collisions occur during the first 64 bytes.
\end{itemize}
\subsection{Switching domain}
\paragraph{Collision domain:} In \emph{hub-based} Ethernet segments, network devices must take turns when transmitting. The network segments that share the same bandwidth between devices are known as collision domains. Therefore, all ports of a hub are in the same collision domain. However, each port on a switch, or a router is a separate collision domain.
\begin{figure}[hbtp]
\caption{An example of collision domains}
\centering
\includegraphics[scale=0.8]{pictures/CollisionDomains.jpg}
\end{figure}
\paragraph{Broadcast domain}is a domain in which a broadcast is forwarded. A broadcast domain contains all devices that can reach each other at the data link layer (OSI layer 2) by using broadcast. All ports on a hub or a switch are by default in the same broadcast domain. All hosts in the a VLAN are in the same broadcast domain regardless connecting to different switches. Every port on a router locates in a separate broadcast domain. Note that routers don't forward broadcasts from one broadcast domain to another.
\subsection{Memory Buffering on Switches}
There are two methods of memory buffering: Port-based Memory Buffering and Shared Memory Buffering.
\paragraph{Port-based Memory Buffering:} Frames are stored in queues that are linked to specific incoming and outgoing ports. A frame is transmitted to the outgoing port only when all the frames ahead of it in the queue have been successfully transmitted.
\paragraph{Shared Memory Buffering:} deposits all frames into a common memory buffer that all the ports on the switch share. The frames in the buffer are linked dynamically to the destination port. This allows the packet to be transmitted on a port without order and waiting. This method permits larger frames to be transmitted with fewer dropped frames.
\section{Recovering from system crash}
The boot loader command line supports commands to format the flash file system, reinstall the operating system software, recover from system crash, recover a forgotten password. The boot loader command line can be accessed through a console connection following these steps:
\begin{enumerate}
\item Connect a PC by console cable to the switch console port. Configure terminal emulation software to connect to the switch.
\item Power off the switch by unplugging the switch power cord.
\item Reconnect the power cord to the switch and, within 15 seconds, press and hold down the Mode button while the System LED until it turns briefly amber and then solid green.
\end{enumerate}
\section{Configuration}
\subsection{Basic switch management}
To prepare a switch for remote management, it must be configured with an SVI, IP address, a subnet mask, and a default gateway. This is similar to configuring the IP address information on host devices. Please note that these IP settings are only for remote management access to the switch. The IP settings do not allow the switch to route Layer 3 packets.
\begin{sexylisting}{Basic switch management}
interface vlan 99
ip address 172.17.99.11 255.255.255.0
no shutdown
exit
ip default-gateway 172.17.99.1
\end{sexylisting}
\subsection{Duplex configuration}
When a switch port is operating in full-duplex mode, there is no collision domain associated with the port. In contrast, half-duplex creates collision domain. The following command manually sets the F0/1 to full duplex and 100 Mb/s.
\begin{sexylisting}{Duplex configuration}
interface fa 0/1
duplex full
speed 100
end
show interface
\end{sexylisting}
\subsection{Auto-MDIX}
When auto-MDIX is enabled, the interface automatically detects the required cable connection type (straight-through or crossover) and configures the connection appropriately. In other words, with auto-MDIX enabled, either type of cable can be used to connect to other devices.
\begin{sexylisting}{Auto-MDIX}
interface fastethernet 0/2
mdix auto
end
show controllers ethernet-controller fa 0/2 phy | include Auto-MDIX
\end{sexylisting}
\subsection{SSH}
Before configuring SSH, the switch must be minimally configured with a unique hostname and the correct network connectivity settings. To display the version and configuration data for SSH on the device that you configured as an SSH server, use the \code{show ip ssh} command. To check the SSH connections to the device, use the \code{show ssh} command.
\begin{sexylisting}{SSH configuration}
ip domain-name cisco.com
ip ssh version 2
crypto key generate rsa
username admin secret ccna
line vty 0 15
transport input ssh
login local
end
show ip ssh
show ssh
\end{sexylisting}
\subsection{Port security}
One way to secure ports is by implementing a feature called \emph{port security}. Port-security limits the number of valid MAC addresses allowed on a port. The MAC addresses of legitimate devices are allowed access, whereas other MAC addresses are denied. If a port is configured as a secure port and the maximum number of MAC addresses is reached, any additional attempts to connect by unknown MAC addresses generate a security violation.\\
Enable port-security feature will not work until the \code{switchport port-security} interface configuration command is executed. The type of secure address is based on the configuration and includes the following:
\begin{itemize}
\item \textbf{Static secure MAC addresses} are manually configured on a port. They are stored in the address table and are added to the running configuration on the switch.
%\begin{verbatim}
%S1(config)# interface f0/1
%S1(config-if)# switchport port-security mac-address aaaa.cafe.bbbb
%\end{verbatim}
\item \textbf{Dynamic secure MAC addresses} are dynamically learned and stored only in the address table. They are removed when the switch restarts.
\item \textbf{Sticky secure MAC addresses} can be dynamically learned or manually configured, and then stored in the address table and added to the running configuration. When sticky learning is enabled, the switch converts all dynamically learned MAC addresses, including those that were dynamically learned before sticky learning was enabled, into sticky secure MAC addresses. If sticky learning is disabled, the sticky secure MAC addresses remain part of the address table but are removed from the running configuration.
%\begin{verbatim}
%S1(config)# interface f0/1
%S1(config-if)# switchport port-security mac-address sticky
%\end{verbatim}
\end{itemize}
An interface can be configured for one of three violation modes: Protected, Restricted, and Shutdown. In these modes, a switch drops all frames with unknown source addresses until a sufficient number of these MAC addresses are removed, or the number of maximum allowable addresses is increased. No error messages are displayed in these modes.\\
\tableStart[\caption{Security violation mode}\label{Violation}] {| p{3cm} | p{3cm} | p{3cm} | p{3cm} |}
\head{Violation mode} & \head{Syslog message} & \head{Increase violation counter} & \head{Shut down port}\w
Protected & & & \w
Restricted & * & * & \w
Shutdown & & * & *\w
\tableEnd
%To change the violation mode on a switch port, use the following command:
%
%\begin{verbatim}
%S1(config)# interface f0/1
%S1(config-if)# switchport port-security violation protect
%S1(config-if)# switchport port-security violation restrict
%S1(config-if)# switchport port-security violation shutdown
%\end{verbatim}
\begin{sexylisting}{Port security configuration}
int f0/1
switchport port-security
switchport port-security mac-address sticky
switchport port-security violation restrict
switchport port-security maximum 2
end
show int
show port-security int
\end{sexylisting}
\textbf{Shutdown} is the default violation mode. A port-security violation in this mode causes the interface to become \emph{error-disabled}. You can bring an error-disabled interface back to normal by entering \code{shutdown} followed by \code{no shutdown} command. When a port is error-disabled, the port LED will turn off, and the \code{show interface} command identifies the port status as \verb|err-disabled|. The output of the \code{show port-security int} command shows the port status as \verb|secure-shutdown|.\\
\textbf{Restrict} is the only port security mode that can assist with troubleshooting by sending syslog messages and keeping count of violations.
\section{Troubleshooting}
\subsection{Gathering symptoms}
The output from the \code{show int} command can be used to detect common media issues.
\begin{verbatim}
S1# show int f0/1
FastEthernet0/1 is up, line protocol is up (connected)
Hardware is Lance, address is 0022.91c4.0e01 (bia 0022.91c4.0e01)
MTU 1500 bytes, BW 100000 Kbit/sec, DLY 100 usec,
<output omitted>
\end{verbatim}
\begin{itemize}
\item The first parameter (\verb|FastEthernet0/1 is up|) refers to the \emph{physical layer} and indicates whether the interface is receiving a carrier detect signal. The second parameter (\verb|line protocol is up|) refers to the \emph{data link layer} and indicates whether the data link layer protocol keepalives are being received.
\item If the interface is up and the line protocol is down, there could be an \emph{encapsulation} type mismatch, or the interface on the other end could be \emph{error-disabled}.
\item If the line protocol and the interface are both down, a cable is not attached, or the other end of the connection may be administratively down.
\item If the interface is administratively down, it has been manually disabled (the \verb|shutdown| command has been issued) in the active configuration.
\end{itemize}
\begin{verbatim}
S1# show interfaces FastEthernet 0/1
FastEthernet0/1 is up, line protocol is up (connected)
<output omitted>
3 input errors, 3 CRC, 0 frame, 0 overrun, 0 ignored
0 watchdog, 120 multicast, 0 pause input
0 input packets with dribble condition detected
3594664 packets output, 436549843 bytes, 0 underruns
<output omitted>
\end{verbatim}
\textbf{Input errors} is the sum of all errors in frames that were received on the interface being examined. The reported input errors from the above output include the following:
\begin{itemize}
\item \textbf{Runt frames:} Ethernet frames that are shorter than the 64-byte (minimum allowed length of a frame) are called runt frames. Runt frames are caused by malfunctioning NIC or collisions.
\item \textbf{Giant:} Ethernet frames that are larger than 1518-byte (maximum allowed size of a frame) are called giants.
\item \textbf{CRC errors:} Common causes come from the cable (electrical interference, loose or damaged connections, and incorrect cabling). If you see many CRC errors, there is too much noise on the cable and you should inspect the cable. You should also search for and eliminate noise sources.
\end{itemize}
\begin{verbatim}
S1# show interfaces FastEthernet 0/1
FastEthernet0/1 is up, line protocol is up (connected)
<output omitted>
8 output errors, 1790 collisions, 10 interface resets
0 unknown protocol drops
0 babbles, 235 late collision, 0 deferred
0 lost carrier, 0 no carrier, 0 pause output
0 output buffer failures, 0 output buffers swapped out
\end{verbatim}
\textbf{Output errors} is the sum of all errors that prevented the final transmission of frames out the interface that is being examined. The reported output errors include the following:
\begin{itemize}
\item \textbf{Collisions:} Collisions in half-duplex operations are normal. However, you should never see collisions on an interface configured for full-duplex communication.
\item \textbf{Late collision:} A late collision refers to a collision that occurs after \textbf{512 bits} of the frame have been transmitted. Common causes: Excessive cable lengths, Duplex mismatch.
\end{itemize}
\subsection{Take action}
If the interface is down, take these two actions:
\begin{enumerate}
\item Check the \emph{cable}. Make sure the proper and non-damaged cables are being used.
\item If the interface is still down, the problem may be due to a \emph{speed mismatch}. Manually set the same speed on both connection ends if this problem is suspected.
\end{enumerate}
If the interface is up, but issues with connectivity are still present, do the following:
\begin{enumerate}
\item Using the \verb|show interfaces| command, check for indications of excessive \emph{noise}. Indications may include an increase in the counters for runts, giants, and CRC errors. If there is excessive noise, find and remove the source of the noise, verify that the cable does not exceed the maximum cable length and check the cable type.
\item If noise is not an issue, check for excessive \emph{collisions}. If there are collisions or late collisions, the problem may be due to \emph{duplex mismatch}. If this is true, manually set the duplex to full on both ends of the connection.
\end{enumerate} |
# Ecuación de Poisson
INTRODUCCION
## La ecuación diferencial parcial más sencilla
Solucionaremos la ecuación de Poisson, el problema "Hola Mundo" de la computación científica:
Encontrar la incógnita $u$, conociendo el término fuente $f$, tal que:
\begin{align}
-\triangle u &= f, \ && \text{en} \: \Omega,\\
u &= u_0, && \text{sobre} \: \partial\Omega.
\end{align}
La ecuación modela distintos fenómenos difusivos:
- Conducción de calor, electrostática, flujos no viscosos, ondas.
- Como parte de métodos de solución de EDPs para configuraciones no-clásicas.
## La receta numérica para aproximar su solución
Aproximar numéricamente el problema por métodos numéricos variacionales consta de los siguiente pasos:
- Plantear la formulación variacional del problema.
- Plantear el espacio funcional de aproximación numérica: Galerkin Continuo, Galerkin Discontinuo, Colocación, etc.
- Ensamblar el sistema discreto de ecuaciones, incluyendo las condiciones de contorno.
FEniCS nos reduce este proceso al primer paso!
## Formulación variacional
La formulación variacional la definimos como la integral sobre el dominio $\Omega$ del producto interno entre la ecuación de Poisson y una función vectorial de test $\boldsymbol{v}\in \hat{V}$, donde $\hat{V}$ es el espacio de la funcion de test.
\begin{align*}
-\int_\Omega (\triangle u) v \text{d} x &= \int_\Omega fv \text{d} x, && \text{en} \: \Omega.
\end{align*}
Como $\triangle u$ contiene derivadas de segundo orden sobre $u$, debilitamos la ecuación integrando por partes:
\begin{align*}
-\int_\Omega (\triangle u) v \text{d} x &= \int_\Omega \nabla u \cdot \nabla v \text{d} x - \int_{\partial \Omega}\frac{\partial u}{\partial n} v \text{d} s, && \text{en} \: \Omega.
\end{align*}
donde $\boldsymbol{n}$ es vector normal en el contorno.
$\frac{\partial u}{\partial n}$ es conocido como el flujo en el contorno $\partial \Omega$ y puede ser usado para prescribir una condicion de contorno de tipo Neumann o Robin de la forma $\frac{\partial u}{\partial n} = t$.
Suponiendo que no hay flujos en los contornos del dominio, la formulación variacional está dada por
\begin{align*}
\int_\Omega \nabla u \cdot \nabla v \text{d} x&= \int_\Omega fv \text{d} x, && \text{en} \: \Omega.\\
\end{align*}
### Definición de los espacios discretos de interpolación
Definición de un espacio discreto de aproximación contenido dentro del espacio continuo. Uno para el espacio de la función de test:
\begin{align*}
\widetilde{V}_h\subset \widetilde{V}:=\left\{v\in H(\Omega): v=0 \:\text{sobre} \: \partial\Omega\right\},
\end{align*}
y otra para la función de la incógnita:
\begin{align*}
V_h\subset V:=\left\{v\in H(\Omega): v=u_0 \:\text{sobre} \: \partial\Omega\right\}.
\end{align*}
Tal que, el problema discreto es encontrar $u_h\in V_h\subset V$, tal que:
\begin{align*}
\int_\Omega \nabla u_h \cdot \nabla v_h \text{d} x&= \int_\Omega fv_h \text{d} x, && \text{en} \: \Omega.\\
\end{align*}
para todo $v_h\in \widetilde{V}_h\subset \widetilde{V}$.
### Notación variacional en FEniCS
Este tipo de ecuaciones variacionales discretas se puede escribir usando la siguiente notación: Encontrar $u_h\in V_h\subset V$, tal que:
\begin{align*}
a(u_h,v_h)&=L(v_h),
\end{align*}
para todo $v_h\in \widetilde{V}_h\subset \widetilde{V}$.
Donde $a(u,v)$ es una forma variacional bilineal (lineal en cada argumento) y $L(v)$ es una forma lineal:
\begin{align*}
a(u_h,v_h)&=\int_\Omega \nabla u_h \cdot \nabla v_h \text{d} x,\\
L(v_h)&= \int_\Omega fv_h \text{d} x.\\
\end{align*}
## Sistema discreto de ecuaciones lineales
Introduciendo las funciones de test y de interpolación de la incógnita como polinomios a trozos:
\begin{align*}
v_h=&\sum_i^n \phi_i \subset \widetilde{V}_h\subset \widetilde{V}, &&
u_h=&\sum_j^n U_j\phi_j \subset V_h\subset V.
\end{align*}
La ecuación discreta resulta en:
\begin{align*}
\int_\Omega \partial_k \sum_j^n U_j\phi_j \partial_k \sum_i^n \phi_i \text{d} x =& \int_\Omega f\sum_i \phi_i \text{d} x.
\end{align*}
O mejor:
\begin{align*}
\sum_i^n\sum_j^n\int_{\Omega^e} U_j \partial_k\phi_j \partial_k \phi_i \text{d} x =& \sum_i^n \int_{\Omega^e} f \phi_i \text{d} x.
\end{align*}
Deshaciendo las sumatorias y el álgebra lineal:
\begin{align*}
\begin{bmatrix}
a_{11} & a_{12} & a_{13} & \dots & a_{1n} \\
a_{21} & a_{22} & a_{23} & \dots & a_{2n} \\
\dots & \dots & \dots & a_{ij} & \dots \\
a_{n1} & a_{n2} & a_{n3} & \dots & a_{nn}
\end{bmatrix}
\begin{bmatrix}
U_1 \\ U_2 \\ \dots \\ U_n
\end{bmatrix}
=&
\begin{bmatrix}
L_{1} \\ L_{2} \\ \dots \\ L_{3}
\end{bmatrix},
\end{align*}
donde $U_j$ son las incógnitas nodales, $a_{ij}$ viene dada por una integración local sobre cada elemento $a_{ij} = \int_{\Omega^e} U_j \partial_k\phi_j \partial_k \phi_i \text{d} x$ y $L_i$ está dada por $L_i = \int_{\Omega^e} f \phi_i \text{d} x$.
Esto es lo mismo que un sistema lineal del tipo $\mathbb{A}\mathbb{U}=\mathbb{L}$, cuya resolución está dada por:
\begin{align*}
\mathbb{U}=&\mathbb{A}^{-1}\mathbb{L}
\end{align*}
## Implementación en FEniCS
Modelamos un dominio bidimensional cuadrador con condiciones de Dirichlet en sus contornos y un término fuente constante.
### El programa completo
```python
from dolfin import *
import matplotlib.pyplot as plt
# Malla
mesh = UnitSquareMesh(8,8)
# Espacio de funciones para la incognita y test
V= FunctionSpace(mesh,"Lagrange",1)
# Expresion para las condiciones de contorno
u0=Expression("1+ x[0]*x[1] + 2*x[1]*x[1]",degree=2)
# Definicion de las condiciones de contorno
bc = DirichletBC ( V , u0 , "on_boundary")
# Fuente
f=Constant(-6.0)
# Funcion de trial
u= TrialFunction(V)
# Funcion de test
v= TestFunction(V)
# Forma bilineal del lado izquierdo
a = inner(grad(u), grad(v))*dx
# Forma lineal del lado derecho
L=f*v*dx
# Funcion donde se almacena el resultado
u = Function(V)
# Solucion del sistema algebraico
solve(a==L, u, bc)
#Impresion usando paraview
vtkfile = File('poisson_solution.pvd')
vtkfile << u
```
Calling FFC just-in-time (JIT) compiler, this may take some time.
Calling FFC just-in-time (JIT) compiler, this may take some time.
### Importar paquetes
Importamos los paquetes de solucion (dolfin), de mallado (mshr), numpy para realizar operaciones numericas y matplotlib para ver los resultados
```python
from dolfin import *
import matplotlib.pyplot as plt
```
### Dominio geometrico y mallado
Definimos el dominio $\Omega$ y generamos la malla directamente usando FEniCS:
```python
mesh = UnitSquareMesh(8,8)
```
Las posibilidades que existen de generación de dominios con la librería **mshr** son inmensas.
### Definición de los espacios funcionales
FEniCS tienen programada internamente una gran cantidad de familias de elementos finitos, incluyendo: Lagrangeanos, Curl, Div, Discontinuos, y la posibilidad de realizar distintas combinaciones de espacios funcionales entre ellos.
Una vez creada la malla, podemos crear un espacio funcional de elementos finitos V sobre dicho dominio geométrico discreto:
```python
V= FunctionSpace(mesh,"Lagrange",1)
```
El segundo argumento especifica el tipo de elemento. El tipo de elemento aquí es "Lagrange", lo que implica la familia de elementos estándar de Lagrange. También puede utilizar 'P' para especificar este tipo de elemento. FEniCS soporta todas las familias de elementos simplex y la notación definida en la Tabla Periódica de Elementos Finitos.
El tercer argumento 1 especifica el grado del elemento finito. En este caso, el estándar 𝖯1 elemento lineal de Lagrange, que es un triángulo con nodos en los tres vértices. Algunos se refieren a este elemento como el "triángulo lineal". La solución calculada $u$ será continua en los elementos y variará linealmente en $(x,y)$ dentro de cada elemento. Las aproximaciones polinomiales de mayor grado sobre cada celda se obtienen trivialmente aumentando el tercer parámetro. Cambiar el segundo parámetro a 'DP' crea un espacio funcional para métodos de Galerkin discontinuos.
### Definición de las funciones de trial y test
En matemáticas, distinguimos entre los espacios de interpolación de la incógnita $V$ y el de prueba o test $\tilde{V}$. La única diferencia en el problema actual son las condiciones de contorno. En FEniCS no especificamos las condiciones de contorno como parte del espacio funcional, por lo que es suficiente trabajar con un espacio común $V$ para las distintas funciones:
```python
u = TrialFunction(V)
v = TestFunction(V)
```
### Definición de condiciones de contorno tipo Dirichlet
El siguiente paso es especificar la condición de contorno $u= u_D$ sobre $\partial\Omega$. Esto se hace muy fácilmente con la siguiente rutina:
```python
bc = DirichletBC(V, u0, "on_boundary")
```
donde $u_D$ es una expresión que define los valores de la solución en el contorno del dominio computacional. Dicho valor se puede determinar por una función (u objeto) definida sobre todo el dominio espacial, pero evaluada únicamente en el contorno.
La clase **DirichletBC** sirve para imponer condiciones de contorno en cada espacio funcional (incógnita).
Define que la función de la incógnita $u$ definida en el espacio $V$ debe igualarse a la expresión $u_D$ evaluada en la región "on_boundary".
Las condiciones de contorno del tipo $u = uD$ se conocen como condiciones de Dirichlet. Para el presente método de elementos finitos para el problema de Poisson, también se denominan condiciones de contorno esenciales, ya que deben imponerse explícitamente como parte del espacio funcional de la incógnita (en contraste con las que pueden definirse implícitamente como parte de la formulación variacional). Naturalmente, la clase FEniCS utilizada para definir las condiciones de contorno de Dirichlet se denomina DirichletBC. Esa clase instancia un objeto bc que se usa más adelante para ensamblar el sistema de ecuaciones lineales.
Ahora bien, la variable $u_D$ se refiere a un objeto **Expression**, que se utiliza para representar una función matemática. La construcción típica de ese tipo de objeto se da con la siguiente rutina:
```python
u0 = Expression(formula, degree=1)
```
donde **formula** es una cadena que contiene una expresión matemática. La fórmula debe escribirse con sintaxis C ++ y se convierte automáticamente en una función C ++ compilada y eficiente.
La expresión puede depender de las variables x[0] y x[1] correspondientes a las coordenadas $(x,y)$. En 3D, la expresión también puede depender de la variable x[2] correspondiente a la coordenada $z$. Este problema introductorio supone una expresión de la forma $u_D(x,y) = 1 + x2 + 2y^2$. Entonces, la expresión se puede escribir como 1 + x [0] * x [0] + 2 * x [1] * x [1]:
```python
u0=Expression("1+ x[0]*x[1] + 2*x[1]*x[1]", degree=2)
```
Establecemos el grado **degree** de la fórmula como 2 para que $u_D$ pueda representar la solución cuadrática exacta de nuestro problema de prueba.
La clase **Expression** es muy flexible y sirve para crear expresiones complicadas definidas por el usuario. Funciones espaciales, temporales u otras.
Por ejemplo, la fuente $f=-6$ puede ser definida como:
```python
f = Expression("-6",degree=0)
```
O más eficientemente con la clase Función Constante (en espacio y tiempo):
```python
f = Constant(-6.0)
```
Lo único que nos falta es definir la región sobre la cual se evalúa la expresión para $u_D$. Esto se realiza con el argumento "on_boundary". Otras opciones para determinar fácilmente la región de imposición de las condiciones de Dirichlet son:
- "on\_boundary" Todo el contorno del dominio
- "near(x[0],0.0)" En la región del contorno x=0.
- "near(x[0],0.0) || near(x[1],1.0)" En la región del contorno x=0 o y=1.
### Definición del problema variacional
Ahora tenemos todos los ingredientes que necesitamos para definir el problema variacional:
```python
a = inner(grad(u), grad(v))*dx
L = f*v*dx
```
En esencia, estas dos líneas especifican el problema EDP a resolver. Se entiende la estrecha correspondencia entre la sintaxis de Python y las fórmulas matemáticas $\nabla u \cdot \nabla v dx$ y $fvdx$. Esta es una fortaleza clave de FEniCS: las fórmulas en la formulación variacional se traducen directamente a un código Python muy similar, una característica que facilita la formulación y resolución de problemas EDP complicados.
### Ensamblaje y solución del problema variacional
FEniCS realiza el ensamblaje del sistema lineal (impone las condiciones de contorno) y llama a uno de los solucionadores externos (según el problema).
```python
# Compute solution
u = Function(V)
# Solucion del sistema algebraico
solve(a==L, u, bc)
```
Se usa la función $u$ tanto como función trial como para guardar la solución que entrega el solucionador.
## Post-procesamiento
### Visualización de la solución
Posproceso, visualización y salida de datos puede realizarse:
- Interno: Numpy, Matplotlib, etc.
- Externo: .pvd, .xml, .xdmf (reestablecer casos).
Por ejemplo, para escribir un archivo que pueda ser visualizado en Paraview, se escriben las dos líneas siguientes:
```python
vtkfile = File("poisson_solution.pvd")
vtkfile << u
```
Una para crear el archivo que guarda los datos.
La otra línea para salvar la información dentro del archivo creado.
|
great(ii1,a1).
great(bb1,s1).
great(v1,m1).
great(p1,n1).
great(c1,r1).
great(d1,n1).
great(a1,s1).
great(c1,e1).
great(s1,n1).
great(g1,ee1).
great(a1,ff1).
great(q1,x1).
great(ii1,x1).
great(dd1,b1).
great(q1,v1).
great(f1,d1).
great(y1,n1).
great(e1,b1).
great(e1,k1).
great(k1,o1).
great(g1,i1).
great(h1,d1).
great(z1,kk1).
great(d1,s1).
great(g1,cc1).
great(y1,dd1).
great(u1,i1).
great(y1,bb1).
great(g1,kk1).
great(t1,n1).
|
#' Create a data frame tbl.
#'
#' Deprecated: please use [tibble::as_tibble()] instead.
#'
#' @export
#' @keywords internal
#' @param data a data frame
tbl_df <- function(data) {
# Works in tibble < 1.5.0 too, because .name_repair will be
# swallowed by the ellipsis
as_tibble(data, .name_repair = "check_unique")
}
#' @export
as.tbl.data.frame <- function(x, ...) {
tbl_df(x)
}
#' @export
tbl_vars.data.frame <- function(x) names(x)
#' @export
same_src.data.frame <- function(x, y) {
is.data.frame(y)
}
#' @export
auto_copy.tbl_df <- function(x, y, copy = FALSE, ...) {
as.data.frame(y)
}
# Verbs ------------------------------------------------------------------------
#' @export
arrange.tbl_df <- function(.data, ..., .by_group = FALSE) {
dots <- quos(...)
arrange_impl(.data, dots, environment())
}
#' @export
arrange_.tbl_df <- function(.data, ..., .dots = list(), .by_group = FALSE) {
dots <- compat_lazy_dots(.dots, caller_env(), ...)
arrange_impl(.data, dots, environment())
}
#' @export
filter.tbl_df <- function(.data, ..., .preserve = FALSE) {
dots <- quos(...)
if (any(have_name(dots))) {
bad <- dots[have_name(dots)]
bad_eq_ops(bad, "must not be named, do you need `==`?")
} else if (is_empty(dots)) {
return(.data)
}
quo <- all_exprs(!!!dots, .vectorised = TRUE)
out <- filter_impl(.data, quo)
if (!.preserve && is_grouped_df(.data)) {
attr(out, "groups") <- regroup(attr(out, "groups"), environment())
}
out
}
#' @export
filter_.tbl_df <- function(.data, ..., .dots = list()) {
dots <- compat_lazy_dots(.dots, caller_env(), ...)
filter(.data, !!!dots)
}
#' @export
slice.tbl_df <- function(.data, ..., .preserve = FALSE) {
dots <- quos(...)
if (is_empty(dots)) {
return(.data)
}
quo <- quo(c(!!!dots))
out <- slice_impl(.data, quo)
if (!.preserve && is_grouped_df(.data)) {
attr(out, "groups") <- regroup(attr(out, "groups"), environment())
}
out
}
#' @export
slice_.tbl_df <- function(.data, ..., .dots = list()) {
dots <- compat_lazy_dots(.dots, caller_env(), ...)
slice(.data, !!!dots)
}
#' @export
mutate.tbl_df <- function(.data, ...) {
dots <- quos(..., .named = TRUE)
mutate_impl(.data, dots)
}
#' @export
mutate_.tbl_df <- function(.data, ..., .dots = list()) {
dots <- compat_lazy_dots(.dots, caller_env(), ..., .named = TRUE)
mutate_impl(.data, dots)
}
#' @export
summarise.tbl_df <- function(.data, ...) {
dots <- quos(..., .named = TRUE)
summarise_impl(.data, dots)
}
#' @export
summarise_.tbl_df <- function(.data, ..., .dots = list()) {
dots <- compat_lazy_dots(.dots, caller_env(), ..., .named = TRUE)
summarise_impl(.data, dots)
}
# Joins ------------------------------------------------------------------------
#' Join data frame tbls
#'
#' See [join] for a description of the general purpose of the
#' functions.
#'
#' @inheritParams inner_join
#' @param ... included for compatibility with the generic; otherwise ignored.
#' @param na_matches
#' Use `"never"` to always treat two `NA` or `NaN` values as
#' different, like joins for database sources, similarly to
#' `merge(incomparables = FALSE)`.
#' The default, `"na"`, always treats two `NA` or `NaN` values as equal, like [merge()].
#' Users and package authors can change the default behavior by calling
#' `pkgconfig::set_config("dplyr::na_matches" = "never")`.
#' @examples
#' if (require("Lahman")) {
#' batting_df <- tbl_df(Batting)
#' person_df <- tbl_df(Master)
#'
#' uperson_df <- tbl_df(Master[!duplicated(Master$playerID), ])
#'
#' # Inner join: match batting and person data
#' inner_join(batting_df, person_df)
#' inner_join(batting_df, uperson_df)
#'
#' # Left join: match, but preserve batting data
#' left_join(batting_df, uperson_df)
#'
#' # Anti join: find batters without person data
#' anti_join(batting_df, person_df)
#' # or people who didn't bat
#' anti_join(person_df, batting_df)
#' }
#' @name join.tbl_df
NULL
check_na_matches <- function(na_matches) {
na_matches <- match.arg(na_matches, choices = c("na", "never"))
accept_na_match <- (na_matches == "na")
accept_na_match
}
#' @export
#' @rdname join.tbl_df
inner_join.tbl_df <- function(x, y, by = NULL, copy = FALSE,
suffix = c(".x", ".y"), ...,
na_matches = pkgconfig::get_config("dplyr::na_matches")) {
check_valid_names(tbl_vars(x))
check_valid_names(tbl_vars(y))
by <- common_by(by, x, y)
suffix <- check_suffix(suffix)
na_matches <- check_na_matches(na_matches)
y <- auto_copy(x, y, copy = copy)
vars <- join_vars(tbl_vars(x), tbl_vars(y), by, suffix)
by_x <- vars$idx$x$by
by_y <- vars$idx$y$by
aux_x <- vars$idx$x$aux
aux_y <- vars$idx$y$aux
out <- inner_join_impl(x, y, by_x, by_y, aux_x, aux_y, na_matches, environment())
names(out) <- vars$alias
reconstruct_join(out, x, vars)
}
#' @export
#' @rdname join.tbl_df
nest_join.tbl_df <- function(x, y, by = NULL, copy = FALSE, keep = FALSE, name = NULL, ...) {
name_var <- name %||% expr_name(enexpr(y))
check_valid_names(tbl_vars(x))
check_valid_names(tbl_vars(y))
by <- common_by(by, x, y)
y <- auto_copy(x, y, copy = copy)
vars <- join_vars(tbl_vars(x), tbl_vars(y), by)
by_x <- vars$idx$x$by
by_y <- vars$idx$y$by
aux_y <- vars$idx$y$aux
if (keep) {
aux_y <- c(by_y, aux_y)
}
out <- nest_join_impl(x, y, by_x, by_y, aux_y, name_var, environment())
out
}
#' @export
#' @rdname join.tbl_df
left_join.tbl_df <- function(x, y, by = NULL, copy = FALSE,
suffix = c(".x", ".y"), ...,
na_matches = pkgconfig::get_config("dplyr::na_matches")) {
check_valid_names(tbl_vars(x))
check_valid_names(tbl_vars(y))
by <- common_by(by, x, y)
suffix <- check_suffix(suffix)
na_matches <- check_na_matches(na_matches)
y <- auto_copy(x, y, copy = copy)
vars <- join_vars(tbl_vars(x), tbl_vars(y), by, suffix)
by_x <- vars$idx$x$by
by_y <- vars$idx$y$by
aux_x <- vars$idx$x$aux
aux_y <- vars$idx$y$aux
out <- left_join_impl(x, y, by_x, by_y, aux_x, aux_y, na_matches, environment())
names(out) <- vars$alias
reconstruct_join(out, x, vars)
}
#' @export
#' @rdname join.tbl_df
right_join.tbl_df <- function(x, y, by = NULL, copy = FALSE,
suffix = c(".x", ".y"), ...,
na_matches = pkgconfig::get_config("dplyr::na_matches")) {
check_valid_names(tbl_vars(x))
check_valid_names(tbl_vars(y))
by <- common_by(by, x, y)
suffix <- check_suffix(suffix)
na_matches <- check_na_matches(na_matches)
y <- auto_copy(x, y, copy = copy)
vars <- join_vars(tbl_vars(x), tbl_vars(y), by, suffix)
by_x <- vars$idx$x$by
by_y <- vars$idx$y$by
aux_x <- vars$idx$x$aux
aux_y <- vars$idx$y$aux
out <- right_join_impl(x, y, by_x, by_y, aux_x, aux_y, na_matches, environment())
names(out) <- vars$alias
reconstruct_join(out, x, vars)
}
#' @export
#' @rdname join.tbl_df
full_join.tbl_df <- function(x, y, by = NULL, copy = FALSE,
suffix = c(".x", ".y"), ...,
na_matches = pkgconfig::get_config("dplyr::na_matches")) {
check_valid_names(tbl_vars(x))
check_valid_names(tbl_vars(y))
by <- common_by(by, x, y)
suffix <- check_suffix(suffix)
na_matches <- check_na_matches(na_matches)
y <- auto_copy(x, y, copy = copy)
vars <- join_vars(tbl_vars(x), tbl_vars(y), by, suffix)
by_x <- vars$idx$x$by
by_y <- vars$idx$y$by
aux_x <- vars$idx$x$aux
aux_y <- vars$idx$y$aux
out <- full_join_impl(x, y, by_x, by_y, aux_x, aux_y, na_matches, environment())
names(out) <- vars$alias
reconstruct_join(out, x, vars)
}
#' @export
#' @rdname join.tbl_df
semi_join.tbl_df <- function(x, y, by = NULL, copy = FALSE, ...,
na_matches = pkgconfig::get_config("dplyr::na_matches")) {
check_valid_names(tbl_vars(x), warn_only = TRUE)
check_valid_names(tbl_vars(y), warn_only = TRUE)
by <- common_by(by, x, y)
y <- auto_copy(x, y, copy = copy)
out <- semi_join_impl(x, y, by$x, by$y, check_na_matches(na_matches), environment())
if (is_grouped_df(x)) {
out <- grouped_df_impl(out, group_vars(x))
}
out
}
#' @export
#' @rdname join.tbl_df
anti_join.tbl_df <- function(x, y, by = NULL, copy = FALSE, ...,
na_matches = pkgconfig::get_config("dplyr::na_matches")) {
check_valid_names(tbl_vars(x), warn_only = TRUE)
check_valid_names(tbl_vars(y), warn_only = TRUE)
by <- common_by(by, x, y)
y <- auto_copy(x, y, copy = copy)
out <- anti_join_impl(x, y, by$x, by$y, check_na_matches(na_matches), environment())
if (is_grouped_df(x)) {
out <- grouped_df_impl(out, group_vars(x))
}
out
}
reconstruct_join <- function(out, x, vars) {
if (is_grouped_df(x)) {
groups_in_old <- match(group_vars(x), tbl_vars(x))
groups_in_alias <- match(groups_in_old, vars$x)
out <- grouped_df_impl(out, vars$alias[groups_in_alias])
}
out
}
# Set operations ---------------------------------------------------------------
#' @export
# Can't use NextMethod() in R 3.1, r-lib/rlang#486
distinct.tbl_df <- distinct.data.frame
#' @export
# Can't use NextMethod() in R 3.1, r-lib/rlang#486
distinct_.tbl_df <- distinct_.data.frame
|
\lab{Intro to pandas II}{Intro to pandas II}
In this lab, we explore in further detail two specific areas where pandas can be a very useful tool:
analyzing sequential data, and working with large datasets that can't be stored entirely in memory.
\begin{warn}
This lab assumes pandas 0.14.0. Errors may occur if you have an earlier version.
You can check the version of pandas you are running by the following:
\begin{lstlisting}
>>> import pandas as pd
>>> pd.__version__
'0.14.0'
\end{lstlisting}
\end{warn}
\section*{Time Series Analysis}
A \emph{time series} is a particular type of data set that consists of a sequence of measurements or observations
generated at successive points in time. Examples include the yearly average temperate of a city, or
the price of a given stock measured daily.
\begin{comment}
This section needs beefing up. Topics to cover include:
-using the date_range function to create dateTimeIndexes
-showing different types of string reps that can be parsed, using format string to speed up parsing
-resampling of a time series to change frequency levels.
-slicing time series using date strings
-the truncate method for time series
-load in financial data, use some of the above techniques, do a fun, simple application.
\end{comment}
\section*{Working With Large Datasets}
In the real world, a data scientist is often confronted with large datasets that can't be held in memory all at once.
There are various solutions to this problem; in this section, we will explore how pandas uses the HDF5 file format
to allow us to work with datasets on disk.
HDF5, which stands for ``Hierarchical Data Format", is a data storage system especially suited for large numerical datasets.
Rich and efficient software libraries have been developed over the years to enable fast read and write operations,
which make HDF5 a competitive option for working with large datasets in many applications. The Python library pytables
is one such library, and the HDF5 capabilities in pandas are built directly on top of pytables.
We have two primary learning goals: how to get our data into the proper HDF5 format, and how to intelligently work with
the data once it's tidied up. Let's dive in.
\subsection*{Writing HDF5 Data}
The primary way we will interact with HDF5 data goes through the \li{HDFStore} object, which behaves somewhat like a dictionary.
To begin, let's instantiate such an object, and write data to it. Make sure to execute the code snippets throughout to ensure that
everything works as expected on your machine.
\begin{lstlisting}
>>> # we will create an HDFStore with the filename test_store.h5
>>> my_store = pd.HDFStore('test_store.h5')
>>> my_store
<class 'pandas.io.pytables.HDFStore'>
File path: test_store.h5
Empty
\end{lstlisting}
The file \li{'test_store.h5'} has just been created in your working directory, although it contains nothing as yet.
Write some pandas data to the store:
\begin{lstlisting}
>>> # instantiate data, write to store
>>> ts = pd.Series(index=['A', 'B', 'C', 'D'], data = np.random.randn(4))
>>> df = pd.DataFrame(index=range(6), columns=['a','b'], data=np.random.random((6,2)))
>>> my_store['ts'] = ts
>>> my_store['df'] = df
>>> my_store
<class 'pandas.io.pytables.HDFStore'>
File path: test_store.h5
/df frame (shape->[6,2])
/ts series (shape->[4])
\end{lstlisting}
Note the dict-like syntax for writing data to the store. We now see that the store contains two objects, which
can easily be retrieved in the following manner:
\begin{lstlisting}
>>> # retrieve the df from the store, check it is the same
>>> store_df = my_store['df']
>>> (df == store_df).all()
a True
b True
dtype: bool
\end{lstlisting}
Removing an object that you have written to the store can be accomplished as follows (although note that removing the
object doesn't necessarily free up space on the hard disk, so the file size may not decrease):
\begin{lstlisting}
>>> # let's remove the series ts
>>> del my_store['ts'] # or my_store.remove('ts')
>>> my_store
<class 'pandas.io.pytables.HDFStore'>
File path: test_store.h5
/df frame (shape->[6,2])
\end{lstlisting}
The read and write operations that we have explored so far work just fine for small objects that can fit entirely in memory,
but the story is different when it comes to writing large datasets to an HDF5 file. Suppose we have a CSV file containing the
large dataset that we want to work with. One basic approach to storing this data in HDF5 format is to read and write it by
\emph{chunks}, that is, move the data into an HDF5 store a few lines at a time. This ensures that we never have to read too much
of the data into memory at once.
The \li{read_csv} function in pandas allows for reading a file by chunks of rows. We simply need to specify the keyword argument
\li{chunksize}, which gives the number of rows of the file to read in each time. Most other pandas data readers have a similar
option for loading data by chunks. It is also important to specify the correct data types of each column when reading in the chunks
of data. This will ensure that a consistent data type is used when writing to the HDF5 store. To do this, create a dict that
maps each column name to its correct data type. Columns containing strings should have the \li{object} datatype, and columns
containing numerical data may be ints or floats. Any column that contains date data should NOT be included in the dictionary,
but rather should be passed as the \li{parse_dates} keyword argument (a list of the column names containing dates).
To iteratively write data to a single object in an HDF5 store, we must use the \li{append} method. This will store the data in a
particular format called a \emph{table}, an on-disk data structure geared toward efficient querying of the rows. There are a few
parameters that we must tune in order to write the data successfully.
\begin{itemize}
\item \li{key}: This is the target object in the HDF5 store to which we want to write.
\item \li{value}: This is the actual chunk of data (such as a \li{DataFrame}) that we want to append to the store.
\item \li{data_columns}: A list of the column names of the incoming data that should be indexed. You should include all
columns that you will use in subsequent queries of the data. For example, if my dataset has a column labeled `A', and I anticipate
wanting to select all rows where the value in column `A' is greater than, say, 0, then it is imperative that \li{data_columns} includes
`A'. Try to avoid including columns that aren't needed in the queries, as performance can decrease with a larger number of indexed
columns. This argument only needs to be specified for the \emph{first} chunk to be written.
\item \li{min_itemsize}: This is an int that specifies the maximum length of a string found in the dataset. If you are unsure of the
exact length of the longest string, try setting this to a high default value (say 100). If you attempt to write data containing
a string whose length exceeds \li{min_itemsize}, an error is raised. This argument is also only required for the first chunk.
\item \li{index}: This argument is a boolean flag that indicates whether the data should be indexed as it is written. By setting
\li{index=False}, the data is written much faster.
\end{itemize}
In the code below, we create a CSV file containing toy data, then write it by chunks to our HDF5 store.
\begin{lstlisting}
>>> # first create the toy CSV file
>>> n_rows = 10000
>>> n_cols = 3
>>> csv_path = 'toy_data.csv'
>>> csv_file = open(csv_path, 'w')
>>> csv_file.write("A B C\n")
>>> for i in xrange(n_rows):
>>> for num in np.random.randn(3):
>>> csv_file.write(' ' + str(num))
>>> csv_file.write('\n')
>>> csv_file.close()
>>> # now iteratively write the data to the store
>>> n_chunk = 1000
>>> col_types = {'A':np.float, 'B':np.float, 'C':np.float}
>>> reader = pd.read_csv(csv_path, sep=' ', dtype=col_types, index_col=False, chunksize=n_chunk, skipinitialspace=True)
>>> first = True # a flag for the very first chunk
>>> data_cols=['B', 'C'] # queries involving cols B and C will be allowed
>>> for chunk in reader:
>>> if first:
>>> my_store.append('toy_data', chunk, data_columns=data_cols, index=False)
>>> first = False
>>> else:
>>> my_store.append('toy_data', chunk, index=False)
>>> my_store
<class 'pandas.io.pytables.HDFStore'>
File path: test_store.h5
/df frame (shape->[6,2])
/toy_data frame_table (typ->appendable,nrows->10000,ncols->3,indexers->[index],dc->[B,C])
\end{lstlisting}
If an error of any type occurs when writing your data, and you need to start over, it is necessary to remove
the previously written data, since the \li{append} function doesn't overwrite existing data.
Now that the data is in the HDF5 store, we should index the table, which can speed up query operations.
This is done as follows:
\begin{lstlisting}
>>> my_store.create_table_index('toy_data', optlevel=9, kind='full')
\end{lstlisting}
Obviously the toy data in this example is small enough to fit in memory, but it illustrates a basic approach
to moving large datasets into a HDF5 store.
\begin{problem}
Write the data contained in the file \li{campaign.csv} to an HDF5 store using the chunking approach.
We recommend setting the \li{chunksize} argument to 50,000. There will be just over 100 chunks for this
chunk size, so you can track your progress by printing out a counter, if you wish. The whole writing
process will likely take a few minutes.
The file \li{campaign_format.txt} contains information about the dataset, including the column names and descriptions.
Consult this file and note which, if any, columns contain date information. Use this information to appropriately
set the \li{parse_dates} argument in the \li{read_csv} function. This argument should be a list of the column names
that include date information. Note also that some of the columns contain strings, so remember the
\li{min_itemsize} argument. Finally, you will be analyzing this data in the remainder of the lab, so glance over
the problems below to determine which columns need to be indexed.
Once you have finished writing to the store, create a table index for the data, just as shown in the example above.
\end{problem}
\subsection*{Working With On-Disk Arrays}
Now that we have the data in a HDF5 table, how do we work with it? The key here is to only read in subsets
of the data, since trying to read the entire dataset at once may result in swamping the memory and crashing
the system. The \li{select} method allows us to do just this. It takes two basic arguments: first, the name
of the table in the store that we want to query, and second, a query statement. Remember, the
query statement may not reference columns that weren't included in \li{data_columns}.
\begin{lstlisting}
>>> # this query is OK
>>> my_store.select('toy_data', where = ["'B' < 0", "'C' > 0"])
>>> # this query is NOT OK
>>> my_store.select('toy_data', where = ["'A' < .5"])
\end{lstlisting}
Note that each logical statement in the \li{where} list is combined with a logical AND.
Let's look at some simple examples with our campaign dataset. We assume that the data is in a HDF5 store called
\li{store}. Follow along to make sure you get the same results.
\begin{lstlisting}
>>> # get a list of the candidates; result should be 14 candidates
>>> cands = store.select_column('campaign', 'cand_nm').unique()
>>> # find number of contributions from UT
>>> n_UT = len(store.select('campaign',where = ["'contbr_st' == 'UT'", "columns='contbr_st'"]))
>>> n_UT
50462
>>> # find number of UT contributions to Romney
>>> n_rom_UT = len(store.select('campaign', where = ["'contbr_st' == 'UT'", "'cand_nm'=='Romney, Mitt'", "columns='contbr_st'"]))
>>> n_rom_UT
26962
>>> # proportion of UT contributions that went to Romney
>>> np.float(n_rom_UT)/n_UT
0.534303039911
\end{lstlisting}
\begin{problem}
How many contributors in California gave to Obama? To Romney?
\end{problem}
It is also possible to execute more complicated queries involving grouping operations, although some care is required.
Consider the following question: how many contributions came from each state, and what is the average contribution
from each state? To answer this question, we need to aggregate information grouped by each state. If we could hold
the data in memory, we could use a simply \li{groupby} operation, but since our data resides on disk, the solution is
a bit more involved. Fortunately, the \li{'contbr_st'} column alone is small enough to load into memory, so we do that.
We can then utilize the \li{Series} method \li{value_counts}, which counts the number of occurrences of each distinct
value in the column. In this way, we obtain a \li{Series} indexed by the states, and containing the number of
contributions from each state.
\begin{lstlisting}
>>> # load in the state column, then calculate the counts
>>> states = store.select_column('campaign','contbr_st')
>>> states = states.value_counts()
\end{lstlisting}
Next, we want to iterate through each state, and calculate the mean contribution.
\begin{lstlisting}
>>> st_contb = []
>>> for state in states.index:
>>> grp = store.select('campaign', where=["'contbr_st'=\"{}\"".format(state), "columns='contb_receipt_amt'"])
>>> st_contb.append(grp['contb_receipt_amt'].mean())
\end{lstlisting}
To tidy up our results, we create a \li{DataFrame} indexed by the state, containing the number of contributions
and average contribution. Then we plot top results.
\begin{lstlisting}
>>> state_info = pd.DataFrame({'Count':states, 'Avg Contb':st_contb})
>>> state_info.sort(columns='Count', ascending=False, inplace=True)
>>> plt.subplot(211)
>>> state_info['Count'][:10].plot(kind='bar')
>>> plt.subplot(212)
>>> state_info['Avg Contb'][:10].plot(kind='bar')
>>> plt.show()
\end{lstlisting}
Results are shown in Figure \ref{pandas:states}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{states.pdf}
\caption{Top 10 contributing states (top), and their average contributions (bottom).}
\label{pandas:states}
\end{figure}
\begin{problem}
Calculate the total net contributions to each candidate, and plot the results in a bar graph.
Your result should match Figure \ref{pandas:cand_contb}.
\end{problem}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{cand_contb.pdf}
\caption{Total net contributions to each candidate.}
\label{pandas:cand_contb}
\end{figure}
\begin{problem}
Calculate the frequency of the 20 most common occupations of contributors in the dataset.
Also calculate the average positive contribution amount for each of these 20 occupations.
Plot the results in two bar graphs. You results should match Figure \ref{pandas:occupation}.
\end{problem}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{occupation.pdf}
\caption{Top 20 occupations of contributors (above) and average contribution of each
occupation (below).}
\label{pandas:occupation}
\end{figure}
What if you are interested in the contributions to a candidate as a function of time?
Let's first aim to create a \li{DataFrame} containing the contribution amount and date for
all contributions going to Ron Paul.
\begin{lstlisting}
>>> cand = 'Paul, Ron'
>>> cand_contb = store.select('campaign', where=["'cand_nm'==\"{}\"".format(cand)])[['contb_receipt_amt', 'contb_receipt_dt']]
\end{lstlisting}
Next, we need to group by date, and apply the sum function to add up contributions for each particular date.
This can be done with the \li{groupby} function as follows:
\begin{lstlisting}
>>> contb = cand_contb.groupby(by='contb_receipt_dt').sum()
\end{lstlisting}
Plotting this time series yields Figure \ref{pandas:paul}.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{paul.pdf}
\caption{Campaign Contributions to Ron Paul over time.}
\label{pandas:paul}
\end{figure}
\begin{problem}
Plot the running total of campaign contributions as a function of time
for Mitt Romney, Barack Obama, and Newt Gingrich (all on the same graph).
Your results should match Figure \ref{pandas:cand_time}.
\end{problem}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{cand_time.pdf}
\caption{Running contribution totals for three candidates.}
\label{pandas:cand_time}
\end{figure}
Each data project brings with it a new set of problems and pitfalls, but a careful application of the principles
in this lab will provide a good starting point for working with large datasets in pandas.
|
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f g : X →[M'] Y
h : f.toFun = g.toFun
⊢ f = g
[PROOFSTEP]
cases f
[GOAL]
case mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
g : X →[M'] Y
toFun✝ : X → Y
map_smul'✝ : ∀ (m : M') (x : X), toFun✝ (m • x) = m • toFun✝ x
h : { toFun := toFun✝, map_smul' := map_smul'✝ }.toFun = g.toFun
⊢ { toFun := toFun✝, map_smul' := map_smul'✝ } = g
[PROOFSTEP]
cases g
[GOAL]
case mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
toFun✝¹ : X → Y
map_smul'✝¹ : ∀ (m : M') (x : X), toFun✝¹ (m • x) = m • toFun✝¹ x
toFun✝ : X → Y
map_smul'✝ : ∀ (m : M') (x : X), toFun✝ (m • x) = m • toFun✝ x
h : { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }.toFun = { toFun := toFun✝, map_smul' := map_smul'✝ }.toFun
⊢ { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } = { toFun := toFun✝, map_smul' := map_smul'✝ }
[PROOFSTEP]
congr
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
g : Y →[M'] Z
f : X →[M'] Y
m : M'
x : X
⊢ ↑g (↑f (m • x)) = ↑g (m • ↑f x)
[PROOFSTEP]
rw [f.map_smul]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : X →[M'] Y
x : X
⊢ ↑(comp (MulActionHom.id M') f) x = ↑f x
[PROOFSTEP]
rw [comp_apply, id_apply]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : X →[M'] Y
x : X
⊢ ↑(comp f (MulActionHom.id M')) x = ↑f x
[PROOFSTEP]
rw [comp_apply, id_apply]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : A →[M] B
g : B → A
h₁ : Function.LeftInverse g ↑f
h₂ : Function.RightInverse g ↑f
m : M
x : B
⊢ g (m • x) = g (m • ↑f (g x))
[PROOFSTEP]
rw [h₂]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : A →[M] B
g : B → A
h₁ : Function.LeftInverse g ↑f
h₂ : Function.RightInverse g ↑f
m : M
x : B
⊢ g (m • ↑f (g x)) = g (↑f (m • g x))
[PROOFSTEP]
rw [f.map_smul]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : A →[M] B
g : B → A
h₁ : Function.LeftInverse g ↑f
h₂ : Function.RightInverse g ↑f
m : M
x : B
⊢ g (↑f (m • g x)) = m • g x
[PROOFSTEP]
rw [h₁]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f g : A →+[M] B
h : (fun m => m.toFun) f = (fun m => m.toFun) g
⊢ f = g
[PROOFSTEP]
rcases f with ⟨tF, _, _⟩
[GOAL]
case mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
g : A →+[M] B
tF : A →[M] B
map_zero'✝ : MulActionHom.toFun tF 0 = 0
map_add'✝ : ∀ (x y : A), MulActionHom.toFun tF (x + y) = MulActionHom.toFun tF x + MulActionHom.toFun tF y
h : (fun m => m.toFun) { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ } = (fun m => m.toFun) g
⊢ { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ } = g
[PROOFSTEP]
rcases g with ⟨tG, _, _⟩
[GOAL]
case mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
tF : A →[M] B
map_zero'✝¹ : MulActionHom.toFun tF 0 = 0
map_add'✝¹ : ∀ (x y : A), MulActionHom.toFun tF (x + y) = MulActionHom.toFun tF x + MulActionHom.toFun tF y
tG : A →[M] B
map_zero'✝ : MulActionHom.toFun tG 0 = 0
map_add'✝ : ∀ (x y : A), MulActionHom.toFun tG (x + y) = MulActionHom.toFun tG x + MulActionHom.toFun tG y
h :
(fun m => m.toFun) { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ } =
(fun m => m.toFun) { toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ }
⊢ { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ } =
{ toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ }
[PROOFSTEP]
cases tF
[GOAL]
case mk.mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
tG : A →[M] B
map_zero'✝¹ : MulActionHom.toFun tG 0 = 0
map_add'✝¹ : ∀ (x y : A), MulActionHom.toFun tG (x + y) = MulActionHom.toFun tG x + MulActionHom.toFun tG y
toFun✝ : A → B
map_smul'✝ : ∀ (m : M) (x : A), toFun✝ (m • x) = m • toFun✝ x
map_zero'✝ : MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } 0 = 0
map_add'✝ :
∀ (x y : A),
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } (x + y) =
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } x +
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } y
h :
(fun m => m.toFun)
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ } =
(fun m => m.toFun) { toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }
⊢ { toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝, map_add' := map_add'✝ } =
{ toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }
[PROOFSTEP]
cases tG
[GOAL]
case mk.mk.mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
toFun✝¹ : A → B
map_smul'✝¹ : ∀ (m : M) (x : A), toFun✝¹ (m • x) = m • toFun✝¹ x
map_zero'✝¹ : MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } 0 = 0
map_add'✝¹ :
∀ (x y : A),
MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } (x + y) =
MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } x +
MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } y
toFun✝ : A → B
map_smul'✝ : ∀ (m : M) (x : A), toFun✝ (m • x) = m • toFun✝ x
map_zero'✝ : MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } 0 = 0
map_add'✝ :
∀ (x y : A),
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } (x + y) =
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } x +
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } y
h :
(fun m => m.toFun)
{ toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ } =
(fun m => m.toFun)
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝, map_add' := map_add'✝ }
⊢ { toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ } =
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝, map_add' := map_add'✝ }
[PROOFSTEP]
congr
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f g : A →+[M] B
h : ↑f = ↑g
⊢ f = g
[PROOFSTEP]
ext a
[GOAL]
case a
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f g : A →+[M] B
h : ↑f = ↑g
a : A
⊢ ↑f a = ↑g a
[PROOFSTEP]
exact MulActionHom.congr_fun h a
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f g : A →+[M] B
h : ↑f = ↑g
⊢ f = g
[PROOFSTEP]
ext a
[GOAL]
case a
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f g : A →+[M] B
h : ↑f = ↑g
a : A
⊢ ↑f a = ↑g a
[PROOFSTEP]
exact FunLike.congr_fun h a
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
x : A
⊢ ↑(DistribMulActionHom.id M) x = x
[PROOFSTEP]
rfl
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
src✝ : A →+ B := 0
m : M
x✝ : A
⊢ ZeroHom.toFun (↑src✝) (m • x✝) = m • ZeroHom.toFun (↑src✝) x✝
[PROOFSTEP]
change (0 : B) = m • (0 : B)
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
src✝ : A →+ B := 0
m : M
x✝ : A
⊢ 0 = m • 0
[PROOFSTEP]
rw [smul_zero]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : A →+[M] B
x : A
⊢ ↑(comp (DistribMulActionHom.id M) f) x = ↑f x
[PROOFSTEP]
rw [comp_apply, id_apply]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : A →+[M] B
x : A
⊢ ↑(comp f (DistribMulActionHom.id M)) x = ↑f x
[PROOFSTEP]
rw [comp_apply, id_apply]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²⁵ : SMul M' X
Y : Type u_3
inst✝²⁴ : SMul M' Y
Z : Type u_4
inst✝²³ : SMul M' Z
M : Type u_5
inst✝²² : Monoid M
A : Type u_6
inst✝²¹ : AddMonoid A
inst✝²⁰ : DistribMulAction M A
A' : Type u_7
inst✝¹⁹ : AddGroup A'
inst✝¹⁸ : DistribMulAction M A'
B : Type u_8
inst✝¹⁷ : AddMonoid B
inst✝¹⁶ : DistribMulAction M B
B' : Type u_9
inst✝¹⁵ : AddGroup B'
inst✝¹⁴ : DistribMulAction M B'
C : Type u_10
inst✝¹³ : AddMonoid C
inst✝¹² : DistribMulAction M C
R : Type u_11
inst✝¹¹ : Semiring R
inst✝¹⁰ : MulSemiringAction M R
R' : Type u_12
inst✝⁹ : Ring R'
inst✝⁸ : MulSemiringAction M R'
S : Type u_13
inst✝⁷ : Semiring S
inst✝⁶ : MulSemiringAction M S
S' : Type u_14
inst✝⁵ : Ring S'
inst✝⁴ : MulSemiringAction M S'
T : Type u_15
inst✝³ : Semiring T
inst✝² : MulSemiringAction M T
inst✝¹ : AddMonoid M'
inst✝ : DistribMulAction R M'
f g : R →+[R] M'
h : ↑f 1 = ↑g 1
⊢ f = g
[PROOFSTEP]
ext x
[GOAL]
case a
M' : Type u_1
X : Type u_2
inst✝²⁵ : SMul M' X
Y : Type u_3
inst✝²⁴ : SMul M' Y
Z : Type u_4
inst✝²³ : SMul M' Z
M : Type u_5
inst✝²² : Monoid M
A : Type u_6
inst✝²¹ : AddMonoid A
inst✝²⁰ : DistribMulAction M A
A' : Type u_7
inst✝¹⁹ : AddGroup A'
inst✝¹⁸ : DistribMulAction M A'
B : Type u_8
inst✝¹⁷ : AddMonoid B
inst✝¹⁶ : DistribMulAction M B
B' : Type u_9
inst✝¹⁵ : AddGroup B'
inst✝¹⁴ : DistribMulAction M B'
C : Type u_10
inst✝¹³ : AddMonoid C
inst✝¹² : DistribMulAction M C
R : Type u_11
inst✝¹¹ : Semiring R
inst✝¹⁰ : MulSemiringAction M R
R' : Type u_12
inst✝⁹ : Ring R'
inst✝⁸ : MulSemiringAction M R'
S : Type u_13
inst✝⁷ : Semiring S
inst✝⁶ : MulSemiringAction M S
S' : Type u_14
inst✝⁵ : Ring S'
inst✝⁴ : MulSemiringAction M S'
T : Type u_15
inst✝³ : Semiring T
inst✝² : MulSemiringAction M T
inst✝¹ : AddMonoid M'
inst✝ : DistribMulAction R M'
f g : R →+[R] M'
h : ↑f 1 = ↑g 1
x : R
⊢ ↑f x = ↑g x
[PROOFSTEP]
rw [← mul_one x, ← smul_eq_mul R, f.map_smul, g.map_smul, h]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f g : R →+*[M] S
h : (fun m => m.toFun) f = (fun m => m.toFun) g
⊢ f = g
[PROOFSTEP]
rcases f with ⟨⟨tF, _, _⟩, _, _⟩
[GOAL]
case mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
g : R →+*[M] S
tF : R →[M] S
map_zero'✝ : MulActionHom.toFun tF 0 = 0
map_add'✝ : ∀ (x y : R), MulActionHom.toFun tF (x + y) = MulActionHom.toFun tF x + MulActionHom.toFun tF y
map_one'✝ :
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom 1 = 1
map_mul'✝ :
∀ (x y : R),
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom (x * y) =
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom x *
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom y
h :
(fun m => m.toFun)
{ toDistribMulActionHom := { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ } =
(fun m => m.toFun) g
⊢ { toDistribMulActionHom := { toMulActionHom := tF, map_zero' := map_zero'✝, map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ } =
g
[PROOFSTEP]
rcases g with ⟨⟨tG, _, _⟩, _, _⟩
[GOAL]
case mk.mk.mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
tF : R →[M] S
map_zero'✝¹ : MulActionHom.toFun tF 0 = 0
map_add'✝¹ : ∀ (x y : R), MulActionHom.toFun tF (x + y) = MulActionHom.toFun tF x + MulActionHom.toFun tF y
map_one'✝¹ :
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom 1 = 1
map_mul'✝¹ :
∀ (x y : R),
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom
(x * y) =
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom x *
MulActionHom.toFun { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom y
tG : R →[M] S
map_zero'✝ : MulActionHom.toFun tG 0 = 0
map_add'✝ : ∀ (x y : R), MulActionHom.toFun tG (x + y) = MulActionHom.toFun tG x + MulActionHom.toFun tG y
map_one'✝ :
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom 1 = 1
map_mul'✝ :
∀ (x y : R),
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom (x * y) =
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom x *
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ }.toMulActionHom y
h :
(fun m => m.toFun)
{ toDistribMulActionHom := { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ },
map_one' := map_one'✝¹, map_mul' := map_mul'✝¹ } =
(fun m => m.toFun)
{ toDistribMulActionHom := { toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ }
⊢ { toDistribMulActionHom := { toMulActionHom := tF, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ },
map_one' := map_one'✝¹, map_mul' := map_mul'✝¹ } =
{ toDistribMulActionHom := { toMulActionHom := tG, map_zero' := map_zero'✝, map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ }
[PROOFSTEP]
cases tF
[GOAL]
case mk.mk.mk.mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
tG : R →[M] S
map_zero'✝¹ : MulActionHom.toFun tG 0 = 0
map_add'✝¹ : ∀ (x y : R), MulActionHom.toFun tG (x + y) = MulActionHom.toFun tG x + MulActionHom.toFun tG y
map_one'✝¹ :
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom 1 = 1
map_mul'✝¹ :
∀ (x y : R),
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom
(x * y) =
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom x *
MulActionHom.toFun { toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ }.toMulActionHom y
toFun✝ : R → S
map_smul'✝ : ∀ (m : M) (x : R), toFun✝ (m • x) = m • toFun✝ x
map_zero'✝ : MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } 0 = 0
map_add'✝ :
∀ (x y : R),
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } (x + y) =
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } x +
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } y
map_one'✝ :
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
1 =
1
map_mul'✝ :
∀ (x y : R),
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
(x * y) =
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
x *
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
y
h :
(fun m => m.toFun)
{
toDistribMulActionHom :=
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ } =
(fun m => m.toFun)
{ toDistribMulActionHom := { toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ },
map_one' := map_one'✝¹, map_mul' := map_mul'✝¹ }
⊢ {
toDistribMulActionHom :=
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ } =
{ toDistribMulActionHom := { toMulActionHom := tG, map_zero' := map_zero'✝¹, map_add' := map_add'✝¹ },
map_one' := map_one'✝¹, map_mul' := map_mul'✝¹ }
[PROOFSTEP]
cases tG
[GOAL]
case mk.mk.mk.mk.mk.mk
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
toFun✝¹ : R → S
map_smul'✝¹ : ∀ (m : M) (x : R), toFun✝¹ (m • x) = m • toFun✝¹ x
map_zero'✝¹ : MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } 0 = 0
map_add'✝¹ :
∀ (x y : R),
MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } (x + y) =
MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } x +
MulActionHom.toFun { toFun := toFun✝¹, map_smul' := map_smul'✝¹ } y
map_one'✝¹ :
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ }.toMulActionHom
1 =
1
map_mul'✝¹ :
∀ (x y : R),
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ }.toMulActionHom
(x * y) =
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ }.toMulActionHom
x *
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ }.toMulActionHom
y
toFun✝ : R → S
map_smul'✝ : ∀ (m : M) (x : R), toFun✝ (m • x) = m • toFun✝ x
map_zero'✝ : MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } 0 = 0
map_add'✝ :
∀ (x y : R),
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } (x + y) =
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } x +
MulActionHom.toFun { toFun := toFun✝, map_smul' := map_smul'✝ } y
map_one'✝ :
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
1 =
1
map_mul'✝ :
∀ (x y : R),
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
(x * y) =
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
x *
MulActionHom.toFun
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ }.toMulActionHom
y
h :
(fun m => m.toFun)
{
toDistribMulActionHom :=
{ toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ },
map_one' := map_one'✝¹, map_mul' := map_mul'✝¹ } =
(fun m => m.toFun)
{
toDistribMulActionHom :=
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ }
⊢ {
toDistribMulActionHom :=
{ toMulActionHom := { toFun := toFun✝¹, map_smul' := map_smul'✝¹ }, map_zero' := map_zero'✝¹,
map_add' := map_add'✝¹ },
map_one' := map_one'✝¹, map_mul' := map_mul'✝¹ } =
{
toDistribMulActionHom :=
{ toMulActionHom := { toFun := toFun✝, map_smul' := map_smul'✝ }, map_zero' := map_zero'✝,
map_add' := map_add'✝ },
map_one' := map_one'✝, map_mul' := map_mul'✝ }
[PROOFSTEP]
congr
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : R →+*[M] S
x : R
⊢ ↑(comp (MulSemiringActionHom.id M) f) x = ↑f x
[PROOFSTEP]
rw [comp_apply, id_apply]
[GOAL]
M' : Type u_1
X : Type u_2
inst✝²³ : SMul M' X
Y : Type u_3
inst✝²² : SMul M' Y
Z : Type u_4
inst✝²¹ : SMul M' Z
M : Type u_5
inst✝²⁰ : Monoid M
A : Type u_6
inst✝¹⁹ : AddMonoid A
inst✝¹⁸ : DistribMulAction M A
A' : Type u_7
inst✝¹⁷ : AddGroup A'
inst✝¹⁶ : DistribMulAction M A'
B : Type u_8
inst✝¹⁵ : AddMonoid B
inst✝¹⁴ : DistribMulAction M B
B' : Type u_9
inst✝¹³ : AddGroup B'
inst✝¹² : DistribMulAction M B'
C : Type u_10
inst✝¹¹ : AddMonoid C
inst✝¹⁰ : DistribMulAction M C
R : Type u_11
inst✝⁹ : Semiring R
inst✝⁸ : MulSemiringAction M R
R' : Type u_12
inst✝⁷ : Ring R'
inst✝⁶ : MulSemiringAction M R'
S : Type u_13
inst✝⁵ : Semiring S
inst✝⁴ : MulSemiringAction M S
S' : Type u_14
inst✝³ : Ring S'
inst✝² : MulSemiringAction M S'
T : Type u_15
inst✝¹ : Semiring T
inst✝ : MulSemiringAction M T
f : R →+*[M] S
x : R
⊢ ↑(comp f (MulSemiringActionHom.id M)) x = ↑f x
[PROOFSTEP]
rw [comp_apply, id_apply]
|
{-# OPTIONS --safe #-}
open import Definition.Typed.EqualityRelation
module Definition.LogicalRelation {{eqrel : EqRelSet}} where
open EqRelSet {{...}}
open import Definition.Untyped as U
open import Definition.Typed
open import Definition.Typed.Weakening
open import Definition.Typed.Reduction
open import Tools.Product
import Tools.PropositionalEquality as PE
import Data.Fin as Fin
import Data.Nat as Nat
-- The different cases of the logical relation are spread out through out
-- this file. This is due to them having different dependencies.
-- We will refer to expressions that satisfies the logical relation as reducible.
-- Reducibility of Neutrals:
-- Neutral type
record _⊩ne_^[_,_] (Γ : Con Term) (A : Term) (r : Relevance) (l : Level) : Set where
constructor ne
field
K : Term
D : Γ ⊢ A :⇒*: K ^ [ r , ι l ]
neK : Neutral K
K≡K : Γ ⊢ K ~ K ∷ (Univ r l) ^ [ ! , next l ]
-- Neutral type equality
record _⊩ne_≡_^[_,_]/_ (Γ : Con Term) (A B : Term) (r : Relevance) (l : Level) ([A] : Γ ⊩ne A ^[ r , l ]) : Set where
constructor ne₌
open _⊩ne_^[_,_] [A]
field
M : Term
D′ : Γ ⊢ B :⇒*: M ^ [ r , ι l ]
neM : Neutral M
K≡M : Γ ⊢ K ~ M ∷ (Univ r l) ^ [ ! , next l ]
-- Neutral term in WHNF
record _⊩neNf_∷_^_ (Γ : Con Term) (k A : Term) (r : TypeInfo) : Set where
inductive
constructor neNfₜ
field
neK : Neutral k
⊢k : Γ ⊢ k ∷ A ^ r
k≡k : Γ ⊢ k ~ k ∷ A ^ r
-- Neutral relevant term
record _⊩ne_∷_^_/_ (Γ : Con Term) (t A : Term) (l : Level) ([A] : Γ ⊩ne A ^[ ! , l ]) : Set where
inductive
constructor neₜ
open _⊩ne_^[_,_] [A]
field
k : Term
d : Γ ⊢ t :⇒*: k ∷ K ^ ι l
nf : Γ ⊩neNf k ∷ K ^ [ ! , ι l ]
-- Neutral irrelevant term
record _⊩neIrr_∷_^_/_ (Γ : Con Term) (t A : Term) (l : Level) ([A] : Γ ⊩ne A ^[ % , l ]) : Set where
inductive
constructor neₜ
open _⊩ne_^[_,_] [A]
field
d : Γ ⊢ t ∷ A ^ [ % , ι l ]
-- Neutral term equality in WHNF
record _⊩neNf_≡_∷_^_ (Γ : Con Term) (k m A : Term) (r : TypeInfo) : Set where
inductive
constructor neNfₜ₌
field
neK : Neutral k
neM : Neutral m
k≡m : Γ ⊢ k ~ m ∷ A ^ r
-- Neutral relevant term equality
record _⊩ne_≡_∷_^_/_ (Γ : Con Term) (t u A : Term) (l : Level) ([A] : Γ ⊩ne A ^[ ! , l ]) : Set where
constructor neₜ₌
open _⊩ne_^[_,_] [A]
field
k m : Term
d : Γ ⊢ t :⇒*: k ∷ K ^ ι l
d′ : Γ ⊢ u :⇒*: m ∷ K ^ ι l
nf : Γ ⊩neNf k ≡ m ∷ K ^ [ ! , ι l ]
-- Neutral irrelevant term equality
record _⊩neIrr_≡_∷_^_/_ (Γ : Con Term) (t u A : Term) (l : Level) ([A] : Γ ⊩ne A ^[ % , l ]) : Set where
constructor neₜ₌
open _⊩ne_^[_,_] [A]
field
d : Γ ⊢ t ∷ A ^ [ % , ι l ]
d′ : Γ ⊢ u ∷ A ^ [ % , ι l ]
-- Reducibility of natural numbers:
-- Natural number type
_⊩ℕ_ : (Γ : Con Term) (A : Term) → Set
Γ ⊩ℕ A = Γ ⊢ A :⇒*: ℕ ^ [ ! , ι ⁰ ]
-- Natural number type equality
_⊩ℕ_≡_ : (Γ : Con Term) (A B : Term) → Set
Γ ⊩ℕ A ≡ B = Γ ⊢ B ⇒* ℕ ^ [ ! , ι ⁰ ]
mutual
-- Natural number term
data _⊩ℕ_∷ℕ (Γ : Con Term) (t : Term) : Set where
ℕₜ : (n : Term) (d : Γ ⊢ t :⇒*: n ∷ ℕ ^ ι ⁰) (n≡n : Γ ⊢ n ≅ n ∷ ℕ ^ [ ! , ι ⁰ ])
(prop : Natural-prop Γ n)
→ Γ ⊩ℕ t ∷ℕ
-- WHNF property of natural number terms
data Natural-prop (Γ : Con Term) : (n : Term) → Set where
sucᵣ : ∀ {n} → Γ ⊩ℕ n ∷ℕ → Natural-prop Γ (suc n)
zeroᵣ : Natural-prop Γ zero
ne : ∀ {n} → Γ ⊩neNf n ∷ ℕ ^ [ ! , ι ⁰ ] → Natural-prop Γ n
mutual
-- Natural number term equality
data _⊩ℕ_≡_∷ℕ (Γ : Con Term) (t u : Term) : Set where
ℕₜ₌ : (k k′ : Term) (d : Γ ⊢ t :⇒*: k ∷ ℕ ^ ι ⁰) (d′ : Γ ⊢ u :⇒*: k′ ∷ ℕ ^ ι ⁰)
(k≡k′ : Γ ⊢ k ≅ k′ ∷ ℕ ^ [ ! , ι ⁰ ])
(prop : [Natural]-prop Γ k k′) → Γ ⊩ℕ t ≡ u ∷ℕ
-- WHNF property of Natural number term equality
data [Natural]-prop (Γ : Con Term) : (n n′ : Term) → Set where
sucᵣ : ∀ {n n′} → Γ ⊩ℕ n ≡ n′ ∷ℕ → [Natural]-prop Γ (suc n) (suc n′)
zeroᵣ : [Natural]-prop Γ zero zero
ne : ∀ {n n′} → Γ ⊩neNf n ≡ n′ ∷ ℕ ^ [ ! , ι ⁰ ] → [Natural]-prop Γ n n′
-- Natural extraction from term WHNF property
natural : ∀ {Γ n} → Natural-prop Γ n → Natural n
natural (sucᵣ x) = sucₙ
natural zeroᵣ = zeroₙ
natural (ne (neNfₜ neK ⊢k k≡k)) = ne neK
-- Natural extraction from term equality WHNF property
split : ∀ {Γ a b} → [Natural]-prop Γ a b → Natural a × Natural b
split (sucᵣ x) = sucₙ , sucₙ
split zeroᵣ = zeroₙ , zeroₙ
split (ne (neNfₜ₌ neK neM k≡m)) = ne neK , ne neM
-- Reducibility of Empty
-- Empty type
_⊩Empty_^_ : (Γ : Con Term) (A : Term) (l : Level) → Set
Γ ⊩Empty A ^ l = Γ ⊢ A :⇒*: Empty l ^ [ % , ι l ]
-- Empty type equality
_⊩Empty_≡_^_ : (Γ : Con Term) (A B : Term) (l : Level) → Set
Γ ⊩Empty A ≡ B ^ l = Γ ⊢ B ⇒* Empty l ^ [ % , ι l ]
data Empty-prop (Γ : Con Term) (n : Term) (l : Level) : Set where
ne : Γ ⊢ n ∷ Empty l ^ [ % , ι l ] → Empty-prop Γ n l
-- -- Empty term
data _⊩Empty_∷Empty^_ (Γ : Con Term) (t : Term) (l : Level) : Set where
Emptyₜ : (prop : Empty-prop Γ t l) → Γ ⊩Empty t ∷Empty^ l
data [Empty]-prop (Γ : Con Term) : (n n′ : Term) (l : Level) → Set where
ne : ∀ {n n′ l} → Γ ⊢ n ∷ Empty l ^ [ % , ι l ] → Γ ⊢ n′ ∷ Empty l ^ [ % , ι l ] → [Empty]-prop Γ n n′ l
-- Empty term equality
data _⊩Empty_≡_∷Empty^_ (Γ : Con Term) (t u : Term) (l : Level) : Set where
Emptyₜ₌ : (prop : [Empty]-prop Γ t u l) → Γ ⊩Empty t ≡ u ∷Empty^ l
-- Logical relation
record LogRelKit : Set₁ where
constructor Kit
field
_⊩U_^_ : (Γ : Con Term) → Term → TypeLevel → Set
_⊩Π_^[_,_] : (Γ : Con Term) → Term → Relevance → Level → Set
_⊩∃_^_ : (Γ : Con Term) → Term → Level → Set
_⊩_^_ : (Γ : Con Term) → Term → TypeInfo → Set
_⊩_≡_^_/_ : (Γ : Con Term) (A B : Term) (r : TypeInfo) → Γ ⊩ A ^ r → Set
_⊩_∷_^_/_ : (Γ : Con Term) (t A : Term) (r : TypeInfo) → Γ ⊩ A ^ r → Set
_⊩_≡_∷_^_/_ : (Γ : Con Term) (t u A : Term) (r : TypeInfo) → Γ ⊩ A ^ r → Set
module LogRel (l : TypeLevel) (rec : ∀ {l′} → l′ <∞ l → LogRelKit) where
-- Reducibility of Universe:
-- Universe type
record _⊩¹U_^_ (Γ : Con Term) (A : Term) (ll : TypeLevel) : Set where
constructor Uᵣ
field
r : Relevance
l′ : Level
l< : ι l′ <∞ l
eq : next l′ PE.≡ ll
d : Γ ⊢ A :⇒*: Univ r l′ ^ [ ! , next l′ ]
-- Universe type equality
_⊩¹U_≡_^_/_ : (Γ : Con Term) (A B : Term) (ll : TypeLevel) ([A] : Γ ⊩¹U A ^ ll) → Set
Γ ⊩¹U A ≡ B ^ ll / [A] = Γ ⊢ B ⇒* Univ (_⊩¹U_^_.r [A]) (_⊩¹U_^_.l′ [A]) ^ [ ! , ll ]
-- Universe term
record _⊩¹U_∷_^_/_ (Γ : Con Term) (t : Term) (A : Term) (ll : TypeLevel) ([A] : Γ ⊩¹U A ^ ll) : Set where
constructor Uₜ
open _⊩¹U_^_ [A]
open LogRelKit (rec l<)
field
K : Term
d : Γ ⊢ t :⇒*: K ∷ Univ r l′ ^ next l′
typeK : Type K
K≡K : Γ ⊢ K ≅ K ∷ Univ r l′ ^ [ ! , next l′ ]
[t] : ∀ {ρ Δ} → ρ ∷ Δ ⊆ Γ → (⊢Δ : ⊢ Δ) → Δ ⊩ U.wk ρ t ^ [ r , ι l′ ]
-- Universe term equality
record _⊩¹U_≡_∷_^_/_ (Γ : Con Term) (t u : Term) (X : Term) (ll : TypeLevel) ([X] : Γ ⊩¹U X ^ ll) : Set where
constructor Uₜ₌
open _⊩¹U_^_ [X]
open LogRelKit (rec l<)
field
[t] : Γ ⊩¹U t ∷ X ^ ll / [X]
[u] : Γ ⊩¹U u ∷ X ^ ll / [X]
A≡B : Γ ⊢ _⊩¹U_∷_^_/_.K [t] ≅ _⊩¹U_∷_^_/_.K [u] ∷ Univ r l′ ^ [ ! , next l′ ]
[t≡u] : ∀ {ρ Δ} → ([ρ] : ρ ∷ Δ ⊆ Γ) → (⊢Δ : ⊢ Δ) → Δ ⊩ U.wk ρ t ≡ U.wk ρ u ^ [ r , ι l′ ] / _⊩¹U_∷_^_/_.[t] [t] [ρ] ⊢Δ
mutual
-- Reducibility of Π:
-- Π-type
record _⊩¹Π_^[_,_] (Γ : Con Term) (A : Term) (r : Relevance) (lΠ : Level) : Set where
inductive
eta-equality
constructor Πᵣ
field
rF : Relevance
lF : Level
lG : Level
lF≤ : lF ≤ lΠ
lG≤ : lG ≤ lΠ
F : Term
G : Term
D : Γ ⊢ A :⇒*: Π F ^ rF ° lF ▹ G ° lG ° lΠ ^ [ r , ι lΠ ]
⊢F : Γ ⊢ F ^ [ rF , ι lF ]
⊢G : Γ ∙ F ^ [ rF , ι lF ] ⊢ G ^ [ r , ι lG ]
A≡A : Γ ⊢ Π F ^ rF ° lF ▹ G ° lG ° lΠ ≅ Π F ^ rF ° lF ▹ G ° lG ° lΠ ^ [ r , ι lΠ ]
[F] : ∀ {ρ Δ} → ρ ∷ Δ ⊆ Γ → (⊢Δ : ⊢ Δ) → Δ ⊩¹ U.wk ρ F ^ [ rF , ι lF ]
[G] : ∀ {ρ Δ a}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ Δ ⊩¹ a ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ
→ Δ ⊩¹ U.wk (lift ρ) G [ a ] ^ [ r , ι lG ]
G-ext : ∀ {ρ Δ a b}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ ([a] : Δ ⊩¹ a ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
→ ([b] : Δ ⊩¹ b ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
→ Δ ⊩¹ a ≡ b ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ
→ Δ ⊩¹ U.wk (lift ρ) G [ a ] ≡ U.wk (lift ρ) G [ b ] ^ [ r , ι lG ] / [G] [ρ] ⊢Δ [a]
-- Π-type equality
record _⊩¹Π_≡_^[_,_]/_ (Γ : Con Term) (A B : Term) (r : Relevance) (lΠ : Level) ([A] : Γ ⊩¹Π A ^[ r , lΠ ]) : Set where
inductive
eta-equality
constructor Π₌
open _⊩¹Π_^[_,_] [A]
field
F′ : Term
G′ : Term
D′ : Γ ⊢ B ⇒* Π F′ ^ rF ° lF ▹ G′ ° lG ° lΠ ^ [ r , ι lΠ ]
A≡B : Γ ⊢ Π F ^ rF ° lF ▹ G ° lG ° lΠ ≅ Π F′ ^ rF ° lF ▹ G′ ° lG ° lΠ ^ [ r , ι lΠ ]
[F≡F′] : ∀ {ρ Δ}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ Δ ⊩¹ U.wk ρ F ≡ U.wk ρ F′ ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ
[G≡G′] : ∀ {ρ Δ a}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ ([a] : Δ ⊩¹ a ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
→ Δ ⊩¹ U.wk (lift ρ) G [ a ] ≡ U.wk (lift ρ) G′ [ a ] ^ [ r , ι lG ] / [G] [ρ] ⊢Δ [a]
-- relevant Term of Π-type
_⊩¹Π_∷_^_/_ : (Γ : Con Term) (t A : Term) (lΠ : Level) ([A] : Γ ⊩¹Π A ^[ ! , lΠ ]) → Set
Γ ⊩¹Π t ∷ A ^ lΠ / Πᵣ rF lF lG lF≤ lG≤ F G D ⊢F ⊢G A≡A [F] [G] G-ext =
∃ λ f → Γ ⊢ t :⇒*: f ∷ Π F ^ rF ° lF ▹ G ° lG ° lΠ ^ ι lΠ
× Function f
× Γ ⊢ f ≅ f ∷ Π F ^ rF ° lF ▹ G ° lG ° lΠ ^ [ ! , ι lΠ ]
× (∀ {ρ Δ a b}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
([a] : Δ ⊩¹ a ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
([b] : Δ ⊩¹ b ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
([a≡b] : Δ ⊩¹ a ≡ b ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
→ Δ ⊩¹ U.wk ρ f ∘ a ^ lΠ ≡ U.wk ρ f ∘ b ^ lΠ ∷ U.wk (lift ρ) G [ a ] ^ [ ! , ι lG ] / [G] [ρ] ⊢Δ [a])
× (∀ {ρ Δ a} → ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ ([a] : Δ ⊩¹ a ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
→ Δ ⊩¹ U.wk ρ f ∘ a ^ lΠ ∷ U.wk (lift ρ) G [ a ] ^ [ ! , ι lG ] / [G] [ρ] ⊢Δ [a])
-- Issue: Agda complains about record use not being strictly positive.
-- Therefore we have to use ×
-- Irrelevant term of Π-type
_⊩¹Πirr_∷_^_/_ : (Γ : Con Term) (t A : Term) (l′ : Level) ([A] : Γ ⊩¹Π A ^[ % , l′ ]) → Set
Γ ⊩¹Πirr t ∷ A ^ l′ / Πᵣ rF lF lG lF≤ lG≤ F G D ⊢F ⊢G A≡A [F] [G] G-ext =
Γ ⊢ t ∷ Π F ^ rF ° lF ▹ G ° lG ° l′ ^ [ % , ι l′ ]
-- Term equality of Π-type
_⊩¹Π_≡_∷_^_/_ : (Γ : Con Term) (t u A : Term) (l′ : Level) ([A] : Γ ⊩¹Π A ^[ ! , l′ ]) → Set
Γ ⊩¹Π t ≡ u ∷ A ^ l′ / Πᵣ rF lF lG lF≤ lG≤ F G D ⊢F ⊢G A≡A [F] [G] G-ext =
let [A] = Πᵣ rF lF lG lF≤ lG≤ F G D ⊢F ⊢G A≡A [F] [G] G-ext
in ∃₂ λ f g →
( Γ ⊢ t :⇒*: f ∷ Π F ^ rF ° lF ▹ G ° lG ° l′ ^ ι l′ )
× ( Γ ⊢ u :⇒*: g ∷ Π F ^ rF ° lF ▹ G ° lG ° l′ ^ ι l′ )
× Function f
× Function g
× Γ ⊢ f ≅ g ∷ Π F ^ rF ° lF ▹ G ° lG ° l′ ^ [ ! , ι l′ ]
× Γ ⊩¹Π t ∷ A ^ l′ / [A]
× Γ ⊩¹Π u ∷ A ^ l′ / [A]
× (∀ {ρ Δ a} → ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ ([a] : Δ ⊩¹ a ∷ U.wk ρ F ^ [ rF , ι lF ] / [F] [ρ] ⊢Δ)
→ Δ ⊩¹ U.wk ρ f ∘ a ^ l′ ≡ U.wk ρ g ∘ a ^ l′ ∷ U.wk (lift ρ) G [ a ] ^ [ ! , ι lG ] / [G] [ρ] ⊢Δ [a])
-- Issue: Same as above.
-- Irrelevant term equality of Π-type
_⊩¹Πirr_≡_∷_^_/_ : (Γ : Con Term) (t u A : Term) (l′ : Level) ([A] : Γ ⊩¹Π A ^[ % , l′ ] ) → Set
Γ ⊩¹Πirr t ≡ u ∷ A ^ l′ / Πᵣ rF lF lG lF≤ lG≤ F G D ⊢F ⊢G A≡A [F] [G] G-ext =
(Γ ⊢ t ∷ Π F ^ rF ° lF ▹ G ° lG ° l′ ^ [ % , ι l′ ])
×
(Γ ⊢ u ∷ Π F ^ rF ° lF ▹ G ° lG ° l′ ^ [ % , ι l′ ])
-- Existential types
record _⊩¹∃_^_ (Γ : Con Term) (A : Term) (l′ : Level) : Set where
inductive
eta-equality
constructor ∃ᵣ
field
F : Term
G : Term
D : Γ ⊢ A :⇒*: ∃ F ▹ G ^ [ % , ι l′ ]
⊢F : Γ ⊢ F ^ [ % , ι l′ ]
⊢G : Γ ∙ F ^ [ % , ι l′ ] ⊢ G ^ [ % , ι l′ ]
A≡A : Γ ⊢ (∃ F ▹ G) ≅ (∃ F ▹ G) ^ [ % , ι l′ ]
[F] : ∀ {ρ Δ} → ρ ∷ Δ ⊆ Γ → (⊢Δ : ⊢ Δ) → Δ ⊩¹ U.wk ρ F ^ [ % , ι l′ ]
[G] : ∀ {ρ Δ a}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ Δ ⊩¹ a ∷ U.wk ρ F ^ [ % , ι l′ ] / [F] [ρ] ⊢Δ
→ Δ ⊩¹ U.wk (lift ρ) G [ a ] ^ [ % , ι l′ ]
G-ext : ∀ {ρ Δ a b}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ ([a] : Δ ⊩¹ a ∷ U.wk ρ F ^ [ % , ι l′ ] / [F] [ρ] ⊢Δ)
→ ([b] : Δ ⊩¹ b ∷ U.wk ρ F ^ [ % , ι l′ ] / [F] [ρ] ⊢Δ)
→ Δ ⊩¹ a ≡ b ∷ U.wk ρ F ^ [ % , ι l′ ] / [F] [ρ] ⊢Δ
→ Δ ⊩¹ U.wk (lift ρ) G [ a ] ≡ U.wk (lift ρ) G [ b ] ^ [ % , ι l′ ] / [G] [ρ] ⊢Δ [a]
-- ∃-type equality
record _⊩¹∃_≡_^_/_ (Γ : Con Term) (A B : Term) (l′ : Level) ([A] : Γ ⊩¹∃ A ^ l′) : Set where
inductive
eta-equality
constructor ∃₌
open _⊩¹∃_^_ [A]
field
F′ : Term
G′ : Term
D′ : Γ ⊢ B ⇒* ∃ F′ ▹ G′ ^ [ % , ι l′ ]
A≡B : Γ ⊢ ∃ F ▹ G ≅ ∃ F′ ▹ G′ ^ [ % , ι l′ ]
[F≡F′] : ∀ {ρ Δ}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ Δ ⊩¹ U.wk ρ F ≡ U.wk ρ F′ ^ [ % , ι l′ ] / [F] [ρ] ⊢Δ
[G≡G′] : ∀ {ρ Δ a}
→ ([ρ] : ρ ∷ Δ ⊆ Γ) (⊢Δ : ⊢ Δ)
→ ([a] : Δ ⊩¹ a ∷ U.wk ρ F ^ [ % , ι l′ ] / [F] [ρ] ⊢Δ)
→ Δ ⊩¹ U.wk (lift ρ) G [ a ] ≡ U.wk (lift ρ) G′ [ a ] ^ [ % , ι l′ ] / [G] [ρ] ⊢Δ [a]
-- Terms of ∃-types (always irrelevant)
_⊩¹∃_∷_^_/_ : (Γ : Con Term) (t A : Term) (l′ : Level) ([A] : Γ ⊩¹∃ A ^ l′) → Set
Γ ⊩¹∃ t ∷ A ^ l′ / ∃ᵣ F G D ⊢F ⊢G A≡A [F] [G] G-ext =
Γ ⊢ t ∷ ∃ F ▹ G ^ [ % , ι l′ ]
-- Term equality for ∃-types
_⊩¹∃_≡_∷_^_/_ : (Γ : Con Term) (t u A : Term) (l′ : Level) ([A] : Γ ⊩¹∃ A ^ l′) → Set
Γ ⊩¹∃ t ≡ u ∷ A ^ l′ / ∃ᵣ F G D ⊢F ⊢G A≡A [F] [G] G-ext =
(Γ ⊢ t ∷ ∃ F ▹ G ^ [ % , ι l′ ])
×
(Γ ⊢ u ∷ ∃ F ▹ G ^ [ % , ι l′ ])
-- Logical relation definition
data _⊩¹_^_ (Γ : Con Term) : Term → TypeInfo → Set where
Uᵣ : ∀ {A ll} → (UA : Γ ⊩¹U A ^ ll) → Γ ⊩¹ A ^ [ ! , ll ]
ℕᵣ : ∀ {A} → Γ ⊩ℕ A → Γ ⊩¹ A ^ [ ! , ι ⁰ ]
Emptyᵣ : ∀ {A l} → Γ ⊩Empty A ^ l → Γ ⊩¹ A ^ [ % , ι l ]
ne : ∀ {A r l} → Γ ⊩ne A ^[ r , l ] → Γ ⊩¹ A ^ [ r , ι l ]
Πᵣ : ∀ {A r l} → Γ ⊩¹Π A ^[ r , l ] → Γ ⊩¹ A ^ [ r , ι l ]
∃ᵣ : ∀ {A l} → Γ ⊩¹∃ A ^ l → Γ ⊩¹ A ^ [ % , ι l ]
emb : ∀ {A r l′} (l< : l′ <∞ l) (let open LogRelKit (rec l<))
([A] : Γ ⊩ A ^ r) → Γ ⊩¹ A ^ r
_⊩¹_≡_^_/_ : (Γ : Con Term) (A B : Term) (r : TypeInfo) → Γ ⊩¹ A ^ r → Set
Γ ⊩¹ A ≡ B ^ [ .! , l ] / Uᵣ UA = Γ ⊩¹U A ≡ B ^ l / UA
Γ ⊩¹ A ≡ B ^ [ .! , .ι ⁰ ] / ℕᵣ D = Γ ⊩ℕ A ≡ B
Γ ⊩¹ A ≡ B ^ [ .% , .ι l ] / Emptyᵣ D = Γ ⊩Empty A ≡ B ^ l
Γ ⊩¹ A ≡ B ^ [ r , ι l ] / ne neA = Γ ⊩ne A ≡ B ^[ r , l ]/ neA
Γ ⊩¹ A ≡ B ^ [ r , ι l ] / Πᵣ ΠA = Γ ⊩¹Π A ≡ B ^[ r , l ]/ ΠA
Γ ⊩¹ A ≡ B ^ [ .% , ι l ] / ∃ᵣ ∃A = Γ ⊩¹∃ A ≡ B ^ l / ∃A
Γ ⊩¹ A ≡ B ^ r / emb l< [A] = Γ ⊩ A ≡ B ^ r / [A]
where open LogRelKit (rec l<)
_⊩¹_∷_^_/_ : (Γ : Con Term) (t A : Term) (r : TypeInfo) → Γ ⊩¹ A ^ r → Set
Γ ⊩¹ t ∷ A ^ [ .! , ll ] / Uᵣ UA = Γ ⊩¹U t ∷ A ^ ll / UA
Γ ⊩¹ t ∷ A ^ .([ ! , ι ⁰ ]) / ℕᵣ x = Γ ⊩ℕ t ∷ℕ
Γ ⊩¹ t ∷ A ^ [ .% , ι ll ] / Emptyᵣ x = Γ ⊩Empty t ∷Empty^ ll
Γ ⊩¹ t ∷ A ^ .([ ! , ι l ]) / ne {r = !} {l} neA = Γ ⊩ne t ∷ A ^ l / neA
Γ ⊩¹ t ∷ A ^ .([ % , ι l ]) / ne {r = %} {l} neA = Γ ⊩neIrr t ∷ A ^ l / neA
Γ ⊩¹ t ∷ A ^ [ ! , ι l ] / Πᵣ ΠA = Γ ⊩¹Π t ∷ A ^ l / ΠA
Γ ⊩¹ t ∷ A ^ [ % , ι l ] / Πᵣ ΠA = Γ ⊩¹Πirr t ∷ A ^ l / ΠA
Γ ⊩¹ t ∷ A ^ .([ % , ι l ]) / ∃ᵣ {l = l} ∃A = Γ ⊩¹∃ t ∷ A ^ l / ∃A
Γ ⊩¹ t ∷ A ^ r / emb l< [A] = Γ ⊩ t ∷ A ^ r / [A]
where open LogRelKit (rec l<)
_⊩¹_≡_∷_^_/_ : (Γ : Con Term) (t u A : Term) (r : TypeInfo) → Γ ⊩¹ A ^ r → Set
Γ ⊩¹ t ≡ u ∷ A ^ [ .! , ll ] / Uᵣ UA = Γ ⊩¹U t ≡ u ∷ A ^ ll / UA
Γ ⊩¹ t ≡ u ∷ A ^ .([ ! , ι ⁰ ]) / ℕᵣ D = Γ ⊩ℕ t ≡ u ∷ℕ
Γ ⊩¹ t ≡ u ∷ A ^ [ .% , ι ll ] / Emptyᵣ D = Γ ⊩Empty t ≡ u ∷Empty^ ll
Γ ⊩¹ t ≡ u ∷ A ^ .([ ! , ι l ]) / ne {r = !} {l} neA = Γ ⊩ne t ≡ u ∷ A ^ l / neA
Γ ⊩¹ t ≡ u ∷ A ^ .([ % , ι l ]) / ne {r = %} {l} neA = Γ ⊩neIrr t ≡ u ∷ A ^ l / neA
Γ ⊩¹ t ≡ u ∷ A ^ [ ! , ι l ] / Πᵣ ΠA = Γ ⊩¹Π t ≡ u ∷ A ^ l / ΠA
Γ ⊩¹ t ≡ u ∷ A ^ [ % , ι l ] / Πᵣ ΠA = Γ ⊩¹Πirr t ≡ u ∷ A ^ l / ΠA
Γ ⊩¹ t ≡ u ∷ A ^ .([ % , ι l ]) / ∃ᵣ {l = l} ∃A = Γ ⊩¹∃ t ≡ u ∷ A ^ l / ∃A
Γ ⊩¹ t ≡ u ∷ A ^ r / emb l< [A] = Γ ⊩ t ≡ u ∷ A ^ r / [A]
where open LogRelKit (rec l<)
kit : LogRelKit
kit = Kit _⊩¹U_^_ _⊩¹Π_^[_,_] _⊩¹∃_^_
_⊩¹_^_ _⊩¹_≡_^_/_ _⊩¹_∷_^_/_ _⊩¹_≡_∷_^_/_
open LogRel public using (Uᵣ; ℕᵣ; Emptyᵣ; ne; Πᵣ ; ∃ᵣ ; emb; Uₜ; Uₜ₌; Π₌; ∃₌)
-- Patterns for the non-records of Π
pattern Πₜ a b c d e f = a , b , c , d , e , f
pattern Πₜ₌ a b c d e f g h i j = a , b , c , d , e , f , g , h , i , j
pattern Uᵣ′ A ll r l a e d = Uᵣ {A = A} {ll = ll} (Uᵣ r l a e d)
pattern ne′ b c d e = ne (ne b c d e)
pattern Πᵣ′ a a' a'' lf lg b c d e f g h i j = Πᵣ (Πᵣ a a' a'' lf lg b c d e f g h i j)
pattern ∃ᵣ′ a b c d e f g h i = ∃ᵣ (∃ᵣ a b c d e f g h i)
-- we need to split the LogRelKit into the level part and the general part to convince Agda termination checker
logRelRec : ∀ l {l′} → l′ <∞ l → LogRelKit
logRelRec (ι ⁰) = λ ()
logRelRec (ι ¹) X = LogRel.kit (ι ⁰) λ ()
logRelRec ∞ X = LogRel.kit (ι ¹) (λ X → LogRel.kit (ι ⁰) λ ())
kit : ∀ (i : TypeLevel) → LogRelKit
kit l = LogRel.kit l (logRelRec l)
_⊩′⟨_⟩U_^_ : (Γ : Con Term) (l : TypeLevel) → Term → TypeLevel → Set
Γ ⊩′⟨ l ⟩U A ^ ll = Γ ⊩U A ^ ll where open LogRelKit (kit l)
_⊩′⟨_⟩Π_^[_,_] : (Γ : Con Term) (l : TypeLevel) → Term → Relevance → Level → Set
Γ ⊩′⟨ l ⟩Π A ^[ r , lΠ ] = Γ ⊩Π A ^[ r , lΠ ] where open LogRelKit (kit l)
_⊩′⟨_⟩∃_^_ : (Γ : Con Term) (l : TypeLevel) → Term → Level → Set
Γ ⊩′⟨ l ⟩∃ A ^ l' = Γ ⊩∃ A ^ l' where open LogRelKit (kit l)
_⊩⟨_⟩_^_ : (Γ : Con Term) (l : TypeLevel) → Term → TypeInfo → Set
Γ ⊩⟨ l ⟩ A ^ r = Γ ⊩ A ^ r where open LogRelKit (kit l)
_⊩⟨_⟩_≡_^_/_ : (Γ : Con Term) (l : TypeLevel) (A B : Term) (r : TypeInfo) → Γ ⊩⟨ l ⟩ A ^ r → Set
Γ ⊩⟨ l ⟩ A ≡ B ^ r / [A] = Γ ⊩ A ≡ B ^ r / [A] where open LogRelKit (kit l)
_⊩⟨_⟩_∷_^_/_ : (Γ : Con Term) (l : TypeLevel) (t A : Term) (r : TypeInfo) → Γ ⊩⟨ l ⟩ A ^ r → Set
Γ ⊩⟨ l ⟩ t ∷ A ^ r / [A] = Γ ⊩ t ∷ A ^ r / [A] where open LogRelKit (kit l)
_⊩⟨_⟩_≡_∷_^_/_ : (Γ : Con Term) (l : TypeLevel) (t u A : Term) (r : TypeInfo) → Γ ⊩⟨ l ⟩ A ^ r → Set
Γ ⊩⟨ l ⟩ t ≡ u ∷ A ^ r / [A] = Γ ⊩ t ≡ u ∷ A ^ r / [A] where open LogRelKit (kit l)
-- Well-typed irrelevant terms are always reducible
logRelIrr : ∀ {l t Γ l' A} ([A] : Γ ⊩⟨ l ⟩ A ^ [ % , l' ]) (⊢t : Γ ⊢ t ∷ A ^ [ % , l' ]) → Γ ⊩⟨ l ⟩ t ∷ A ^ [ % , l' ] / [A]
logRelIrr (Emptyᵣ [[ ⊢A , ⊢B , D ]]) ⊢t = Emptyₜ (ne (conv ⊢t (reduction D (id ⊢B) Emptyₙ Emptyₙ (refl ⊢B))))
logRelIrr (ne x) ⊢t = neₜ ⊢t
logRelIrr (Πᵣ′ rF lF lG _ _ F G D ⊢F ⊢G A≡A [F] [G] G-ext) ⊢t = conv ⊢t (reduction (red D) (id (_⊢_:⇒*:_^_.⊢B D)) Πₙ Πₙ (refl (_⊢_:⇒*:_^_.⊢B D)))
logRelIrr (∃ᵣ′ F G D ⊢F ⊢G A≡A [F] [G] G-ext) ⊢t = conv ⊢t (reduction (red D) (id (_⊢_:⇒*:_^_.⊢B D)) ∃ₙ ∃ₙ (refl (_⊢_:⇒*:_^_.⊢B D)))
logRelIrr {ι ¹} (emb X [A]) ⊢t = logRelIrr [A] ⊢t
logRelIrr {∞} (emb X [A]) ⊢t = logRelIrr [A] ⊢t
-- Well-typed irrelevant terms are reducibly equal as soon as they have the same type
logRelIrrEq : ∀ {l t u Γ l' A} ([A] : Γ ⊩⟨ l ⟩ A ^ [ % , l' ]) (⊢t : Γ ⊢ t ∷ A ^ [ % , l' ]) (⊢u : Γ ⊢ u ∷ A ^ [ % , l' ]) → Γ ⊩⟨ l ⟩ t ≡ u ∷ A ^ [ % , l' ] / [A]
logRelIrrEq (Emptyᵣ [[ ⊢A , ⊢B , D ]]) ⊢t ⊢u = Emptyₜ₌ (ne ((conv ⊢t (reduction D (id ⊢B) Emptyₙ Emptyₙ (refl ⊢B))))
(conv ⊢u (reduction D (id ⊢B) Emptyₙ Emptyₙ (refl ⊢B))))
logRelIrrEq (ne x) ⊢t ⊢u = neₜ₌ ⊢t ⊢u
logRelIrrEq (Πᵣ′ rF lF lG _ _ F G D ⊢F ⊢G A≡A [F] [G] G-ext) ⊢t ⊢u = (conv ⊢t (reduction (red D) (id (_⊢_:⇒*:_^_.⊢B D)) Πₙ Πₙ (refl (_⊢_:⇒*:_^_.⊢B D))) ) , (conv ⊢u (reduction (red D) (id (_⊢_:⇒*:_^_.⊢B D)) Πₙ Πₙ (refl (_⊢_:⇒*:_^_.⊢B D))) )
logRelIrrEq (∃ᵣ′ F G D ⊢F ⊢G A≡A [F] [G] G-ext) ⊢t ⊢u = (conv ⊢t (reduction (red D) (id (_⊢_:⇒*:_^_.⊢B D)) ∃ₙ ∃ₙ (refl (_⊢_:⇒*:_^_.⊢B D))) ) , (conv ⊢u (reduction (red D) (id (_⊢_:⇒*:_^_.⊢B D)) ∃ₙ ∃ₙ (refl (_⊢_:⇒*:_^_.⊢B D))) )
logRelIrrEq {ι ¹} (emb X [A]) ⊢t = logRelIrrEq [A] ⊢t
logRelIrrEq {∞} (emb X [A]) ⊢t = logRelIrrEq [A] ⊢t
|
Formal statement is: lemma Cauchy_converges_subseq: fixes u::"nat \<Rightarrow> 'a::metric_space" assumes "Cauchy u" "strict_mono r" "(u \<circ> r) \<longlonglongrightarrow> l" shows "u \<longlonglongrightarrow> l" Informal statement is: If a Cauchy sequence has a convergent subsequence, then it converges. |
open import Data.Product
open import Relation.Binary.PropositionalEquality hiding ([_] ; Extensionality)
open import Relation.Nullary
open import Relation.Nullary.Negation
open import EffectAnnotations
module Types where
-- BASE AND GROUND TYPES
postulate BType : Set -- set of base types
postulate dec-bty : (B B' : BType) → Dec (B ≡ B')
GType = BType
-- VALUE AND COMPUTATION TYPES
mutual
data VType : Set where
`` : GType → VType
_⇒_ : VType → CType → VType
⟨_⟩ : VType → VType
data CType : Set where
_!_ : VType → O × I → CType
infix 30 _⇒_
infix 30 _!_
-- PROCESS TYPES
data PTypeShape : Set where
_!_ : VType → I → PTypeShape
_∥_ : PTypeShape → PTypeShape → PTypeShape
data PType : O → Set where
_‼_,_ : (X : VType) →
(o : O) →
(i : I) →
---------------
PType o
_∥_ : {o o' : O} →
(PP : PType o) →
(QQ : PType o') →
---------------------------
PType (o ∪ₒ o')
-- ACTION OF INTERRUPTS ON PROCESS TYPES
_↓ₚₚ_ : (op : Σₛ) → {o : O} →
PType o → Σ[ o' ∈ O ] PType o'
op ↓ₚₚ (X ‼ o , i) with op ↓ₑ (o , i)
... | (o' , i') =
o' , (X ‼ o' , i')
op ↓ₚₚ (PP ∥ QQ) with op ↓ₚₚ PP | op ↓ₚₚ QQ
... | (o'' , PP') | (o''' , QQ') =
(o'' ∪ₒ o''') , (PP' ∥ QQ')
_↓ₚ_ : (op : Σₛ) → {o : O} →
(PP : PType o) → PType (proj₁ (op ↓ₚₚ PP))
op ↓ₚ PP = proj₂ (op ↓ₚₚ PP)
-- ACTION OF INTERRUPTS ON PROCESS TYPES PRESERVES SIGNAL ANNOTATIONS
{- LEMMA 4.1 -}
↓ₚₚ-⊑ₒ : {op : Σₛ}
{o : O} →
(PP : PType o) →
----------------------
o ⊑ₒ proj₁ (op ↓ₚₚ PP)
↓ₚₚ-⊑ₒ (X ‼ o , i) =
↓ₑ-⊑ₒ
↓ₚₚ-⊑ₒ (PP ∥ QQ) =
∪ₒ-fun (↓ₚₚ-⊑ₒ PP) (↓ₚₚ-⊑ₒ QQ)
|
module Js.Node.Module
import Js
%default total
%access export
dir : JS_IO String
dir = js "__dirname" (JS_IO String)
path : JS_IO String
path = js "__filename" (JS_IO String)
|
\documentclass{article}
\usepackage[english]{babel}
\usepackage[]{amsthm} %lets us use \begin{proof}
\usepackage[]{amssymb} %gives us the character \varnothing
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage[font={small,it}]{caption}
\title{Perspective Correct Interpolation of Vertex Attributes}
\author{Samuel S. Egger}
\date\today
%This information doesn't actually show up on your document unless you use the maketitle command below
\begin{document}
\maketitle %This command prints the title based on information entered above
%Section and subsection automatically number unless you put the asterisk next to them.
\section*{Texture Mapping}
Texture mapping can roughly be summarized as the process of mapping an image onto the surface of an object in three-dimensional Euclidean space (we will from now on refer to this space as camera space). The texture mapping happens in the rasterization stage of the graphics pipeline after a scene from camera space has been projected onto a plane ($z=-d$). We call this plane the image plane.
In order to rasterize a triangular polygon from the image plane onto the screen, we first transform its vertices into screen space (or pixel space) and for each pixel inside the polygon we determine its color. When using a texture, we lookup the pixels color in that texture.
\subsection*{$z$-Interpolation}
\begin{figure}[!ht]
\centering
\def\svgwidth{80mm}
\input{drawing.pdf_tex}
\caption{Sideview (facing down the negative $x$-axis) of a triangle being projected onto the image plane}
\label{fig:aufbau}
\end{figure}
Let there be an edge in camera space that goes from $p'$ to $p''$. During rasterization we only know the depth value $z$ for $q'$ and $q''$. For each pixel position $q$ we have to somehow figure out the corresponding depth value.
The $z$-value for $p$ can by determined by a simple linear interpolation using the equation \[p_{z}=p'_{z}+\alpha(p''_{z}-p_{z}')\textrm{.}\]
However, we want to know $p_{z}$ as a function of $q_{x}$, that is \[z = f(x)\; \textrm{for}\;x\in{[q'_{x},\,q''_{x}]}\textrm{.}\]
For that in turn we need to figure out what $\alpha$ is in terms of $q$. In terms of $p$, $\alpha$ is given by the equation
\[\alpha=\frac{p_{z}-p'_{z}}{p''_{z}-p'_{z}}\textrm{.}\]
\end{document} |
Formal statement is: lemma bilinear_lneg: "bilinear h \<Longrightarrow> h (- x) y = - h x y" Informal statement is: If $h$ is bilinear, then $h(-x)y = -h(x)y$. |
/*
Copyright (c) 2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#ifndef _ISHIKO_CPP_TESTFRAMEWORK_CORE_FILECOMPARISONTESTCHECK_HPP_
#define _ISHIKO_CPP_TESTFRAMEWORK_CORE_FILECOMPARISONTESTCHECK_HPP_
#include "TestCheck.hpp"
#include "TestContext.hpp"
#include <boost/filesystem.hpp>
namespace Ishiko
{
class FileComparisonTestCheck : public TestCheck
{
public:
FileComparisonTestCheck(boost::filesystem::path outputFilePath, boost::filesystem::path referenceFilePath);
static FileComparisonTestCheck CreateFromContext(const TestContext& context,
const boost::filesystem::path& outputFilePath, const boost::filesystem::path& referenceFilePath);
Result run() override;
const boost::filesystem::path& outputFilePath() const;
const boost::filesystem::path& referenceFilePath() const;
private:
boost::filesystem::path m_outputFilePath;
boost::filesystem::path m_referenceFilePath;
};
}
#endif
|
Set Warnings "-notation-overridden,-parsing,-deprecated-hint-without-locality".
From Coq Require Import Bool.Bool.
From Coq Require Import Strings.String.
From Coq Require Import Arith.Arith.
From Coq Require Import Arith.EqNat. Import Nat.
From Coq Require Import Arith.PeanoNat.
From Coq Require Import Lia.
From Coq Require Import Strings.String.
From Coq Require Import Logic.Eqdep_dec.
From Coq Require Import Logic.FunctionalExtensionality.
From PFPL Require Import PartialMap_Set.
From PFPL Require Import Definitions.
From PFPL Require Import Lemmas_Vars.
From PFPL Require Import Lemmas_Rename.
From PFPL Require Import Lemmas_Same_Structure.
From PFPL Require Import Induction_Expr.
Lemma alpha_equiv_refl : forall e,
alpha_equiv_rel e e.
Proof.
induction e using expr_ind; intros.
- apply alpha_equiv_rel_id.
- apply alpha_equiv_rel_let.
apply H. apply same_structure_refl.
intros.
apply H0.
apply rename_keeps_structure.
- apply alpha_equiv_rel_num.
- apply alpha_equiv_rel_str. apply eqb_refl.
- apply alpha_equiv_rel_plus.
apply H. apply same_structure_refl.
apply H0. apply same_structure_refl.
- apply alpha_equiv_rel_times.
apply H. apply same_structure_refl.
apply H0. apply same_structure_refl.
- apply alpha_equiv_rel_cat.
apply H. apply same_structure_refl.
apply H0. apply same_structure_refl.
- apply alpha_equiv_rel_len.
apply H. apply same_structure_refl.
Qed.
Lemma alpha_equiv_sym : forall e e',
alpha_equiv_rel e e' -> alpha_equiv_rel e' e.
Proof.
intros e e' H. induction H.
- apply alpha_equiv_rel_id.
- apply alpha_equiv_rel_let.
assumption.
intros. apply H1; assumption.
- apply alpha_equiv_rel_num.
- apply alpha_equiv_rel_str.
rewrite eqb_sym. assumption.
- apply alpha_equiv_rel_plus; assumption.
- apply alpha_equiv_rel_times; assumption.
- apply alpha_equiv_rel_cat; assumption.
- apply alpha_equiv_rel_len; assumption.
Qed.
Lemma alpha_equiv_have_same_structure : forall e e',
alpha_equiv_rel e e' -> same_structure e e'.
Proof.
intros e e' H. induction H; simpl; auto; constructor; auto.
remember (max (get_fresh_var e2) (get_fresh_var e2')) as z.
apply (same_structure_trans _ (rename e2 x z) _).
apply rename_keeps_structure.
apply (same_structure_trans _ (rename e2' x' z) _).
apply H1.
subst z.
apply (fresh_var_not_in_all_vars_left e2 e2').
subst z.
apply (fresh_var_not_in_all_vars_right e2 e2').
apply same_structure_sym.
apply rename_keeps_structure.
Qed.
Lemma diff_constructor_not_alpha : forall e e',
diff_constructor e e' ->
forall e'' e''',
same_structure e e'' -> same_structure e' e''' ->
alpha_equiv_rel e'' e''' -> False.
Proof.
intros.
assert (H3 := alpha_equiv_have_same_structure e'' e''' H2).
assert (H4 := same_structure_trans e e'' e''' H0 H3).
apply same_structure_sym in H1.
assert (H5 := same_structure_trans e e''' e' H4 H1).
clear H0 H1 H2 H3 H4 e'' e'''. rename H5 into H2.
destruct e.
all: destruct e'.
all: inversion H.
all: inversion H2.
Qed.
Lemma alpha_equiv_same_free_vars : forall e e',
alpha_equiv_rel e e' -> free_vars e = free_vars e'.
Proof.
intros e e' H. induction H; simpl; auto.
- rewrite <- IHalpha_equiv_rel.
remember (max
(get_fresh_var (ELet e1 x e2))
(get_fresh_var (ELet e1' x' e2'))
) as z.
assert (XZ : (x =? z) = false).
{
assert (T := fresh_var_not_in_all_vars_left (ELet e1 x e2) (ELet e1' x' e2')).
rewrite <- Heqz in T.
simpl in T. unfold unionSet in T.
apply orb_false_iff in T.
destruct T.
unfold updateSet in H3.
destruct (x =? z). discriminate.
reflexivity.
}
assert (X'Z : (x' =? z) = false).
{
assert (T := fresh_var_not_in_all_vars_right (ELet e1 x e2) (ELet e1' x' e2')).
rewrite <- Heqz in T.
simpl in T. unfold unionSet in T.
apply orb_false_iff in T.
destruct T.
unfold updateSet in H3.
destruct (x' =? z). discriminate.
reflexivity.
}
assert (Zfresh : all_vars e2 z = false).
{
assert (T := fresh_var_not_in_all_vars_left (ELet e1 x e2) (ELet e1' x' e2')).
rewrite <- Heqz in T.
simpl in T. unfold unionSet in T.
apply orb_false_iff in T. destruct T.
unfold updateSet in H3.
destruct (x =? z). discriminate. assumption.
}
assert (Zfresh' : all_vars e2' z = false).
{
assert (T := fresh_var_not_in_all_vars_right (ELet e1 x e2) (ELet e1' x' e2')).
rewrite <- Heqz in T.
simpl in T. unfold unionSet in T.
apply orb_false_iff in T. destruct T.
unfold updateSet in H3.
destruct (x' =? z). discriminate. assumption.
}
assert (T2 : alpha_equiv_rel (rename e2 x z) (rename e2' x' z)).
{ apply H0; assumption. }
assert (T3 : free_vars (rename e2 x z) = free_vars (rename e2' x' z)).
{ apply H1; assumption. }
assert (T4 := rename_removes_free_vars e2 x z XZ).
assert (T5 := rename_removes_free_vars e2' x' z X'Z).
assert (T6 := rename_keeps_other_free_vars e2 x z).
assert (T7 := rename_keeps_other_free_vars e2' x' z).
assert (R : removeFromSet (free_vars e2) x = removeFromSet (free_vars e2') x').
{
apply functional_extensionality. intros.
unfold removeFromSet.
case_eq (x =? x0); case_eq (x' =? x0); intros.
reflexivity.
apply Nat.eqb_eq in H3. subst x0.
rewrite Nat.eqb_sym in H2.
assert (T8 := T7 x H2 XZ).
rewrite <- T3 in T8.
symmetry. rewrite T8. assumption.
apply Nat.eqb_eq in H2. subst x0.
rewrite Nat.eqb_sym in H3.
assert (T9 := T6 x' H3 X'Z).
rewrite T3 in T9.
rewrite T5 in T9.
assumption.
rewrite Nat.eqb_sym in H2.
rewrite Nat.eqb_sym in H3.
case_eq (x0 =? z); intros.
+ apply Nat.eqb_eq in H4. subst x0.
rewrite not_in_expr_not_free.
rewrite not_in_expr_not_free.
all: auto.
+ assert (T8 := T7 x0 H2 H4).
assert (T9 := T6 x0 H3 H4).
rewrite T8. rewrite T9.
rewrite T3. reflexivity.
}
rewrite R. reflexivity.
- rewrite IHalpha_equiv_rel1. rewrite IHalpha_equiv_rel2. auto.
- rewrite IHalpha_equiv_rel1. rewrite IHalpha_equiv_rel2. auto.
- rewrite IHalpha_equiv_rel1. rewrite IHalpha_equiv_rel2. auto.
Qed.
|
= = = NHL = = =
|
[STATEMENT]
lemma confluentI:
"(\<And>x y y'. (x, y) \<in> R \<Longrightarrow> (x, y') \<in> R \<Longrightarrow> \<exists>z. (y, z) \<in> R \<and> (y', z) \<in> R) \<Longrightarrow> confluent R"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>x y y'. \<lbrakk>(x, y) \<in> R; (x, y') \<in> R\<rbrakk> \<Longrightarrow> \<exists>z. (y, z) \<in> R \<and> (y', z) \<in> R) \<Longrightarrow> confluent R
[PROOF STEP]
unfolding confluent_def
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (\<And>x y y'. \<lbrakk>(x, y) \<in> R; (x, y') \<in> R\<rbrakk> \<Longrightarrow> \<exists>z. (y, z) \<in> R \<and> (y', z) \<in> R) \<Longrightarrow> \<forall>x y y'. (x, y) \<in> R \<and> (x, y') \<in> R \<longrightarrow> (y, y') \<in> joinable R
[PROOF STEP]
by (blast intro: joinableI) |
{-# OPTIONS --without-K #-}
open import lib.Basics
open import lib.types.Group
open import lib.types.Pi
open import lib.types.Sigma
open import lib.types.Truncation
open import lib.groups.GroupProduct
open import lib.groups.Homomorphisms
module lib.groups.TruncationGroup where
module _ {i} {El : Type i} (GS : GroupStructure El) where
Trunc-group-struct : GroupStructure (Trunc 0 El)
Trunc-group-struct = record {
ident = [ ident GS ];
inv = Trunc-fmap (inv GS);
comp = _⊗_;
unitl = t-unitl;
unitr = t-unitr;
assoc = t-assoc;
invl = t-invl;
invr = t-invr}
where
open GroupStructure
infix 80 _⊗_
_⊗_ = Trunc-fmap2 (comp GS)
abstract
t-unitl : (t : Trunc 0 El) → [ ident GS ] ⊗ t == t
t-unitl = Trunc-elim (λ _ → =-preserves-level _ Trunc-level)
(ap [_] ∘ unitl GS)
t-unitr : (t : Trunc 0 El) → t ⊗ [ ident GS ] == t
t-unitr = Trunc-elim (λ _ → =-preserves-level _ Trunc-level)
(ap [_] ∘ unitr GS)
t-assoc : (t₁ t₂ t₃ : Trunc 0 El) → (t₁ ⊗ t₂) ⊗ t₃ == t₁ ⊗ (t₂ ⊗ t₃)
t-assoc = Trunc-elim
(λ _ → Π-level (λ _ → Π-level (λ _ → =-preserves-level _ Trunc-level)))
(λ a → Trunc-elim
(λ _ → Π-level (λ _ → =-preserves-level _ Trunc-level))
(λ b → Trunc-elim
(λ _ → =-preserves-level _ Trunc-level)
(λ c → ap [_] (assoc GS a b c))))
t-invl : (t : Trunc 0 El) → Trunc-fmap (inv GS) t ⊗ t == [ ident GS ]
t-invl = Trunc-elim (λ _ → =-preserves-level _ Trunc-level)
(ap [_] ∘ invl GS)
t-invr : (t : Trunc 0 El) → t ⊗ Trunc-fmap (inv GS) t == [ ident GS ]
t-invr = Trunc-elim (λ _ → =-preserves-level _ Trunc-level)
(ap [_] ∘ invr GS)
Trunc-group : Group i
Trunc-group = record {
El = Trunc 0 El;
El-level = Trunc-level;
group-struct = Trunc-group-struct }
Trunc-group-× : ∀ {i j} {A : Type i} {B : Type j}
(GS : GroupStructure A) (HS : GroupStructure B)
→ Trunc-group (×-group-struct GS HS) == Trunc-group GS ×ᴳ Trunc-group HS
Trunc-group-× GS HS = group-ua
(record {
f = Trunc-rec (×-level Trunc-level Trunc-level)
(λ {(a , b) → ([ a ] , [ b ])});
pres-comp =
Trunc-elim
(λ _ → (Π-level (λ _ → =-preserves-level _
(×-level Trunc-level Trunc-level))))
(λ a → Trunc-elim
(λ _ → =-preserves-level _ (×-level Trunc-level Trunc-level))
(λ b → idp))} ,
is-eq _
(uncurry (Trunc-rec (→-level Trunc-level)
(λ a → Trunc-rec Trunc-level (λ b → [ a , b ]))))
(uncurry (Trunc-elim
(λ _ → Π-level (λ _ → =-preserves-level _
(×-level Trunc-level Trunc-level)))
(λ a → Trunc-elim
(λ _ → =-preserves-level _
(×-level Trunc-level Trunc-level))
(λ b → idp))))
(Trunc-elim (λ _ → =-preserves-level _ Trunc-level) (λ _ → idp)))
Trunc-group-hom : ∀ {i j} {A : Type i} {B : Type j}
{GS : GroupStructure A} {HS : GroupStructure B} (f : A → B)
→ ((a₁ a₂ : A) → f (GroupStructure.comp GS a₁ a₂)
== GroupStructure.comp HS (f a₁) (f a₂))
→ (Trunc-group GS →ᴳ Trunc-group HS)
Trunc-group-hom {A = A} {GS = GS} {HS = HS} f p =
record {f = Trunc-fmap f; pres-comp = pres-comp}
where
abstract
pres-comp : (t₁ t₂ : Trunc 0 A) →
Trunc-fmap f (Trunc-fmap2 (GroupStructure.comp GS) t₁ t₂)
== Trunc-fmap2 (GroupStructure.comp HS)
(Trunc-fmap f t₁) (Trunc-fmap f t₂)
pres-comp =
Trunc-elim (λ _ → Π-level (λ _ → =-preserves-level _ Trunc-level))
(λ a₁ → Trunc-elim (λ _ → =-preserves-level _ Trunc-level)
(λ a₂ → ap [_] (p a₁ a₂)))
Trunc-group-iso : ∀ {i} {A B : Type i}
{GS : GroupStructure A} {HS : GroupStructure B} (f : A → B)
→ ((a₁ a₂ : A) → f (GroupStructure.comp GS a₁ a₂)
== GroupStructure.comp HS (f a₁) (f a₂))
→ is-equiv f → Trunc-group GS ≃ᴳ Trunc-group HS
Trunc-group-iso f pres-comp ie =
(Trunc-group-hom f pres-comp ,
is-eq _ (Trunc-fmap (is-equiv.g ie))
(Trunc-elim (λ _ → =-preserves-level _ Trunc-level)
(λ b → ap [_] (is-equiv.f-g ie b)))
(Trunc-elim (λ _ → =-preserves-level _ Trunc-level)
(λ a → ap [_] (is-equiv.g-f ie a))))
Trunc-group-abelian : ∀ {i} {A : Type i} (GS : GroupStructure A)
→ ((a₁ a₂ : A) → GroupStructure.comp GS a₁ a₂ == GroupStructure.comp GS a₂ a₁)
→ is-abelian (Trunc-group GS)
Trunc-group-abelian GS ab =
Trunc-elim (λ _ → Π-level (λ _ → =-preserves-level _ Trunc-level)) $
λ a₁ → Trunc-elim (λ _ → =-preserves-level _ Trunc-level) $
λ a₂ → ap [_] (ab a₁ a₂)
|
Formal statement is: lemma one_step: assumes a: "a \<in> s" "j < n" assumes *: "\<And>a'. a' \<in> s \<Longrightarrow> a' \<noteq> a \<Longrightarrow> a' j = p'" shows "a j \<noteq> p'" Informal statement is: If $a$ is an element of $s$ and $j < n$, and if $a'$ is any element of $s$ such that $a' |
Formal statement is: lemma SUP_Lim: fixes X :: "nat \<Rightarrow> 'a::{complete_linorder,linorder_topology}" assumes inc: "incseq X" and l: "X \<longlonglongrightarrow> l" shows "(SUP n. X n) = l" Informal statement is: If $X$ is an increasing sequence of real numbers that converges to $l$, then $\sup_n X_n = l$. |
import typing
import numpy as np
import pandas as pd
from .h3ronpy import op as native_op
def kring_distances(h3indexes: np.ndarray, k_max: int, k_min: int = 0) -> pd.DataFrame:
"""
Vectorized k-ring building
Returns a dataframe with the columns `h3index` (the ring center), `ring_h3index` and `ring_k`.
:param h3indexes:
:param k_max:
:param k_min:
:return:
"""
h3index, ring_h3index, ring_k = native_op.kring_distances(h3indexes, k_min, k_max)
return pd.DataFrame({
"h3index": h3index,
"ring_h3index": ring_h3index,
"ring_k": ring_k
})
def kring_distances_agg_np(h3indexes: np.ndarray, k_max: int, k_min: int = 0, aggregation_method: str = 'min') -> \
typing.Tuple[np.ndarray, np.ndarray]:
"""
Vectorized k-ring building, with the k-values of the rings being aggregated to their `min` or
`max` value for each cell.
:param h3indexes:
:param k_max:
:param k_min:
:param aggregation_method:
:return:
"""
return native_op.kring_distances_agg(h3indexes, k_min, k_max, aggregation_method)
def kring_distances_agg(h3indexes: np.ndarray, k_max: int, k_min: int = 0,
aggregation_method: str = 'min') -> pd.DataFrame:
h3indexes_out, k_out = kring_distances_agg_np(h3indexes, k_max, k_min=k_min, aggregation_method=aggregation_method)
return pd.DataFrame({"h3index": h3indexes_out, "k": k_out})
|
type RHS_IE_Scalar{F,uType,tType} <: Function
f::F
u_old::uType
t::tType
dt::tType
end
function (p::RHS_IE_Scalar)(u,resid)
resid[1] = u[1] - p.u_old[1] - p.dt*p.f(p.t+p.dt,u[1])[1]
end
@inline function initialize!(integrator,cache::ImplicitEulerConstantCache,f=integrator.f)
cache.uhold[1] = integrator.uprev; cache.u_old[1] = integrator.uprev
integrator.kshortsize = 2
integrator.k = eltype(integrator.sol.k)(integrator.kshortsize)
integrator.fsalfirst = f(integrator.t,integrator.uprev)
end
@inline function perform_step!(integrator,cache::ImplicitEulerConstantCache,f=integrator.f)
@unpack t,dt,uprev,u,k = integrator
@unpack uhold,u_old,rhs,adf = cache
u_old[1] = uhold[1]
if integrator.iter > 1 && !integrator.u_modified
uhold[1] = current_extrapolant(t+dt,integrator)
end # else uhold is previous value.
rhs.t = t
rhs.dt = dt
if alg_autodiff(integrator.alg)
nlres = NLsolve.nlsolve(adf,uhold)
else
nlres = NLsolve.nlsolve(rhs,uhold,autodiff=alg_autodiff(integrator.alg))
end
uhold[1] = nlres.zero[1]
k = f(t+dt,uhold[1])
integrator.fsallast = k
u = uhold[1]
integrator.k[1] = integrator.fsalfirst
integrator.k[2] = k
@pack integrator = t,dt,u
end
type RHS_IE{F,uType,tType,DiffCacheType,SizeType,uidxType} <: Function
f::F
u_old::uType
t::tType
dt::tType
dual_cache::DiffCacheType
sizeu::SizeType
uidx::uidxType
end
function (p::RHS_IE)(uprev,resid)
du = get_du(p.dual_cache, eltype(uprev))
p.f(p.t+p.dt,reshape(uprev,p.sizeu),du)
for i in p.uidx
resid[i] = uprev[i] - p.u_old[i] - p.dt*du[i]
end
end
@inline function initialize!(integrator,cache::ImplicitEulerCache,f=integrator.f)
integrator.fsalfirst = cache.fsalfirst
integrator.fsallast = cache.k
f(integrator.t,integrator.uprev,integrator.fsalfirst)
integrator.kshortsize = 2
integrator.k = eltype(integrator.sol.k)(integrator.kshortsize)
integrator.k[1] = integrator.fsalfirst
integrator.k[2] = integrator.fsallast
end
@inline function perform_step!(integrator,cache::ImplicitEulerCache,f=integrator.f)
@unpack t,dt,uprev,u,k = integrator
uidx = eachindex(integrator.uprev)
@unpack u_old,dual_cache,k,adf,rhs,uhold = cache
copy!(u_old,uhold)
if integrator.iter > 1 && !integrator.u_modified
current_extrapolant!(uhold,t+dt,integrator)
end # else uhold is previous value.
rhs.t = t
rhs.dt = dt
rhs.uidx = uidx
rhs.sizeu = size(u)
if alg_autodiff(integrator.alg)
nlres = NLsolve.nlsolve(adf,uhold)
else
nlres = NLsolve.nlsolve(rhs,uhold,autodiff=alg_autodiff(integrator.alg))
end
copy!(uhold,nlres.zero)
f(t+dt,u,k)
@pack integrator = t,dt,u
end
type RHS_Trap{F,uType,rateType,tType,SizeType,DiffCacheType,uidxType} <: Function
f::F
u_old::uType
f_old::rateType
t::tType
dt::tType
sizeu::SizeType
dual_cache::DiffCacheType
uidx::uidxType
end
function (p::RHS_Trap)(uprev,resid)
du1 = get_du(p.dual_cache, eltype(uprev))
p.f(p.t+p.dt,reshape(uprev,p.sizeu),du1)
for i in p.uidx
resid[i] = @muladd uprev[i] - p.u_old[i] - (p.dt/2)*(du1[i]+p.f_old[i])
end
end
@inline function initialize!(integrator,cache::TrapezoidCache,f=integrator.f)
@unpack k,fsalfirst = cache
integrator.fsalfirst = fsalfirst
integrator.fsallast = cache.k
f(integrator.t,integrator.uprev,integrator.fsalfirst)
integrator.kshortsize = 2
integrator.k = eltype(integrator.sol.k)(integrator.kshortsize)
integrator.k[1] = integrator.fsalfirst
integrator.k[2] = integrator.fsallast
end
@inline function perform_step!(integrator,cache::TrapezoidCache,f=integrator.f)
@unpack t,dt,uprev,u,k = integrator
uidx = eachindex(integrator.uprev)
@unpack u_old,dual_cache,k,rhs,adf,uhold = cache
copy!(u_old,uhold)
if integrator.iter > 1 && !integrator.u_modified
current_extrapolant!(uhold,t+dt,integrator)
end # else uhold is previous value.
# copy!(rhs.fsalfirst,fsalfirst) Implicitly done by pointers: fsalfirst === fsalfirst == rhs.fsalfirst
rhs.t = t
rhs.dt = dt
rhs.uidx = uidx
rhs.sizeu = size(u)
if alg_autodiff(integrator.alg)
nlres = NLsolve.nlsolve(adf,uhold)
else
nlres = NLsolve.nlsolve(rhs,uhold,autodiff=alg_autodiff(integrator.alg))
end
copy!(uhold,nlres.zero)
f(t+dt,u,k)
@pack integrator = t,dt,u
end
type RHS_Trap_Scalar{F,uType,rateType,tType} <: Function
f::F
u_old::uType
f_old::rateType
t::tType
dt::tType
end
function (p::RHS_Trap_Scalar)(uprev,resid)
resid[1] = @muladd uprev[1] - p.u_old[1] - (p.dt/2)*(p.f_old + p.f(p.t+p.dt,uprev[1])[1])
end
@inline function initialize!(integrator,cache::TrapezoidConstantCache,f=integrator.f)
cache.uhold[1] = integrator.uprev; cache.u_old[1] = integrator.uprev
integrator.fsalfirst = f(integrator.t,integrator.uprev)
integrator.kshortsize = 2
integrator.k = eltype(integrator.sol.k)(integrator.kshortsize)
end
@inline function perform_step!(integrator,cache::TrapezoidConstantCache,f=integrator.f)
@unpack t,dt,uprev,u,k = integrator
@unpack uhold,u_old,rhs,adf = cache
u_old[1] = uhold[1]
if integrator.iter > 1 && !integrator.u_modified
uhold[1] = current_extrapolant(t+dt,integrator)
end # else uhold is previous value.
rhs.t = t
rhs.dt = dt
rhs.f_old = integrator.fsalfirst
if alg_autodiff(integrator.alg)
nlres = NLsolve.nlsolve(adf,uhold)
else
nlres = NLsolve.nlsolve(rhs,uhold,autodiff=alg_autodiff(integrator.alg))
end
uhold[1] = nlres.zero[1]
k = f(t+dt,uhold[1])
integrator.fsallast = k
u = uhold[1]
integrator.k[1] = integrator.fsalfirst
integrator.k[2] = integrator.fsallast
@pack integrator = t,dt,u
end
|
State Before: α : Type u_1
β : Type u_2
γ : Type ?u.1609
δ : Type ?u.1612
x : Option α
f : α → Option β
b : β
⊢ Option.bind x f = some b ↔ ∃ a, x = some a ∧ f a = some b State After: no goals Tactic: cases x <;> simp |
module Idris.Doc.HTML
import Core.Context
import Core.Core
import Core.Directory
import Data.Strings
import Parser.Lexer.Source
import Libraries.Text.PrettyPrint.Prettyprinter
import Libraries.Text.PrettyPrint.Prettyprinter.Render.HTML
import Libraries.Text.PrettyPrint.Prettyprinter.SimpleDocTree
import Idris.Doc.String
import Idris.Package.Types
import Idris.Pretty
import Idris.Version
%default covering
getNS : Name -> String
getNS (NS ns _) = show ns
getNS _ = ""
hasNS : Name -> Bool
hasNS (NS _ _) = True
hasNS _ = False
tryCanonicalName : {auto c : Ref Ctxt Defs} ->
FC -> Name -> Core (Maybe Name)
tryCanonicalName fc n with (hasNS n)
tryCanonicalName fc n | True
= do defs <- get Ctxt
case !(lookupCtxtName n (gamma defs)) of
[(n, _, _)] => pure $ Just n
_ => pure Nothing
tryCanonicalName fc n | False = pure Nothing
packageInternal : {auto c : Ref Ctxt Defs} ->
Name -> Core Bool
packageInternal (NS ns _) =
do let mi = nsAsModuleIdent ns
catch ((const True) <$> nsToSource emptyFC mi) (\_ => pure False)
packageInternal _ = pure False
prettyNameRoot : Name -> String
prettyNameRoot n =
let root = htmlEscape $ nameRoot n in
if isOpName n then "(" ++ root ++ ")" else root
renderHtml : {auto c : Ref Ctxt Defs} ->
SimpleDocTree IdrisDocAnn ->
Core String
renderHtml STEmpty = pure neutral
renderHtml (STChar ' ') = pure " "
renderHtml (STChar c) = pure $ cast c
renderHtml (STText _ text) = pure $ htmlEscape text
renderHtml (STLine _) = pure "<br>"
renderHtml (STAnn Declarations rest) = pure $ "<dl class=\"decls\">" <+> !(renderHtml rest) <+> "</dl>"
renderHtml (STAnn (Decl n) rest) = pure $ "<dt id=\"" ++ (htmlEscape $ show n) ++ "\">" <+> !(renderHtml rest) <+> "</dt>"
renderHtml (STAnn DocStringBody rest) = pure $ "<dd>" <+> !(renderHtml rest) <+> "</dd>"
renderHtml (STAnn DCon rest) = do
resthtml <- renderHtml rest
pure $ "<span class=\"name constructor\">" <+> resthtml <+> "</span>"
renderHtml (STAnn (TCon n) rest) = do
pure $ "<span class=\"name type\">" <+> (prettyNameRoot n) <+> "</span>"
renderHtml (STAnn (Fun n) rest) = do
pure $ "<span class=\"name function\">" <+> (prettyNameRoot n) <+> "</span>"
renderHtml (STAnn Header rest) = do
resthtml <- renderHtml rest
pure $ "<b>" <+> resthtml <+> "</b>"
renderHtml (STAnn (Syntax (SynRef n)) rest) = do
resthtml <- renderHtml rest
Just cName <- tryCanonicalName emptyFC n
| Nothing => pure $ "<span class=\"implicit\">" <+> resthtml <+> "</span>"
True <- packageInternal cName
| False => pure $ "<span class=\"type resolved\" title=\"" <+> (htmlEscape $ show cName) <+> "\">" <+> (htmlEscape $ nameRoot cName) <+> "</span>"
pure $ "<a class=\"type\" href=\"" ++ (htmlEscape $ getNS cName) ++ ".html#" ++ (htmlEscape $ show cName) ++ "\">" <+> (htmlEscape $ nameRoot cName) <+> "</a>"
renderHtml (STAnn ann rest) = do
resthtml <- renderHtml rest
pure $ "<!-- ann ignored START -->" ++ resthtml ++ "<!-- ann END -->"
renderHtml (STConcat docs) = pure $ fastConcat !(traverse renderHtml docs)
removeNewlinesFromDeclarations : SimpleDocTree IdrisDocAnn -> SimpleDocTree IdrisDocAnn
removeNewlinesFromDeclarations = go False
where
go : Bool -> SimpleDocTree IdrisDocAnn -> SimpleDocTree IdrisDocAnn
go False l@(STLine i) = l
go True l@(STLine i) = STEmpty
go ignoring (STConcat docs) = STConcat $ map (go ignoring) docs
go _ (STAnn Declarations rest) = STAnn Declarations $ go True rest
go _ (STAnn ann rest) = STAnn ann $ go False rest
go _ doc = doc
docDocToHtml : {auto c : Ref Ctxt Defs} ->
Doc IdrisDocAnn ->
Core String
docDocToHtml doc =
let dt = SimpleDocTree.fromStream $ layoutUnbounded doc in
renderHtml $ removeNewlinesFromDeclarations dt
htmlPreamble : String -> String -> String -> String
htmlPreamble title root class = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
++ "<title>" ++ htmlEscape title ++ "</title>"
++ "<link rel=\"stylesheet\" href=\"" ++ root ++ "styles.css\"></head>"
++ "<body class=\"" ++ class ++ "\">"
++ "<header><strong>Idris2Doc</strong> : " ++ htmlEscape title
++ "<nav><a href=\"" ++ root ++ "index.html\">Index</a></nav></header>"
++ "<div class=\"container\">"
htmlFooter : String
htmlFooter = "</div><footer>Produced by Idris 2 version " ++ (showVersion True version) ++ "</footer></body></html>"
export
renderDocIndex : PkgDesc -> String
renderDocIndex pkg = fastConcat $
[ htmlPreamble (name pkg) "" "index"
, "<h1>Package ", name pkg, " - Namespaces</h1>"
, "<ul class=\"names\">"] ++
(map moduleLink $ modules pkg) ++
[ "</ul>"
, htmlFooter
]
where
moduleLink : (ModuleIdent, String) -> String
moduleLink (mod, filename) =
"<li><a class=\"code\" href=\"docs/" ++ (show mod) ++ ".html\">" ++ (show mod) ++ "</a></li>"
export
renderModuleDoc : {auto c : Ref Ctxt Defs} ->
ModuleIdent ->
Doc IdrisDocAnn ->
Core String
renderModuleDoc mod allModuleDocs = pure $ fastConcat
[ htmlPreamble (show mod) "../" "namespace"
, "<h1>", show mod, "</h1>"
, !(docDocToHtml allModuleDocs)
, htmlFooter
]
|
#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_linalg.h>
#include <getopt.h>
#include <string.h>
/******************************************************************************/
#define H 0.5
#define maxnd 2000
#define neutral 0
#define selected 1
#define max_n_int_evaluated 1000
#define max_n_s_evaluated 2000
#define undefined -99999999999.99
#define undefined_int 999999
#define max_str_len 100
#define n_decimal_places 6
#define max_s_ranges 100
#define s_evaluated_vec_file_const "s_evaluated.dat"
#define t2_evaluated_vec_file_const "t2_evaluated.dat"
#define n2_evaluated_vec_file_const "n2_evaluated.dat"
#define s_range_file_const "s_ranges_evaluated.dat"
#define phase_1_dir_const "n1_n2_t2_s_vec_dir"
#define phase_2_dir_const "n2_t2_s_vec_dir"
#define const_pop_file "control_generate_allele_distrib_n1.out.bin"
/******************************************************************************/
/*Function List*/
double compute_weighted_average(double *weighted_vec, double *phase1_mut_vec,
double *phase2_mut_vec, int n1d, int n2d);
float assign_float_from_read_buff(char *buffer, int start);
int get_average_egf_vecs_1_and_2(double s,int n1, int n2, double t2_real,
int t2_lower, int t2_upper, double *egf_vec, char *buffer_p1_n2_t2_lower,
char *buffer_p2_n2_t2_lower, char *buffer_p1_n2_t2_upper,
char *buffer_p2_n2_t2_upper);
get_upper_lower_int(double parm, int *lower, int *upper, int n_int_evaluated, int *int_evaluated_vec);
get_upper_lower_double(double parm, double*lower, double *upper,int n_int_evaluated, double *double_evaluated_vec);
get_s_ranges();
get_int_evaluated_vec(int *int_evaluated_vec, int *n_int_evaluated,
int *int_lower, int *int_step, char *int_evaluated_vec_file);
scale_vector(double *vec, int n2, double total_density_s0);
int get_binary_egf_vec(char *buffer, int n, int t2, double s, double *egf_vec);
fold_vector_double(double *vec, int counter);
fold_vector_int(int *vec, int counter);
int nearest_n2_ind(int n2_real);
read_phase1_phase2_file_into_buffer(int n1, int phase, int n2, int t2, char *buffer,
int file_size_bytes);
read_const_pop_file_into_buffer(int n1, char *buffer, int file_size_bytes);
compute_weighted_average_egf_vec(double t2_real, int t2_lower, int t2_upper,
double *egf_vec_lower, double *egf_vec_upper,
double *egf_vec, int n2d);
double compute_weighted_average(double *weighted_vec, double *phase1_mut_vec,
double *phase2_mut_vec, int n1d, int n2d);
int get_const_pop_egf_vec(double s, int n1, double *egf_vec, char *buffer_const_pop,
int assign_tds0_mode);
assign_int_from_read_buff(int *res, char *buffer, int start);
float assign_float_from_read_buff(char *buffer, int start);
int compute_s_tab_num(double s);
int compute_file_size_bytes(int n);
set_up_file_name(int n1, char *froot, char *file_name);
get_data_path(char *data_path);
get_s_evaluated_vec(double *s_evaluated_vec, int *n_s_evaluated,
int *n_s_evaluated_file, char *s_evaluated_vec_file);
get_lower_upper(int ind, double *s_evaluated_vec, int n_s_evaluated,
double *lower, double *upper);
dumpvector(double *v, int min, int max, char *s);
dumpmatrix(double **m, int s1,
int rows, int s2, int cols, char *s);
double selfn(double q, double s, double h);
setuprow(double **a, double p, int row, int n);
setupmatrix(double **a, int n1, int n2, double s, double h);
matrixinvert(int N, double **a,double *inverter);
tmiterate(double **a,double *mut1,
int t, int n1, int n2,int decay,double *sumf);
tmiterate2(double **a,double *mut1,
int t, int n1, int n2,int decay,double **a1);
eqf_using_matrix_inversion(int n1,double s,double **a,double *egf_out);
vector_average(int n1,int n2,double *fv1,double *fv2, double *fv_out);
vector_s_average(int n,double P1,double *fv1,double *fv2, double *fv_out);
output_sfs_to_file_thanasis_format(int n, int *sfs1,int *sfs2,char *sfs_filename);
output_sfs_to_file_peter_format(int n,int sample1, int sample2, int *sfs1,int *sfs2,char *sfs_filename);
get_sfs(int alleles,int *par,char *sfs_filename);
get_sfs_peter1(int *total_neu,int *total_sel,int *nalleles,int *sfs_sel,int *sfs_neu,char *sfs_filename);
get_sfs_peter2(int *total_neu,int *total_sel,int *nalleles,int *sfs_sel,int *sfs_neu,char *sfs_filename,int *sel_sites,int *sel_diff,int *neu_sites,int *neu_diff);
int binarysearchcumulative_from_zero(double *array, int size);
double randomly_select_allele_frequency(double *egf_vec, double *temp1, int nd);
set_up_cumulative_allele_freq_vec(int nd, double *egf_vec, double *cum_vec,
char *str);
generate_simulated_data(double *egf_vec, int nsites, int sample_size, int nd,
int *sfs);
egf_scaling_s(int n1,double f0,double *v_s_in, double *v_s_out);
egf_scaling_f0(int n1,double f0,double *fv);
egf_scaling(int N,double f0,double *FV0,double *FVS);
binomial_sampling(int n1,int alleles,int sample, double *invy,int *discrete);
int set_up_density_vec_equal_effects(double s, int n_s_evaluated, double *gamma_density_vec);
int set_up_density_vec_step_effects(double alpha, double beta, int n_s_evaluated, double *gamma_density_vec);
double compute_beta_densities(double alpha, double *s_evaluated_vec,
int n_s_evaluated, double *gamma_density_vec, double beta);
double compute_gamma_densities(double alpha, double *s_evaluated_vec,
int n_s_evaluated, double *gamma_density_vec, double beta);
double calculate_ne(int n1,int n2,int t);
/******************************************************************************/
/*Structure List*/
struct rangestruct
{
double s_lower, s_upper, s_step;
int s_lower_index;
};
struct rangestruct s_ranges[max_s_ranges+1];
/******************************************************************************/
/*Global variable List*/
double allele_freq_sampled[maxnd+1];
double total_density_s0;
char s_evaluated_vec_file[max_str_len], t2_evaluated_vec_file[max_str_len],
n2_evaluated_vec_file[max_str_len], s_range_file[max_str_len],
phase_1_dir[max_str_len], phase_2_dir[max_str_len],
const_pop_dir[max_str_len];
char data_path[max_str_len], file_label_str[max_str_len];
int nranges, trace_level, n_sfs;
int n_s_evaluated, n_s_evaluated_file, gss_n2;
int t2_evaluated_vec[max_n_int_evaluated], n_t2_evaluated, t2_lower;
int t2_step, verbose_mode, neutrals_only_mode;
int n2_evaluated_vec[max_n_int_evaluated], n_n2_evaluated, n2_lower;
double s_evaluated_vec[max_n_s_evaluated];
/******************************************************************************/
|
# Question 1
Considérons le système d'inégalités $Ax \geq b$, $x \geq 0$, où $b \geq 0$. Nous transformons ce
système sous une forme standard en introduisant m variables de surplus $y$ pour
obtenir le système suivant $Ax-y = b$, $x \geq 0$, $y \geq 0$ où $b \geq 0$. Dénotons
\begin{gather*}
b_k = \max_{1 \leq 1 \leq m} \lbrace b_i \rbrace,
\end{gather*}
et considérons le nouveau problème sous forme standard obtenu du précédent en
additionnant la $k$ième ligne à toutes les autres lignes après avoir changé leur signe.
Indiquez pourquoi il suffit d'introduire une seule variable artificielle dans une phase I pour obtenir
une solution de base réalisable initiale.
Illustrer cette procédure sur le problème suivant
\begin{align*}
x_1 + 2x_2 + x_3 &\geq 4 \\
2x_1 + x_2 + x_3 &\geq 5 \\
2x_1 + 3x_2 + 2x_3 &\geq 6 \\
x_j \geq 0,\ j &= 1,2,3.
\end{align*}
## Solution question 1
On introduit les variables $y_1$, $y_2$ et $y_3$ dans le problème pour le mettre sous forme standard
\begin{align*}
x_1 + 2x_2 + x_3 - y_1 & = 4 \\
2x_1 + x_2 + x_3 - y_2 & = 5 \\
2x_1 + 3x_2 + 2x_3 - y_3 & = 6 \\
x_j \geq 0,\ j &= 1,2,3,\\
y_j \geq 0,\ j &= 1,2,3.
\end{align*}
On utilise l'indication, on choisit
\begin{gather*}
b_k = \max_{1 \leq 1 \leq 3} \lbrace b_i \rbrace = b_3
\end{gather*}
et on effectue les opérations comme dans l'énoncé
\begin{align*}
x_1 + x_2 + x_3 - y_3 + y_1 & = 2 \\
2x_2 + x_3 - y_3 + y_2 & = 1 \\
2x_1 + 3x_2 + 2x_3 - y_3 & = 6 \\
x_j \geq 0,\ j &= 1,2,3,\\
y_j \geq 0,\ j &= 1,2,3,\\
t_1 \ge 0.
\end{align*}
On obtient ainsi un système totalement équivalent au premier sur lequel on peut appliquer la phase I qui prend la forme suivante
\begin{align*}
&\max t_1\\
&\begin{aligned}
\text{tel que } \quad x_1 + x_2 + x_3 - y_3 + y_1 & = 2 \\
2x_2 + x_3 - y_3 + y_2 & = 1 \\
2x_1 + 3x_2 + 2x_3 - y_3 + t_1 & = 6 \\
t_1,\ x_j, y_j \geq 0,\ j &= 1,2,3.
\end{aligned}
\end{align*}
De manière générale, on aurait
Pour $i=k$,
\begin{align*}
\sum_{j=1}^{n} a_{kj} x_j - y_k + t_1 = b_k \ge 0
\end{align*}
Pour $i = 1, \ldots, m$ et $i \ne k$,
\begin{align*}
\sum _{j=1}^{n} ( a_{kj} - a_{ij} ) x_j - y_k + y_i = b_k - b_i \ge 0
\end{align*}
Le système est équivalent par construction et il est réalisable puisque les
termes de droites sont non-négatifs.
Pour $i = 1, \ldots, m$ et $i \ne k$, on maintenant que $y_i$ est une variable de base.
Il ne manque plus qu'à déterminer une dernière variable de base et pour ce faire on
fait une phase I en ajoutant la variable $t_1$ à la kième équation.
# Question 2
Question 5 de l'examen intra A2011.
On a le problème suivant
\begin{align*}
\begin{array}{l c c c c c c c}
\min\ z = & -3x_1 & - & x_2 & - & 3x_3 & & \\
\text{tel que } & 2x_1 & + & 1x_2 & + & x_3 & \leq & 2 \\
& x_1 & + & 2x_2 & + & 3x_3 & \leq & 5 \\
& 2x_1 & + & 2x_2 & + & x_3 & \leq & 6 \\
& x_1 && x_2 && x_3 & \geq & 0 \\
\end{array}
\end{align*}
**(a)** Transformer le problème sous forme standard
**(b)** À une itération du simplexe révisé on obtient
\begin{equation}
\begin{array}{ccccccc}
x_1 &\frac{1}{2} & 0 & 0 & 1 \\
x_5 &\frac{-1}{2} & 1 & 0 & 4 \\
x_6 &-1 & 0 & 1 & 4 \\
-z &\frac{3}{2} & 0 & 0 & 3 \\
\end{array}
\end{equation}
où dans la dernière ligne on a mis **l'opposé du vecteur des multiplicateurs** $\lambda^t$ $\left(\lambda^t=c^t_B B^{-1} \right)$.
Quelle est la base associée à cette itération?
**(c)** En partant du tableau du simplexe révisé en **(b)**, continuer l'algorithme du simplexe révisé jusqu'à l'optimum.
**(d)**
Soit le nouveau coût initial $\hat{c}_2 = c_2+\delta$, où $c_2=-1$ est le coût initial associé à $x_2$. Pour quelle valeur de $\delta$ la solution trvouvée en $\textbf{(b)}$ demeure-t-elle optimale?
## Solution question 2
**(a)** Pour transformer le problème sous forme standard, on introduit des variables d'écarts $x_4$, $x_5$ et $x_6$.
\begin{align*}
\begin{array}{l c c c c c c c c c c c c c}
\min z = & -3x_1 & - & x_2 & - & 3x_3 & & & & & & & & \\
\text{tel que } & 2x_1 & + & x_2 & + & x_3 & + & x_4 & & & & &= & 2 \\
& x_1 & + & 2x_2 & + & 3x_3 & & & + & x_5 & & &= & 5 \\
& 2x_1 & + & 2x_2 & + & x_3 & & & & & +& x_6 &= & 6 \\
& x_1, && x_2, && x_3, && x_4, && x_5, && x_6 & \geq & 0
\end{array}
\end{align*}
**(b)**
La base B est composée des colonnes associées aux variables $x_1$, $x_5$ et $x_6$.
$$
B = \begin{pmatrix}
2 & 0 & 0 \\
1 & 1 & 0 \\
2 & 0 & 1
\end{pmatrix}
$$
**(c)**
Pour savoir si nous devons poursuivre la résolution du problème, nous
calculons d'abord les coûts réduits:
Nous disposons dans le tableau de
l'inverse de la base, et du vecteur multiplicateur $\lambda$: $\lambda^t = \left(\frac{-3}{2}, 0, 0 \right)$.
Pour calculer les coûts réduits :
$\bar c^t = c^t - \lambda^t A $
$\bar c^t$ = (0, $\frac{1}{2}$, $\frac{-3}{2}$, $\frac{3}{2}$, 0 0)
$\bar c_3 < 0$ la base courante n'est pas optimale. $x_3$ rentre dans la base.
Déterminons la variable de sortie:
$y_3 = B^{-1}A_3$
$$
y_3 = \begin{pmatrix}
1/2 \\
5/2 \\
0
\end{pmatrix}
$$
De plus, $\min \left\{ \frac{1}{1/2}, \frac{4}{5/2} \right\} = 8/5$.
Ainsi $x_5$ sort de la base.
\begin{align*}
\begin{array} { c c c c c| c}
& & & & & y_3 \\
\hline
x_1 & 1/2 & 0 & 0 & 1 & 1/2 \\
x_5 & -1/2 & 1 & 0 & 4 & 5/2 \\
x_6 & -1 & 0 & 1 & 4 & 0 \\
\hline
-z & 3/2 & 0 & 0 & 3 & -3/2 \\
\hline
\end{array}
\end{align*}
Les opérations sur les lignes se résument ainsi:
$L'_1 \leftarrow L_1 - \frac{1}{2} L'_2$ \\
$L'_2 \leftarrow \frac{2}{5} L_2$ \\
$L'_3 \leftarrow L_3$ \\
$L'_4 \leftarrow L_4 + \frac{3}{2} L' _2$
Le nouveau tableau du simplexe révisé est donc le suivant:
\begin{align*}
\begin{array}{|c| c c c |c|}
\hline
x_1 & 3/5 & -1/5 & 0 & 1/5 \\
x_3 & -1/5 & 2/5 & 0 & 8/5 \\
x_6 & -1 & 0 & 1 & 4 \\
\hline
-z & 6/5 & 3/5 & 0 & 27/5 \\
\hline
\end{array}
\end{align*}
Dès lors,
$$
B^{-1} = \begin{pmatrix}
3/5 & -1/5 & 0 \\
-1/5 & 2/5 & 0 \\
-1 & 0 & 1
\end{pmatrix}
$$
et
$$
\lambda^t = c_b^t B^{-1} = (-6/5 , -3/5, 0).
$$
et nous pouvons calculer les coûts réduits $\bar c^t = c^t - \lambda^tA$:
$$
\bar c^t = (0, 7/5, 0, 6/5, 3/5, 0).
$$
Tous les coûts réduits sont positifs ou nuls. La base courante est donc optimale.
Une solution optimale est donnée par :
$x_1^* = 1/5$, $x_2^* = 0$, $x_3^* = 8/5$, $x_4^* = 0$, $x_5^* = 0$, $x_6^* = 4$, de valeur optimale -27/5.
**(d)**
La solution demeure optimale tant que $(-1 + \delta) - \lambda A_2 \geq 0$.
Alors la solution demeure réalisable pour tout $\delta \geq -7/5$.
### Question supplémentaire : Dualité
**(e)**
Formuler le dual du problème et vérifier que $\lambda = (-1.2, 0.6, 0)$ est une solution réalisable de ce problème.
Le dual de (P) est:
\begin{align*}
\begin{array}{c c c c c c c c}
\max & 2 \lambda_1 & + & 5 \lambda_2 & + & 6 \lambda_3 & & \\
\text{tel que } & 2 \lambda_1 & + & \lambda_2 & + & 2 \lambda_3 & \leq & -3 \\
& \lambda_1 & + & 2 \lambda_2 & + & 2 \lambda_3 & \leq & -1 \\
& \lambda_1 & + & 3 \lambda_2 & + & \lambda_3 & \leq & -3 \\
& \lambda_1 & & & & & \leq & 0 \\
& & & \lambda_2 & & & \leq & 0 \\
& & & & & \lambda_3 & \leq & 0 \\
\end{array}
\end{align*}
Le vecteur $\lambda = (-1.2, 0.6, 0)$ est égal au vecteur des multiplicateurs
optimaux (-6/5, -3/5, 0). Le vecteur des multiplicateurs étant solution
réalisable et optimale du problème dual, on a vérifié que $\lambda$ est
réalisable dans le dual.
## Question 3, \#4 examen Intra 2018
Soit le problème de programmation linéaire suivant
\begin{align*}
\min_x \ &z = –8x_1 – 9x_2 – 7x_3 – 6x_4 – 8x_5 – 9x_6 \\
\mbox{sujet à } & x_1 + x_3 +x_5 = 4 \\
& x_2 + x_4 + x_6 = 2 \\
& x_1 + x_4 = 2 \\
& x_2 + x_5 = 1 \\
& x_j \geq 0,\ j = 1,2,\ldots,6.
\end{align*}
Utilisez la phase I de la méthode à deux phases pour trouver une solution réalisable au problème.
La forme révisée du simplexe est utilisée pour résoudre le problème, et à une certaine itération nous avons le tableau réduit suivant
$$
\begin{matrix}
x_1 & 0 & 0 & 1 & 0 & 2\\
x_2 & 0 & 0 & 0 & 1 & 1\\
x_3 & 1 & 0 & -1 & 0 & 2\\
x_6 & 0 & 1 & 0 & -1 & 1\\
& 7 & 9 & 1 & 0 & 48
\end{matrix}
$$
La dernière ligne contient l'opposé des multiplicateurs, correspondant à $c_B^T B^{-1}$.
Que vaut $B$? Et $B^{-1}$? La solution de base actuelle est-elle optimale? Si oui, justifier votre réponse. Si non, poursuivre l'application de la forme révisée du simplexe pour déterminer une solution optimale.
De quelle quantité faut-il modifier le coût associé à la variable $x_2$ dans la fonction économique (i.e. son coefficient dans la fonction objectif) pour que le coût réduit de cette variable soit nul relativement à la base optimale obtenue au point précédent. Déterminer alors une solution de base optimale alternative.
# Solution question 3
Remarquons tout d'abord que $x_3$ et $x_6$ sont isolées, aussi nous n'avons que deux variables artificielles à ajouter, aux troisième et quatrième contraintes, donnant le problème artificiel suivant:
\begin{align*}
\min_{x} \ & x_7 + x_8 \\
\mbox{sujet à } & x_1 + x_3 +x_5 = 4 \\
& x_2 + x_4 + x_6 = 2 \\
& x_1 + x_4 + x_7 = 2 \\
& x_2 + x_5 + x_8 = 1 \\
& x_j \geq 0,\ j = 1,2,\ldots,8.
\end{align*}
Ceci mène à la séquence suivante d'itérations de l'algorithme du simplexe:
$$
\begin{matrix}
1 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 4 \\
0 & 1 & 0 & 1 & 0 & 1 & 0 & 0 & 2 \\
1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 2 \\
0 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0
\end{matrix}
$$
Après annulation des coûts réduits, nous avons
$$
\begin{matrix}
1 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 4 \\
0 & 1 & 0 & 1 & 0 & 1 & 0 & 0 & 2 \\
1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 2 \\
0 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 1 \\
-1 & -1 & 0 & -1 & -1 & 0 & 0 & 0 & -3
\end{matrix}
$$
Faisons entrer $x_1$ dans la base. $x_7$ sort, donnant
$$
\begin{matrix}
0 & 0 & 1 & -1 & 1 & 0 & -1 & 0 & 2 \\
0 & 1 & 0 & 1 & 0 & 1 & 0 & 0 & 2 \\
1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 2 \\
0 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 1 \\
0 & -1 & 0 & 0 & -1 & 0 & 2 & 1 & -1
\end{matrix}
$$
Nous pouvons à présent faire entrer $x_1$ dans la base, en faisant sortir $x_8$, ce qui donne
$$
\begin{matrix}
0 & 0 & 1 & -1 & 1 & 0 & -1 & 0 & 2 \\
0 & 0 & 0 & 1 & -1 & 1 & 0 & -1 & 1 \\
1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 2 \\
0 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 2 & 2 & 0
\end{matrix}
$$
Dès lors, une solution réalisable au problème initial est $x = (2, 1, 2, 0, 0, 1)$.
La forme révisée du simplexe est utilisée pour résoudre le problème, et à une certaine itération nous avons le tableau réduit suivant
$$
\begin{matrix}
x_1 & 0 & 0 & 1 & 0 & 2\\
x_2 & 0 & 0 & 0 & 1 & 1\\
x_3 & 1 & 0 & -1 & 0 & 2\\
x_6 & 0 & 1 & 0 & -1 & 1\\
& 7 & 9 & 1 & 0 & 48
\end{matrix}
$$
La dernière ligne contient l'opposé des multiplicateurs, correspondant à $c_B^T B^{-1}$.
Que vaut $B$? Et $B^{-1}$? La solution de base actuelle est-elle optimale? Si oui, justifier votre réponse. Si non, poursuivre l'application de la forme révisée du simplexe pour déterminer une solution optimale.
Les variables de base selon le dictionnaire sont $x_1$, $x_2$, $x_3$ et $x_6$. En se référant à la matrice $A$ initiale, incluant les variables artificielles, nous en déduisons
$$
B =
\begin{pmatrix}
1 & 0 & 1 & 0 \\
0 & 1 & 0 & 1 \\
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0
\end{pmatrix}
$$
La base initiale est la matrice identité. Dès lors, les colonnes du simplexe révisé donne immédiatement $B^-1$:
$$
B^{-1} =
\begin{pmatrix}
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
1 & 0 & -1 & 0 \\
0 & 1 & 0 & -1
\end{pmatrix}
$$
Nous pouvons facilement vérifier sous Julia qu'il s'agit bien l'inverse de $B$.
```julia
B = [ 1 0 1 0 ; 0 1 0 1 ; 1 0 0 0 ; 0 1 0 0 ]
invB = [ 0 0 1 0 ; 0 0 0 1 ; 1 0 -1 0 ; 0 1 0 -1 ]
B*invB
```
4×4 Matrix{Int64}:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Pour voir si cette base est optimale, nous devons calculer les coûts réduits. Rappelons que les coûts réduits sont obtenus par
$$
r_D^T = c_D^T - c_B^TB^{-1}D = c_D^T - \lambda^TD,
$$
et de l'énoncé,
$$
\lambda^T = - \begin{pmatrix} 7 & 9 & 1 & 0 \end{pmatrix}.
$$
Nous pouvons le vérifier:
$$
\lambda^T = - \begin{pmatrix} 8 & 9 & 7 & 9 \end{pmatrix}
\begin{pmatrix}
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
1 & 0 & -1 & 0 \\
0 & 1 & 0 & -1
\end{pmatrix}
= - \begin{pmatrix} 7 & 9 & 1 & 0 \end{pmatrix}.
$$
Dès lors,
$$
r_D^T = - \begin{pmatrix} 6 & 8 \end{pmatrix} + \begin{pmatrix} 7 & 9 & 1 & 0 \end{pmatrix}
\begin{pmatrix} 0 & 1 \\ 1 & 0 \\ 1 & 0 \\ 0 & 1 \end{pmatrix}
= \begin{pmatrix} 4 & -1 \end{pmatrix}.
$$
Il persiste un coût réduit négatif. La solution actuelle n'est donc pas optimale.
Note: on a ignoré les deux dernières composantes de $\lambda$, qui correspondent aux variables artificielles.
Nous faisons entrer dans la base $x_5$.
Exprimons $y_5 = B^{-1}a_5$:
$$
y_5 = \begin{pmatrix}
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
1 & 0 & -1 & 0 \\
0 & 1 & 0 & -1
\end{pmatrix}
\begin{pmatrix}
1 \\ 0 \\ 0 \\ 1
\end{pmatrix}
= \begin{pmatrix}
0 \\ 1 \\ 1 \\ -1
\end{pmatrix}
$$
Pivotage
$$
\begin{matrix}
x_1 & 0 & 0 & 1 & 0 & 2 & 0 \\
x_2 & 0 & 0 & 0 & 1 & 1 & 1 \\
x_3 & 1 & 0 & -1 & 0 & 2 & 1 \\
x_6 & 0 & 1 & 0 & -1 & 1 & -1 \\
-z & 7 & 9 & 1 & 0 & 48 & -1 \\
\end{matrix}
$$
Note: nous avons inséré le coût réduit associé à $y_5$ dans la dernière, comme nous devrons l'annuler.
La règle du pivotage nous donne $x_2$ comme variable sortante, ce qui donne
$$
\begin{matrix}
x_1 & 0 & 0 & 1 & 0 & 2 \\
x_5 & 0 & 0 & 0 & 1 & 1 \\
x_3 & 1 & 0 & -1 & -1 & 1 \\
x_6 & 0 & 1 & 0 & 0 & 2 \\
-z & 7 & 9 & 1 & 1 & 49 \\
\end{matrix}
$$
Nous retrouvons les coûts réduits à la dernière ligne, que nous pouvons vérifier:
$$
-\lambda^T = -c_B^TB^{-1} = \begin{pmatrix} 8 & 8 & 7 & 9 \end{pmatrix}
\begin{pmatrix} 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ 1 & 0 & -1 & -1 \\ 0 & 1 & 0 & 0 \end{pmatrix}
= \begin{pmatrix} 7 & 9 & 1 & 1 \end{pmatrix}
$$
et
$$
r_D^T = c_D^T-\lambda^TD = - \begin{pmatrix} 9 & 6 \end{pmatrix} + \begin{pmatrix} 7 & 9 & 1 & 1 \end{pmatrix}
\begin{pmatrix} 0 & 0 \\ 1 & 1 \\ 0 & 1 \\ 1 & 0 \end{pmatrix}
= \begin{pmatrix} 1 & 4 \end{pmatrix}
$$
Tous les coûts réduits sont strictement positifs; nous sommes à l'optimalité. La solution optimale est $(2, 0, 1, 0, 1, 2)$ et la valeur optimale, $-49$.
Vérifions-le avec JuMP
```julia
using JuMP
using GLPK
```
```julia
c = [ -8 -9 -7 -6 -8 -9 ]
A = [ 1 0 1 0 1 0 ; 0 1 0 1 0 1 ; 1 0 0 1 0 0 ; 0 1 0 0 1 0 ]
b = [ 4 2 2 1 ]
```
1×4 Matrix{Int64}:
4 2 2 1
```julia
m = Model(with_optimizer(GLPK.Optimizer))
@variable(m, 0 <= x[1:6])
for i = 1:4
@constraint(m, sum(A[i,j]*x[j] for j = 1:6) == b[i])
end
@objective(m, Min, sum(c[i]*x[i] for i = 1:6))
print(m)
```
```julia
optimize!(m)
println("Objective value: ", objective_value(m))
println("x = ", value.(x))
```
De quelle quantité faut-il modifier le coût associé à la variable $x_2$ dans la fonction économique (i.e. son coefficient dans la fonction objectif) pour que le coût réduit de cette variable soit nul relativement à la base optimale obtenue au point précédent. Déterminer alors une solution de base optimale alternative.
Nous devons donc calculer le coût réduit associé à $x_2$ et déterminer $\Delta c_2$, la quantité à ajouter à $c_2$, le coefficient de $x_2$ dans la fonction objectif.
Il n'est pas nécessaire de calculer tous les coûts réduits, seul celui associé à $x_2$ importe:
$r_2 = c'_2 - \lambda^T a_2$, où $c'_2$ est le coût modifié dans la fonction objectif.
Nous voulons annuler $r_2$, ce qui donne l'équation
$$
0 = c'_2 - \lambda^T a_2.
$$
On en déduit immédiatement qu'il faudrait avoir $c'_2 = \lambda^T a_2$, soit
$$
c'_2 = - \begin{pmatrix} 7 & 9 & 1 & 1 \end{pmatrix} \begin{pmatrix} 0 & 1 & 0 & 1 \end{pmatrix} = -10.
$$
De là
$$
\Delta c_2 = c'_2 - c_2 = -10 + 9 = -1.
$$
Comme seul $c_2$ change, mais pas les autres éléments du problème, les autres coûts réduits sont inchangés, et la solution précédemment obtenue reste optimale. Néanmoins, nous pouvons à présent faire entrer $x_2$ dans la base optimale sans changer la valeur de la fonction objectif.
Nous devons déterminer la variable entrante. Pour ce faire, calculons tout d'abord
$$
y_2 =
\begin{pmatrix}
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
1 & 0 & -1 & -1 \\
0 & 1 & 0 & 0
\end{pmatrix}
\begin{pmatrix}
0 \\ 1 \\ 0 \\ 1
\end{pmatrix}
=
\begin{pmatrix}
0 \\ 1 \\ -1 \\ 1
\end{pmatrix}
$$
Procédons au pivotage
$$
\begin{matrix}
x_1 & 0 & 0 & 1 & 0 & 2 & 0 \\
x_5 & 0 & 0 & 0 & 1 & 1 & 1 \\
x_3 & 1 & 0 & -1 & -1 & 1 & -1 \\
x_6 & 0 & 1 & 0 & 0 & 2 & 1\\
-z & 7 & 9 & 1 & 1 & 49 & 0 \\
\end{matrix}
$$
On voit que $x_5$ sort de la base, pour donner
$$
\begin{matrix}
x_1 & 0 & 0 & 1 & 0 & 2 \\
x_2 & 0 & 0 & 0 & 1 & 1 \\
x_3 & 1 & 0 & -1 & 0 & 2 \\
x_6 & 0 & 1 & 0 & -1 & 1 \\
-z & 7 & 9 & 1 & 1 & 49 \\
\end{matrix}
$$
La nouvelle solution optimale est $(2, 1, 2, 0, 0, 1)$, associée à la même valeur optimale $-49$.
Note: comme la solution avant pivot était optimale, il n'est pas nécessaire de recalculer les nouveaux coûts réduits pour vérifier l'optimalité.
On va néanmoins s'en convaincre:
$$
r_D^T = c_D^T - c_B^TB^{-1}D
= \begin{pmatrix} -6 & -8 \end{pmatrix} + \begin{pmatrix} 7 & 9 & 1 & 1 \end{pmatrix}
\begin{pmatrix} 0 & 1 \\ 1 & 0 \\ 1 & 0 \\ 0 & 1 \end{pmatrix}
= \begin{pmatrix} 4 & 0 \end{pmatrix}
$$
```julia
```
|
A topological space is connected if and only if any two points in the space are in the same connected component. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.