text
stringlengths 0
3.34M
|
---|
//---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_PhotoatomFactory.hpp
//! \author Alex Robinson
//! \brief The photoatom factory class declaration
//!
//---------------------------------------------------------------------------//
#ifndef MONTE_CARLO_PHOTOATOM_FACTORY_HPP
#define MONTE_CARLO_PHOTOATOM_FACTORY_HPP
// Std Lib Includes
#include <string>
#include <memory>
// Boost Includes
#include <boost/filesystem.hpp>
// FRENSIE Includes
#include "MonteCarlo_Photoatom.hpp"
#include "MonteCarlo_PhotonMaterial.hpp"
#include "MonteCarlo_AtomicRelaxationModelFactory.hpp"
#include "MonteCarlo_ScatteringCenterDefinitionDatabase.hpp"
#include "MonteCarlo_MaterialDefinitionDatabase.hpp"
#include "MonteCarlo_SimulationProperties.hpp"
#include "Utility_Map.hpp"
#include "Utility_Set.hpp"
namespace MonteCarlo{
//! The photoatom factory class
class PhotoatomFactory
{
public:
//! The photoatom name map
typedef PhotonMaterial::PhotoatomNameMap PhotoatomNameMap;
//! The scattering center name set
typedef MaterialDefinitionDatabase::ScatteringCenterNameSet ScatteringCenterNameSet;
//! Constructor
PhotoatomFactory(
const boost::filesystem::path& data_directory,
const ScatteringCenterNameSet& photoatom_names,
const ScatteringCenterDefinitionDatabase& photoatom_definitions,
const std::shared_ptr<AtomicRelaxationModelFactory>&
atomic_relaxation_model_factory,
const SimulationProperties& properties,
const bool verbose = false );
//! Destructor
~PhotoatomFactory()
{ /* ... */ }
//! Create the map of photoatoms
void createPhotoatomMap( PhotoatomNameMap& photoatom_name_map ) const;
private:
// Create a photoatom from an ACE table
void createPhotoatomFromACETable(
const boost::filesystem::path& data_directory,
const std::string& photoatom_name,
const double atomic_weight,
const Data::PhotoatomicDataProperties& data_properties,
const std::shared_ptr<AtomicRelaxationModelFactory>&
atomic_relaxation_model_factory,
const SimulationProperties& properties );
// Create a photoatom from a Native table
void createPhotoatomFromNativeTable(
const boost::filesystem::path& data_directory,
const std::string& photoatom_name,
const double atomic_weight,
const Data::PhotoatomicDataProperties& data_properties,
const std::shared_ptr<AtomicRelaxationModelFactory>&
atomic_relaxation_model_factory,
const SimulationProperties& properties );
// The photoatom map
PhotoatomNameMap d_photoatom_name_map;
// The table map (used to prevent multiple reads of the same data file)
std::map<Data::PhotoatomicDataProperties::FileType,PhotoatomNameMap>
d_photoatomic_table_name_map;
// Verbose photoatom construction
bool d_verbose;
};
} // end MonteCarlo namespace
#endif // end MONTE_CARLO_PHOTOATOM_FACTORY_HPP
//---------------------------------------------------------------------------//
// end MonteCarlo_PhotoatomFactory.hpp
//---------------------------------------------------------------------------//
|
{-# LANGUAGE BangPatterns, GADTs, StandaloneDeriving, OverloadedStrings #-}
-- |
-- Module : Criterion
-- Copyright : (c) 2009-2014 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- 'Versus'-type bgroup support
module Criterion.Versus
(
vscsv
, versusReports
, VersusReport(..)
) where
import Criterion.Types
import Criterion.IO.Printf (writeCsv)
import Criterion.Monad (Criterion)
import Control.Monad
import Control.Monad.Trans (liftIO)
import Control.Monad.Reader (asks)
import Control.Arrow ((&&&))
import Data.Function (on)
import qualified Data.Csv as Csv
import Data.List (groupBy, sortBy)
import Statistics.Resampling.Bootstrap (Estimate(..))
import Data.Aeson (ToJSON(..), object, encode, (.=))
data VersusReport where
VersusReport :: (Show l, Ord l) => {
vsReportDescription :: String
, vsReportDataPoints :: [l]
, vsReportData :: [(String, [Estimate])]
, vsReportIndices :: [((String, l), Int)]
} -> VersusReport
deriving instance Show VersusReport
{- This instance is actually incomplete -}
instance ToJSON VersusReport where
toJSON VersusReport{
vsReportDescription = desc
, vsReportDataPoints = dp
, vsReportData = d
} = object [ "name" .= toJSON desc
, "dataPoints" .= toJSON (map show dp)
, "data" .= toJSON (map mkArr d)]
where
mkArr (alg, p) = object [ "alg" .= toJSON alg
, "data" .= toJSON p]
vscsv :: [VersusReport] -> Criterion ()
vscsv = mapM_ f
where f VersusReport{
vsReportDescription = d
, vsReportData = r
, vsReportDataPoints = p} = do
file <- asks vsCsvFile
writeCsv file [d]
writeCsv file $ "name":(map show p)
forM_ r $ \(a, m) -> writeCsv file $ a:(map (show . estPoint) m)
versusReports :: [VersusReport] -> [Report] -> [VersusReport]
versusReports vrpts rpts = map (vsReport rpts) vrpts
vsReport :: [Report] -> VersusReport -> VersusReport
vsReport rpts vr@VersusReport{vsReportIndices = indices} =
vr{vsReportData = map f l}
where
valg = fst . fst
venv = snd . fst
l = groupBy' ((==) `on` valg) valg indices
rpts' = sortBy (compare `on` reportNumber) rpts
f (alg, idx) = (alg, [anMean . reportAnalysis $ rpts'!!i
| (_, i)<-sortBy (compare `on` venv) idx])
groupBy' :: (a -> a -> Bool) -> (a -> b) -> [a] -> [(b, [a])]
groupBy' f g = map (g . head &&& id) . groupBy f
|
{-# OPTIONS --without-K #-}
open import HoTT
module homotopy.ConstantToSetFactorization
{i j} {A : Type i} {B : Type j} (B-is-set : is-set B)
(f : A β B) (f-is-const : β aβ aβ β f aβ == f aβ) where
private
Skel = SetQuotient {A = A} (Ξ» _ _ β Unit)
abstract
Skel-has-all-paths : has-all-paths Skel
Skel-has-all-paths =
SetQuot-elim (Ξ» _ β Ξ -is-set Ξ» _ β =-preserves-set SetQuotient-is-set)
(Ξ» aβ β
SetQuot-elim {P = Ξ» sβ β q[ aβ ] == sβ}
(Ξ» _ β =-preserves-set SetQuotient-is-set)
(Ξ» _ β quot-rel _)
(Ξ» _ β prop-has-all-paths-β (SetQuotient-is-set _ _)))
(Ξ» {aβ aβ} _ β β-cstβapp-in Ξ» sβ β
prop-has-all-paths-β (SetQuotient-is-set _ _))
Skel-is-prop : is-prop Skel
Skel-is-prop = all-paths-is-prop Skel-has-all-paths
Skel-lift : Skel β B
Skel-lift = SetQuot-rec B-is-set f (Ξ» {aβ aβ} _ β f-is-const aβ aβ)
cst-extend : Trunc -1 A β B
cst-extend = Skel-lift β Trunc-rec Skel-is-prop q[_]
-- The beta rule.
-- This is definitionally true, so you don't need it.
cst-extend-Ξ² : cst-extend β [_] == f
cst-extend-Ξ² = idp
|
lemma convex_hull_3_alt: "convex hull {a,b,c} = {a + u *\<^sub>R (b - a) + v *\<^sub>R (c - a) | u v. 0 \<le> u \<and> 0 \<le> v \<and> u + v \<le> 1}" |
import analysis.real
import data.nat.prime data.int.modeq data.complex.basic algebra.euclidean_domain number_theory.pell data.pnat
open nat
-- Questions:
-- Find the continued fraction expansions of the following rational numbers:
-- 69/40
--theorem q1a:
-- 233/144
--theorem q1b:
-- 507/414
--theorem q1c:
-- Define the Fibonacci numbers F(n) by Fβ = Fβ = 1, F(n+1) = F(n) + F(n-1) for i β₯ 2. Describe, for all n > 1, the continued fraction expansion of F(n)/F(n-1).
--theorem q2a:
-- Find the continued fraction expansion of (1+sqrt(5))/2.
--theorem q2b:
-- Show that the limit, as n goes to infinity, of F(n)/F(n-1) is (1+sqrt(5))/2.
--theorem q2c:
-- Show that a positive integer n is expressible as x^2 - xy + y^2, with x and y integers, if and only if for every prime p congruent to 2 mod 3, the exponent of p in the prime factorization of n is even.
-- [Hint: Use unique factorization in the Eisenstein integers.]
theorem q3a (n p k : β) (x y : β€) (hq: prime p) (hp: p β‘ 2 [MOD 3]): n = x^2 -x*y + y^2 β ((p β£ n β§ p^k β£ n) β k β‘ 0 [MOD 2]) := sorry
-- Find x and y such that x^2 - xy + y^2 = 91.
--theorem q3b:
-- Find all solutions to the equation x^2 - 10 y^2 = 1. Explicitly list all the solutions with x < 200 and x,y > 0.
--theorem q4a:
-- Find all solutions to the equation x^2 - 10 y^2 = -1.
--theorem q4b:
-- Find the value of the continued fraction [1;2,2,2,...].
--theorem q5a:
-- Find the value of the continued fraction [1;3,5,1,3,5,...].
--theorem q5b:
-- Show that, for n an integer, we have sqrt(n^2+1) = [n;2n,2n,2n,...].
--theorem q6a:
-- Show that, for n an integer, we have sqrt(n^2+2) = [n;n,2n,n,2n,...].
--theorem q6b: |
function stapx = stnddv2(XYdata,numpnts,reps,dis)
%This function approximates the standard deviation by using neighboring
%values
%This provides a limit on the number of total replicates to consider on
% neighboring points.
maxval= 15;
x= reshape([XYdata.x],length(XYdata(1).x),[])';
n = size(x,1);
if ~exist('dis','var') || isempty(dis)
dis = pdist2(x,x);
end
%Ensure there are enough points available
if numpnts>n, numpnts=n;end
stapx=zeros(n,1);
parfor i=1:n %parfor
%Finds the closest n points
[~,pntsloc] = sort(dis(i,:));
pntsloc=pntsloc(1:numpnts);
y=[];
leny = length(y); %this has to be done to remove a warning
for j=1:numpnts
%Grab y values
y=[y XYdata(pntsloc(j)).y];
leny = length(y);
%If the sampling has many replicates only use close samples
if leny>maxval
%Only give the limit of points
if j~=1, leny=maxval;y=y(1:maxval);end
break;
end
end
stsamps = zeros(reps,1);
for j=1:reps
%Calculate the standard deviation - std func is not used because
% the mean has already been removed
samps = randi(leny,leny,1);
stsamps(j)=std(y(samps));
end
%Find the mean standard deviation
stapx(i)=mean(stsamps);
end
end |
(*<*)
(*
* Knowledge-based programs.
* (C)opyright 2011, Peter Gammie, peteg42 at gmail.com.
* License: BSD
*)
theory Kripke
imports Main
begin
(*>*)
section {*A modal logic of knowledge*}
text{*
\label{sec:kbps-logic-of-knowledge}
We begin with the standard syntax and semantics of the propositional
logic of knowledge based on \emph{Kripke structures}. More extensive
treatments can be found in \citet{Lenzen:1978}, \citet{Chellas:1980},
\citet{Hintikka:1962} and \citet[Chapter~2]{FHMV:1995}.
The syntax includes one knowledge modality per agent, and one for
\emph{common knowledge} amongst a set of agents. It is parameterised
by the type @{typ "'a"} of agents and @{typ "'p"} of propositions.
*}
datatype ('a, 'p) Kform
= Kprop "'p"
| Knot "('a, 'p) Kform"
| Kand "('a, 'p) Kform" "('a, 'p) Kform"
| Kknows "'a" "('a, 'p) Kform" ("\<^bold>K\<^sub>_ _")
| Kcknows "'a list" "('a, 'p) Kform" ("\<^bold>C\<^bsub>_\<^esub> _")
text{*
A Kripke structure consists of a set of \emph{worlds} of type @{typ
"'w"}, one \emph{accessibility relation} between worlds for each agent
and a \emph{valuation function} that indicates the truth of a
proposition at a world. This is a very general story that we will
quickly specialise.
*}
type_synonym 'w Relation = "('w \<times> 'w) set"
record ('a, 'p, 'w) KripkeStructure =
worlds :: "'w set"
relations :: "'a \<Rightarrow> 'w Relation"
valuation :: "'w \<Rightarrow> 'p \<Rightarrow> bool"
definition kripke :: "('a, 'p, 'w) KripkeStructure \<Rightarrow> bool" where
"kripke M \<equiv> \<forall>a. relations M a \<subseteq> worlds M \<times> worlds M"
definition
mkKripke :: "'w set \<Rightarrow> ('a \<Rightarrow> 'w Relation) \<Rightarrow> ('w \<Rightarrow> 'p \<Rightarrow> bool)
\<Rightarrow> ('a, 'p, 'w) KripkeStructure"
where
"mkKripke ws rels val \<equiv>
\<lparr> worlds = ws, relations = \<lambda>a. rels a \<inter> ws \<times> ws, valuation = val \<rparr>"
(*<*)
lemma kripkeI[intro]:
assumes "\<And>a. relations M a \<subseteq> worlds M \<times> worlds M"
shows "kripke M"
using assms unfolding kripke_def by simp
lemma kripke_rels_worlds[dest]:
assumes "(w, w') \<in> relations M a"
assumes M: "kripke M"
shows "w \<in> worlds M \<and> w' \<in> worlds M"
using assms unfolding kripke_def by auto
lemma kripke_tc_rels_worlds[dest]:
assumes R: "(w, w') \<in> (\<Union>a \<in> as. relations M a)\<^sup>+"
assumes M: "kripke M"
shows "w \<in> worlds M \<and> w' \<in> worlds M"
using assms by (induct rule: trancl_induct) auto
lemma kripke_rels_trc_worlds:
assumes R: "(w, w') \<in> (\<Union>a. relations M a)\<^sup>*"
assumes w: "w \<in> worlds M"
assumes M: "kripke M"
assumes W: "W = worlds M"
shows "w' \<in> W"
using assms by (induct rule: rtrancl_induct) auto
lemma mkKripke_kripke[intro, simp]:
"kripke (mkKripke ws rels val)"
unfolding kripke_def mkKripke_def by clarsimp
lemma mkKripke_simps[simp]:
"worlds (mkKripke ws rels val) = ws"
"relations (mkKripke ws rels val) = (\<lambda>a. rels a \<inter> ws \<times> ws)"
"valuation (mkKripke ws rels val) = val"
unfolding mkKripke_def by simp_all
(*>*)
text {*
The standard semantics for knowledge is given by taking the
accessibility relations to be equivalence relations, yielding the
S$5_n$ structures, so-called due to their axiomatisation.
*}
definition S5n :: "('a, 'p, 'w) KripkeStructure \<Rightarrow> bool" where
"S5n M \<equiv> \<forall>a. equiv (worlds M) (relations M a)"
(*<*)
lemma S5nI[intro]: "\<lbrakk> \<And>a. equiv (worlds M) (relations M a) \<rbrakk> \<Longrightarrow> S5n M"
by (simp add: S5n_def)
lemma S5nD[dest]: "S5n M \<Longrightarrow> equiv (worlds M) (relations M a)"
by (simp add: S5n_def)
lemma S5n_kripke[intro]: "S5n M \<Longrightarrow> kripke M"
by (rule kripkeI, erule equivE[OF S5nD], auto simp add: refl_on_def)
lemma S5n_rels_closed:
"S5n M \<Longrightarrow> relations M a `` (relations M a `` X) \<subseteq> relations M a `` X"
apply (drule S5nD[where a=a])
apply (erule equivE)
apply (auto dest: refl_onD symD transD)
done
(*>*)
text{*
Intuitively an agent considers two worlds to be equivalent if it
cannot distinguish between them.
*}
subsection{* Satisfaction *}
text{*
A formula $\phi$ is satisfied at a world $w$ in Kripke structure $M$
in the following way: *}
fun models :: "('a, 'p, 'w) KripkeStructure \<Rightarrow> 'w \<Rightarrow> ('a, 'p) Kform
\<Rightarrow> bool" ("(_, _ \<Turnstile> _)" [80,0,80] 80) where
"M, w \<Turnstile> (Kprop p) = valuation M w p"
| "M, w \<Turnstile> (Knot \<phi>) = (\<not> M, w \<Turnstile> \<phi>)"
| "M, w \<Turnstile> (Kand \<phi> \<psi>) = (M, w \<Turnstile> \<phi> \<and> M, w \<Turnstile> \<psi>)"
| "M, w \<Turnstile> (\<^bold>K\<^sub>a \<phi>) = (\<forall>w' \<in> relations M a `` {w}. M, w' \<Turnstile> \<phi>)"
| "M, w \<Turnstile> (\<^bold>C\<^bsub>as\<^esub> \<phi>) = (\<forall>w' \<in> (\<Union>a \<in> set as. relations M a)\<^sup>+ `` {w}. M, w' \<Turnstile> \<phi>)"
text{*
The first three clauses are standard.
The clause for @{term "Kknows a \<phi>"} expresses the idea that an agent
knows @{term "\<phi>"} at world @{term "w"} in structure @{term "M"} iff
@{term "\<phi>"} is true at all worlds it considers possible.
The clause for @{term "Kcknows as \<phi>"} captures what it means for the
set of agents @{term "as"} to commonly know @{term "\<phi>"}; roughly,
everyone knows @{term "\<phi>"} and knows that everyone knows it, and so
forth. Note that the transitive closure and the reflexive-transitive
closure generate the same relation due to the reflexivity of the
agents' accessibility relations; we use the former as it has a more
pleasant induction principle.
*}
(*<*)
lemma S5n_rels_eq:
assumes S5n: "S5n M"
and ww': "(w, w') \<in> relations M a"
shows "relations M a `` {w} = relations M a `` {w'}"
using S5nD[OF S5n] ww' by - (rule equiv_class_eq, blast+)
text{*
A key property of the semantics for common knowledge is that it forms
an equivalence class itself.
*}
lemma tc_equiv:
assumes E: "\<And>i. i \<in> is \<Longrightarrow> equiv A (f i)"
and is_nempty: "is \<noteq> {}"
shows "equiv A ((\<Union>i\<in>is. f i)\<^sup>+)"
proof(rule equivI)
from E is_nempty show "refl_on A ((\<Union>i\<in>is. f i)\<^sup>+)"
unfolding equiv_def
apply -
apply (rule refl_onI)
apply (rule trancl_Int_subset)
apply (auto dest: refl_onD refl_onD1 refl_onD2)
done
from E show "sym ((\<Union>i\<in>is. f i)\<^sup>+)"
apply -
apply (rule sym_trancl)
unfolding equiv_def sym_def by blast
show "trans ((\<Union>i\<in>is. f i)\<^sup>+)" by (rule trans_trancl)
qed
lemma S5n_tc_rels_eq:
assumes S5n: "S5n M"
and ww': "(w, w') \<in> (\<Union>a \<in> as. relations M a)\<^sup>+"
shows "(\<Union>a \<in> as. relations M a)\<^sup>+ `` {w} = (\<Union>a \<in> as. relations M a)\<^sup>+ `` {w'}"
apply (cases "as = {}")
apply fastforce
apply (rule equiv_class_eq[OF _ ww'])
apply (erule tc_equiv[OF S5nD[OF S5n]])
done
text{* We can show that the standard S5 properties hold of this semantics: *}
lemma S5n_knowledge_generalisation:
"\<lbrakk> S5n M; \<forall>w \<in> worlds M. M, w \<Turnstile> \<phi> \<rbrakk> \<Longrightarrow> M, w \<Turnstile> Kknows a \<phi>"
unfolding S5n_def equiv_def refl_on_def by auto
lemma S5n_knowledge:
"\<lbrakk> S5n M; w \<in> worlds M; M, w \<Turnstile> Kknows a \<phi> \<rbrakk> \<Longrightarrow> M, w \<Turnstile> \<phi>"
unfolding S5n_def equiv_def refl_on_def by auto
lemma S5n_positive_introspection:
"\<lbrakk> S5n M; w \<in> worlds M; M, w \<Turnstile> Kknows a \<phi> \<rbrakk> \<Longrightarrow> M, w \<Turnstile> Kknows a (Kknows a \<phi>)"
unfolding S5n_def equiv_def by simp (blast dest: transD)
lemma S5n_negative_introspection:
"\<lbrakk> S5n M; w \<in> worlds M; M, w \<Turnstile> Knot (Kknows a \<phi>) \<rbrakk>
\<Longrightarrow> M, w \<Turnstile> Kknows a (Knot (Kknows a \<phi>))"
unfolding S5n_def equiv_def by simp (blast dest: symD transD)
(*>*)
text{*
The relation between knowledge and common knowledge can be understood
as follows, following \citet[\S2.4]{FHMV:1995}. Firstly, that $\phi$
is common knowledge to a set of agents $as$ can be seen as asserting
that everyone in $as$ knows $\phi$ and moreover knows that it is
common knowledge amongst $as$.
*}
lemma S5n_common_knowledge_fixed_point:
assumes S5n: "S5n M"
assumes w: "w \<in> worlds M"
assumes a: "a \<in> set as"
shows "M, w \<Turnstile> Kcknows as \<phi>
\<longleftrightarrow> M, w \<Turnstile> Kand (Kknows a \<phi>) (Kknows a (Kcknows as \<phi>))"
(*<*)
proof
assume CK: "M, w \<Turnstile> Kcknows as \<phi>"
from S5n a w CK
have "M, w \<Turnstile> Kknows a \<phi>"
and "M, w \<Turnstile> Kknows a (Kcknows as \<phi>)"
by (auto intro: trancl_into_trancl2)
then show "M, w \<Turnstile> Kand (Kknows a \<phi>) (Kknows a (Kcknows as \<phi>))"
by simp
next
assume "M, w \<Turnstile> Kand (Kknows a \<phi>) (Kknows a (Kcknows as \<phi>))"
hence "M, w \<Turnstile> (Kknows a (Kcknows as \<phi>))" by simp
with S5n w show "M, w \<Turnstile> (Kcknows as \<phi>)" by (rule S5n_knowledge)
qed
(*>*)
text{*
Secondly we can provide an induction schema for the introduction of
common knowledge: from everyone in $as$ knows that $\phi$ implies
$\phi \land \psi$, and that $\phi$ is satisfied at world $w$, infer
that $\psi$ is common knowledge amongst $as$ at $w$.
*}
lemma S5n_common_knowledge_induct:
assumes S5n: "S5n M"
assumes w: "w \<in> worlds M"
assumes E: "\<forall>a \<in> set as. \<forall>w \<in> worlds M.
M, w \<Turnstile> \<phi> \<longrightarrow> M, w \<Turnstile> \<^bold>K\<^sub>a (Kand \<phi> \<psi>)"
assumes p: "M, w \<Turnstile> \<phi>"
shows "M, w \<Turnstile> \<^bold>C\<^bsub>as\<^esub> \<psi>"
(*<*)
proof -
{ fix w' assume ww': "(w, w') \<in> (\<Union>x\<in>set as. relations M x)\<^sup>+"
from ww' S5n E p w have "M, w' \<Turnstile> Kand \<phi> \<psi>"
by ( induct rule: trancl_induct
, simp_all, blast+) }
thus ?thesis by simp
qed
(* We actually use a simpler variant. *)
lemma S5n_common_knowledge_fixed_point_simpler:
assumes S5n: "S5n M"
and w: "w \<in> worlds M"
and a: "a \<in> set as"
shows "M, w \<Turnstile> Kcknows as \<phi> \<longleftrightarrow> M, w \<Turnstile> Kknows a (Kcknows as \<phi>)"
proof
assume CK: "M, w \<Turnstile> Kcknows as \<phi>"
from S5n a w CK show "M, w \<Turnstile> Kknows a (Kcknows as \<phi>)"
by (auto intro: trancl_into_trancl2)
next
assume "M, w \<Turnstile> Kknows a (Kcknows as \<phi>)"
with S5n w show "M, w \<Turnstile> (Kcknows as \<phi>)" by (rule S5n_knowledge)
qed
(*>*)
(* **************************************** *)
subsection {*Generated models*}
text{*
\label{sec:generated_models}
The rest of this section introduces the technical machinery we use to
relate Kripke structures.
Intuitively the truth of a formula at a world depends only on the
worlds that are reachable from it in zero or more steps, using any of
the accessibility relations at each step. Traditionally this result is
called the \emph{generated model property}
\citep[\S3.4]{Chellas:1980}.
Given the model generated by @{term "w"} in @{term "M"}:
*}
definition
gen_model :: "('a, 'p, 'w) KripkeStructure \<Rightarrow> 'w \<Rightarrow> ('a, 'p, 'w) KripkeStructure"
where
"gen_model M w \<equiv>
let ws' = worlds M \<inter> (\<Union>a. relations M a)\<^sup>* `` {w}
in \<lparr> worlds = ws',
relations = \<lambda>a. relations M a \<inter> (ws' \<times> ws'),
valuation = valuation M \<rparr>"
(*<*)
lemma gen_model_worldsD[dest]:
"w' \<in> worlds (gen_model M w) \<Longrightarrow> w' \<in> worlds M"
unfolding gen_model_def by simp
lemma gen_model_world_refl:
"w \<in> worlds M \<Longrightarrow> w \<in> worlds (gen_model M w)"
unfolding gen_model_def by simp
lemma gen_model_rels_worlds[dest]:
assumes "(w', w'') \<in> relations (gen_model M w) a"
shows "w' \<in> worlds (gen_model M w) \<and> w'' \<in> worlds (gen_model M w)"
using assms unfolding gen_model_def by simp
lemma gen_model_rels_tc_worlds[dest]:
assumes "(w', w'') \<in> (\<Union>a \<in> as. relations (gen_model M w) a)\<^sup>+"
shows "w'' \<in> worlds (gen_model M w)"
using assms by (induct rule: trancl_induct) auto
lemma gen_model_rels[dest]:
assumes "(w', w'') \<in> relations (gen_model M w) a"
shows "(w', w'') \<in> relations M a"
using assms unfolding gen_model_def by simp
lemma gen_model_worlds:
"worlds (gen_model M w) = worlds M \<inter> (\<Union>a. relations M a)\<^sup>* `` {w}"
unfolding gen_model_def by simp
lemma gen_model_tc_rels[dest]:
assumes M: "kripke M"
and R: "(w', w'') \<in> (\<Union>a \<in> as. relations (gen_model M w) a)\<^sup>+"
shows "(w', w'') \<in> (\<Union>a \<in> as. relations M a)\<^sup>+"
using R
proof(induct rule: trancl_induct)
case (base y) with M show ?case by auto
next
case (step y z)
with M have "y \<in> worlds (gen_model M w)"
and "z \<in> worlds (gen_model M w)" by auto
with M step show ?case by (auto intro: trancl_into_trancl)
qed
lemma gen_model_rels_rev[dest]:
assumes M: "kripke M"
and "w' \<in> worlds (gen_model M w)"
and "(w', w'') \<in> relations M a"
shows "(w', w'') \<in> relations (gen_model M w) a"
using assms
unfolding gen_model_def by (auto intro: rtrancl_into_rtrancl)
lemma gen_model_tc_rels_rev[dest]:
assumes M: "kripke M"
and R: "(w', w'') \<in> (\<Union>a \<in> as. relations M a)\<^sup>+"
and W: "w' \<in> worlds (gen_model M w)"
shows "(w', w'') \<in> (\<Union>a \<in> as. relations (gen_model M w) a)\<^sup>+"
using R W
proof(induct rule: trancl_induct)
case (base y) with M show ?case by auto
next
case (step y z)
with M have "y \<in> worlds (gen_model M w)"
and "z \<in> worlds (gen_model M w)" by auto
with M step show ?case by (auto intro: trancl_into_trancl)
qed
lemma gen_model_kripke:
shows "kripke (gen_model M w)"
unfolding gen_model_def by auto
(*>*)
text{*
where we take the image of @{term "w"} under the reflexive transitive
closure of the agents' relations, we can show that the satisfaction of
a formula @{term "\<phi>"} at a world @{term "w'"} is preserved, provided
@{term "w'"} is relevant to the world @{term "w"} that the sub-model
is based upon:
*}
lemma gen_model_semantic_equivalence:
assumes M: "kripke M"
assumes w': "w' \<in> worlds (gen_model M w)"
shows "M, w' \<Turnstile> \<phi> \<longleftrightarrow> (gen_model M w), w' \<Turnstile> \<phi>"
(*<*)
proof -
{ fix w w' assume "w' \<in> worlds (gen_model M w)"
hence "M, w' \<Turnstile> \<phi> \<longleftrightarrow> (gen_model M w), w' \<Turnstile> \<phi>"
proof(induct \<phi> arbitrary: w')
case (Kknows a f w') show ?case
proof
assume lhs: "M, w' \<Turnstile> Kknows a f"
with Kknows show "gen_model M w, w' \<Turnstile> Kknows a f" by auto
next
assume rhs: "gen_model M w, w' \<Turnstile> Kknows a f"
with M Kknows show "M, w' \<Turnstile> Kknows a f"
by (simp, blast)
qed
next
case (Kcknows as f w') show ?case
proof
assume lhs: "M, w' \<Turnstile> Kcknows as f"
with M Kcknows show "gen_model M w, w' \<Turnstile> Kcknows as f"
by (simp, blast)
next
assume rhs: "gen_model M w, w' \<Turnstile> Kcknows as f"
with M Kcknows show "M, w' \<Turnstile> Kcknows as f"
by (simp, blast)
qed
qed (simp_all add: gen_model_def) }
with w' show ?thesis by simp
qed
(*>*)
text{*
This is shown by a straightforward structural induction over the
formula @{term "\<phi>"}.
*}
(*<*)
lemma gen_model_S5n:
assumes S5n: "S5n M"
shows "S5n (gen_model M w)"
proof(intro S5nI equivI)
show "\<And>n. refl_on (worlds (gen_model M w)) (relations (gen_model M w) n)"
apply (rule equivE[OF S5nD[OF S5n]])
by - (rule refl_onI, auto simp add: refl_on_def gen_model_def)
show "\<And>n. sym (relations (gen_model M w) n)"
apply (rule equivE[OF S5nD[OF S5n]])
by (unfold gen_model_def sym_def, auto)
show "\<And>n. trans (relations (gen_model M w) n)"
apply (rule equivE[OF S5nD[OF S5n]])
by - (rule transI, simp add: gen_model_def, unfold trans_def, blast)
qed
text{*
If two models generate the same sub-model for a world, they satisfy
the same formulas at that world.
*}
lemma gen_model_eq:
assumes M: "kripke M"
and M': "kripke M'"
and "gen_model M w = gen_model M' w"
and "w' \<in> worlds (gen_model M' w)"
shows "M, w' \<Turnstile> \<phi> \<longleftrightarrow> M', w' \<Turnstile> \<phi>"
using assms gen_model_semantic_equivalence[OF M, where w=w]
gen_model_semantic_equivalence[OF M', where w=w]
by auto
text {*
Our final lemma in this section is technical: it allows us to move
between two Kripke structures that have the same relevant worlds.
*}
lemma gen_model_subset_aux:
assumes R: "\<And>a. relations M a \<inter> T \<times> T = relations M' a \<inter> T \<times> T"
and T: "(\<Union>a. relations M a)\<^sup>* `` {t} \<subseteq> T"
shows "(\<Union>x. relations M x)\<^sup>* `` {t} \<subseteq> (\<Union>x. relations M' x)\<^sup>* `` {t}"
proof -
{ fix x assume "(t, x) \<in> (\<Union>x. relations M x)\<^sup>*"
hence "(t, x) \<in> (\<Union>x. relations M' x)\<^sup>*"
proof(induct rule: rtrancl_induct)
case (step y z)
with R T have "(y, z) \<in> (\<Union>a. relations M' a)"
by (blast dest: rtrancl_trans)
with step show ?case by (blast intro: rtrancl_trans)
qed simp }
thus ?thesis by blast
qed
lemma gen_model_subset:
assumes M: "kripke M"
and M': "kripke M'"
and R: "\<And>a. relations M a \<inter> T \<times> T = relations M' a \<inter> T \<times> T"
and tMT: "(\<Union>a. relations M a)\<^sup>* `` {t} \<subseteq> T"
and tM'T: "(\<Union>a. relations M' a)\<^sup>* `` {t} \<subseteq> T"
and tM: "t \<in> worlds M"
and tM': "t \<in> worlds M'"
and V: "valuation M = valuation M'"
shows "gen_model M t = gen_model M' t"
proof -
from tMT tM'T gen_model_subset_aux[OF R] gen_model_subset_aux[OF R[symmetric]]
have F: "(\<Union>a. relations M a)\<^sup>* `` {t} = (\<Union>a. relations M' a)\<^sup>* `` {t}"
by - (rule, simp_all)
from M tMT tM have G: "(\<Union>a. relations M a)\<^sup>* `` {t} \<subseteq> worlds M"
by (auto dest: kripke_rels_trc_worlds)
from M' tM'T tM' have H: "(\<Union>a. relations M' a)\<^sup>* `` {t} \<subseteq> worlds M'"
by (auto dest: kripke_rels_trc_worlds)
from F G H have WORLDS: "worlds (gen_model M t) = worlds (gen_model M' t)"
unfolding gen_model_def by (auto iff: Int_absorb1)
{ fix a x y
assume XY: "(x, y) \<in> relations M a \<inter> (\<Union>x. relations M x)\<^sup>* `` {t} \<times> (\<Union>x. relations M x)\<^sup>* `` {t}"
from XY tMT
have "(x, y) \<in> relations M a \<inter> T \<times> T" by blast
with R
have "(x, y) \<in> relations M' a \<inter> T \<times> T" by blast
with F XY tM'T
have "(x, y) \<in> relations M' a \<inter> (\<Union>x. relations M' x)\<^sup>* `` {t} \<times> (\<Union>x. relations M' x)\<^sup>* `` {t}"
by blast }
moreover
{ fix a x y
assume XY: "(x, y) \<in> relations M' a \<inter> (\<Union>x. relations M' x)\<^sup>* `` {t} \<times> (\<Union>x. relations M' x)\<^sup>* `` {t}"
from XY tM'T
have "(x, y) \<in> relations M' a \<inter> T \<times> T" by blast
with R
have "(x, y) \<in> relations M a \<inter> T \<times> T" by blast
with F XY tMT
have "(x, y) \<in> relations M a \<inter> (\<Union>x. relations M x)\<^sup>* `` {t} \<times> (\<Union>x. relations M x)\<^sup>* `` {t}"
by blast }
ultimately
have RELATIONS: "\<And>a. relations (gen_model M t) a = relations (gen_model M' t) a"
unfolding gen_model_def
apply -
apply (simp (no_asm) add: Int_absorb1 G H)
apply rule
apply rule
apply auto[1]
apply rule
apply (case_tac x)
apply blast
done
from WORLDS RELATIONS V show ?thesis
unfolding gen_model_def by simp
qed
(*>*)
subsection {*Simulations*}
text{*
\label{sec:kripke-theory-simulations}
A \emph{simulation}, or \emph{p-morphism}, is a mapping from the
worlds of one Kripke structure to another that preserves the truth of
all formulas at related worlds \citep[\S3.4, Ex. 3.60]{Chellas:1980}.
Such a function @{term "f"} must satisfy four properties. Firstly, the
image of the set of worlds of @{term "M"} under @{term "f"} should
equal the set of worlds of @{term "M'"}.
*}
definition
sim_range :: "('a, 'p, 'w1) KripkeStructure
\<Rightarrow> ('a, 'p, 'w2) KripkeStructure \<Rightarrow> ('w1 \<Rightarrow> 'w2) \<Rightarrow> bool"
where
"sim_range M M' f \<equiv> worlds M' = f ` worlds M
\<and> (\<forall>a. relations M' a \<subseteq> worlds M' \<times> worlds M')"
text{* The value of a proposition should be the same at corresponding
worlds: *}
definition
sim_val :: "('a, 'p, 'w1) KripkeStructure
\<Rightarrow> ('a, 'p, 'w2) KripkeStructure \<Rightarrow> ('w1 \<Rightarrow> 'w2) \<Rightarrow> bool"
where
"sim_val M M' f \<equiv> \<forall>u \<in> worlds M. valuation M u = valuation M' (f u)"
text{*
If two worlds are related in @{term "M"}, then the simulation
maps them to related worlds in @{term "M'"}; intuitively the
simulation relates enough worlds. We term this the \emph{forward}
property.
*}
definition
sim_f :: "('a, 'p, 'w1) KripkeStructure
\<Rightarrow> ('a, 'p, 'w2) KripkeStructure \<Rightarrow> ('w1 \<Rightarrow> 'w2) \<Rightarrow> bool"
where
"sim_f M M' f \<equiv>
\<forall>a u v. (u, v) \<in> relations M a \<longrightarrow> (f u, f v) \<in> relations M' a"
text{*
Conversely, if two worlds @{term "f u"} and @{term "v'"} are related
in @{term "M'"}, then there is a pair of related worlds @{term "u"}
and @{term "v"} in @{term "M"} where @{term "f v = v'"}. Intuitively
the simulation makes enough distinctions. We term this the
\emph{reverse} property.
*}
definition
sim_r :: "('a, 'p, 'w1) KripkeStructure
\<Rightarrow> ('a, 'p, 'w2) KripkeStructure \<Rightarrow> ('w1 \<Rightarrow> 'w2) \<Rightarrow> bool"
where
"sim_r M M' f \<equiv> \<forall>a. \<forall>u \<in> worlds M. \<forall>v'.
(f u, v') \<in> relations M' a
\<longrightarrow> (\<exists>v. (u, v) \<in> relations M a \<and> f v = v')"
definition "sim M M' f \<equiv> sim_range M M' f \<and> sim_val M M' f
\<and> sim_f M M' f \<and> sim_r M M' f"
(*<*)
lemma sim_rangeI[intro]:
"\<lbrakk> worlds M' = f ` worlds M; (\<And>a. relations M' a \<subseteq> worlds M' \<times> worlds M') \<rbrakk>
\<Longrightarrow> sim_range M M' f"
unfolding sim_range_def by simp
lemma sim_valI[intro]:
"(\<And>u. u \<in> worlds M \<Longrightarrow> valuation M u = valuation M' (f u))
\<Longrightarrow> sim_val M M' f"
unfolding sim_val_def by simp
lemma sim_fI[intro]:
"(\<And>a u v. (u, v) \<in> relations M a \<Longrightarrow> (f u, f v) \<in> relations M' a)
\<Longrightarrow> sim_f M M' f"
unfolding sim_f_def by simp
lemma sim_fD:
"\<lbrakk> (u, v) \<in> relations M a; sim M M' f \<rbrakk>
\<Longrightarrow> (f u, f v) \<in> relations M' a"
unfolding sim_def sim_f_def by blast
lemma sim_rI[intro]:
"(\<And>a u v'.
\<lbrakk>u \<in> worlds M; (f u, v') \<in> relations M' a\<rbrakk>
\<Longrightarrow> (\<exists>v. (u, v) \<in> relations M a \<and> f v = v'))
\<Longrightarrow> sim_r M M' f"
unfolding sim_r_def by simp
lemma sim_rD:
"\<lbrakk> (f u, v') \<in> relations M' a; sim M M' f; u \<in> worlds M \<rbrakk>
\<Longrightarrow> (\<exists>v. (u, v) \<in> relations M a \<and> f v = v')"
unfolding sim_def sim_r_def by blast
lemma simI[intro]:
"\<lbrakk> sim_range M M' f; sim_val M M' f; sim_f M M' f; sim_r M M' f \<rbrakk>
\<Longrightarrow> sim M M' f"
unfolding sim_def by simp
text{* The identity is a simulation: *}
lemma sim_id: "kripke M \<Longrightarrow> sim M M id"
(*<*)
unfolding sim_def sim_r_def sim_f_def sim_range_def sim_val_def
by auto
(*>*)
(*>*)
text{*
Due to the common knowledge modality, we need to show the simulation
properties lift through the transitive closure. In particular we can
show that forward simulation is preserved:
*}
Reverse simulation also:
*}
lemma sim_r_tc:
assumes M: "kripke M"
assumes s: "sim M M' f"
assumes u: "u \<in> worlds M"
assumes fuv': "(f u, v') \<in> (\<Union>a\<in>as. relations M' a)\<^sup>+"
obtains v where "f v = v'" and "(u, v) \<in> (\<Union>a\<in>as. relations M a)\<^sup>+"
(*<*)
proof -
assume E: "\<And>v. \<lbrakk>f v = v'; (u, v) \<in> (\<Union>a\<in>as. relations M a)\<^sup>+\<rbrakk> \<Longrightarrow> thesis"
from fuv' have as_nempty: "as \<noteq> {}" by auto
from fuv' have "\<exists>v. f v = v' \<and> (u, v) \<in> (\<Union>a\<in>as. relations M a)\<^sup>+"
proof(induct rule: trancl_induct)
case (base v') with u s as_nempty show ?case
by (blast dest: sim_rD)
next
case (step v' w')
hence fuv': "(f u, v') \<in> (\<Union>a\<in>as. relations M' a)\<^sup>+"
and v'w': "(v', w') \<in> (\<Union>a\<in>as. relations M' a)" by fast+
from step
obtain v where vv': "f v = v'"
and uv: "(u, v) \<in> (\<Union>a\<in>as. relations M a)\<^sup>+"
by blast
from s v'w' vv' kripke_tc_rels_worlds[OF uv M]
obtain w where ww': "f w = w'"
and vw: "(v, w) \<in> (\<Union>a\<in>as. relations M a)"
by (blast dest: sim_rD)
from uv vw ww' show ?case by (blast intro: trancl_trans)
qed
with E show thesis by blast
qed
lemma sim_f_trc:
assumes uv': "(u, v) \<in> (\<Union>a. relations M a)\<^sup>*"
and s: "sim M M' f"
shows "(f u, f v) \<in> (\<Union>a. relations M' a)\<^sup>*"
using assms
by - ( induct rule: rtrancl_induct[OF uv']
, auto dest: sim_fD intro: rtrancl_into_rtrancl )
lemma sim_r_trc:
assumes s: "sim M M' f"
and fuv': "(f u, v') \<in> (\<Union>a. relations M' a)\<^sup>*"
and M: "kripke M"
and u: "u \<in> worlds M"
obtains v
where "f v = v'"
and "(u, v) \<in> (\<Union>a. relations M a)\<^sup>*"
proof -
assume E: "\<And>v. \<lbrakk>f v = v'; (u, v) \<in> (\<Union>a. relations M a)\<^sup>*\<rbrakk> \<Longrightarrow> thesis"
from fuv' have "\<exists>v. f v = v' \<and> (u, v) \<in> (\<Union>a. relations M a)\<^sup>*"
proof(induct rule: rtrancl_induct)
case base show ?case by blast
next
case (step v' w')
hence fuv': "(f u, v') \<in> (\<Union>a. relations M' a)\<^sup>*"
and v'w': "(v', w') \<in> (\<Union>a. relations M' a)" by fast+
from step
obtain v where vv': "f v = v'"
and uv: "(u, v) \<in> (\<Union>a. relations M a)\<^sup>*"
by blast
from s v'w' vv' kripke_rels_trc_worlds[OF uv u M]
obtain w where ww': "f w = w'"
and vw: "(v, w) \<in> (\<Union>a. relations M a)"
by (blast dest: sim_rD)
from uv vw ww' show ?case by (blast intro: rtrancl_trans)
qed
with E show thesis by blast
qed
lemma sim_kripke: "\<lbrakk> sim M M' f; kripke M \<rbrakk> \<Longrightarrow> kripke M'"
unfolding sim_def sim_range_def by (rule kripkeI, blast)
lemma sim_S5n:
assumes S5n: "S5n M"
and sim: "sim M M' f"
shows "S5n M'"
proof(intro S5nI equivI)
fix a from S5n sim show "refl_on (worlds M') (relations M' a)"
using sim_kripke S5n_kripke
unfolding S5n_def equiv_def sim_def sim_f_def sim_range_def
by - (rule refl_onI, (simp, blast dest: refl_onD)+)
next
fix a
{ fix u v assume uv: "(u, v) \<in> relations M' a"
from sim uv
obtain u' where uw: "u' \<in> worlds M"
and fu: "u = f u'"
unfolding sim_def sim_range_def by bestsimp
from sim uv fu uw
obtain v' where u'v': "(u', v') \<in> relations M a"
and fv: "v = f v'"
unfolding sim_def sim_r_def sim_range_def by best
from S5n u'v' have "(v', u') \<in> relations M a"
unfolding S5n_def equiv_def by (blast dest: symD)
with sim fu fv have "(v, u) \<in> relations M' a"
unfolding sim_def sim_f_def by simp }
thus "sym (relations M' a)" by (blast intro: symI)
next
fix a
{ fix x y z
assume xy: "(x, y) \<in> relations M' a"
and yz: "(y, z) \<in> relations M' a"
from sim xy
obtain x' where xw: "x' \<in> worlds M"
and fx: "x = f x'"
unfolding sim_def sim_range_def by bestsimp
from sim xy fx xw
obtain y' where x'y': "(x', y') \<in> relations M a"
and fy: "y = f y'"
unfolding sim_def sim_r_def sim_range_def by best
from S5n sim yz fy x'y'
obtain z' where y'z': "(y', z') \<in> relations M a"
and fz: "z = f z'"
unfolding sim_def sim_r_def sim_range_def by best
from S5n x'y' y'z' have "(x', z') \<in> relations M a"
unfolding S5n_def equiv_def by (blast dest: transD)
with sim fx fy fz have "(x, z) \<in> relations M' a"
unfolding sim_def sim_f_def by simp }
thus "trans (relations M' a)" by (blast intro: transI)
qed
(*>*)
text{*
Finally we establish the key property of simulations, that they
preserve the satisfaction of all formulas in the following way:
*}
lemma sim_semantic_equivalence:
assumes M: "kripke M"
assumes s: "sim M M' f"
assumes u: "u \<in> worlds M"
shows "M, u \<Turnstile> \<phi> \<longleftrightarrow> M', f u \<Turnstile> \<phi>"
(*<*)
using u
proof(induct \<phi> arbitrary: u)
case (Kknows a \<psi> u)
hence u: "u \<in> worlds M" by fast
show ?case
proof
assume lhs: "M, u \<Turnstile> Kknows a \<psi>"
{ fix v' assume "(f u, v') \<in> relations M' a"
with s u obtain v where uv: "(u, v) \<in> relations M a"
and vv': "f v = v'"
by (blast dest: sim_rD)
from lhs uv have "M, v \<Turnstile> \<psi>" by simp
with kripke_rels_worlds[OF uv M] vv' Kknows
have "M', v' \<Turnstile> \<psi>" by auto }
thus "M', f u \<Turnstile> Kknows a \<psi>" by simp
next
assume rhs: "M', f u \<Turnstile> Kknows a \<psi>"
{ fix v assume uv: "(u, v) \<in> relations M a"
with s have "(f u, f v) \<in> relations M' a"
by (blast dest: sim_fD)
with rhs have "M', f v \<Turnstile> \<psi>" by simp
with kripke_rels_worlds[OF uv M] Kknows s
have "M, v \<Turnstile> \<psi>" by auto }
thus "M, u \<Turnstile> Kknows a \<psi>" by simp
qed
next
case (Kcknows as \<psi>)
hence u: "u \<in> worlds M" by fast
show ?case
proof
assume lhs: "M, u \<Turnstile> Kcknows as \<psi>"
{ fix v' assume "(f u, v') \<in> (\<Union>x\<in>set as. relations M' x)\<^sup>+"
with M s u
obtain v where uv: "(u, v) \<in> (\<Union>x\<in>set as. relations M x)\<^sup>+"
and vv': "f v = v'"
by (blast intro: sim_r_tc)
from uv lhs have "M, v \<Turnstile> \<psi>" by simp
with kripke_tc_rels_worlds[OF uv M] vv' Kcknows
have "M', v' \<Turnstile> \<psi>" by auto }
thus "M', f u \<Turnstile> Kcknows as \<psi>" by simp
next
assume rhs: "M', f u \<Turnstile> Kcknows as \<psi>"
{ fix v assume uv: "(u, v) \<in> (\<Union>x\<in>set as. relations M x)\<^sup>+"
with s have "(f u, f v) \<in> (\<Union>x\<in>set as. relations M' x)\<^sup>+"
by (blast dest: sim_f_tc)
with rhs have "M', f v \<Turnstile> \<psi>" by simp
with kripke_tc_rels_worlds[OF uv M] Kcknows s
have "M, v \<Turnstile> \<psi>" by auto }
thus "M, u \<Turnstile> Kcknows as \<psi>" by simp
qed
qed (insert s,
auto simp add: sim_range_def sim_def sim_val_def)
(*>*)
text{*
The proof is by structural induction over the formula @{term "\<phi>"}. The
knowledge cases appeal to our two simulation preservation lemmas.
\citet{DBLP:journals/toplas/Sangiorgi09} surveys the history of
p-morphisms and the related concept of \emph{bisimulation}.
This is all we need to know about Kripke structures.
*}
(*<*)
end
(*>*)
|
(* Title: HOL/Lattices_Big.thy
Author: Tobias Nipkow, Lawrence C Paulson and Markus Wenzel
with contributions by Jeremy Avigad
*)
section \<open>Big infimum (minimum) and supremum (maximum) over finite (non-empty) sets\<close>
theory Lattices_Big
imports Groups_Big Option
begin
subsection \<open>Generic lattice operations over a set\<close>
subsubsection \<open>Without neutral element\<close>
locale semilattice_set = semilattice
begin
interpretation comp_fun_idem f
by standard (simp_all add: fun_eq_iff left_commute)
definition F :: "'a set \<Rightarrow> 'a"
where
eq_fold': "F A = the (Finite_Set.fold (\<lambda>x y. Some (case y of None \<Rightarrow> x | Some z \<Rightarrow> f x z)) None A)"
lemma eq_fold:
assumes "finite A"
shows "F (insert x A) = Finite_Set.fold f x A"
proof (rule sym)
let ?f = "\<lambda>x y. Some (case y of None \<Rightarrow> x | Some z \<Rightarrow> f x z)"
interpret comp_fun_idem "?f"
by standard (simp_all add: fun_eq_iff commute left_commute split: option.split)
from assms show "Finite_Set.fold f x A = F (insert x A)"
proof induct
case empty then show ?case by (simp add: eq_fold')
next
case (insert y B) then show ?case by (simp add: insert_commute [of x] eq_fold')
qed
qed
lemma singleton [simp]:
"F {x} = x"
by (simp add: eq_fold)
lemma insert_not_elem:
assumes "finite A" and "x \<notin> A" and "A \<noteq> {}"
shows "F (insert x A) = x \<^bold>* F A"
proof -
from \<open>A \<noteq> {}\<close> obtain b where "b \<in> A" by blast
then obtain B where *: "A = insert b B" "b \<notin> B" by (blast dest: mk_disjoint_insert)
with \<open>finite A\<close> and \<open>x \<notin> A\<close>
have "finite (insert x B)" and "b \<notin> insert x B" by auto
then have "F (insert b (insert x B)) = x \<^bold>* F (insert b B)"
by (simp add: eq_fold)
then show ?thesis by (simp add: * insert_commute)
qed
lemma in_idem:
assumes "finite A" and "x \<in> A"
shows "x \<^bold>* F A = F A"
proof -
from assms have "A \<noteq> {}" by auto
with \<open>finite A\<close> show ?thesis using \<open>x \<in> A\<close>
by (induct A rule: finite_ne_induct) (auto simp add: ac_simps insert_not_elem)
qed
lemma insert [simp]:
assumes "finite A" and "A \<noteq> {}"
shows "F (insert x A) = x \<^bold>* F A"
using assms by (cases "x \<in> A") (simp_all add: insert_absorb in_idem insert_not_elem)
lemma union:
assumes "finite A" "A \<noteq> {}" and "finite B" "B \<noteq> {}"
shows "F (A \<union> B) = F A \<^bold>* F B"
using assms by (induct A rule: finite_ne_induct) (simp_all add: ac_simps)
lemma remove:
assumes "finite A" and "x \<in> A"
shows "F A = (if A - {x} = {} then x else x \<^bold>* F (A - {x}))"
proof -
from assms obtain B where "A = insert x B" and "x \<notin> B" by (blast dest: mk_disjoint_insert)
with assms show ?thesis by simp
qed
lemma insert_remove:
assumes "finite A"
shows "F (insert x A) = (if A - {x} = {} then x else x \<^bold>* F (A - {x}))"
using assms by (cases "x \<in> A") (simp_all add: insert_absorb remove)
lemma closed:
assumes "finite A" "A \<noteq> {}" and elem: "\<And>x y. x \<^bold>* y \<in> {x, y}"
shows "F A \<in> A"
using \<open>finite A\<close> \<open>A \<noteq> {}\<close> proof (induct rule: finite_ne_induct)
case singleton then show ?case by simp
next
case insert with elem show ?case by force
qed
lemma hom_commute:
assumes hom: "\<And>x y. h (x \<^bold>* y) = h x \<^bold>* h y"
and N: "finite N" "N \<noteq> {}"
shows "h (F N) = F (h ` N)"
using N proof (induct rule: finite_ne_induct)
case singleton thus ?case by simp
next
case (insert n N)
then have "h (F (insert n N)) = h (n \<^bold>* F N)" by simp
also have "\<dots> = h n \<^bold>* h (F N)" by (rule hom)
also have "h (F N) = F (h ` N)" by (rule insert)
also have "h n \<^bold>* \<dots> = F (insert (h n) (h ` N))"
using insert by simp
also have "insert (h n) (h ` N) = h ` insert n N" by simp
finally show ?case .
qed
lemma infinite: "\<not> finite A \<Longrightarrow> F A = the None"
unfolding eq_fold' by (cases "finite (UNIV::'a set)") (auto intro: finite_subset fold_infinite)
end
locale semilattice_order_set = binary?: semilattice_order + semilattice_set
begin
lemma bounded_iff:
assumes "finite A" and "A \<noteq> {}"
shows "x \<^bold>\<le> F A \<longleftrightarrow> (\<forall>a\<in>A. x \<^bold>\<le> a)"
using assms by (induct rule: finite_ne_induct) simp_all
lemma boundedI:
assumes "finite A"
assumes "A \<noteq> {}"
assumes "\<And>a. a \<in> A \<Longrightarrow> x \<^bold>\<le> a"
shows "x \<^bold>\<le> F A"
using assms by (simp add: bounded_iff)
lemma boundedE:
assumes "finite A" and "A \<noteq> {}" and "x \<^bold>\<le> F A"
obtains "\<And>a. a \<in> A \<Longrightarrow> x \<^bold>\<le> a"
using assms by (simp add: bounded_iff)
lemma coboundedI:
assumes "finite A"
and "a \<in> A"
shows "F A \<^bold>\<le> a"
proof -
from assms have "A \<noteq> {}" by auto
from \<open>finite A\<close> \<open>A \<noteq> {}\<close> \<open>a \<in> A\<close> show ?thesis
proof (induct rule: finite_ne_induct)
case singleton thus ?case by (simp add: refl)
next
case (insert x B)
from insert have "a = x \<or> a \<in> B" by simp
then show ?case using insert by (auto intro: coboundedI2)
qed
qed
lemma subset_imp:
assumes "A \<subseteq> B" and "A \<noteq> {}" and "finite B"
shows "F B \<^bold>\<le> F A"
proof (cases "A = B")
case True then show ?thesis by (simp add: refl)
next
case False
have B: "B = A \<union> (B - A)" using \<open>A \<subseteq> B\<close> by blast
then have "F B = F (A \<union> (B - A))" by simp
also have "\<dots> = F A \<^bold>* F (B - A)" using False assms by (subst union) (auto intro: finite_subset)
also have "\<dots> \<^bold>\<le> F A" by simp
finally show ?thesis .
qed
end
subsubsection \<open>With neutral element\<close>
locale semilattice_neutr_set = semilattice_neutr
begin
interpretation comp_fun_idem f
by standard (simp_all add: fun_eq_iff left_commute)
definition F :: "'a set \<Rightarrow> 'a"
where
eq_fold: "F A = Finite_Set.fold f \<^bold>1 A"
lemma infinite [simp]:
"\<not> finite A \<Longrightarrow> F A = \<^bold>1"
by (simp add: eq_fold)
lemma empty [simp]:
"F {} = \<^bold>1"
by (simp add: eq_fold)
lemma insert [simp]:
assumes "finite A"
shows "F (insert x A) = x \<^bold>* F A"
using assms by (simp add: eq_fold)
lemma in_idem:
assumes "finite A" and "x \<in> A"
shows "x \<^bold>* F A = F A"
proof -
from assms have "A \<noteq> {}" by auto
with \<open>finite A\<close> show ?thesis using \<open>x \<in> A\<close>
by (induct A rule: finite_ne_induct) (auto simp add: ac_simps)
qed
lemma union:
assumes "finite A" and "finite B"
shows "F (A \<union> B) = F A \<^bold>* F B"
using assms by (induct A) (simp_all add: ac_simps)
lemma remove:
assumes "finite A" and "x \<in> A"
shows "F A = x \<^bold>* F (A - {x})"
proof -
from assms obtain B where "A = insert x B" and "x \<notin> B" by (blast dest: mk_disjoint_insert)
with assms show ?thesis by simp
qed
lemma insert_remove:
assumes "finite A"
shows "F (insert x A) = x \<^bold>* F (A - {x})"
using assms by (cases "x \<in> A") (simp_all add: insert_absorb remove)
lemma subset:
assumes "finite A" and "B \<subseteq> A"
shows "F B \<^bold>* F A = F A"
proof -
from assms have "finite B" by (auto dest: finite_subset)
with assms show ?thesis by (simp add: union [symmetric] Un_absorb1)
qed
lemma closed:
assumes "finite A" "A \<noteq> {}" and elem: "\<And>x y. x \<^bold>* y \<in> {x, y}"
shows "F A \<in> A"
using \<open>finite A\<close> \<open>A \<noteq> {}\<close> proof (induct rule: finite_ne_induct)
case singleton then show ?case by simp
next
case insert with elem show ?case by force
qed
end
locale semilattice_order_neutr_set = binary?: semilattice_neutr_order + semilattice_neutr_set
begin
lemma bounded_iff:
assumes "finite A"
shows "x \<^bold>\<le> F A \<longleftrightarrow> (\<forall>a\<in>A. x \<^bold>\<le> a)"
using assms by (induct A) simp_all
lemma boundedI:
assumes "finite A"
assumes "\<And>a. a \<in> A \<Longrightarrow> x \<^bold>\<le> a"
shows "x \<^bold>\<le> F A"
using assms by (simp add: bounded_iff)
lemma boundedE:
assumes "finite A" and "x \<^bold>\<le> F A"
obtains "\<And>a. a \<in> A \<Longrightarrow> x \<^bold>\<le> a"
using assms by (simp add: bounded_iff)
lemma coboundedI:
assumes "finite A"
and "a \<in> A"
shows "F A \<^bold>\<le> a"
proof -
from assms have "A \<noteq> {}" by auto
from \<open>finite A\<close> \<open>A \<noteq> {}\<close> \<open>a \<in> A\<close> show ?thesis
proof (induct rule: finite_ne_induct)
case singleton thus ?case by (simp add: refl)
next
case (insert x B)
from insert have "a = x \<or> a \<in> B" by simp
then show ?case using insert by (auto intro: coboundedI2)
qed
qed
lemma subset_imp:
assumes "A \<subseteq> B" and "finite B"
shows "F B \<^bold>\<le> F A"
proof (cases "A = B")
case True then show ?thesis by (simp add: refl)
next
case False
have B: "B = A \<union> (B - A)" using \<open>A \<subseteq> B\<close> by blast
then have "F B = F (A \<union> (B - A))" by simp
also have "\<dots> = F A \<^bold>* F (B - A)" using False assms by (subst union) (auto intro: finite_subset)
also have "\<dots> \<^bold>\<le> F A" by simp
finally show ?thesis .
qed
end
subsection \<open>Lattice operations on finite sets\<close>
context semilattice_inf
begin
sublocale Inf_fin: semilattice_order_set inf less_eq less
defines
Inf_fin ("\<Sqinter>\<^sub>f\<^sub>i\<^sub>n _" [900] 900) = Inf_fin.F ..
end
context semilattice_sup
begin
sublocale Sup_fin: semilattice_order_set sup greater_eq greater
defines
Sup_fin ("\<Squnion>\<^sub>f\<^sub>i\<^sub>n _" [900] 900) = Sup_fin.F ..
end
subsection \<open>Infimum and Supremum over non-empty sets\<close>
context lattice
begin
lemma Inf_fin_le_Sup_fin [simp]:
assumes "finite A" and "A \<noteq> {}"
shows "\<Sqinter>\<^sub>f\<^sub>i\<^sub>nA \<le> \<Squnion>\<^sub>f\<^sub>i\<^sub>nA"
proof -
from \<open>A \<noteq> {}\<close> obtain a where "a \<in> A" by blast
with \<open>finite A\<close> have "\<Sqinter>\<^sub>f\<^sub>i\<^sub>nA \<le> a" by (rule Inf_fin.coboundedI)
moreover from \<open>finite A\<close> \<open>a \<in> A\<close> have "a \<le> \<Squnion>\<^sub>f\<^sub>i\<^sub>nA" by (rule Sup_fin.coboundedI)
ultimately show ?thesis by (rule order_trans)
qed
lemma sup_Inf_absorb [simp]:
"finite A \<Longrightarrow> a \<in> A \<Longrightarrow> \<Sqinter>\<^sub>f\<^sub>i\<^sub>nA \<squnion> a = a"
by (rule sup_absorb2) (rule Inf_fin.coboundedI)
lemma inf_Sup_absorb [simp]:
"finite A \<Longrightarrow> a \<in> A \<Longrightarrow> a \<sqinter> \<Squnion>\<^sub>f\<^sub>i\<^sub>nA = a"
by (rule inf_absorb1) (rule Sup_fin.coboundedI)
end
context distrib_lattice
begin
lemma sup_Inf1_distrib:
assumes "finite A"
and "A \<noteq> {}"
shows "sup x (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nA) = \<Sqinter>\<^sub>f\<^sub>i\<^sub>n{sup x a|a. a \<in> A}"
using assms by (simp add: image_def Inf_fin.hom_commute [where h="sup x", OF sup_inf_distrib1])
(rule arg_cong [where f="Inf_fin"], blast)
lemma sup_Inf2_distrib:
assumes A: "finite A" "A \<noteq> {}" and B: "finite B" "B \<noteq> {}"
shows "sup (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nA) (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nB) = \<Sqinter>\<^sub>f\<^sub>i\<^sub>n{sup a b|a b. a \<in> A \<and> b \<in> B}"
using A proof (induct rule: finite_ne_induct)
case singleton then show ?case
by (simp add: sup_Inf1_distrib [OF B])
next
case (insert x A)
have finB: "finite {sup x b |b. b \<in> B}"
by (rule finite_surj [where f = "sup x", OF B(1)], auto)
have finAB: "finite {sup a b |a b. a \<in> A \<and> b \<in> B}"
proof -
have "{sup a b |a b. a \<in> A \<and> b \<in> B} = (\<Union>a\<in>A. \<Union>b\<in>B. {sup a b})"
by blast
thus ?thesis by(simp add: insert(1) B(1))
qed
have ne: "{sup a b |a b. a \<in> A \<and> b \<in> B} \<noteq> {}" using insert B by blast
have "sup (\<Sqinter>\<^sub>f\<^sub>i\<^sub>n(insert x A)) (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nB) = sup (inf x (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nA)) (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nB)"
using insert by simp
also have "\<dots> = inf (sup x (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nB)) (sup (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nA) (\<Sqinter>\<^sub>f\<^sub>i\<^sub>nB))" by(rule sup_inf_distrib2)
also have "\<dots> = inf (\<Sqinter>\<^sub>f\<^sub>i\<^sub>n{sup x b|b. b \<in> B}) (\<Sqinter>\<^sub>f\<^sub>i\<^sub>n{sup a b|a b. a \<in> A \<and> b \<in> B})"
using insert by(simp add:sup_Inf1_distrib[OF B])
also have "\<dots> = \<Sqinter>\<^sub>f\<^sub>i\<^sub>n({sup x b |b. b \<in> B} \<union> {sup a b |a b. a \<in> A \<and> b \<in> B})"
(is "_ = \<Sqinter>\<^sub>f\<^sub>i\<^sub>n?M")
using B insert
by (simp add: Inf_fin.union [OF finB _ finAB ne])
also have "?M = {sup a b |a b. a \<in> insert x A \<and> b \<in> B}"
by blast
finally show ?case .
qed
lemma inf_Sup1_distrib:
assumes "finite A" and "A \<noteq> {}"
shows "inf x (\<Squnion>\<^sub>f\<^sub>i\<^sub>nA) = \<Squnion>\<^sub>f\<^sub>i\<^sub>n{inf x a|a. a \<in> A}"
using assms by (simp add: image_def Sup_fin.hom_commute [where h="inf x", OF inf_sup_distrib1])
(rule arg_cong [where f="Sup_fin"], blast)
lemma inf_Sup2_distrib:
assumes A: "finite A" "A \<noteq> {}" and B: "finite B" "B \<noteq> {}"
shows "inf (\<Squnion>\<^sub>f\<^sub>i\<^sub>nA) (\<Squnion>\<^sub>f\<^sub>i\<^sub>nB) = \<Squnion>\<^sub>f\<^sub>i\<^sub>n{inf a b|a b. a \<in> A \<and> b \<in> B}"
using A proof (induct rule: finite_ne_induct)
case singleton thus ?case
by(simp add: inf_Sup1_distrib [OF B])
next
case (insert x A)
have finB: "finite {inf x b |b. b \<in> B}"
by(rule finite_surj[where f = "%b. inf x b", OF B(1)], auto)
have finAB: "finite {inf a b |a b. a \<in> A \<and> b \<in> B}"
proof -
have "{inf a b |a b. a \<in> A \<and> b \<in> B} = (\<Union>a\<in>A. \<Union>b\<in>B. {inf a b})"
by blast
thus ?thesis by(simp add: insert(1) B(1))
qed
have ne: "{inf a b |a b. a \<in> A \<and> b \<in> B} \<noteq> {}" using insert B by blast
have "inf (\<Squnion>\<^sub>f\<^sub>i\<^sub>n(insert x A)) (\<Squnion>\<^sub>f\<^sub>i\<^sub>nB) = inf (sup x (\<Squnion>\<^sub>f\<^sub>i\<^sub>nA)) (\<Squnion>\<^sub>f\<^sub>i\<^sub>nB)"
using insert by simp
also have "\<dots> = sup (inf x (\<Squnion>\<^sub>f\<^sub>i\<^sub>nB)) (inf (\<Squnion>\<^sub>f\<^sub>i\<^sub>nA) (\<Squnion>\<^sub>f\<^sub>i\<^sub>nB))" by(rule inf_sup_distrib2)
also have "\<dots> = sup (\<Squnion>\<^sub>f\<^sub>i\<^sub>n{inf x b|b. b \<in> B}) (\<Squnion>\<^sub>f\<^sub>i\<^sub>n{inf a b|a b. a \<in> A \<and> b \<in> B})"
using insert by(simp add:inf_Sup1_distrib[OF B])
also have "\<dots> = \<Squnion>\<^sub>f\<^sub>i\<^sub>n({inf x b |b. b \<in> B} \<union> {inf a b |a b. a \<in> A \<and> b \<in> B})"
(is "_ = \<Squnion>\<^sub>f\<^sub>i\<^sub>n?M")
using B insert
by (simp add: Sup_fin.union [OF finB _ finAB ne])
also have "?M = {inf a b |a b. a \<in> insert x A \<and> b \<in> B}"
by blast
finally show ?case .
qed
end
context complete_lattice
begin
lemma Inf_fin_Inf:
assumes "finite A" and "A \<noteq> {}"
shows "\<Sqinter>\<^sub>f\<^sub>i\<^sub>nA = \<Sqinter>A"
proof -
from assms obtain b B where "A = insert b B" and "finite B" by auto
then show ?thesis
by (simp add: Inf_fin.eq_fold inf_Inf_fold_inf inf.commute [of b])
qed
lemma Sup_fin_Sup:
assumes "finite A" and "A \<noteq> {}"
shows "\<Squnion>\<^sub>f\<^sub>i\<^sub>nA = \<Squnion>A"
proof -
from assms obtain b B where "A = insert b B" and "finite B" by auto
then show ?thesis
by (simp add: Sup_fin.eq_fold sup_Sup_fold_sup sup.commute [of b])
qed
end
subsection \<open>Minimum and Maximum over non-empty sets\<close>
context linorder
begin
sublocale Min: semilattice_order_set min less_eq less
+ Max: semilattice_order_set max greater_eq greater
defines
Min = Min.F and Max = Max.F ..
end
syntax
"_MIN1" :: "pttrns \<Rightarrow> 'b \<Rightarrow> 'b" ("(3MIN _./ _)" [0, 10] 10)
"_MIN" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b" ("(3MIN _\<in>_./ _)" [0, 0, 10] 10)
"_MAX1" :: "pttrns \<Rightarrow> 'b \<Rightarrow> 'b" ("(3MAX _./ _)" [0, 10] 10)
"_MAX" :: "pttrn \<Rightarrow> 'a set \<Rightarrow> 'b \<Rightarrow> 'b" ("(3MAX _\<in>_./ _)" [0, 0, 10] 10)
translations
"MIN x y. f" \<rightleftharpoons> "MIN x. MIN y. f"
"MIN x. f" \<rightleftharpoons> "CONST Min (CONST range (\<lambda>x. f))"
"MIN x\<in>A. f" \<rightleftharpoons> "CONST Min ((\<lambda>x. f) ` A)"
"MAX x y. f" \<rightleftharpoons> "MAX x. MAX y. f"
"MAX x. f" \<rightleftharpoons> "CONST Max (CONST range (\<lambda>x. f))"
"MAX x\<in>A. f" \<rightleftharpoons> "CONST Max ((\<lambda>x. f) ` A)"
text \<open>An aside: \<^const>\<open>Min\<close>/\<^const>\<open>Max\<close> on linear orders as special case of \<^const>\<open>Inf_fin\<close>/\<^const>\<open>Sup_fin\<close>\<close>
lemma Inf_fin_Min:
"Inf_fin = (Min :: 'a::{semilattice_inf, linorder} set \<Rightarrow> 'a)"
by (simp add: Inf_fin_def Min_def inf_min)
lemma Sup_fin_Max:
"Sup_fin = (Max :: 'a::{semilattice_sup, linorder} set \<Rightarrow> 'a)"
by (simp add: Sup_fin_def Max_def sup_max)
context linorder
begin
lemma dual_min:
"ord.min greater_eq = max"
by (auto simp add: ord.min_def max_def fun_eq_iff)
lemma dual_max:
"ord.max greater_eq = min"
by (auto simp add: ord.max_def min_def fun_eq_iff)
lemma dual_Min:
"linorder.Min greater_eq = Max"
proof -
interpret dual: linorder greater_eq greater by (fact dual_linorder)
show ?thesis by (simp add: dual.Min_def dual_min Max_def)
qed
lemma dual_Max:
"linorder.Max greater_eq = Min"
proof -
interpret dual: linorder greater_eq greater by (fact dual_linorder)
show ?thesis by (simp add: dual.Max_def dual_max Min_def)
qed
lemmas Min_singleton = Min.singleton
lemmas Max_singleton = Max.singleton
lemmas Min_insert = Min.insert
lemmas Max_insert = Max.insert
lemmas Min_Un = Min.union
lemmas Max_Un = Max.union
lemmas hom_Min_commute = Min.hom_commute
lemmas hom_Max_commute = Max.hom_commute
lemma Min_in [simp]:
assumes "finite A" and "A \<noteq> {}"
shows "Min A \<in> A"
using assms by (auto simp add: min_def Min.closed)
lemma Max_in [simp]:
assumes "finite A" and "A \<noteq> {}"
shows "Max A \<in> A"
using assms by (auto simp add: max_def Max.closed)
lemma Min_insert2:
assumes "finite A" and min: "\<And>b. b \<in> A \<Longrightarrow> a \<le> b"
shows "Min (insert a A) = a"
proof (cases "A = {}")
case True
then show ?thesis by simp
next
case False
with \<open>finite A\<close> have "Min (insert a A) = min a (Min A)"
by simp
moreover from \<open>finite A\<close> \<open>A \<noteq> {}\<close> min have "a \<le> Min A" by simp
ultimately show ?thesis by (simp add: min.absorb1)
qed
lemma Max_insert2:
assumes "finite A" and max: "\<And>b. b \<in> A \<Longrightarrow> b \<le> a"
shows "Max (insert a A) = a"
proof (cases "A = {}")
case True
then show ?thesis by simp
next
case False
with \<open>finite A\<close> have "Max (insert a A) = max a (Max A)"
by simp
moreover from \<open>finite A\<close> \<open>A \<noteq> {}\<close> max have "Max A \<le> a" by simp
ultimately show ?thesis by (simp add: max.absorb1)
qed
lemma Max_const[simp]: "\<lbrakk> finite A; A \<noteq> {} \<rbrakk> \<Longrightarrow> Max ((\<lambda>_. c) ` A) = c"
using Max_in image_is_empty by blast
lemma Min_const[simp]: "\<lbrakk> finite A; A \<noteq> {} \<rbrakk> \<Longrightarrow> Min ((\<lambda>_. c) ` A) = c"
using Min_in image_is_empty by blast
lemma Min_le [simp]:
assumes "finite A" and "x \<in> A"
shows "Min A \<le> x"
using assms by (fact Min.coboundedI)
lemma Max_ge [simp]:
assumes "finite A" and "x \<in> A"
shows "x \<le> Max A"
using assms by (fact Max.coboundedI)
lemma Min_eqI:
assumes "finite A"
assumes "\<And>y. y \<in> A \<Longrightarrow> y \<ge> x"
and "x \<in> A"
shows "Min A = x"
proof (rule order.antisym)
from \<open>x \<in> A\<close> have "A \<noteq> {}" by auto
with assms show "Min A \<ge> x" by simp
next
from assms show "x \<ge> Min A" by simp
qed
lemma Max_eqI:
assumes "finite A"
assumes "\<And>y. y \<in> A \<Longrightarrow> y \<le> x"
and "x \<in> A"
shows "Max A = x"
proof (rule order.antisym)
from \<open>x \<in> A\<close> have "A \<noteq> {}" by auto
with assms show "Max A \<le> x" by simp
next
from assms show "x \<le> Max A" by simp
qed
lemma eq_Min_iff:
"\<lbrakk> finite A; A \<noteq> {} \<rbrakk> \<Longrightarrow> m = Min A \<longleftrightarrow> m \<in> A \<and> (\<forall>a \<in> A. m \<le> a)"
by (meson Min_in Min_le order.antisym)
lemma Min_eq_iff:
"\<lbrakk> finite A; A \<noteq> {} \<rbrakk> \<Longrightarrow> Min A = m \<longleftrightarrow> m \<in> A \<and> (\<forall>a \<in> A. m \<le> a)"
by (meson Min_in Min_le order.antisym)
lemma eq_Max_iff:
"\<lbrakk> finite A; A \<noteq> {} \<rbrakk> \<Longrightarrow> m = Max A \<longleftrightarrow> m \<in> A \<and> (\<forall>a \<in> A. a \<le> m)"
by (meson Max_in Max_ge order.antisym)
lemma Max_eq_iff:
"\<lbrakk> finite A; A \<noteq> {} \<rbrakk> \<Longrightarrow> Max A = m \<longleftrightarrow> m \<in> A \<and> (\<forall>a \<in> A. a \<le> m)"
by (meson Max_in Max_ge order.antisym)
context
fixes A :: "'a set"
assumes fin_nonempty: "finite A" "A \<noteq> {}"
begin
lemma Min_ge_iff [simp]:
"x \<le> Min A \<longleftrightarrow> (\<forall>a\<in>A. x \<le> a)"
using fin_nonempty by (fact Min.bounded_iff)
lemma Max_le_iff [simp]:
"Max A \<le> x \<longleftrightarrow> (\<forall>a\<in>A. a \<le> x)"
using fin_nonempty by (fact Max.bounded_iff)
lemma Min_gr_iff [simp]:
"x < Min A \<longleftrightarrow> (\<forall>a\<in>A. x < a)"
using fin_nonempty by (induct rule: finite_ne_induct) simp_all
lemma Max_less_iff [simp]:
"Max A < x \<longleftrightarrow> (\<forall>a\<in>A. a < x)"
using fin_nonempty by (induct rule: finite_ne_induct) simp_all
lemma Min_le_iff:
"Min A \<le> x \<longleftrightarrow> (\<exists>a\<in>A. a \<le> x)"
using fin_nonempty by (induct rule: finite_ne_induct) (simp_all add: min_le_iff_disj)
lemma Max_ge_iff:
"x \<le> Max A \<longleftrightarrow> (\<exists>a\<in>A. x \<le> a)"
using fin_nonempty by (induct rule: finite_ne_induct) (simp_all add: le_max_iff_disj)
lemma Min_less_iff:
"Min A < x \<longleftrightarrow> (\<exists>a\<in>A. a < x)"
using fin_nonempty by (induct rule: finite_ne_induct) (simp_all add: min_less_iff_disj)
lemma Max_gr_iff:
"x < Max A \<longleftrightarrow> (\<exists>a\<in>A. x < a)"
using fin_nonempty by (induct rule: finite_ne_induct) (simp_all add: less_max_iff_disj)
end
lemma Max_eq_if:
assumes "finite A" "finite B" "\<forall>a\<in>A. \<exists>b\<in>B. a \<le> b" "\<forall>b\<in>B. \<exists>a\<in>A. b \<le> a"
shows "Max A = Max B"
proof cases
assume "A = {}" thus ?thesis using assms by simp
next
assume "A \<noteq> {}" thus ?thesis using assms
by(blast intro: order.antisym Max_in Max_ge_iff[THEN iffD2])
qed
lemma Min_antimono:
assumes "M \<subseteq> N" and "M \<noteq> {}" and "finite N"
shows "Min N \<le> Min M"
using assms by (fact Min.subset_imp)
lemma Max_mono:
assumes "M \<subseteq> N" and "M \<noteq> {}" and "finite N"
shows "Max M \<le> Max N"
using assms by (fact Max.subset_imp)
lemma mono_Min_commute:
assumes "mono f"
assumes "finite A" and "A \<noteq> {}"
shows "f (Min A) = Min (f ` A)"
proof (rule linorder_class.Min_eqI [symmetric])
from \<open>finite A\<close> show "finite (f ` A)" by simp
from assms show "f (Min A) \<in> f ` A" by simp
fix x
assume "x \<in> f ` A"
then obtain y where "y \<in> A" and "x = f y" ..
with assms have "Min A \<le> y" by auto
with \<open>mono f\<close> have "f (Min A) \<le> f y" by (rule monoE)
with \<open>x = f y\<close> show "f (Min A) \<le> x" by simp
qed
lemma mono_Max_commute:
assumes "mono f"
assumes "finite A" and "A \<noteq> {}"
shows "f (Max A) = Max (f ` A)"
proof (rule linorder_class.Max_eqI [symmetric])
from \<open>finite A\<close> show "finite (f ` A)" by simp
from assms show "f (Max A) \<in> f ` A" by simp
fix x
assume "x \<in> f ` A"
then obtain y where "y \<in> A" and "x = f y" ..
with assms have "y \<le> Max A" by auto
with \<open>mono f\<close> have "f y \<le> f (Max A)" by (rule monoE)
with \<open>x = f y\<close> show "x \<le> f (Max A)" by simp
qed
lemma finite_linorder_max_induct [consumes 1, case_names empty insert]:
assumes fin: "finite A"
and empty: "P {}"
and insert: "\<And>b A. finite A \<Longrightarrow> \<forall>a\<in>A. a < b \<Longrightarrow> P A \<Longrightarrow> P (insert b A)"
shows "P A"
using fin empty insert
proof (induct rule: finite_psubset_induct)
case (psubset A)
have IH: "\<And>B. \<lbrakk>B < A; P {}; (\<And>A b. \<lbrakk>finite A; \<forall>a\<in>A. a<b; P A\<rbrakk> \<Longrightarrow> P (insert b A))\<rbrakk> \<Longrightarrow> P B" by fact
have fin: "finite A" by fact
have empty: "P {}" by fact
have step: "\<And>b A. \<lbrakk>finite A; \<forall>a\<in>A. a < b; P A\<rbrakk> \<Longrightarrow> P (insert b A)" by fact
show "P A"
proof (cases "A = {}")
assume "A = {}"
then show "P A" using \<open>P {}\<close> by simp
next
let ?B = "A - {Max A}"
let ?A = "insert (Max A) ?B"
have "finite ?B" using \<open>finite A\<close> by simp
assume "A \<noteq> {}"
with \<open>finite A\<close> have "Max A \<in> A" by auto
then have A: "?A = A" using insert_Diff_single insert_absorb by auto
then have "P ?B" using \<open>P {}\<close> step IH [of ?B] by blast
moreover
have "\<forall>a\<in>?B. a < Max A" using Max_ge [OF \<open>finite A\<close>] by fastforce
ultimately show "P A" using A insert_Diff_single step [OF \<open>finite ?B\<close>] by fastforce
qed
qed
lemma finite_linorder_min_induct [consumes 1, case_names empty insert]:
"\<lbrakk>finite A; P {}; \<And>b A. \<lbrakk>finite A; \<forall>a\<in>A. b < a; P A\<rbrakk> \<Longrightarrow> P (insert b A)\<rbrakk> \<Longrightarrow> P A"
by (rule linorder.finite_linorder_max_induct [OF dual_linorder])
lemma finite_ranking_induct[consumes 1, case_names empty insert]:
fixes f :: "'b \<Rightarrow> 'a"
assumes "finite S"
assumes "P {}"
assumes "\<And>x S. finite S \<Longrightarrow> (\<And>y. y \<in> S \<Longrightarrow> f y \<le> f x) \<Longrightarrow> P S \<Longrightarrow> P (insert x S)"
shows "P S"
using \<open>finite S\<close>
proof (induction rule: finite_psubset_induct)
case (psubset A)
{
assume "A \<noteq> {}"
hence "f ` A \<noteq> {}" and "finite (f ` A)"
using psubset finite_image_iff by simp+
then obtain a where "f a = Max (f ` A)" and "a \<in> A"
by (metis Max_in[of "f ` A"] imageE)
then have "P (A - {a})"
using psubset member_remove by blast
moreover
have "\<And>y. y \<in> A \<Longrightarrow> f y \<le> f a"
using \<open>f a = Max (f ` A)\<close> \<open>finite (f ` A)\<close> by simp
ultimately
have ?case
by (metis \<open>a \<in> A\<close> DiffD1 insert_Diff assms(3) finite_Diff psubset.hyps)
}
thus ?case
using assms(2) by blast
qed
lemma Least_Min:
assumes "finite {a. P a}" and "\<exists>a. P a"
shows "(LEAST a. P a) = Min {a. P a}"
proof -
{ fix A :: "'a set"
assume A: "finite A" "A \<noteq> {}"
have "(LEAST a. a \<in> A) = Min A"
using A proof (induct A rule: finite_ne_induct)
case singleton show ?case by (rule Least_equality) simp_all
next
case (insert a A)
have "(LEAST b. b = a \<or> b \<in> A) = min a (LEAST a. a \<in> A)"
by (auto intro!: Least_equality simp add: min_def not_le Min_le_iff insert.hyps dest!: less_imp_le)
with insert show ?case by simp
qed
} from this [of "{a. P a}"] assms show ?thesis by simp
qed
lemma infinite_growing:
assumes "X \<noteq> {}"
assumes *: "\<And>x. x \<in> X \<Longrightarrow> \<exists>y\<in>X. y > x"
shows "\<not> finite X"
proof
assume "finite X"
with \<open>X \<noteq> {}\<close> have "Max X \<in> X" "\<forall>x\<in>X. x \<le> Max X"
by auto
with *[of "Max X"] show False
by auto
qed
end
lemma sum_le_card_Max: "finite A \<Longrightarrow> sum f A \<le> card A * Max (f ` A)"
using sum_bounded_above[of A f "Max (f ` A)"] by simp
lemma card_Min_le_sum: "finite A \<Longrightarrow> card A * Min (f ` A) \<le> sum f A"
using sum_bounded_below[of A "Min (f ` A)" f] by simp
context linordered_ab_semigroup_add
begin
lemma Min_add_commute:
fixes k
assumes "finite S" and "S \<noteq> {}"
shows "Min ((\<lambda>x. f x + k) ` S) = Min(f ` S) + k"
proof -
have m: "\<And>x y. min x y + k = min (x+k) (y+k)"
by (simp add: min_def order.antisym add_right_mono)
have "(\<lambda>x. f x + k) ` S = (\<lambda>y. y + k) ` (f ` S)" by auto
also have "Min \<dots> = Min (f ` S) + k"
using assms hom_Min_commute [of "\<lambda>y. y+k" "f ` S", OF m, symmetric] by simp
finally show ?thesis by simp
qed
lemma Max_add_commute:
fixes k
assumes "finite S" and "S \<noteq> {}"
shows "Max ((\<lambda>x. f x + k) ` S) = Max(f ` S) + k"
proof -
have m: "\<And>x y. max x y + k = max (x+k) (y+k)"
by (simp add: max_def order.antisym add_right_mono)
have "(\<lambda>x. f x + k) ` S = (\<lambda>y. y + k) ` (f ` S)" by auto
also have "Max \<dots> = Max (f ` S) + k"
using assms hom_Max_commute [of "\<lambda>y. y+k" "f ` S", OF m, symmetric] by simp
finally show ?thesis by simp
qed
end
context linordered_ab_group_add
begin
lemma minus_Max_eq_Min [simp]:
"finite S \<Longrightarrow> S \<noteq> {} \<Longrightarrow> - Max S = Min (uminus ` S)"
by (induct S rule: finite_ne_induct) (simp_all add: minus_max_eq_min)
lemma minus_Min_eq_Max [simp]:
"finite S \<Longrightarrow> S \<noteq> {} \<Longrightarrow> - Min S = Max (uminus ` S)"
by (induct S rule: finite_ne_induct) (simp_all add: minus_min_eq_max)
end
context complete_linorder
begin
lemma Min_Inf:
assumes "finite A" and "A \<noteq> {}"
shows "Min A = Inf A"
proof -
from assms obtain b B where "A = insert b B" and "finite B" by auto
then show ?thesis
by (simp add: Min.eq_fold complete_linorder_inf_min [symmetric] inf_Inf_fold_inf inf.commute [of b])
qed
lemma Max_Sup:
assumes "finite A" and "A \<noteq> {}"
shows "Max A = Sup A"
proof -
from assms obtain b B where "A = insert b B" and "finite B" by auto
then show ?thesis
by (simp add: Max.eq_fold complete_linorder_sup_max [symmetric] sup_Sup_fold_sup sup.commute [of b])
qed
end
lemma disjnt_ge_max: \<^marker>\<open>contributor \<open>Lars Hupel\<close>\<close>
\<open>disjnt X Y\<close> if \<open>finite Y\<close> \<open>\<And>x. x \<in> X \<Longrightarrow> x > Max Y\<close>
using that by (auto simp add: disjnt_def) (use Max_less_iff in blast)
subsection \<open>Arg Min\<close>
context ord
begin
definition is_arg_min :: "('b \<Rightarrow> 'a) \<Rightarrow> ('b \<Rightarrow> bool) \<Rightarrow> 'b \<Rightarrow> bool" where
"is_arg_min f P x = (P x \<and> \<not>(\<exists>y. P y \<and> f y < f x))"
definition arg_min :: "('b \<Rightarrow> 'a) \<Rightarrow> ('b \<Rightarrow> bool) \<Rightarrow> 'b" where
"arg_min f P = (SOME x. is_arg_min f P x)"
definition arg_min_on :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b set \<Rightarrow> 'b" where
"arg_min_on f S = arg_min f (\<lambda>x. x \<in> S)"
end
syntax
"_arg_min" :: "('b \<Rightarrow> 'a) \<Rightarrow> pttrn \<Rightarrow> bool \<Rightarrow> 'b"
("(3ARG'_MIN _ _./ _)" [1000, 0, 10] 10)
translations
"ARG_MIN f x. P" \<rightleftharpoons> "CONST arg_min f (\<lambda>x. P)"
lemma is_arg_min_linorder: fixes f :: "'a \<Rightarrow> 'b :: linorder"
shows "is_arg_min f P x = (P x \<and> (\<forall>y. P y \<longrightarrow> f x \<le> f y))"
by(auto simp add: is_arg_min_def)
lemma is_arg_min_antimono: fixes f :: "'a \<Rightarrow> ('b::order)"
shows "\<lbrakk> is_arg_min f P x; f y \<le> f x; P y \<rbrakk> \<Longrightarrow> is_arg_min f P y"
by (simp add: order.order_iff_strict is_arg_min_def)
lemma arg_minI:
"\<lbrakk> P x;
\<And>y. P y \<Longrightarrow> \<not> f y < f x;
\<And>x. \<lbrakk> P x; \<forall>y. P y \<longrightarrow> \<not> f y < f x \<rbrakk> \<Longrightarrow> Q x \<rbrakk>
\<Longrightarrow> Q (arg_min f P)"
apply (simp add: arg_min_def is_arg_min_def)
apply (rule someI2_ex)
apply blast
apply blast
done
lemma arg_min_equality:
"\<lbrakk> P k; \<And>x. P x \<Longrightarrow> f k \<le> f x \<rbrakk> \<Longrightarrow> f (arg_min f P) = f k"
for f :: "_ \<Rightarrow> 'a::order"
apply (rule arg_minI)
apply assumption
apply (simp add: less_le_not_le)
by (metis le_less)
lemma wf_linord_ex_has_least:
"\<lbrakk> wf r; \<forall>x y. (x, y) \<in> r\<^sup>+ \<longleftrightarrow> (y, x) \<notin> r\<^sup>*; P k \<rbrakk>
\<Longrightarrow> \<exists>x. P x \<and> (\<forall>y. P y \<longrightarrow> (m x, m y) \<in> r\<^sup>*)"
apply (drule wf_trancl [THEN wf_eq_minimal [THEN iffD1]])
apply (drule_tac x = "m ` Collect P" in spec)
by force
lemma ex_has_least_nat: "P k \<Longrightarrow> \<exists>x. P x \<and> (\<forall>y. P y \<longrightarrow> m x \<le> m y)"
for m :: "'a \<Rightarrow> nat"
apply (simp only: pred_nat_trancl_eq_le [symmetric])
apply (rule wf_pred_nat [THEN wf_linord_ex_has_least])
apply (simp add: less_eq linorder_not_le pred_nat_trancl_eq_le)
by assumption
lemma arg_min_nat_lemma:
"P k \<Longrightarrow> P(arg_min m P) \<and> (\<forall>y. P y \<longrightarrow> m (arg_min m P) \<le> m y)"
for m :: "'a \<Rightarrow> nat"
apply (simp add: arg_min_def is_arg_min_linorder)
apply (rule someI_ex)
apply (erule ex_has_least_nat)
done
lemmas arg_min_natI = arg_min_nat_lemma [THEN conjunct1]
lemma is_arg_min_arg_min_nat: fixes m :: "'a \<Rightarrow> nat"
shows "P x \<Longrightarrow> is_arg_min m P (arg_min m P)"
by (metis arg_min_nat_lemma is_arg_min_linorder)
lemma arg_min_nat_le: "P x \<Longrightarrow> m (arg_min m P) \<le> m x"
for m :: "'a \<Rightarrow> nat"
by (rule arg_min_nat_lemma [THEN conjunct2, THEN spec, THEN mp])
lemma ex_min_if_finite:
"\<lbrakk> finite S; S \<noteq> {} \<rbrakk> \<Longrightarrow> \<exists>m\<in>S. \<not>(\<exists>x\<in>S. x < (m::'a::order))"
by(induction rule: finite.induct) (auto intro: order.strict_trans)
lemma ex_is_arg_min_if_finite: fixes f :: "'a \<Rightarrow> 'b :: order"
shows "\<lbrakk> finite S; S \<noteq> {} \<rbrakk> \<Longrightarrow> \<exists>x. is_arg_min f (\<lambda>x. x \<in> S) x"
unfolding is_arg_min_def
using ex_min_if_finite[of "f ` S"]
by auto
lemma arg_min_SOME_Min:
"finite S \<Longrightarrow> arg_min_on f S = (SOME y. y \<in> S \<and> f y = Min(f ` S))"
unfolding arg_min_on_def arg_min_def is_arg_min_linorder
apply(rule arg_cong[where f = Eps])
apply (auto simp: fun_eq_iff intro: Min_eqI[symmetric])
done
lemma arg_min_if_finite: fixes f :: "'a \<Rightarrow> 'b :: order"
assumes "finite S" "S \<noteq> {}"
shows "arg_min_on f S \<in> S" and "\<not>(\<exists>x\<in>S. f x < f (arg_min_on f S))"
using ex_is_arg_min_if_finite[OF assms, of f]
unfolding arg_min_on_def arg_min_def is_arg_min_def
by(auto dest!: someI_ex)
lemma arg_min_least: fixes f :: "'a \<Rightarrow> 'b :: linorder"
shows "\<lbrakk> finite S; S \<noteq> {}; y \<in> S \<rbrakk> \<Longrightarrow> f(arg_min_on f S) \<le> f y"
by(simp add: arg_min_SOME_Min inv_into_def2[symmetric] f_inv_into_f)
lemma arg_min_inj_eq: fixes f :: "'a \<Rightarrow> 'b :: order"
shows "\<lbrakk> inj_on f {x. P x}; P a; \<forall>y. P y \<longrightarrow> f a \<le> f y \<rbrakk> \<Longrightarrow> arg_min f P = a"
apply(simp add: arg_min_def is_arg_min_def)
apply(rule someI2[of _ a])
apply (simp add: less_le_not_le)
by (metis inj_on_eq_iff less_le mem_Collect_eq)
subsection \<open>Arg Max\<close>
context ord
begin
definition is_arg_max :: "('b \<Rightarrow> 'a) \<Rightarrow> ('b \<Rightarrow> bool) \<Rightarrow> 'b \<Rightarrow> bool" where
"is_arg_max f P x = (P x \<and> \<not>(\<exists>y. P y \<and> f y > f x))"
definition arg_max :: "('b \<Rightarrow> 'a) \<Rightarrow> ('b \<Rightarrow> bool) \<Rightarrow> 'b" where
"arg_max f P = (SOME x. is_arg_max f P x)"
definition arg_max_on :: "('b \<Rightarrow> 'a) \<Rightarrow> 'b set \<Rightarrow> 'b" where
"arg_max_on f S = arg_max f (\<lambda>x. x \<in> S)"
end
syntax
"_arg_max" :: "('b \<Rightarrow> 'a) \<Rightarrow> pttrn \<Rightarrow> bool \<Rightarrow> 'a"
("(3ARG'_MAX _ _./ _)" [1000, 0, 10] 10)
translations
"ARG_MAX f x. P" \<rightleftharpoons> "CONST arg_max f (\<lambda>x. P)"
lemma is_arg_max_linorder: fixes f :: "'a \<Rightarrow> 'b :: linorder"
shows "is_arg_max f P x = (P x \<and> (\<forall>y. P y \<longrightarrow> f x \<ge> f y))"
by(auto simp add: is_arg_max_def)
lemma arg_maxI:
"P x \<Longrightarrow>
(\<And>y. P y \<Longrightarrow> \<not> f y > f x) \<Longrightarrow>
(\<And>x. P x \<Longrightarrow> \<forall>y. P y \<longrightarrow> \<not> f y > f x \<Longrightarrow> Q x) \<Longrightarrow>
Q (arg_max f P)"
apply (simp add: arg_max_def is_arg_max_def)
apply (rule someI2_ex)
apply blast
apply blast
done
lemma arg_max_equality:
"\<lbrakk> P k; \<And>x. P x \<Longrightarrow> f x \<le> f k \<rbrakk> \<Longrightarrow> f (arg_max f P) = f k"
for f :: "_ \<Rightarrow> 'a::order"
apply (rule arg_maxI [where f = f])
apply assumption
apply (simp add: less_le_not_le)
by (metis le_less)
lemma ex_has_greatest_nat_lemma:
"P k \<Longrightarrow> \<forall>x. P x \<longrightarrow> (\<exists>y. P y \<and> \<not> f y \<le> f x) \<Longrightarrow> \<exists>y. P y \<and> \<not> f y < f k + n"
for f :: "'a \<Rightarrow> nat"
by (induct n) (force simp: le_Suc_eq)+
lemma ex_has_greatest_nat:
assumes "P k"
and "\<forall>y. P y \<longrightarrow> (f:: 'a \<Rightarrow> nat) y < b"
shows "\<exists>x. P x \<and> (\<forall>y. P y \<longrightarrow> f y \<le> f x)"
proof (rule ccontr)
assume "\<nexists>x. P x \<and> (\<forall>y. P y \<longrightarrow> f y \<le> f x)"
then have "\<forall>x. P x \<longrightarrow> (\<exists>y. P y \<and> \<not> f y \<le> f x)"
by auto
then have "\<exists>y. P y \<and> \<not> f y < f k + (b - f k)"
using assms ex_has_greatest_nat_lemma[of P k f "b - f k"]
by blast
then show "False"
using assms by auto
qed
lemma arg_max_nat_lemma:
"\<lbrakk> P k; \<forall>y. P y \<longrightarrow> f y < b \<rbrakk>
\<Longrightarrow> P (arg_max f P) \<and> (\<forall>y. P y \<longrightarrow> f y \<le> f (arg_max f P))"
for f :: "'a \<Rightarrow> nat"
apply (simp add: arg_max_def is_arg_max_linorder)
apply (rule someI_ex)
apply (erule (1) ex_has_greatest_nat)
done
lemmas arg_max_natI = arg_max_nat_lemma [THEN conjunct1]
lemma arg_max_nat_le: "P x \<Longrightarrow> \<forall>y. P y \<longrightarrow> f y < b \<Longrightarrow> f x \<le> f (arg_max f P)"
for f :: "'a \<Rightarrow> nat"
by (blast dest: arg_max_nat_lemma [THEN conjunct2, THEN spec, of P])
end
|
{-# OPTIONS --without-K #-}
open import HoTT
open import homotopy.HSpace renaming (HSpaceStructure to HSS)
open import homotopy.WedgeExtension
module homotopy.Pi2HSusp where
module Pi2HSusp {i} (A : Type i) (gA : has-level β¨ 1 β© A)
(cA : is-connected β¨0β© A) (A-H : HSS A)
(ΞΌcoh : HSS.ΞΌe- A-H (HSS.e A-H) == HSS.ΞΌ-e A-H (HSS.e A-H))
where
{- TODO this belongs somewhere else, but where? -}
private
Type=-ext : β {i} {A B : Type i} (p q : A == B)
β ((x : A) β coe p x == coe q x) β p == q
Type=-ext p q Ξ± =
! (ua-Ξ· p)
β ap ua (pair= (Ξ»= Ξ±) (prop-has-all-paths-β (is-equiv-is-prop (coe q))))
β ua-Ξ· q
open HSpaceStructure A-H
open ConnectedHSpace A cA A-H
P : Suspension A β Type i
P x = Trunc β¨ 1 β© (north A == x)
module Codes = SuspensionRec A A A (Ξ» a β ua (ΞΌ-equiv a))
Codes : Suspension A β Type i
Codes = Codes.f
Codes-level : (x : Suspension A) β has-level β¨ 1 β© (Codes x)
Codes-level = Suspension-elim A gA gA
(Ξ» _ β prop-has-all-paths-β has-level-is-prop)
encodeβ : {x : Suspension A} β (north A == x) β Codes x
encodeβ Ξ± = transport Codes Ξ± e
encode : {x : Suspension A} β P x β Codes x
encode {x} = Trunc-rec (Codes-level x) encodeβ
decode' : A β P (north A)
decode' a = [ (merid A a β ! (merid A e)) ]
abstract
transport-Codes-mer : (a a' : A)
β transport Codes (merid A a) a' == ΞΌ a a'
transport-Codes-mer a a' =
coe (ap Codes (merid A a)) a'
=β¨ Codes.glue-Ξ² a |in-ctx (Ξ» w β coe w a') β©
coe (ua (ΞΌ-equiv a)) a'
=β¨ coe-Ξ² (ΞΌ-equiv a) a' β©
ΞΌ a a' β
transport-Codes-mer-e-! : (a : A)
β transport Codes (! (merid A e)) a == a
transport-Codes-mer-e-! a =
coe (ap Codes (! (merid A e))) a
=β¨ ap-! Codes (merid A e) |in-ctx (Ξ» w β coe w a) β©
coe (! (ap Codes (merid A e))) a
=β¨ Codes.glue-Ξ² e |in-ctx (Ξ» w β coe (! w) a) β©
coe (! (ua (ΞΌ-equiv e))) a
=β¨ Type=-ext (ua (ΞΌ-equiv e)) idp (Ξ» x β coe-Ξ² _ x β ΞΌe- x)
|in-ctx (Ξ» w β coe (! w) a) β©
coe (! idp) a β
abstract
encode-decode' : (a : A) β encode (decode' a) == a
encode-decode' a =
transport Codes (merid A a β ! (merid A e)) e
=β¨ trans-β {B = Codes} (merid A a) (! (merid A e)) e β©
transport Codes (! (merid A e)) (transport Codes (merid A a) e)
=β¨ transport-Codes-mer a e β ΞΌ-e a
|in-ctx (Ξ» w β transport Codes (! (merid A e)) w) β©
transport Codes (! (merid A e)) a
=β¨ transport-Codes-mer-e-! a β©
a β
abstract
homomorphism : (a a' : A)
β Path {A = Trunc β¨ 1 β© (north A == south A)}
[ merid A (ΞΌ a a' ) ] [ merid A a' β ! (merid A e) β merid A a ]
homomorphism = WedgeExt.ext args
where
args : WedgeExt.args {aβ = e} {bβ = e}
args = record {m = β¨-2β©; n = β¨-2β©; cA = cA; cB = cA;
P = Ξ» a a' β (_ , Trunc-level {n = β¨ 1 β©} _ _);
f = Ξ» a β ap [_] $
merid A (ΞΌ a e)
=β¨ ap (merid A) (ΞΌ-e a) β©
merid A a
=β¨ ap (Ξ» w β w β merid A a) (! (!-inv-r (merid A e)))
β β-assoc (merid A e) (! (merid A e)) (merid A a) β©
merid A e β ! (merid A e) β merid A a β;
g = Ξ» a' β ap [_] $
merid A (ΞΌ e a')
=β¨ ap (merid A) (ΞΌe- a') β©
merid A a'
=β¨ ! (β-unit-r (merid A a'))
β ap (Ξ» w β merid A a' β w) (! (!-inv-l (merid A e))) β©
merid A a' β ! (merid A e) β merid A e β ;
p = ap (Ξ» {(pβ , pβ) β ap [_] $
merid A (ΞΌ e e) =β¨ pβ β©
merid A e =β¨ pβ β©
merid A e β ! (merid A e) β merid A e β})
(pairΓ= (ap (Ξ» x β ap (merid A) x) (! ΞΌcoh)) (coh (merid A e)))}
where coh : {B : Type i} {b b' : B} (p : b == b')
β ap (Ξ» w β w β p) (! (!-inv-r p)) β β-assoc p (! p) p
== ! (β-unit-r p) β ap (Ξ» w β p β w) (! (!-inv-l p))
coh idp = idp
decode : {x : Suspension A} β Codes x β P x
decode {x} = Suspension-elim A {P = Ξ» x β Codes x β P x}
decode'
(Ξ» a β [ merid A a ])
(Ξ» a β β-β-from-transp (Ξ»= $ STS a))
x
where
abstract
STS : (a a' : A) β transport P (merid A a) (decode' a')
== [ merid A (transport Codes (merid A a) a') ]
STS a a' =
transport P (merid A a) [ merid A a' β ! (merid A e) ]
=β¨ transport-Trunc (Ξ» x β north A == x) (merid A a) _ β©
[ transport (Ξ» x β north A == x) (merid A a) (merid A a' β ! (merid A e)) ]
=β¨ ap [_] (trans-pathfrom {A = Suspension A} (merid A a) _) β©
[ (merid A a' β ! (merid A e)) β merid A a ]
=β¨ ap [_] (β-assoc (merid A a') (! (merid A e)) (merid A a)) β©
[ merid A a' β ! (merid A e) β merid A a ]
=β¨ ! (homomorphism a a') β©
[ merid A (ΞΌ a a') ]
=β¨ ap ([_] β merid A) (! (transport-Codes-mer a a')) β©
[ merid A (transport Codes (merid A a) a') ] β
abstract
decode-encode : {x : Suspension A} (tΞ± : P x)
β decode {x} (encode {x} tΞ±) == tΞ±
decode-encode {x} = Trunc-elim
{P = Ξ» tΞ± β decode {x} (encode {x} tΞ±) == tΞ±}
(Ξ» _ β =-preserves-level β¨ 1 β© Trunc-level)
(J (Ξ» y p β decode {y} (encode {y} [ p ]) == [ p ])
(ap [_] (!-inv-r (merid A e))))
main-lemma-eqv : Trunc β¨ 1 β© (north A == north A) β A
main-lemma-eqv = equiv encode decode' encode-decode' decode-encode
βmain-lemma : βTrunc β¨ 1 β© (βΞ© (βSusp (A , e))) == (A , e)
βmain-lemma = βua main-lemma-eqv idp
abstract
main-lemma-iso : (t1 : 1 β 0) β
Ξ©^-Group 1 t1 (βTrunc β¨ 1 β© (βΞ© (βSusp (A , e)))) Trunc-level
βα΄³ Ξ©^-Group 1 t1 (βTrunc β¨ 1 β© (A , e)) Trunc-level
main-lemma-iso _ = (record {f = f; pres-comp = pres-comp} , ie)
where
h : fst (βTrunc β¨ 1 β© (βΞ© (βSusp (A , e)))
ββ βTrunc β¨ 1 β© (A , e))
h = (Ξ» x β [ encode x ]) , idp
f : Ξ© (βTrunc β¨ 1 β© (βΞ© (βSusp (A , e)))) β Ξ© (βTrunc β¨ 1 β© (A , e))
f = fst (ap^ 1 h)
pres-comp : (p q : Ξ©^ 1 (βTrunc β¨ 1 β© (βΞ© (βSusp (A , e)))))
β f (conc^ 1 (β-Sβ O _) p q) == conc^ 1 (β-Sβ O _) (f p) (f q)
pres-comp = ap^-conc^ 1 (β-Sβ O _) h
ie : is-equiv f
ie = is-equiv-ap^ 1 h (snd $ ((unTrunc-equiv A gA)β»ΒΉ βe main-lemma-eqv))
abstract
Οβ-Suspension : (t1 : 1 β 0) (t2 : 2 β 0)
β Ο 2 t2 (βSusp (A , e)) == Ο 1 t1 (A , e)
Οβ-Suspension t1 t2 =
Ο 2 t2 (βSusp (A , e))
=β¨ Ο-inner-iso 1 t1 t2 (βSusp (A , e)) β©
Ο 1 t1 (βΞ© (βSusp (A , e)))
=β¨ ! (Ο-Trunc-shift-iso 1 t1 (βΞ© (βSusp (A , e)))) β©
Ξ©^-Group 1 t1 (βTrunc β¨ 1 β© (βΞ© (βSusp (A , e)))) Trunc-level
=β¨ group-ua (main-lemma-iso t1) β©
Ξ©^-Group 1 t1 (βTrunc β¨ 1 β© (A , e)) Trunc-level
=β¨ Ο-Trunc-shift-iso 1 t1 (A , e) β©
Ο 1 t1 (A , e) β
|
import math
import numpy as np
import pandas as pd
from lmfit import Model
import datetime as dt
def get_rows(df, lookup, where):
df_temp = df[df[where].isin(lookup)]
df_temp = df_temp.reset_index(drop=True)
return df_temp
|
module Haskell.Prim.String where
open import Agda.Builtin.Char
open import Agda.Builtin.Unit
open import Agda.Builtin.FromString
import Agda.Builtin.String as Str
open import Haskell.Prim
open import Haskell.Prim.List
open import Haskell.Prim.Foldable
--------------------------------------------------
-- String
String = List Char
instance
iIsStringString : IsString String
iIsStringString .IsString.Constraint _ = β€
iIsStringString .fromString s = Str.primStringToList s
private
cons : Char β List String β List String
cons c [] = (c β· []) β· []
cons c (s β· ss) = (c β· s) β· ss
lines : String β List String
lines [] = []
lines ('\n' β· s) = [] β· lines s
lines (c β· s) = cons c (lines s)
private
mutual
space : String β List String
space [] = []
space (c β· s) = if primIsSpace c then space s else cons c (word s)
word : String β List String
word [] = []
word (c β· s) = if primIsSpace c then [] β· space s else cons c (word s)
words : String β List String
words [] = []
words s@(c β· sβ) = if primIsSpace c then space sβ else word s
unlines : List String β String
unlines = concatMap (_++ "\n")
unwords : List String β String
unwords [] = ""
unwords (w β· []) = w
unwords (w β· ws) = w ++ ' ' β· unwords ws
|
import AI.HNN.FF.Network
import Numeric.LinearAlgebra
samples :: Samples Double
samples = [
(fromList [ 1, 1, 1, 1, 1
, 0, 0, 0, 0, 1
, 0, 0, 1, 1, 1
, 0, 0, 0, 0, 1
, 1, 1, 1, 1, 1 ], fromList [1]), -- three
(fromList [ 1, 1, 1, 1, 1
, 0, 0, 0, 0, 1
, 1, 1, 1, 1, 1
, 0, 0, 0, 0, 1
, 1, 1, 1, 1, 1 ], fromList [1]), -- three
(fromList [ 0, 1, 1, 1, 1
, 0, 0, 0, 0, 1
, 0, 0, 0, 1, 1
, 0, 0, 0, 0, 1
, 0, 1, 1, 1, 1 ], fromList [1]), -- three
(fromList [ 1, 1, 1, 1, 1
, 1, 0, 0, 0, 1
, 1, 0, 0, 0, 1
, 1, 0, 0, 0, 1
, 1, 1, 1, 1, 1 ], fromList [0]), -- not a three
(fromList [ 1, 1, 1, 1, 1
, 1, 0, 0, 0, 0
, 1, 0, 0, 0, 0
, 1, 0, 0, 0, 0
, 1, 0, 0, 0, 0 ], fromList [0]), -- not a three
(fromList [ 0, 1, 1, 1, 0
, 0, 1, 0, 1, 0
, 0, 1, 1, 1, 0
, 0, 1, 0, 1, 0
, 0, 1, 1, 1, 0 ], fromList [0]), -- not a three
(fromList [ 0, 0, 1, 0, 0
, 0, 1, 1, 0, 0
, 1, 0, 1, 0, 0
, 0, 0, 1, 0, 0
, 0, 0, 1, 0, 0 ], fromList [0]) ] -- not a three
main :: IO ()
main = do
n <- createNetwork 25 [250] 1
let n' = trainNTimes 10000 0.5 tanh tanh' n samples
mapM_ (print . output n' tanh . fst) samples
putStrLn "-------------"
print . output n' tanh $ testInput
where testInput = fromList [ 0, 0, 1, 1, 1
, 0, 0, 0, 0, 1
, 0, 0, 1, 1, 1
, 0, 0, 0, 0, 1
, 0, 0, 1, 1, 1 ]
{-
OUTPUT:
fromList [0.9996325368507625]
fromList [0.9997784075859734]
fromList [0.9996165887689248]
fromList [-2.8107935971909852e-2]
fromList [7.001808876464477e-3]
fromList [2.54989546107178e-2]
fromList [5.286805464313172e-4]
-------------
fromList [0.9993713524712442]
-}
|
State Before: Ξ± Ξ² : Type u
c : Cardinal
h : c < β΅β
β’ β(βtoNat c) = c State After: no goals Tactic: rw [toNat_apply_of_lt_aleph0 h, β Classical.choose_spec (lt_aleph0.1 h)] |
{-# OPTIONS --without-K #-}
{-
Imports everything that is not imported by something else.
This is not supposed to be used anywhere, this is just a simple way to
do `make all'
This file is intentionally named index.agda so that
Agda will generate index.html.
-}
module index where
-- import Spaces.IntervalProps
-- import Algebra.F2NotCommutative
import homotopy.LoopSpaceCircle
import homotopy.HopfJunior
import homotopy.Hopf
import homotopy.CoverClassification
import homotopy.AnyUniversalCoverIsPathSet
import homotopy.PathSetIsInital
-- import Spaces.LoopSpaceDecidableWedgeCircles
-- import Homotopy.PullbackIsPullback
-- import Homotopy.PushoutIsPushout
-- import Homotopy.Truncation
-- import Sets.QuotientUP
-- import Spaces.PikSn
-- import Homotopy.VanKampen
|
theory Networks_Impl_Refine
imports
TA_Impl.Normalized_Zone_Semantics_Impl_Refine Networks_Impl TA_Impl.TA_Impl_Misc
begin
unbundle no_library_syntax
(* XXX Rename this way *)
lemmas mem_nth = aux
locale Network_Reachability_Problem_precompiled_defs' =
Network_Reachability_Problem_precompiled_defs +
fixes na :: nat
begin
text \<open>Definition of implementation auxiliaries (later connected to the automaton via proof)\<close>
(*
definition
"trans_i_map \<equiv>
map (map (map (\<lambda> (g, a, r, l').
case a of Sil a \<Rightarrow> (g, a, r, l')) o filter (\<lambda> (g, a, r, l').
case a of Sil a \<Rightarrow> True | _ \<Rightarrow> False))) trans"
*)
definition
"trans_i_map =
map (map (List.map_filter
(\<lambda> (g, (a, b), r, l'). case a of Sil a \<Rightarrow> Some (g, (a, b), r, l') | _ \<Rightarrow> None)
)) trans"
definition
"trans_in_map \<equiv>
map (map (map
(\<lambda> (g, (a, b), r, l'). case a of In a \<Rightarrow> (g, (a, b), r, l')) o filter (\<lambda> (g, (a, b), r, l').
case a of In a \<Rightarrow> True | _ \<Rightarrow> False))
) trans"
definition
"trans_out_map \<equiv>
map (map (map
(\<lambda> (g, (a, b), r, l'). case a of Out a \<Rightarrow> (g, (a, b), r, l')) o filter (\<lambda> (g, (a, b), r, l').
case a of Out a \<Rightarrow> True | _ \<Rightarrow> False))
) trans"
abbreviation
"nested_list_to_iarray xs \<equiv> IArray (map IArray xs)"
(* XXX Optimize by using a better data structure? *)
definition
"actions_by_state i \<equiv> fold (\<lambda> t acc. acc[fst (fst (snd t)) := (i, t) # (acc ! fst (fst (snd t)))])"
definition
"all_actions_by_state t L \<equiv>
fold (\<lambda> i. actions_by_state i (t !! i !! (L ! i))) [0..<p] (repeat [] na)"
definition
"pairs_by_action L OUT \<equiv> concat o
map (\<lambda> (i, g1, (a, b1), r1, l1). List.map_filter
(\<lambda> (j, g2, (_, b2), r2, l2).
if i \<noteq> j then Some (g1 @ g2, (a, Syn b1 b2), r1 @ r2, L[i := l1, j := l2]) else None)
OUT)"
definition
"trans_s_fun L \<equiv>
let
In = all_actions_by_state (nested_list_to_iarray trans_in_map) L;
Out = all_actions_by_state (nested_list_to_iarray trans_out_map) L
in
concat (map (\<lambda> a. pairs_by_action L (Out ! a) (In ! a)) [0..<na])
"
definition
"trans_i_from L i \<equiv>
map (\<lambda> (g, (a, b), r, l'). (g, (a, Act b), r, L[i := l']))
((IArray (map IArray trans_i_map)) !! i !! (L ! i))"
definition
"trans_i_fun L \<equiv> concat (map (trans_i_from L) [0..<p])"
definition
"trans_fun L \<equiv> trans_s_fun L @ trans_i_fun L"
lemma trans_i_fun_trans_fun:
assumes "(g, a, r, L') \<in> set (trans_i_fun L)"
shows "(g, a, r, L') \<in> set (trans_fun L)"
using assms unfolding trans_fun_def by auto
lemma trans_s_fun_trans_fun:
assumes "(g, a, r, L') \<in> set (trans_s_fun L)"
shows "(g, a, r, L') \<in> set (trans_fun L)"
using assms unfolding trans_fun_def by auto
end (* End of locale for implementation definitions *)
context Product_TA_Defs
begin
lemma state_set_states:
"state_set (trans_of product_ta) \<subseteq> states"
unfolding state_set_def trans_of_def product_trans_def states_def
product_trans_def product_ta_def product_trans_i_def product_trans_s_def
apply auto
apply blast
apply blast
apply (subst list_update_nth_split)
apply simp
apply force
apply (subst list_update_nth_split)
apply (simp; fail)
apply safe
apply (simp add: Network_Reachability_Problem_precompiled_defs.N_def)
apply force
apply (subst list_update_nth_split)
apply (simp add: Network_Reachability_Problem_precompiled_defs.N_def)
apply force
done
end
locale Network_Reachability_Problem_precompiled' =
Network_Reachability_Problem_precompiled +
Network_Reachability_Problem_precompiled_defs' +
assumes action_set:
"\<forall> T \<in> set trans. \<forall> xs \<in> set T. \<forall> (_, (a, _), _, _) \<in> set xs. pred_act (\<lambda> a. a < na) a"
begin
sublocale Defs: Reachability_Problem_Impl_Defs A init "PR_CONST F" m by standard
lemma states_n:
"product.states \<subseteq> {xs. length xs = p \<and> set xs \<subseteq> {0..<n}}"
unfolding product.states_def
apply simp
unfolding N_def trans_of_def T_def
using state_set trans_length apply safe
apply (drule aux)
apply safe
using state_set
apply clarsimp
apply rotate_tac
subgoal for x i
apply (erule ballE[where x = i])
apply auto
unfolding process_length(2)[symmetric]
by (force dest: nth_mem) (* XXX Slow *)
done
lemma state_set_n:
"state_set (trans_of A) \<subseteq> {xs. length xs = p \<and> set xs \<subseteq> {0..<n}}"
using states_n product.state_set_states by blast
lemma T_T:
"product.T = map T [0..<p]"
unfolding T_def trans_of_def N_def by auto
lemma states_length_p:
assumes "l \<in> product.states"
shows "length l = p"
using assms length_N product.states_length by simp
lemma trans_length_simp[simp]:
assumes "i < p"
shows "length (trans ! i) = n"
using assms trans_length process_length by (auto dest: nth_mem)
lemma in_trans_in_mapI:
assumes
"q < p" "l < n" "i < length (trans ! q ! l)"
"(g1, (In a, b), r1, l1') = trans ! q ! l ! i"
shows "(g1, (a, b), r1, l1') \<in> set (IArray (map IArray trans_in_map) !! q !! l)"
using assms process_length(2) trans_length unfolding trans_in_map_def
by (force dest: nth_mem intro!: image_eqI[where x = "(g1, (In a, b), r1, l1')"])
lemma in_trans_out_mapI:
assumes
"q < p" "l < n" "i < length (trans ! q ! l)"
"(g1, (Out a, b), r1, l1') = trans ! q ! l ! i"
shows "(g1, (a, b), r1, l1') \<in> set (IArray (map IArray trans_out_map) !! q !! l)"
using assms process_length(2) trans_length unfolding trans_out_map_def
by (force dest: nth_mem intro!: image_eqI[where x = "(g1, (Out a, b), r1, l1')"])
lemma in_trans_in_mapD:
assumes
"(g1, (a, b), r1, l1') \<in> set (IArray (map IArray trans_in_map) !! q !! l)"
"q < p" "l < n"
obtains i where
"i < length (trans ! q ! l) \<and> (g1, (In a, b), r1, l1') = trans ! q ! l ! i"
using assms process_length(2) unfolding trans_in_map_def
by (fastforce dest: mem_nth split: act.split_asm)
(* XXX Remove duplication *)
lemma in_trans_out_mapD:
assumes
"(g1, (a, b), r1, l1') \<in> set (IArray (map IArray trans_out_map) !! q !! l)"
"q < p" "l < n"
obtains i where
"i < length (trans ! q ! l) \<and> (g1, (Out a, b), r1, l1') = trans ! q ! l ! i"
using assms process_length(2) unfolding trans_out_map_def
by (fastforce dest: mem_nth split: act.split_asm)
lemma in_actions_by_stateI:
assumes
"(g1, (a, b), r1, l1') \<in> set xs" "a < length acc"
shows
"(q, g1, (a, b), r1, l1') \<in> set (actions_by_state q xs acc ! a)
\<and> a < length (actions_by_state q xs acc)"
using assms unfolding actions_by_state_def
apply (induction xs arbitrary: acc)
apply (simp; fail)
apply simp
apply (erule disjE)
apply (rule fold_acc_preserv
[where P = "\<lambda> acc. (q, g1, (a, b), r1, l1') \<in> set (acc ! a) \<and> a < length acc"]
)
apply (subst list_update_nth_split; auto)
by auto
lemma in_actions_by_state_preserv:
assumes
"(q, g1, (a, b), r1, l1') \<in> set (acc ! a)" "a < length acc"
shows
"(q, g1, (a, b), r1, l1') \<in> set (actions_by_state y xs acc ! a)
\<and> a < length (actions_by_state y xs acc)"
using assms unfolding actions_by_state_def
apply -
apply (rule fold_acc_preserv
[where P = "\<lambda> acc. (q, g1, (a, b), r1, l1') \<in> set (acc ! a) \<and> a < length acc"]
)
apply (subst list_update_nth_split; auto)
by auto
lemma length_actions_by_state_preserv[simp]:
shows "length (actions_by_state y xs acc) = length acc"
unfolding actions_by_state_def by (auto intro: fold_acc_preserv simp: list_update_nth_split)
lemma in_all_actions_by_stateI:
assumes
"a < na" "q < p" "L ! q < n" "(g1, (a, b), r1, l1') \<in> set (M !! q !! (L ! q))"
shows
"(q, g1, (a, b), r1, l1') \<in> set (all_actions_by_state M L ! a)"
unfolding all_actions_by_state_def
apply (rule fold_acc_ev_preserv
[where P = "\<lambda> acc. (q, g1, (a, b), r1, l1') \<in> set (acc ! a)" and Q = "\<lambda> acc. a < length acc",
THEN conjunct1]
)
apply (rule in_actions_by_state_preserv[THEN conjunct1])
using assms by (auto intro: in_actions_by_stateI[THEN conjunct1])
lemma actions_by_state_inj:
assumes "j < length acc"
shows "\<forall> (q, a) \<in> set (actions_by_state i xs acc ! j). (q, a) \<notin> set (acc ! j) \<longrightarrow> i = q"
unfolding actions_by_state_def
apply (rule fold_acc_preserv
[where P =
"\<lambda> acc'. (\<forall> (q, a) \<in> set (acc' ! j). (q, a) \<notin> set (acc ! j) \<longrightarrow> i = q) \<and> j < length acc'",
THEN conjunct1])
subgoal for x acc
by (cases "fst (fst (snd x)) = j"; simp)
using assms by auto
lemma actions_by_state_inj':
assumes "j < length acc" "(q, a) \<notin> set (acc ! j)" "(q, a) \<in> set (actions_by_state i xs acc ! j)"
shows "i = q"
using actions_by_state_inj[OF assms(1)] assms(2-) by fast
lemma in_actions_by_stateD:
assumes
"(q, g, (a, b), t) \<in> set (actions_by_state i xs acc ! j)" "(q, g, (a, b), t) \<notin> set (acc ! j)"
"j < length acc"
shows
"(g, (a, b), t) \<in> set xs \<and> j = a"
using assms unfolding actions_by_state_def
apply -
apply (drule fold_evD
[where y = "(g, (a, b), t)" and Q = "\<lambda> acc'. length acc' = length acc"
and R = "\<lambda> (_, (a', _), t). a' = j"]
)
apply assumption
(* XXX Define asm split rule *)
apply (subst (asm) list_update_nth_split[of j]; force)
apply simp+
apply (subst (asm) list_update_nth_split[of j]; force)
by auto
lemma in_all_actions_by_stateD:
assumes
"(q, g1, (a, b), r1, l1') \<in> set (all_actions_by_state M L ! a')" "a' < na"
shows
"(g1, (a, b), r1, l1') \<in> set (M !! q !! (L ! q)) \<and> q < p \<and> a' = a"
using assms
unfolding all_actions_by_state_def
apply -
apply (drule fold_evD''[where y = q and Q = "\<lambda> acc. length acc = na"])
apply (simp; fail)
apply (drule actions_by_state_inj'[rotated])
apply (simp; fail)+
apply safe
apply (drule in_actions_by_stateD)
apply assumption
apply (rule fold_acc_preserv)
apply (simp; fail)+
subgoal premises prems
proof -
from prems(2) have "q \<in> set [0..<p]" by auto
then show ?thesis by simp
qed
by (auto intro: fold_acc_preserv dest!: in_actions_by_stateD)
lemma length_all_actions_by_state_preserv:
"length (all_actions_by_state M L) = na"
unfolding all_actions_by_state_def by (auto intro: fold_acc_preserv)
lemma less_naI:
assumes
"q < p"
"(g1, (In a, b), r1, l1') = trans ! q ! l ! j"
"l < n"
"j < length (trans ! q ! l)"
shows "a < na"
using action_set assms process_length(2) trans_length by (force dest!: nth_mem)
lemma in_actions_trans_in_mapI:
assumes
"pa < p"
"(g1, (In a, b), r1, l1') = trans ! pa ! (L ! pa) ! j"
"L ! pa < n"
"j < length (trans ! pa ! (L ! pa))"
shows "(pa, g1, (a, b), r1, l1') \<in> set (all_actions_by_state (IArray (map IArray trans_in_map)) L ! a)"
apply (rule in_all_actions_by_stateI)
using assms action_set process_length(2) trans_length apply (fastforce dest!: nth_mem)
using assms by (fastforce intro: in_trans_in_mapI)+
lemma in_actions_trans_out_mapI:
assumes
"pa < p"
"(g1, (Out a, b), r1, l1') = trans ! pa ! (L ! pa) ! j"
"L ! pa < n"
"j < length (trans ! pa ! (L ! pa))"
shows "(pa, g1, (a, b), r1, l1') \<in> set (all_actions_by_state (IArray (map IArray trans_out_map)) L ! a)"
apply (rule in_all_actions_by_stateI)
using assms action_set process_length(2) trans_length apply (fastforce dest!: nth_mem)
using assms by (fastforce intro: in_trans_out_mapI)+
lemma in_pairs_by_actionI:
assumes
"pa \<noteq> q"
"(pa, g1, (a, b1), r1, l1') \<in> set ys"
"(q, g2, (a, b2), r2, l2') \<in> set xs"
shows "(g1 @ g2, (a, Syn b1 b2), r1 @ r2, L[pa := l1', q := l2']) \<in> set (pairs_by_action L xs ys)"
using assms
unfolding pairs_by_action_def
apply clarsimp
apply (rule bexI[rotated], assumption)
by (force simp: set_map_filter)+
lemma in_pairs_by_actionD:
assumes
"(g, (a, b), r, L') \<in> set (pairs_by_action L xs ys)"
"\<forall> (q, g, (a'', b), r, L') \<in> set xs. a'' = a'"
"\<forall> (q, g, (a'', n), r, L') \<in> set ys. a'' = a'"
obtains pa q g1 g2 b1 b2 r1 r2 l1' l2' where
"pa \<noteq> q"
"(pa, g1, (a, b1), r1, l1') \<in> set ys"
"(q, g2, (a, b2), r2, l2') \<in> set xs"
"L' = L[pa := l1', q := l2']"
"g = g1 @ g2" "b = Syn b1 b2" "r = r1 @ r2"
proof -
from assms(1) obtain pa q g1 g2 b1 b2 r1 r2 l1' l2' where
"(q, g1, (a, b1), r1, l1') \<in> set ys" "(pa, g2, (a, b2), r2, l2') \<in> set xs" "pa \<noteq> q"
"Some (g1 @ g2, a, Syn b1 b2, r1 @ r2, L[q := l1', pa := l2']) = Some (g, a, b, r, L')"
unfolding pairs_by_action_def using assms(2,3) by (force split: if_split_asm simp: set_map_filter)
then show ?thesis by - (rule that; auto)
qed
lemma in_trans_funD:
assumes "y \<in> set (trans_fun L)"
shows "y \<in> set (trans_s_fun L) \<or> y \<in> set (trans_i_fun L)"
using assms unfolding trans_fun_def by auto
lemma states_len[intro]:
assumes
"q < p" "L \<in> product.states"
shows
"L ! q < n"
using assms states_n by (force dest: nth_mem)
lemma trans_fun_trans_of':
"(trans_fun, trans_of A) \<in> transition_rel (product.states)"
unfolding transition_rel_def T_def
apply simp
apply rule
unfolding trans_of_def
apply safe
subgoal for L g a b r L'
unfolding product.product_ta_def product.product_trans_def
apply simp
apply safe
subgoal
apply (rule trans_i_fun_trans_fun)
unfolding product.product_trans_i_def
apply safe
unfolding T_T T_def states_length_p
apply clarsimp
(* Could be a lemma from here *)
unfolding trans_fun_def trans_i_fun_def trans_i_from_def trans_i_map_def
apply clarsimp
apply (rule bexI)
prefer 2
apply simp
using process_length(2)
apply simp
apply (drule nth_mem)
subgoal premises prems for pa b l' j
proof -
have "(g, (Sil a, b), r, l') \<in> set (trans ! pa ! (L ! pa))" using prems by auto
then show ?thesis by (force simp: set_map_filter)
qed
done
subgoal
apply (rule trans_s_fun_trans_fun)
unfolding product.product_trans_s_def
apply safe
unfolding T_T T_def states_length_p
apply clarsimp
(* Could be a lemma from here *)
unfolding trans_s_fun_def
apply clarsimp
by (fastforce intro: less_naI in_actions_trans_out_mapI in_actions_trans_in_mapI in_pairs_by_actionI)
done
subgoal for L g a b r L'
apply (drule in_trans_funD)
apply (erule disjE)
unfolding product.product_ta_def product.product_trans_def
apply simp
apply (rule disjI2)
subgoal
unfolding product.product_trans_s_def
apply safe
unfolding T_T T_def states_length_p
apply simp
unfolding trans_s_fun_def
apply clarsimp
subgoal for x
apply (erule in_pairs_by_actionD[where a' = x])
apply (auto dest: in_all_actions_by_stateD; fail)
apply (auto dest: in_all_actions_by_stateD; fail)
apply (drule in_all_actions_by_stateD, assumption)
apply (drule in_all_actions_by_stateD, assumption)
apply safe
apply (erule in_trans_in_mapD)
apply simp
apply blast
apply (erule in_trans_out_mapD)
apply blast
apply blast
by (fastforce simp: states_length_p)
done
subgoal
apply simp
apply (rule disjI1)
unfolding product.product_trans_i_def
unfolding T_T T_def trans_i_fun_def trans_i_from_def trans_i_map_def
using trans_length process_length(2) states_len
apply (clarsimp simp: set_map_filter states_length_p)
by (force split: act.split_asm dest!: mem_nth) (* XXX Slow *)
done
done
lemma trans_fun_trans_of[intro, simp]:
"(trans_fun, trans_of A) \<in> transition_rel Defs.states"
using trans_fun_trans_of' product.state_set_states init_states
unfolding state_set_def transition_rel_def T_def by blast
definition "inv_fun L \<equiv> concat (map (\<lambda> i. IArray (map IArray inv) !! i !! (L ! i)) [0..<p])"
lemma I_I:
"product.I = map I [0..<p]"
unfolding I_def inv_of_def N_def by auto
lemma inv_fun_inv_of[intro, simp]:
"(inv_fun, inv_of A) \<in> inv_rel Defs.states"
unfolding inv_rel_def state_set_def apply clarsimp
using product.state_set_states process_length(1) n_gt_0
unfolding inv_fun_def product.product_invariant_def I_I init_def
by - (rule arg_cong[where f = concat]; force simp add: states_length_p I_def)
definition "final_fun L = list_ex (\<lambda> i. List.member (final ! i) (L ! i)) [0..<p]"
term list_ex term List.member
term local.F
lemma final_fun_final[intro, simp]:
"(final_fun, F) \<in> inv_rel Defs.states"
using state_set_n
unfolding state_set_def init_def F_def final_fun_def inv_rel_def in_set_member[symmetric] list_ex_iff
by force
thm conj_ac(3)[symmetric]
lemma fst_clkp_set'D:
assumes "(c, d) \<in> clkp_set'"
shows "c > 0" "c \<le> m" "d \<in> range int"
using assms clock_set consts_nats unfolding Nats_def clk_set'_def by force+
lemma k_ceiling':
"\<forall>c\<in>{1..m}. k ! c = nat (Max ({d. (c, d) \<in> clkp_set'} \<union> {0}))"
using k_ceiling by auto (* XXX *)
lemma k_k'[intro]:
"map int k = default_ceiling.k'"
apply (rule nth_equalityI)
using k_length default_ceiling.length_k' apply (auto; fail)
unfolding default_ceiling.k'_def apply (simp add: clkp_set'_eq k_length default_ceiling_def del: upt_Suc)
using k_ceiling' k_ceiling(2) apply safe
subgoal for i by (cases "i = 0") auto
apply (frule fst_clkp_set'D(1))
apply clarsimp
apply (rule cong[of nat, OF HOL.refl])
apply (subst Max_insert)
using finite_clkp_set_A [[simproc add: finite_Collect]]
apply (auto intro: finite_Image simp: clkp_set'_eq; fail)
apply (auto; fail)
subgoal for i
using Max_in[of "{d. (i, d) \<in> clkp_set'}"] fst_clkp_set'D(3) finite_clkp_set_A
by (force intro: finite_Image simp: clkp_set'_eq)
done
lemma iarray_k'[intro]:
"(uncurry0 (return (IArray (map int k))), uncurry0 (RETURN default_ceiling.k'))
\<in> unit_assn\<^sup>k \<rightarrow>\<^sub>a iarray_assn"
unfolding br_def by sepref_to_hoare sep_auto
lemma init_has_trans:
"init \<in> fst ` (trans_of A) \<longleftrightarrow> trans_fun init \<noteq> []"
apply standard
using trans_fun_trans_of unfolding transition_rel_def apply force
using trans_fun_trans_of' init_states unfolding transition_rel_def by fast
lemma
assumes "init \<in> fst ` (trans_of A)"
shows "init \<in> state_set (trans_of A)"
using assms by (rule UnI1)
end (* End of locale assuming specific format for actions *)
ML \<open>
fun pull_let u t =
let
val t1 = abstract_over (u, t);
val r1 = Const (@{const_name "HOL.Let"}, dummyT) $ u $ Abs ("I", dummyT, t1);
val ct1 = Syntax.check_term @{context} r1;
val g1 =
Goal.prove @{context} [] [] (Logic.mk_equals (t, ct1))
(fn {context, ...} => EqSubst.eqsubst_tac context [0] [@{thm Let_def}] 1
THEN resolve_tac context [@{thm Pure.reflexive}] 1)
in g1 end;
fun get_rhs thm =
let
val Const ("Pure.eq", _) $ _ $ r = Thm.full_prop_of thm
in r end;
fun get_lhs thm =
let
val Const ("Pure.imp", _) $ (Const ("Pure.eq", _) $ l $ _) $ _ = Thm.full_prop_of thm
in l end;
fun pull_tac' u ctxt thm =
let
val l = get_lhs thm;
val rewr = pull_let u l;
in Local_Defs.unfold_tac ctxt [rewr] thm end;
fun pull_tac u ctxt = SELECT_GOAL (pull_tac' u ctxt) 1;
\<close>
context Network_Reachability_Problem_precompiled'
begin
sublocale
Reachability_Problem_Impl
trans_fun inv_fun final_fun "IArray k" A init "PR_CONST F" m "default_ceiling A"
unfolding PR_CONST_def by (standard; rule)
lemma length_states[intro, simp]:
"length L' = p" if "L' \<in> states"
using that product.state_set_states init_states states_length_p unfolding state_set_def by auto
(* XXX Unused *)
lemma length_reachable:
"length L' = p" if "default_ceiling.E\<^sup>*\<^sup>* default_ceiling.a\<^sub>0 (L', u)"
using that reachable_states unfolding default_ceiling.reachable_def by auto
lemma length_steps:
"length L' = p" if "conv_A A \<turnstile> \<langle>init, u\<rangle> \<rightarrow>* \<langle>L', u'\<rangle>" "\<forall>c\<in>{1..m}. u c = 0"
using that default_ceiling.reachable_decides_emptiness'[of L'] by (auto intro: length_reachable)
lemma F_reachable_correct':
"default_ceiling.F_reachable
\<longleftrightarrow> (\<exists> L' u u'.
conv_A A \<turnstile> \<langle>init, u\<rangle> \<rightarrow>* \<langle>L', u'\<rangle>
\<and> (\<forall> c \<in> {1..m}. u c = 0) \<and> (\<exists> i < length L'. L' ! i \<in> set (final ! i))
)"
unfolding default_ceiling.F_reachable_def default_ceiling.reachable_def
using default_ceiling.reachability_check unfolding F_def by auto
lemma F_reachable_correct'':
"default_ceiling.F_reachable
\<longleftrightarrow> (\<exists> L' u u'.
conv_A A \<turnstile> \<langle>init, u\<rangle> \<rightarrow>* \<langle>L', u'\<rangle>
\<and> (\<forall> c \<in> {1..m}. u c = 0) \<and> (\<exists> i < p. L' ! i \<in> set (final ! i))
)"
unfolding F_reachable_correct' using length_steps by metis
lemma product_invariant_conv:
"product'.product_invariant = conv_cc o product.product_invariant"
unfolding product'.product_invariant_def product.product_invariant_def
apply clarsimp
apply (rule ext)
apply (simp add: map_concat)
apply(tactic \<open>Cong_Tac.cong_tac @{context} @{thm cong} 1\<close>)
apply simp
by (simp add: inv_of_def split: prod.split)
lemma product_trans_i_conv:
"product'.product_trans_i = conv_t ` product.product_trans_i"
unfolding product'.product_trans_i_def product.product_trans_i_def
apply clarsimp
apply safe
unfolding T_T
apply (subst (asm) (2) N_def)
apply (force simp add: states_length_p trans_of_def image_Collect)
(* XXX Use tactic here *)
by (force simp: trans_of_def N_def states_length_p)
lemma product_trans_t_conv:
"product'.product_trans_s = conv_t ` product.product_trans_s"
unfolding product'.product_trans_s_def product.product_trans_s_def
apply clarsimp
apply safe
unfolding T_T
apply (subst (asm) (2) N_def)
apply (subst (asm) (2) N_def)
apply simp
apply (simp add: states_length_p trans_of_def image_Collect)
apply (simp only: ex_simps[symmetric])
apply (tactic \<open>rotate_ex_tac @{context} 1\<close>)
apply (fastforce simp add: states_length_p)
apply (simp add: states_length_p trans_of_def image_Collect N_def del: ex_simps)
apply (tactic \<open>rearrange_ex_tac @{context} 1\<close>)
apply (simp only: ex_simps)
apply (rule, rule, assumption)
apply (simp only: ex_simps[symmetric])
apply (tactic \<open>rearrange_ex_tac @{context} 1\<close>)
apply simp
apply (rule, rule, assumption, rule, assumption)
apply (rule exI, rule exI, rule conjI, rule HOL.refl)+
by force
lemma product_trans_conv:
"product'.product_trans = conv_t ` product.product_trans"
unfolding product'.product_trans_def product.product_trans_def
unfolding product_trans_t_conv product_trans_i_conv image_Un ..
lemma product_conv: "product'.product_ta = conv_A A"
unfolding product'.product_ta_def product.product_ta_def
unfolding product_trans_conv product_invariant_conv
by simp
lemma F_reachable_correct:
"default_ceiling.F_reachable
\<longleftrightarrow> (\<exists> L' u u'.
map conv_A N \<turnstile>\<^sub>N \<langle>init, u\<rangle> \<rightarrow>* \<langle>L', u'\<rangle>
\<and> (\<forall> c \<in> {1..m}. u c = 0) \<and> (\<exists> i < p. L' ! i \<in> set (final ! i))
)"
unfolding F_reachable_correct'' product'.product_correct[symmetric] product_conv ..
definition
"reachability_checker \<equiv> worklist_algo2 subsumes_impl a\<^sub>0_impl F_impl succs_impl"
theorem reachability_check:
"(uncurry0 reachability_checker,
uncurry0 (
RETURN (\<exists> L' u u'.
map conv_A N \<turnstile>\<^sub>N \<langle>init, u\<rangle> \<rightarrow>* \<langle>L', u'\<rangle>
\<and> (\<forall> c \<in> {1..m}. u c = 0) \<and> (\<exists> i < p. L' ! i \<in> set (final ! i)))
)
)
\<in> unit_assn\<^sup>k \<rightarrow>\<^sub>a bool_assn"
using hnr_F_reachable unfolding reachability_checker_def F_reachable_correct .
corollary reachability_checker_hoare:
"<emp> reachability_checker
<\<lambda> r. \<up>(r \<longleftrightarrow> (\<exists> L' u u'.
map conv_A N \<turnstile>\<^sub>N \<langle>init, u\<rangle> \<rightarrow>* \<langle>L', u'\<rangle>
\<and> (\<forall> c \<in> {1..m}. u c = 0) \<and> (\<exists> i < p. L' ! i \<in> set (final ! i)))
)
>\<^sub>t"
apply (rule cons_post_rule)
using reachability_check[to_hnr] apply (simp add: hn_refine_def)
by (sep_auto simp: pure_def)
subsubsection \<open>Post-processing\<close>
schematic_goal succs_impl_alt_def:
"succs_impl \<equiv> ?impl"
unfolding succs_impl_def
apply (tactic \<open>pull_tac @{term "IArray (map int k)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "inv_fun"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "trans_fun"} @{context}\<close>)
unfolding inv_fun_def[abs_def] trans_fun_def[abs_def] trans_s_fun_def trans_i_fun_def trans_i_from_def
apply (tactic \<open>pull_tac @{term "IArray (map IArray inv)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "IArray (map IArray trans_out_map)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "IArray (map IArray trans_in_map)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "IArray (map IArray trans_i_map)"} @{context}\<close>)
by (rule Pure.reflexive)
thm trans_s_fun_def
lemma reachability_checker_alt_def':
"reachability_checker \<equiv>
let
sub = subsumes_impl;
start = a\<^sub>0_impl;
final = F_impl;
succs = succs_impl
in worklist_algo2 sub start final succs"
unfolding reachability_checker_def by simp
schematic_goal reachability_checker_alt_def:
"reachability_checker \<equiv> ?impl"
unfolding reachability_checker_alt_def' succs_impl_def
(*apply (tactic \<open>pull_tac @{term "IArray (map IArray inv)"} @{context}\<close>) *)
apply (tactic \<open>pull_tac @{term "IArray (map int k)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "inv_fun"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "trans_fun"} @{context}\<close>)
unfolding inv_fun_def trans_fun_def trans_s_fun_def trans_i_fun_def trans_i_from_def
apply (tactic \<open>pull_tac @{term "IArray (map IArray inv)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "IArray (map IArray trans_out_map)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "IArray (map IArray trans_in_map)"} @{context}\<close>)
apply (tactic \<open>pull_tac @{term "IArray (map IArray trans_i_map)"} @{context}\<close>)
unfolding init_dbm_impl_def a\<^sub>0_impl_def
unfolding F_impl_def
unfolding final_fun_def[abs_def]
unfolding subsumes_impl_def
by (rule Pure.reflexive)
end (* End of locale *)
(* XXX Move *)
lemma bex_n_simp:
"(\<exists> x \<in> set [0..<n]. P x) \<longleftrightarrow> (\<exists> x < n. P x)"
by auto
(* XXX Move *)
lemma ball_n_simp:
"(\<forall> x \<in> set [0..<n]. P x) \<longleftrightarrow> (\<forall> x < n. P x)"
by auto
subsection \<open>Check preconditions\<close>
context Network_Reachability_Problem_precompiled_defs
begin
abbreviation
"check_nat_subs \<equiv> \<forall> (_, d) \<in> clkp_set'. d \<ge> 0"
lemma check_nat_subs:
"check_nat_subs \<longleftrightarrow> snd ` clkp_set' \<subseteq> \<nat>"
unfolding Nats_def apply safe
subgoal for _ _ b using rangeI[of int "nat b"] by auto
by auto
definition
"check_pre \<equiv>
length inv = p \<and> length trans = p
\<and> (\<forall> I \<in> set inv. length I = n) \<and> (\<forall> T \<in> set trans. length T = n)
\<and> length k = m + 1 \<and> p > 0 \<and> m > 0 \<and> n > 0
\<and> (\<forall> q < p. trans ! q ! 0 \<noteq> [])
\<and> k ! 0 = 0 \<and> check_nat_subs \<and> clk_set' = {1..m}
\<and> (\<forall> T \<in> set trans. \<forall> xs \<in> set T. \<forall> (_, _, _, l) \<in> set xs. l < n)"
abbreviation
"check_k_in c \<equiv> k ! c = 0 \<or> (c, k ! c) \<in> clkp_set'"
definition
"check_ceiling \<equiv>
(\<forall> (c, d) \<in> clkp_set'. 0 < c \<and> c \<le> m \<longrightarrow> k ! c \<ge> d) \<and> (\<forall> c \<in> {1..m}. check_k_in c)"
lemma finite_clkp_set'[intro, simp]:
"finite clkp_set'"
unfolding clkp_set'_def by auto
lemma check_ceiling:
"check_ceiling \<longleftrightarrow> (\<forall> c \<in> {1..m}. k ! c = Max ({d. (c, d) \<in> clkp_set'} \<union> {0 :: int}))"
unfolding check_ceiling_def
proof (safe, goal_cases)
case prems: (1 c)
then show ?case
apply -
apply (rule HOL.sym)
apply (rule Max_eqI)
using [[simproc add: finite_Collect]] by (auto intro: finite_Image)
next
case prems: (2 a b)
then show ?case
apply simp
apply (rule Max_ge)
using [[simproc add: finite_Collect]] by (auto intro: finite_Image)
next
case prems: (3 c)
with Max_in[of "{d. (c, d) \<in> clkp_set'} \<union> {0}"] show ?case
using [[simproc add: finite_Collect]] by (force intro: finite_Image)
qed
definition
"check_trans_complete \<equiv>
(\<forall> q1 < p. \<forall> t1 \<in> T q1. case t1 of (l1, g1, In a, r1, l1')
\<Rightarrow> \<exists> q2 < p. \<exists> l2 g2 r2 l2'. q1 \<noteq> q2 \<and> (l2, g2, Out a, r2, l2') \<in> T q2 | _ \<Rightarrow> True)
\<and> (\<forall> q1 < p. \<forall> t1 \<in> T q1. case t1 of (l1, g1, Out a, r1, l1')
\<Rightarrow> \<exists> q2 < p. \<exists> l2 g2 r2 l2'. q1 \<noteq> q2 \<and> (l2, g2, In a, r2, l2') \<in> T q2 | _ \<Rightarrow> True)"
(* XXX Simplify proofs further up with this? *)
lemma T_alt_def:
"T i = {(l, t) | l t. l < n \<and> t \<in> set (trans ! i ! l)}"
unfolding T_def
apply safe
apply (force dest!: nth_mem)
by (force dest!: mem_nth)
lemma check_trans_1:
"(\<forall> q1 < p. \<forall> t1 \<in> T q1. case t1 of (l1, g1, In a, r1, l1')
\<Rightarrow> \<exists> q2 < p. \<exists> l2 g2 r2 l2'. q1 \<noteq> q2 \<and> (l2, g2, Out a, r2, l2') \<in> T q2 | _ \<Rightarrow> True)
\<longleftrightarrow>
list_all (\<lambda> q1. list_all (\<lambda> l. list_all (\<lambda> t1. case t1 of (g1, In a, r1, l1')
\<Rightarrow> list_ex (\<lambda> q2. q1 \<noteq> q2 \<and>
list_ex (\<lambda> l. list_ex (\<lambda> t. fst (snd t) = Out a) (trans ! q2 ! l)) [0..<n])
[0..<p]
| _ \<Rightarrow> True)
(trans ! q1 ! l))
[0..<n])
[0..<p]"
unfolding list_ex_iff list_all_iff T_alt_def bex_n_simp ball_n_simp
by (force split: act.split) (* XXX Slow *)
lemma check_trans_2:
"(\<forall> q1 < p. \<forall> t1 \<in> T q1. case t1 of (l1, g1, Out a, r1, l1')
\<Rightarrow> \<exists> q2 < p. \<exists> l2 g2 r2 l2'. q1 \<noteq> q2 \<and> (l2, g2, In a, r2, l2') \<in> T q2 | _ \<Rightarrow> True)
\<longleftrightarrow>
list_all (\<lambda> q1. list_all (\<lambda> l. list_all (\<lambda> t1. case t1 of (g1, Out a, r1, l1')
\<Rightarrow> list_ex (\<lambda> q2. q1 \<noteq> q2 \<and>
list_ex (\<lambda> l. list_ex (\<lambda> t. fst (snd t) = In a) (trans ! q2 ! l)) [0..<n])
[0..<p]
| _ \<Rightarrow> True)
(trans ! q1 ! l))
[0..<n])
[0..<p]"
unfolding list_ex_iff list_all_iff T_alt_def bex_n_simp ball_n_simp
by (force split: act.split) (* XXX Slow *)
lemma check_trans_complete_alt_def:
"check_trans_complete \<longleftrightarrow>
list_all (\<lambda> q1. list_all (\<lambda> l. list_all (\<lambda> t1. case t1 of (g1, In a, r1, l1')
\<Rightarrow> list_ex (\<lambda> q2. q1 \<noteq> q2 \<and>
list_ex (\<lambda> l. list_ex (\<lambda> t. fst (snd t) = Out a) (trans ! q2 ! l)) [0..<n])
[0..<p]
| _ \<Rightarrow> True)
(trans ! q1 ! l))
[0..<n])
[0..<p]
\<and> list_all (\<lambda> q1. list_all (\<lambda> l. list_all (\<lambda> t1. case t1 of (g1, Out a, r1, l1')
\<Rightarrow> list_ex (\<lambda> q2. q1 \<noteq> q2 \<and>
list_ex (\<lambda> l. list_ex (\<lambda> t. fst (snd t) = In a) (trans ! q2 ! l)) [0..<n])
[0..<p]
| _ \<Rightarrow> True)
(trans ! q1 ! l))
[0..<n])
[0..<p]"
unfolding check_trans_complete_def check_trans_1 check_trans_2 by (rule HOL.refl)
lemma check_axioms:
"Network_Reachability_Problem_precompiled p n m k inv trans
\<longleftrightarrow> check_pre \<and> check_ceiling \<and> check_trans_complete"
unfolding
Network_Reachability_Problem_precompiled_def check_ceiling check_pre_def
check_trans_complete_def check_nat_subs
by auto
end
lemmas Network_Reachability_Problem_precompiled_defs.check_axioms[code]
lemmas Network_Reachability_Problem_precompiled_defs.clkp_set'_def[code]
lemmas Network_Reachability_Problem_precompiled_defs.clk_set'_def[code]
lemmas Network_Reachability_Problem_precompiled_defs.check_pre_def[code]
lemmas Network_Reachability_Problem_precompiled_defs.check_ceiling_def[code]
lemmas Network_Reachability_Problem_precompiled_defs.check_trans_complete_alt_def[code]
lemmas Network_Reachability_Problem_precompiled_defs.init_def[code]
lemmas [code] =
Network_Reachability_Problem_precompiled_defs'.trans_out_map_def
Network_Reachability_Problem_precompiled_defs'.trans_in_map_def
Network_Reachability_Problem_precompiled_defs'.trans_i_map_def
Network_Reachability_Problem_precompiled_defs'.all_actions_by_state_def
Network_Reachability_Problem_precompiled_defs'.actions_by_state_def
Network_Reachability_Problem_precompiled_defs'.pairs_by_action_def
lemmas [code] =
Network_Reachability_Problem_precompiled'_axioms_def
Network_Reachability_Problem_precompiled'_def
pred_act_def
export_code Network_Reachability_Problem_precompiled in SML module_name Test
export_code Network_Reachability_Problem_precompiled' in SML module_name Test
concrete_definition succs_impl' uses Network_Reachability_Problem_precompiled'.succs_impl_alt_def
thm succs_impl'_def succs_impl'.refine
concrete_definition reachability_checker_impl
uses Network_Reachability_Problem_precompiled'.reachability_checker_alt_def
export_code reachability_checker_impl in SML_imp module_name TA
thm reachability_checker_impl_def reachability_checker_impl.refine
hide_const check_and_verify
definition [code]:
"check_and_verify p n m k I T na final \<equiv>
if Network_Reachability_Problem_precompiled' p n m k I T na
then reachability_checker_impl p m k I T na final \<bind> (\<lambda> x. return (Some x))
else return None"
lemmas [sep_heap_rules] = Network_Reachability_Problem_precompiled'.reachability_checker_hoare
theorem reachability_check:
"(uncurry0 (check_and_verify p n m k I T na final),
uncurry0 (
RETURN (
if (Network_Reachability_Problem_precompiled' p n m k I T na)
then Some (
\<exists> l' u u'.
map conv_A (Network_Reachability_Problem_precompiled_defs.N p n I T) \<turnstile>\<^sub>N \<langle>repeat 0 p, u\<rangle> \<rightarrow>* \<langle>l', u'\<rangle>
\<and> (\<forall> c \<in> {1..m}. u c = 0) \<and> (\<exists> q < p. l' ! q \<in> set (final ! q))
)
else None
)
)
)
\<in> unit_assn\<^sup>k \<rightarrow>\<^sub>a id_assn"
by sepref_to_hoare
(sep_auto simp: reachability_checker_impl.refine[symmetric] check_and_verify_def
Network_Reachability_Problem_precompiled_defs.init_def)
export_code open check_and_verify checking SML_imp
end (* End of theory *)
|
If $p$ is a polynomial whose coefficients are given by the list $xs$, and $xs$ has no trailing zeros, then $p$ is equal to the polynomial whose coefficients are given by $xs$. |
+++
title = "Predictive asymmetry"
subtitle = ""
date = 2019-04-15T00:00:00
lastmod = 2019-04-15T00:00:00
draft = false
# Authors. Comma separated list, e.g. `["Bob Smith", "David Jones"]`.
authors = ["Kristian A. Haaga", "David Diego", "Bjarte Hannisdal"]
tags = []
summary = "A simple and robust test for causal directionality in complex systems."
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["deep-learning"]` references
# `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
# projects = ["asymmetrytest"]
+++
## A brief tutorial on the predictive asymmetry test
Here's an example of how to compute the remarkable predictive asymmetry test of causality from time series proposed by Haaga *et al.* (forthcoming). The ``jupyter`` notebook was run using Julia 1.2 with our package <a href=https://www.earthsystemevolution.com/project/causalitytools/>``CausalityTools.jl``</a>.
Let's start by importing the necessary functions.
```julia
using CausalityTools, UncertainData
using StatsBase # statistical functions, e.g. mean
using Distributions # probability distributions
using Plots; pyplot() # use pyplot backend
using LaTeXStrings # enable TeX i pyplot
```
## Some example data
Let's create some example data with three dynamical variables coupled $x \to y \to z$.
```julia
npts = 400
y = rand(npts, 3)
N = Normal(0, 1)
aβ, aβ = 0.7, 0.1
bβ, bβ = 0.75, 0.2
cβ, cβ = 0.6, 0.2
Cββ, Cββ = 0.5, 0.5
ΞΎβ, ΞΎβ, ΞΎβ = 0.3, 0.3, 0.3
for t in 5:npts
y[t,1] = aβ*y[t-1,1] - aβ*y[t-4,1] + ΞΎβ*rand(N)
y[t,2] = bβ*y[t-1,2] - bβ*y[t-4,2] + Cββ*y[t-1,1] + ΞΎβ*rand(N)
y[t,3] = cβ*y[t-1,3] - cβ*y[t-3,3] + Cββ*y[t-1,2] + ΞΎβ*rand(N)
end
x, y, z = [y[:, i] for i = 1:3]
labs = "x", "y", "z"
plot(1:npts, x, c = :black, label = "x", lw = .5,
xlabel = "time", ylabel = "", size = (700, 400))
plot!(1:npts, y, c = :red, label = "y", lw = .5)
plot!(1:npts, z, c = :blue, label = "z", lw = .5)
```
## Predictive asymmetry test for causality
Now, we'll try to see if we can recover the unidirectional relationships using the predictive asymmetry test. To compute the predictive asymmetry, we'll use the transfer operator grid (Diego et al., 2019) transfer entropy test. To understand the parameters of the test, we need some background on transfer entropy:
### Transfer entropy
Let's say we have a source time series $S$ and a target time series $T$. For convenience, define
$$ \begin{align} T_f^{(k)} &= \{(T(t+\eta_k), \ldots, T(t+\eta_2), T(t+\eta_1))\}, \label{eq:Tf} \\ T_{pp}^{(l)} &= \{ (T(t), T(t-\tau_1), T(t-\tau_2), \ldots, T(t - \tau_{l - 1})) \\ S_{pp}^{(m)} &= \{(S(t), S(t-\tau_1), S(t-\tau_2), \ldots, S(t-\tau_{m - 1}))\} \end{align} $$
Combining into a generalised delay reconstruction:
$$ \begin{align} \mathbb{E} = (T_f^{(k)}, T_{pp}^{(l)}, S_{pp}^{(m)}) \end{align} $$
With that, we have an embedding that we can use to compute transfer entropy:
$$ \begin{align} TE_{S \rightarrow T} = \int_{\mathbb{E}} P(T_f, T_{pp}, S_{pp}) \log_{2}{\left(\frac{P(T_f | T_{pp}, S_{pp})}{P(T_f | T_{pp})}\right)} \end{align} $$.
### Deciding on test parameters
To organise our test, we can create an instance of a `TransferOperatorGridTest`, which has the following signature:
```julia
TransferOperatorGridTest(k::Int = 1, l::Int = 1, m::Int = 1, n::Int = 1,
Ο::Int = 1, b = 2, estimator::TransferOperatorGrid = TransferOperatorGrid(),
binning_summary_statistic::Function = StatsBase.mean,
binning::RectangularBinning, Ξ·s)
```
To get the full documentation, type `?TransferOperatorGridTest`.
#### Parameter list
What's important for us are
- `k`, `l`, and `m`, which dictate the dimension of the delay reconstruction.
- The `binning`, which is a `RectangularBinning` instance.
- `Ξ·s` is/are the prediction lag(s).
- `b` is the base of the logarithm.
- The `Ο` parameter is the reconstruction delay, which only matters for `k + l + m > 3`.
With that in mind, let's set up a very simple test.
```julia
# Use a three-dimensional delay reconstruction
k, l, m = 1, 1, 1
# Use a rectangular partition where the number of bin elements scale
# with the number of points (following Krakovska et al., 2018).
n_subdivisions = floor(Int, npts^(1/(k+l+m+1)))
binning = RectangularBinning(n_subdivisions)
# Compute the predictive asymmetry for Ξ· ranging from -8 to 8.
Ξ·s = -8:8
te_test = TransferOperatorGridTest(k = k, l = l, m = m, binning = binning, Ξ·s = Ξ·s)
```
TransferOperatorGridTest(k = 1, l = 1, m = 1, n = 1, Ο = 1, b = 2, estimator = TransferOperatorGrid(), binning_summary_statistic = mean, binning = RectangularBinning(4), Ξ·s = -8:8)
Now, we can use this transfer entropy test as input to a `PredictiveAsymmetryTest` instance.
```julia
pa_test = PredictiveAsymmetryTest(predictive_test = te_test)
```
PredictiveAsymmetryTest{TransferOperatorGridTest}(predictive_test = TransferOperatorGridTest(k = 1, l = 1, m = 1, n = 1, Ο = 1, b = 2, estimator = TransferOperatorGrid(), binning_summary_statistic = mean, binning = RectangularBinning(4), Ξ·s = -8:8))
## Applying the test
```julia
pa_xy = causality(x, y, pa_test)
pa_yx = causality(y, x, pa_test)
pa_yz = causality(y, z, pa_test)
pa_zy = causality(z, y, pa_test)
pa_xz = causality(x, z, pa_test)
pa_zx = causality(z, x, pa_test);
```
```julia
p_xy = plot(xlabel = "Prediction lag", ylabel = L"\mathbb{A} (bits)",
ylims = [-0.8, 0.8])
plot!(1:maximum(Ξ·s), pa_xy, label = L"x \to y", c = :black)
plot!(1:maximum(Ξ·s), pa_yx, label = L"y \to x", c = :red)
hline!([0], lw = 2, ls = :dot, Ξ± = 0.5, c = :black, label = "")
p_yz = plot(xlabel = "Prediction lag", ylabel = L"\mathbb{A} (bits)",
ylims = [-0.8, 0.8])
plot!(1:maximum(Ξ·s), pa_yz, label = L"y \to z", c = :red)
plot!(1:maximum(Ξ·s), pa_zy, label = L"z \to y", c = :blue)
hline!([0], lw = 2, ls = :dot, Ξ± = 0.5, c = :black, label = "")
p_xz = plot(xlabel = "Prediction lag", ylabel = L"\mathbb{A} (bits)",
ylims = [-0.8, 0.8])
plot!(1:maximum(Ξ·s), pa_xz, label = L"x \to z", c = :black)
plot!(1:maximum(Ξ·s), pa_zx, label = L"z \to x", c = :blue)
hline!([0], lw = 2, ls = :dot, Ξ± = 0.5, c = :black, label = "")
plot(p_xy, p_yz, p_xz, layout = grid(3, 1), size = (600, 600), legend = :topleft)
```
The direct influences $\mathbb{A}_{x \to y}$ and $\mathbb{A}_{y \to z}$ are both positive and of equal strength, while the indirect influence $\mathbb{A}_{x \to z}$ is weaker. In the non-causal direction, $\mathbb{A}_{y \to x}$, $\mathbb{A}_{z \to y}$ and $\mathbb{A}_{z \to x}$ are all negative. We thus recover the underlying directionality and relative strength of couplings.
```julia
```
|
module QLib
( quantumRun
) where
import Data.Complex
import Data.Bits
import qualified Data.List as L
import Text.Printf
import Numeric.LinearAlgebra
quantumRun :: IO ()
quantumRun = do putStrLn "Some Func"
let a = newRegister 4
putStrLn $ show a
-- putStrLn $ printf "%b" (3 :: Int)
-- let c = Qubit $ fromList [1 :+ 0, 0]
-- putStrLn $ show c
-- let d = sauliX c
-- putStrLn $ show d
-- let e = Register $ take 5 $ repeat (Qubit $ fromList [1, 0])
-- --let e = sauliZ d
-- putStrLn $ show e
--data Qubit = Qubit (Double, Int)
data Qubit = Qubit { probability :: Double, qubit :: Int }
instance Eq Qubit where
x == y = qubit x == qubit y
instance Ord Qubit where
x <= y = qubit x <= qubit y
instance Show Qubit where
show x = (show . probability $ x) ++ " |" ++ (show . qubit $ x) ++ ">"
data Register = Register { nStates :: Int, qubits :: [Qubit] }
instance Show Register where
--show (Register a x) = (show a) (show x) ++ ">"
show x = concatMap ((flip (++) "\n") . show) $ qubits x
instance Eq Register where
x == y = qubits x == qubits y
newRegister :: Int -> Register
newRegister n = Register { nStates = n, qubits = [blankQubit (x-1) | x <- [1..2^n] ] }
where blankQubit 0 = Qubit { probability = 1.0, qubit = 0 }
blankQubit y = Qubit { probability = 0.0, qubit = y }
sauliX :: Register -> Int -> Register
sauliX xs pos = map (\x -> x `xor` pos) xs
--newRegister :: Int -> QuantumRegister
--newRegister 0 = QuantumRegister 0 []
--newRegister 1 = QuantumRegister 1 [ (Register 0 [Zero]), (Register 0 [One]) ]
--newRegister x = QuantumRegister x [
--sauliX :: Qubit -> Qubit
--sauliX (Qubit x) = Qubit (xgate #> x)
-- where xgate = (2><2)[0, 1, 1, 0] :: Matrix C
--
--sauliY :: Qubit -> Qubit
--sauliY (Qubit x) = Qubit (ygate #> x)
-- where ygate = (2><2)[0:+1, 0, 0, 0:+1] :: Matrix C
--
--sauliZ :: Qubit -> Qubit
--sauliZ (Qubit x) = Qubit (zgate #> x)
-- where zgate = (2><2)[1, 0, 0, -1] :: Matrix C
--data Bit = Zero | One deriving Eq
--
--instance Show Bit where
-- show Zero = "|0>"
-- show One = "|1>"
--
--data Qubit a = Qubit (Complex a) (Complex a) deriving Show
--
--sauliX :: Qubit a -> Qubit a
--sauliX (Qubit x y) = Qubit y x
--
--sauliY :: (Fractional a, RealFloat a) => Qubit a -> Qubit a
--sauliY (Qubit x y) = Qubit rotY rotX
-- where i = 0 :+ 1
-- rotY = -y*i
-- rotX = x*i
--
--sauliZ :: (RealFloat a) => Qubit a -> Qubit a
--sauliZ (Qubit x y) = Qubit x (-y)
--data Qubit a = Qubit (Vector a)
--
---- Show the Qubit using Ket notation
--instance (Show a, Numeric a) => Show (Qubit a) where
-- show (Qubit x) = '(':(show first) ++ ")|0> + (" ++ (show second) ++ ")|1>"
-- where first = (fromList [1, 0]) <.> x
-- second = fromList [0, 1] <.> x
--
--notGate :: Qubit R -> Qubit R
--notGate (Qubit x) = let invertMatrix = (2><2) [-1, 0, 0, -1] in
-- Qubit (invertMatrix #> x)
|
example (h : a = b) : Nat.succ (a + 1) = Nat.succ (b + 1) := by
congr
example (h : a = b) : Nat.succ (a + 1) = Nat.succ (b + 1) := by
congr 1
show a + 1 = b + 1
rw [h]
def f (p : Prop) (a : Nat) (h : a > 0) [Decidable p] : Nat :=
if p then
a - 1
else
a + 1
example (h : a = b) : f True (a + 1) (by simp_arith) = f (0 = 0) (b + 1) (by simp_arith) := by
congr
decide
example (h : a = b) : f True (a + 1) (by simp_arith) = f (0 = 0) (b + 1) (by simp_arith) := by
congr 1
Β· decide
Β· show a + 1 = b + 1
rw [h]
example (hβ : Ξ± = Ξ²) (hβ : Ξ± = Ξ³) (a : Ξ±) : HEq (cast hβ a) (cast hβ a) := by
congr
Β· subst hβ hβ; rfl
Β· subst hβ hβ; apply heq_of_eq; rfl
example (f : Nat β Nat) (g : Nat β Nat) : f (g (x + y)) = f (g (y + x)) := by
congr 2
rw [Nat.add_comm]
example (p q r : Prop) (h : q = r) : (p β q) = (p β r) := by
congr
example (p q r s : Prop) (hβ : q = r) (hβ : r = s) : (p β q) = (p β s) := by
congr
rw [hβ, hβ]
|
# Support Vector Machine (SVM) classification for machine learning.
#
# SVM is a binary classifier. The objective of the SVM is to find the best
# separating hyperplane in vector space which is also referred to as the
# decision boundary. And it decides what separating hyperplane is the 'best'
# because the distance from it and the associating data it is separating is the
# greatest at the plane in question.
# Importing the data set
dataset = read.csv('Social_Network_Ads.csv')
dataset = dataset[, 3:5]
# Splitting the Dataset into a Training set and a Test set
# install.packages('caTools')
# library(caTools)
set.seed(123) # choose random number, only same number for debugging
split = sample.split(dataset$Purchased, SplitRatio = 0.75)
training_set = subset(dataset, split==TRUE)
test_set = subset(dataset, split==FALSE)
# Feature scaling, normalize scale is important. Especially on algorithms
# involving euclidian distance. Two main feature scaling formulas are:
# Standardisation: x_stand = (x-mean(x))/(standard_deviation(x))
# Normalisation: x_norm = (x-min(x))/(max(x)-min(x))
training_set[, 1:2] = scale(training_set[, 1:2])
test_set[, 1:2] = scale(test_set[, 1:2])
# Fitting the Classifier Model to the training_set
# install.packages('e1071')
# library(e1071)
classifier = svm(formula = Purchased ~ ., data = training_set,
type = 'C-classification', kernel = 'linear')
# Predict the test_set results by using the classifier
y_pred = predict(classifier, newdata = test_set[-3])
# Making the Confusion Matrix
cm = table(test_set[, 3], y_pred)
# Plot the training_set results
# install.packages('ElemStatLearn')
# library(ElemStatLearn)
set = training_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)
grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
prob_set = predict(classifier, type = 'response', newdata = grid_set)
y_grid = ifelse(prob_set>0.5, 1, 0)
plot(set[, -3],
main = 'SVM Classifier (Training set)',
xlab = 'Age', ylab = 'Estimated Salary',
xlim = range(X1), ylim = range(X2))
contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
# Plot the test_set results
# install.packages('ElemStatLearn')
# library(ElemStatLearn)
set = test_set
X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)
X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)
grid_set = expand.grid(X1, X2)
colnames(grid_set) = c('Age', 'EstimatedSalary')
prob_set = predict(classifier, type = 'response', newdata = grid_set)
y_grid = ifelse(prob_set>0.5, 1, 0)
plot(set[, -3],
main = 'SVM Classifier (testing set)',
xlab = 'Age', ylab = 'Estimated Salary',
xlim = range(X1), ylim = range(X2))
contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)
points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))
points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
|
theory PhiSem_Int_ArbiPrec
imports PhiSem_Generic_Boolean PhiSem_Common_Int
begin
chapter \<open>Integer of Arbitrary Precision\<close>
section \<open>Semantics\<close>
subsection \<open>Type\<close>
virtual_datatype \<phi>spec_int_ty =
T_aint :: unit
debt_axiomatization T_aint :: \<open>unit type_entry\<close>
where \<phi>spec_int_ty_ax: \<open>\<phi>spec_int_ty TY_CONS_OF T_aint\<close>
interpretation \<phi>spec_int_ty TY_CONS_OF \<open>TYPE(TY_N)\<close> \<open>TYPE(TY)\<close> T_aint using \<phi>spec_int_ty_ax .
hide_fact \<phi>spec_int_ty_ax
abbreviation aint where \<open>aint \<equiv> T_aint.mk ()\<close>
subsection \<open>Value\<close>
virtual_datatype \<phi>spec_int_val =
V_aint :: \<open>int\<close>
debt_axiomatization V_aint :: \<open>int value_entry\<close>
where \<phi>spec_int_val_ax: \<open>\<phi>spec_int_val VAL_CONS_OF V_aint\<close>
interpretation \<phi>spec_int_val VAL_CONS_OF \<open>TYPE(VAL_N)\<close> \<open>TYPE(VAL)\<close> V_aint using \<phi>spec_int_val_ax .
hide_fact \<phi>spec_int_val_ax \<phi>spec_int_val_axioms
subsection \<open>Semantics\<close>
debt_axiomatization
WT_aint[simp]: \<open>Well_Type aint = { V_aint.mk i |i. True } \<close>
and can_eqcmp_aint[simp]: "Can_EqCompare res (V_aint.mk i1) (V_aint.mk i2)"
and eqcmp_aint[simp]: "EqCompare (V_aint.mk i1) (V_aint.mk i2) \<longleftrightarrow> i1 = i2"
and zero_aint[simp]: \<open>Zero aint = Some (V_aint.mk 0)\<close>
(*lemma Valid_Types[simp]:
\<open>Valid_Type aint\<close>
unfolding Inhabited_def
apply simp
using less_exp by blast *)
section \<open>\<phi>-Types\<close>
subsection \<open>Integer in the normal sense\<close>
definition \<phi>AInt :: "(VAL, int) \<phi>" ("\<int>")
where "\<phi>AInt = (\<lambda>z. { V_aint.mk z})"
lemma \<phi>AInt_expn[\<phi>expns]:
"p \<in> (x \<Ztypecolon> \<int>) \<longleftrightarrow> p = V_aint.mk x"
unfolding \<phi>Type_def by (simp add: \<phi>AInt_def)
lemma \<phi>AInt_inhabited[elim!,\<phi>inhabitance_rule]:
"Inhabited (x \<Ztypecolon> \<int>) \<Longrightarrow> C \<Longrightarrow> C"
unfolding Inhabited_def by (simp add: \<phi>expns)
lemma [\<phi>reason 1000]:
"\<phi>Equal \<int> (\<lambda>x y. True) (=)"
unfolding \<phi>Equal_def by (simp add: \<phi>expns eq_nat_nat_iff)
lemma [\<phi>reason 1000]:
"\<phi>Zero aint \<int> 0"
unfolding \<phi>Zero_def by (simp add: \<phi>expns)
lemma \<phi>Int_semty[\<phi>reason 1000]:
\<open>\<phi>SemType (x \<Ztypecolon> \<int>) aint\<close>
unfolding \<phi>SemType_def subset_iff
by (simp add: \<phi>expns)
subsection \<open>Natural Nmber\<close>
definition \<phi>ANat ("\<nat>") where [\<phi>defs]: "\<nat> n = (of_nat n \<Ztypecolon> \<int>)"
lemma [\<phi>reason 1000]:
" Threshold_Cost 4
\<Longrightarrow> \<p>\<r>\<e>\<m>\<i>\<s>\<e> 0 \<le> x \<and> y = nat x
\<Longrightarrow> x \<Ztypecolon> \<int> \<i>\<m>\<p>\<l>\<i>\<e>\<s> y \<Ztypecolon> \<nat>"
\<medium_left_bracket> construct\<phi> \<open>nat x \<Ztypecolon> \<nat>\<close> \<medium_right_bracket>. .
lemma [\<phi>reason 1000]:
\<open> \<p>\<r>\<e>\<m>\<i>\<s>\<e> 0 \<le> x
\<Longrightarrow> x \<Ztypecolon> \<int> \<i>\<m>\<p>\<l>\<i>\<e>\<s> nat x \<Ztypecolon> \<nat> @action to \<nat>\<close> \<medium_left_bracket> \<medium_right_bracket>. .
lemma [\<phi>reason 1000]:
" Threshold_Cost 2
\<Longrightarrow> \<p>\<r>\<e>\<m>\<i>\<s>\<e> Int.int x = y
\<Longrightarrow> x \<Ztypecolon> \<nat> \<i>\<m>\<p>\<l>\<i>\<e>\<s> y \<Ztypecolon> \<int>" \<medium_left_bracket> destruct\<phi> _ \<medium_right_bracket>. .
lemma [\<phi>reason 1000]:
" x \<Ztypecolon> \<nat> \<i>\<m>\<p>\<l>\<i>\<e>\<s> Int.int x \<Ztypecolon> \<int> @action to \<int> " \<medium_left_bracket> \<medium_right_bracket>. .
lemma \<phi>ANat_elim[elim!,\<phi>inhabitance_rule]:
"Inhabited (n \<Ztypecolon> \<nat>) \<Longrightarrow> C \<Longrightarrow> C" .
lemma [\<phi>reason 1000]: \<open>\<phi>SemType (n \<Ztypecolon> \<nat>) aint\<close> \<medium_left_bracket> to \<int> \<medium_right_bracket>. .
lemma [\<phi>reason 1000]: "\<phi>Zero aint \<nat> 0" \<medium_left_bracket> \<open>0 \<Ztypecolon> \<int>\<close> \<medium_right_bracket>. .
lemma [\<phi>reason 1000]: \<open>\<phi>Equal \<nat> (\<lambda>_ _. True) (=)\<close> \<medium_left_bracket> to \<int> \<medium_right_bracket>. .
section \<open>Instructions\<close>
subsection \<open>Arithmetic Operations\<close>
definition op_const_aint :: "int \<Rightarrow> VAL proc"
where "op_const_aint const = Return (\<phi>arg (V_aint.mk const))"
definition op_aadd :: "(VAL \<times> VAL, VAL) proc'"
where "op_aadd =
\<phi>M_caseV (\<lambda>vb va.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
Return (\<phi>arg (V_aint.mk (val_a + val_b)))
)))"
definition op_asub :: "(VAL \<times> VAL, VAL) proc'"
where "op_asub =
\<phi>M_caseV (\<lambda>va vb.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
Return (\<phi>arg (V_aint.mk (val_b - val_a)))
)))"
definition op_amul :: "(VAL \<times> VAL, VAL) proc'"
where "op_amul =
\<phi>M_caseV (\<lambda>va vb.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
Return (\<phi>arg (V_aint.mk (val_b * val_a)))
)))"
definition op_audiv :: "(VAL \<times> VAL, VAL) proc'"
where "op_audiv =
\<phi>M_caseV (\<lambda>va vb.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
Return (\<phi>arg (V_aint.mk (val_b div val_a)))
)))"
definition op_alshr :: "(VAL \<times> VAL, VAL) proc'"
where "op_alshr =
\<phi>M_caseV (\<lambda>va vb.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
\<phi>M_assert (0 \<le> val_a) \<ggreater>
Return (\<phi>arg (V_aint.mk (val_b div 2 ^ (Int.nat val_a))))
)))"
definition op_alshl :: "(VAL \<times> VAL, VAL) proc'"
where "op_alshl =
\<phi>M_caseV (\<lambda>va vb.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
\<phi>M_assert (0 \<le> val_a) \<ggreater>
Return (\<phi>arg (V_aint.mk (val_b * 2 ^ (Int.nat val_a))))
)))"
definition op_a_lt :: "(VAL \<times> VAL, VAL) proc'"
where "op_a_lt =
\<phi>M_caseV (\<lambda>va vb.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
Return (\<phi>arg (V_bool.mk (val_b < val_a)))
)))"
definition op_a_le :: "(VAL \<times> VAL, VAL) proc'"
where "op_a_le =
\<phi>M_caseV (\<lambda>va vb.
\<phi>M_getV aint V_aint.dest va (\<lambda>val_a.
\<phi>M_getV aint V_aint.dest vb (\<lambda>val_b.
Return (\<phi>arg (V_bool.mk (val_b \<le> val_a)))
)))"
section \<open>Abstraction of Instructions\<close>
subsection \<open>Arithmetic Operations\<close>
subsubsection \<open>Constant Integer\<close>
lemma op_const_aint_\<phi>app[\<phi>synthesis 300]:
\<open> Check_Literal x
\<Longrightarrow> \<p>\<r>\<o>\<c> op_const_aint x \<lbrace> Void \<longmapsto> \<v>\<a>\<l> x \<Ztypecolon> \<int> \<rbrace>\<close>
unfolding op_const_aint_def Premise_def
by (rule, simp add: \<phi>expns)
lemma op_const_anat_\<phi>app[\<phi>synthesis 300]:
\<open> \<s>\<i>\<m>\<p>\<l>\<i>\<f>\<y> x' : of_nat x \<comment>\<open>TODO: improve this!\<close>
\<Longrightarrow> Check_Literal x'
\<Longrightarrow> \<p>\<r>\<o>\<c> op_const_aint x' \<lbrace> Void \<longmapsto> \<v>\<a>\<l> x \<Ztypecolon> \<nat> \<rbrace>\<close>
\<medium_left_bracket> op_const_aint[where x=x'] \<medium_right_bracket>. .
lemma [\<phi>reason 1210
for \<open>Synthesis_Parse (numeral ?n::nat) (?X :: ?'ret \<Rightarrow> assn)\<close>
\<open>Synthesis_Parse (1::nat) (?X :: ?'ret \<Rightarrow> assn)\<close>
\<open>Synthesis_Parse (0::nat) (?X :: ?'ret \<Rightarrow> assn)\<close>
]:
\<open> Synthesis_Parse (n \<Ztypecolon> \<nat>) X
\<Longrightarrow> Synthesis_Parse n X\<close>
for X :: \<open>'ret \<Rightarrow> assn\<close>
unfolding Synthesis_Parse_def ..
lemma [\<phi>reason 1210
for \<open>Synthesis_Parse (numeral ?n::int) (?X :: ?'ret \<Rightarrow> assn)\<close>
\<open>Synthesis_Parse (1::int) (?X :: ?'ret \<Rightarrow> assn)\<close>
\<open>Synthesis_Parse (0::int) (?X :: ?'ret \<Rightarrow> assn)\<close>
]:
\<open> Synthesis_Parse (n \<Ztypecolon> \<int>) X
\<Longrightarrow> Synthesis_Parse n X\<close>
for X :: \<open>'ret \<Rightarrow> assn\<close>
unfolding Synthesis_Parse_def ..
(* lemma op_const_size_t:
\<open>\<p>\<r>\<o>\<c> op_const_size_t n \<lbrace> Void \<longmapsto> \<v>\<a>\<l> n \<Ztypecolon> Size \<rbrace>\<close>
unfolding op_const_size_t_def Premise_def
by (\<phi>reason, simp add: \<phi>expns Big_def) *)
(* lemma [\<phi>reason 1200
for \<open>\<p>\<r>\<o>\<c> ?f \<lbrace> ?X' \<longmapsto> ?X\<heavy_comma> SYNTHESIS \<v>\<a>\<l> (numeral ?n) \<Ztypecolon> Size \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> ?E @action synthesis ?G\<close>
\<open>\<p>\<r>\<o>\<c> ?f \<lbrace> ?X' \<longmapsto> ?X\<heavy_comma> SYNTHESIS \<v>\<a>\<l> 0 \<Ztypecolon> Size \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> ?E @action synthesis ?G\<close>
\<open>\<p>\<r>\<o>\<c> ?f \<lbrace> ?X' \<longmapsto> ?X\<heavy_comma> SYNTHESIS \<v>\<a>\<l> 1 \<Ztypecolon> Size \<rbrace> \<t>\<h>\<r>\<o>\<w>\<s> ?E @action synthesis ?G\<close>
]:
\<open>\<p>\<r>\<o>\<c> op_const_size_t n \<lbrace> R \<longmapsto> R\<heavy_comma> SYNTHESIS \<v>\<a>\<l> n \<Ztypecolon> Size \<rbrace> @action synthesis G\<close>
unfolding Synthesis_def Action_Tag_def
using op_const_size_t[THEN \<phi>frame, simplified] . *)
subsubsection \<open>Integer Arithmetic\<close>
paragraph \<open>Addition\<close>
declare [[\<phi>trace_reasoning = 1]]
lemma op_add_aint_\<phi>app
[\<phi>overload add,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<int>\<close> \<Rightarrow> \<open>\<lambda>v. x + y \<Ztypecolon> _\<close> (1200)]:
\<open> \<p>\<r>\<o>\<c> op_aadd (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<int> \<longmapsto> \<v>\<a>\<l> x + y \<Ztypecolon> \<int> \<rbrace> \<close>
unfolding op_aadd_def Premise_def
by (cases vx; cases vy; simp, rule, rule, simp add: \<phi>expns, rule,
simp add: \<phi>expns, rule, simp add: \<phi>expns)
lemma op_add_anat_\<phi>app
[\<phi>overload add,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. x + y \<Ztypecolon> _\<close> (1200)]:
\<open> \<p>\<r>\<o>\<c> op_aadd (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<nat> \<longmapsto> \<v>\<a>\<l> x + y \<Ztypecolon> \<nat> \<rbrace> \<close>
\<medium_left_bracket> op_add_aint \<medium_right_bracket> by fastforce .
paragraph \<open>Subtraction\<close>
lemma op_sub_aint_\<phi>app[\<phi>overload sub,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<int>\<close> \<Rightarrow> \<open>\<lambda>v. x - y \<Ztypecolon> _\<close> (1200)]:
\<open> \<p>\<r>\<o>\<c> op_asub (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<int> \<longmapsto> \<v>\<a>\<l> x - y \<Ztypecolon> \<int> \<rbrace>\<close>
unfolding op_asub_def Premise_def
by (cases vx; cases vy; simp, rule, rule, simp add: \<phi>expns,
rule, simp add: \<phi>expns, rule, simp add: \<phi>expns)
lemma op_sub_anat_\<phi>app[\<phi>overload sub,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. x - y \<Ztypecolon> _\<close> (1200)]:
\<open> \<p>\<r>\<e>\<m>\<i>\<s>\<e> y \<le> x
\<Longrightarrow> \<p>\<r>\<o>\<c> op_asub (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<nat> \<longmapsto> \<v>\<a>\<l> x - y \<Ztypecolon> \<nat> \<rbrace>\<close>
\<medium_left_bracket> op_sub_aint \<medium_right_bracket> using nat_minus_as_int the_\<phi> by presburger .
paragraph \<open>Times\<close>
lemma op_mul_aint[\<phi>overload mul,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<int>\<close> \<Rightarrow> \<open>\<lambda>v. x * y \<Ztypecolon> _\<close> (1200)]:
\<open> \<p>\<r>\<o>\<c> op_amul (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<int> \<longmapsto> \<v>\<a>\<l> x * y \<Ztypecolon> \<int> \<rbrace>\<close>
unfolding op_amul_def
by (cases vx; cases vy; simp, rule, rule, simp add: \<phi>expns,
rule, simp add: \<phi>expns, rule, simp add: \<phi>expns)
lemma op_mul_anat[\<phi>overload mul,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. x * y \<Ztypecolon> _\<close> (1200)]:
\<open> \<p>\<r>\<o>\<c> op_amul (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<nat> \<longmapsto> \<v>\<a>\<l> x * y \<Ztypecolon> \<nat> \<rbrace>\<close>
\<medium_left_bracket> op_mul_aint \<medium_right_bracket>
by (simp add: nat_mult_distrib) .
paragraph \<open>Division\<close>
lemma op_udiv_aint_\<phi>app[\<phi>overload div,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<int>\<close> \<Rightarrow> \<open>\<lambda>v. x div y \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_audiv (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<int> \<longmapsto> \<v>\<a>\<l> x div y \<Ztypecolon> \<int> \<rbrace>\<close>
unfolding op_audiv_def
by (cases vx; cases vy; simp, rule, rule, simp add: \<phi>expns, rule, simp add: \<phi>expns,
rule, simp add: \<phi>expns)
lemma op_udiv_anat_\<phi>app[\<phi>overload div,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. x div y \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_audiv (\<phi>V_pair vy vx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[vx] \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[vy] \<nat> \<longmapsto> \<v>\<a>\<l> x div y \<Ztypecolon> \<nat> \<rbrace>\<close>
\<medium_left_bracket> op_udiv_aint \<medium_right_bracket>
by (simp add: div_int_pos_iff nat_div_distrib) .
paragraph \<open>Right Shift\<close>
lemma op_lshr_aint_pre_\<phi>app:
\<open> \<p>\<r>\<e>\<m>\<i>\<s>\<e> 0 \<le> y
\<Longrightarrow> \<p>\<r>\<o>\<c> op_alshr (\<phi>V_pair raw2 raw1) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[raw1] \<int> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[raw2] \<int> \<longmapsto> \<v>\<a>\<l> drop_bit (nat y) x \<Ztypecolon> \<int> \<rbrace>\<close>
unfolding op_alshr_def Premise_def
apply (cases raw1; cases raw2; simp; rule, rule, simp add: \<phi>expns, rule, simp add: \<phi>expns, rule,
rule \<phi>M_assert, simp add: \<phi>expns, rule, simp add: \<phi>expns)
using drop_bit_int_def by presburger
lemma op_lshr_aint_\<phi>app[\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. drop_bit y x \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_alshr (\<phi>V_pair raw2 raw1) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[raw1] \<int> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[raw2] \<nat> \<longmapsto> \<v>\<a>\<l> drop_bit y x \<Ztypecolon> \<int> \<rbrace>\<close>
\<medium_left_bracket> op_lshr_aint_pre \<medium_right_bracket>. .
lemma op_lshr_anat_\<phi>app[\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>ret. drop_bit y x \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_alshr (\<phi>V_pair raw2 raw1) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[raw1] \<nat> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[raw2] \<nat> \<longmapsto> \<v>\<a>\<l> drop_bit y x \<Ztypecolon> \<nat> \<rbrace>\<close>
\<medium_left_bracket> op_lshr_aint \<medium_right_bracket>
by (simp add: drop_bit_of_nat) .
paragraph \<open>Left Shift\<close>
lemma op_lshl_aint_pre_\<phi>app:
\<open> \<p>\<r>\<e>\<m>\<i>\<s>\<e> 0 \<le> y
\<Longrightarrow> \<p>\<r>\<o>\<c> op_alshl (\<phi>V_pair raw2 raw1) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[raw1] \<int> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[raw2] \<int> \<longmapsto> \<v>\<a>\<l> push_bit (nat y) x \<Ztypecolon> \<int> \<rbrace>\<close>
unfolding op_alshl_def Premise_def
by (cases raw1; cases raw2; simp; rule, rule, simp add: \<phi>expns, rule, simp add: \<phi>expns, rule,
rule \<phi>M_assert, simp add: \<phi>expns, rule, simp add: \<phi>expns push_bit_int_def)
lemma op_lshl_aint_\<phi>app[\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. push_bit y x \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_alshl (\<phi>V_pair raw2 raw1) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[raw1] \<int> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[raw2] \<nat> \<longmapsto> \<v>\<a>\<l> push_bit y x \<Ztypecolon> \<int> \<rbrace>\<close>
\<medium_left_bracket> op_lshl_aint_pre \<medium_right_bracket>. .
lemma op_lshl_anat_\<phi>app[\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. push_bit y x \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_alshl (\<phi>V_pair raw2 raw1) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[raw1] \<nat> \<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[raw2] \<nat> \<longmapsto> \<v>\<a>\<l> push_bit y x \<Ztypecolon> \<nat> \<rbrace>\<close>
\<medium_left_bracket> op_lshl_aint \<medium_right_bracket> by (simp add: push_bit_of_nat) .
paragraph \<open>Less Than\<close>
lemma op_lt_aint[\<phi>overload less,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<int>\<close> \<Rightarrow> \<open>\<lambda>v. x < y \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_a_lt (\<phi>V_pair rawy rawx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[rawx] \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[rawy] \<int> \<longmapsto> \<v>\<a>\<l> x < y \<Ztypecolon> \<bool> \<rbrace>\<close>
unfolding op_a_lt_def
by (cases rawx; cases rawy; simp, rule, rule, simp add: \<phi>expns, rule,
simp add: \<phi>expns, rule, simp add: \<phi>expns)
lemma op_lt_anat[\<phi>overload less,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. x < y \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_a_lt (\<phi>V_pair rawy rawx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[rawx] \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[rawy] \<nat> \<longmapsto> \<v>\<a>\<l> x < y \<Ztypecolon> \<bool> \<rbrace>\<close>
\<medium_left_bracket> op_lt_aint \<medium_right_bracket>. .
paragraph \<open>Less Equal\<close>
lemma op_le_aint_\<phi>app[\<phi>overload less_equal,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<int>\<close> \<Rightarrow> \<open>\<lambda>v. x \<le> y \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_a_le (\<phi>V_pair rawy rawx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[rawx] \<int>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[rawy] \<int> \<longmapsto> \<v>\<a>\<l> x \<le> y \<Ztypecolon> \<bool> \<rbrace>\<close>
unfolding op_a_le_def
by (cases rawx; cases rawy; simp, rule, rule, simp add: \<phi>expns,
rule, simp add: \<phi>expns, rule, simp add: \<phi>expns)
lemma op_le_anat_\<phi>app[\<phi>overload less_equal,
\<phi>synthesis for _ (100)
and \<open>x \<Ztypecolon> \<v>\<a>\<l> \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l> \<nat>\<close> \<Rightarrow> \<open>\<lambda>v. x \<le> y \<Ztypecolon> _\<close> (1200)]:
\<open>\<p>\<r>\<o>\<c> op_a_le (\<phi>V_pair rawy rawx) \<lbrace> x \<Ztypecolon> \<v>\<a>\<l>[rawx] \<nat>\<heavy_comma> y \<Ztypecolon> \<v>\<a>\<l>[rawy] \<nat> \<longmapsto> \<v>\<a>\<l> x \<le> y \<Ztypecolon> \<bool> \<rbrace>\<close>
\<medium_left_bracket> op_le_aint \<medium_right_bracket>. .
end |
View Job Details : RN-ICU - Travel Nursing: ICU Travel Nursing Opportunity in Kearney, NE!
View Job Details : RN-Medical Surgical - Travel Nursing: Medical Surgical Travel Nursing Opportunities in Kearney, NE!
Email this "Rn Network Jobs in Kearney, NE" search to your friends. |
The miners found that the row of cottages that served as their homes had been devastated and some of their families killed , seemingly at random . One found his family alive and safe in a makeshift hospital , but another emerged to discover his wife and four children had died . Fifteen @-@ year @-@ old Lillian Clark , working a late shift that night in the town 's boarding house , had been given permission to stay overnight for the first time . She was the only member of her family to survive . Her father was working outside the mine when the slide hit , while her mother and six siblings were buried in their home . All 12 men living at the CPR work camp were killed , but 128 more who were scheduled to move into the camp the day before the slide had not arrived β the train that was supposed to take them there from Morrissey , British Columbia , failed to pick them up . The Spokane Flyer , a passenger train heading west from Lethbridge , was saved by CPR brakeman Sid <unk> , one of two men who rushed across the rock @-@ strewn ground to warn the train that the track had been buried under the slide . Through falling rocks and a dust cloud that impaired his visibility , <unk> ran for 2 kilometres ( 1 @.@ 2 mi ) to warn the oncoming locomotive of the danger . The CPR gave him a letter of commendation and a $ 25 cheque in recognition of his heroism .
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Pendulum.Model (
Pendulum(..),
mkPendlumSystem,
stepPendulum
) where
import qualified Data.Vector.Sized as V
import GHC.TypeLits (KnownNat)
import Numeric.Hamilton
import Numeric.LinearAlgebra.Static
data Pendulum n = Pendulum
{ _lengthes :: V.Vector n Double
, _masses :: V.Vector n Double
, _config :: Config n
}
gravity :: Floating a => a
gravity = 9.8
toFloating :: Floating a => Double -> a
toFloating = fromRational . toRational
duplicate :: [a] -> [a]
duplicate = concatMap (\x -> [x, x])
merge :: [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys) = x : y : merge xs ys
evenElems :: [a] -> [a]
evenElems [] = []
evenElems (_:[]) = []
evenElems (_:x:xs) = x : evenElems xs
toVector :: forall a m. KnownNat m => [a] -> V.Vector m a
toVector = (\(Just x) -> x) . V.fromList
mkPendlumSystem :: forall m n. (KnownNat m, KnownNat n) => Pendulum n -> System m n
mkPendlumSystem p =
let lengthes = V.toList (_lengthes p)
masses = V.toList (_masses p)
masses' :: R m
masses' = vector (duplicate masses)
coordinates :: Floating a => V.Vector n a -> V.Vector m a
coordinates v =
let ths = V.toList v
ls = map toFloating lengthes
xs = scanl1 (+) (zipWith (*) ls (map sin ths))
ys = (* (-1.0)) <$> scanl1 (+) (zipWith (*) ls (map cos ths))
in toVector (merge xs ys)
potential :: Floating a => V.Vector m a -> a
potential v =
let ys = evenElems (V.toList v)
ms = map toFloating masses
in gravity * foldl1 (+) (zipWith (*) ms ys)
in mkSystem' masses' coordinates potential
stepPendulum :: forall m n. (KnownNat m, KnownNat n) => Double -> System m n -> Pendulum n -> Pendulum n
stepPendulum dt system pd =
let phase = toPhase system (_config pd)
phase' = stepHam dt system phase
in pd {_config = fromPhase system phase'}
|
From iris.proofmode Require Import tactics.
From machine_program_logic.program_logic Require Import weakestpre.
From HypVeri.lang Require Import lang trans_extra.
From HypVeri.algebra Require Import base pagetable mem trans.
From HypVeri.rules Require Import mem_send.
From HypVeri.logrel Require Import logrel logrel_extra.
From HypVeri Require Import proofmode.
Import uPred.
Section ftlr_share.
Context `{hypconst:HypervisorConstants}.
Context `{hypparams:!HypervisorParameters}.
Context `{vmG: !gen_VMG Ξ£}.
Lemma ftlr_share {i mem_acc_tx ai regs rxs ps_acc p_tx p_rx instr trans r0} P:
(β trans trans' rxs rxs', delete i rxs = delete i rxs' -> except i trans = except i trans' ->
(β (x:VMID), x β i -> trans_rel_secondary x trans trans') ->
P trans rxs β£β’ P trans' rxs') ->
base_extra.is_total_gmap regs ->
base_extra.is_total_gmap rxs ->
{[p_tx; p_rx]} β ps_acc ->
currently_accessible_in_trans_memory_pages i trans β ps_acc β {[p_tx; p_rx]} ->
p_rx β ps_acc β {[p_rx; p_tx]} βͺ accessible_in_trans_memory_pages i trans ->
p_tx β ps_acc β {[p_rx; p_tx]} βͺ accessible_in_trans_memory_pages i trans ->
regs !! PC = Some ai ->
tpa ai β ps_acc ->
tpa ai β p_tx ->
dom mem_acc_tx = set_of_addr (ps_acc β {[p_tx]}) ->
tpa ai β ps_acc β {[p_tx]} ->
mem_acc_tx !! ai = Some instr ->
decode_instruction instr = Some Hvc ->
regs !! R0 = Some r0 ->
decode_hvc_func r0 = Some Share ->
p_tx β p_rx ->
β’ β· (β (a : gmap reg_name Addr) (a0 : gset PID) (a1 : gmap Addr transaction) (a2 : gmap VMID (option (Addr * VMID))),
βbase_extra.is_total_gmap a2β -β
βbase_extra.is_total_gmap aβ -β
β{[p_tx; p_rx]} β a0β -β
βcurrently_accessible_in_trans_memory_pages i a1 β a0 β {[p_tx; p_rx]}β -β
βp_rx β a0 β {[p_rx; p_tx]} βͺ accessible_in_trans_memory_pages i a1β -β
βp_tx β a0 β {[p_rx; p_tx]} βͺ accessible_in_trans_memory_pages i a1β -β
([β map] rβ¦w β a, r @@ i ->r w) -β
TX@i:=p_tx -β
p_tx -@O> - β p_tx -@E> true -β
mailbox.rx_page i p_rx -β
i -@A> a0 -β
pagetable_entries_excl_owned i (a0 β {[p_rx; p_tx]} β currently_accessible_in_trans_memory_pages i a1) -β
transaction_hpool_global_transferred a1 -β
transaction_pagetable_entries_transferred i a1 -β
retrievable_transaction_transferred i a1 -β
rx_state_get i a2 -β
rx_states_global (delete i a2) -β
transaction_pagetable_entries_owned i a1 -β
retrieved_transaction_owned i a1 -β
(β mem : lang.mem, memory_pages (a0 βͺ (accessible_in_trans_memory_pages i a1)) mem) -β
(P a1 a2) -β
WP ExecI @ i {{ _, True }}) -β
([β map] rβ¦w β regs, r @@ i ->r w) -β
TX@i:=p_tx -β
p_tx -@O> - β p_tx -@E> true -β
i -@A> ps_acc -β
pagetable_entries_excl_owned i (ps_acc β {[p_rx; p_tx]} β (currently_accessible_in_trans_memory_pages i trans)) -β
transaction_hpool_global_transferred trans -β
transaction_pagetable_entries_transferred i trans -β
retrievable_transaction_transferred i trans -β
rx_state_get i rxs -β
mailbox.rx_page i p_rx -β
rx_states_global (delete i rxs) -β
transaction_pagetable_entries_owned i trans -β
retrieved_transaction_owned i trans -β
(β mem1 : mem, memory_pages ((ps_acc βͺ (accessible_in_trans_memory_pages i trans)) β ps_acc) mem1) -β
([β map] kβ¦v β mem_acc_tx, k ->a v) -β
(β mem2 : mem, memory_page p_tx mem2) -β
(P trans rxs) -β
SSWP ExecI @ i {{ bm, (if bm.1 then VMProp_holds i (1 / 2) else True) -β WP bm.2 @ i {{ _, True }} }}.
Proof.
iIntros (P_eq Htotal_regs Htotal_rxs Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx Hlookup_PC Hin_ps_acc Hneq_ptx Hdom_mem_acc_tx Hin_ps_acc_tx
Hlookup_mem_ai Heqn Hlookup_reg_R0).
iIntros (Hdecode_hvc Hneq_mb) "IH regs tx pgt_tx pgt_acc pgt_owned trans_hpool_global tran_pgt_transferred retri rx_state rx other_rx
tran_pgt_owned retri_owned mem_rest mem_acc_tx mem_tx P".
set ps_mem_in_trans := accessible_in_trans_memory_pages i trans.
pose proof (Htotal_regs R1) as[r1 Hlookup_reg_R1].
pose proof (Htotal_regs R2) as[r2 Hlookup_reg_R2].
iDestruct (reg_big_sepM_split_upd4 i Hlookup_PC Hlookup_reg_R0 Hlookup_reg_R1 Hlookup_reg_R2 with "[$regs]")
as "(PC & R0 & R1 & R2 & Hacc_regs)";eauto.
iDestruct (mem_big_sepM_split mem_acc_tx Hlookup_mem_ai with "mem_acc_tx") as "[mem_instr Hacc_mem_acc_tx]".
destruct (decide (page_size < r1)%Z).
{ (* the length of msg exceeds [page_size] *)
iApply (mem_send_invalid_len ai with "[PC mem_instr pgt_acc R0 R1 R2 tx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity.
iNext. iIntros "(PC & mem_instr & pgt_acc & R0 & R1 & R2 & tx) _".
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned trans_hpool_global
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx $mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
iDestruct "mem_tx" as (mem_tx) "mem_tx".
destruct (parse_transaction_descriptor mem_tx p_tx (Z.to_nat r1)) as [tran_des|] eqn:Heq_parse_tran.
2:{ (* cannot parse the msg as a descriptor *)
iApply (mem_send_invalid_msg ai with "[PC mem_instr pgt_acc R0 R1 R2 tx mem_tx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. exact Heq_parse_tran. iFrame.
iNext. iIntros "(PC & mem_instr & pgt_acc & R0 & R1 & R2 & tx & mem_tx) _".
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned trans_hpool_global
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
destruct (validate_transaction_descriptor i tran_des) eqn:Hvalid_tran_des.
2:{ (* validation of descriptor fails, apply [mem_send_invalid_des] *)
iApply (mem_send_invalid_des ai with "[PC mem_instr pgt_acc R0 R1 R2 tx mem_tx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. exact Heq_parse_tran. done. iFrame.
iNext. iIntros "(PC & mem_instr & pgt_acc & R0 & R1 & R2 & tx & mem_tx) _".
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned trans_hpool_global
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
pose proof (Hvalid_tran_des) as Hvalid_trans_des'.
apply validate_descriptor in Hvalid_tran_des as [j [ps_share [-> Hneq_sr]]].
destruct (decide (ps_share β ps_acc)) as [Hsubseteq_share | Hnsubseteq_share].
2:{ (* no access to at least one page in ps_share, apply [mem_send_not_acc] *)
apply not_subseteq in Hnsubseteq_share as [p [Hin_p_share Hnin_p_acc]].
iApply (mem_send_not_acc ai p with "[PC mem_instr pgt_acc R0 R1 R2 tx mem_tx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. exact Heq_parse_tran. done. simpl; exact Hin_p_share. iFrame.
iNext. iIntros "(PC & mem_instr & R0 & R1 & R2 & tx & mem_tx & pgt_acc) _".
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned trans_hpool_global
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
destruct (decide (p_tx β ps_share)) as [Hin_ptx_share | Hnin_ptx_share].
{ (* tx is not owned by i, apply [mem_send_not_owned] *)
iDestruct "pgt_tx" as "[own_tx excl_tx]".
iApply (mem_send_not_owned1 ai with "[PC mem_instr pgt_acc R0 R1 R2 tx mem_tx own_tx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. exact Heq_parse_tran. done. simpl; exact Hin_ptx_share. iFrame.
iNext. iIntros "(PC & mem_instr & pgt_acc & R0 & R1 & R2 & tx & mem_tx & own_tx) _".
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx [$own_tx $excl_tx] rx pgt_acc pgt_owned trans_hpool_global
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
destruct (decide (p_rx β ps_share)) as [Hin_prx_share | Hnin_prx_share].
{ (* rx is not owned by i, apply [mem_send_not_owned] *)
iDestruct "rx" as "[rx [own_rx excl_rx]]".
iApply (mem_send_not_owned1 ai with "[PC mem_instr pgt_acc R0 R1 R2 tx mem_tx own_rx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. exact Heq_parse_tran. done. simpl; exact Hin_prx_share. iFrame.
iNext. iIntros "(PC & mem_instr & pgt_acc & R0 & R1 & R2 & tx & mem_tx & own_rx) _".
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx [$rx $own_rx $excl_rx] pgt_acc pgt_owned trans_hpool_global
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
assert (Hsubseteq_share' : ps_share β ps_acc β {[p_rx;p_tx]}).
{ set_solver + Hsubseteq_share Hnin_ptx_share Hnin_prx_share. }
clear Hsubseteq_share Hnin_ptx_share Hnin_prx_share.
iDestruct "trans_hpool_global" as (hpool) "(%Heq_hsall & fresh_handles & trans)".
destruct (decide (ps_share β ps_acc β {[p_rx; p_tx]} β (pages_in_trans trans))) as [Hsubseteq_share'' | Hnsubseteq_share].
{ (* all pages are exclusively owned, ok to perceed *)
assert (ps_share β ps_acc β {[p_rx; p_tx]} β ps_mem_in_trans) as Hsubseteq.
{
assert (ps_mem_in_trans β (pages_in_trans trans)).
{
rewrite /ps_mem_in_trans.
apply pages_in_trans_subseteq.
apply map_filter_subseteq.
}
set_solver + H Hsubseteq_share''.
}
iDestruct (fresh_handles_disj with "[$fresh_handles trans]") as "%Hdisj_hpool".
{ iDestruct (big_sepM_sep with "trans") as "[$ _]". }
iDestruct (big_sepS_union_acc _ ps_share with "pgt_owned") as "[pgt_oe_share Hacc_pgt_oe]".
{ pose proof (currently_accessible_accessible_memory_pages_subseteq i trans) as Hs.
set_solver + Hs Hsubseteq . }
destruct (decide (hpool = β
)).
{ (* no avaiable fresh handles, apply [mem_share_no_fresh_handles] *)
iApply (mem_send_no_fresh_handles ai hpool j mem_tx ps_share with "[PC mem_instr pgt_acc pgt_oe_share R0 R1 R2 fresh_handles tx mem_tx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. intro;apply Hneq_sr,symmetry;done. set_solver + Hsubseteq_share'. iFrame.
iNext. iIntros "(PC & mem_instr & pgt_oe_share & pgt_acc & R0 & R1 & R2 & fresh_handles & tx & mem_tx ) _".
iDestruct ("Hacc_pgt_oe" $! ps_share with "[] pgt_oe_share") as "pgt_owned".
{ iPureIntro;set_solver +. }
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f _ _ _ with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc [pgt_owned] [fresh_handles trans]
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
rewrite /pagetable_entries_excl_owned /pgt.
iApply (big_sepS_subseteq with "pgt_owned").
rewrite difference_union_L. set_solver +.
iExists hpool. by iFrame.
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
iApply (mem_share ai j mem_tx hpool ps_share with "[PC mem_instr pgt_acc pgt_oe_share R0 R1 R2 fresh_handles tx mem_tx]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. intro;apply Hneq_sr,symmetry;done. set_solver + Hsubseteq_share'. iFrame.
iNext. iIntros "(PC & mem_instr & pgt_oe_share & pgt_acc & R0 & R1 & (%wh & %Hin_wh & R2 & tran_share & retri_share & fresh_handles) & tx & mem_tx ) _".
iDestruct ("Hacc_pgt_oe" $! β
with "[] []") as "pgt_owned".
{ iPureIntro. set_solver +. }
{ rewrite big_sepS_empty //. }
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f _ _ _ with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
(* we will specialize IH with the new [trans'] *)
pose (<[wh := (i, j, ps_share, Sharing, false)]>trans) as trans'.
assert (Hlookup_wh_None: trans !! wh = None).
rewrite -not_elem_of_dom.
set_solver + Hin_wh Hdisj_hpool.
assert (ps_share βͺ accessible_in_trans_memory_pages i trans = accessible_in_trans_memory_pages i trans') as Hrewrite.
{
rewrite /trans' /accessible_in_trans_memory_pages.
rewrite map_filter_insert_True.
rewrite pages_in_trans_insert //.
rewrite map_filter_lookup_None.
eauto. simpl. left.
split;auto.
intro. destruct H as [H []]. inversion H.
}
iDestruct (trans_split with "tran_share") as "[tran_share tran_share']".
iDestruct (trans_split with "tran_share'") as "[tran_share' tran_share'']".
rewrite half_of_half.
iDestruct (pgt_split_quarter with "pgt_oe_share") as "[pgt_oe_share_1 pgt_oe_share_3]".
iApply ("IH" $! _ ps_acc trans' _ Htotal_rxs Htotal_regs' Hsubset_mb with "[] [] [] regs tx pgt_tx rx pgt_acc [pgt_owned]
[fresh_handles tran_share trans pgt_oe_share_3] [tran_pgt_transferred] [retri retri_share tran_share'']
rx_state other_rx [tran_pgt_owned tran_share' pgt_oe_share_1] [retri_owned] [mem_rest mem_acc_tx mem_tx] [P]").
{
iPureIntro.
rewrite /currently_accessible_in_trans_memory_pages /trans'.
rewrite map_filter_insert_True.
2: { left;done. }
rewrite pages_in_trans_insert.
2: { apply map_filter_lookup_None. left;done. }
set_solver + Hsubset_acc Hsubseteq.
}
{
rewrite -Hrewrite.
rewrite union_assoc_L.
iPureIntro.
set_solver + Hsubseteq_share' Hnin_rx.
}
{
rewrite -Hrewrite.
rewrite union_assoc_L.
iPureIntro.
set_solver + Hsubseteq_share' Hnin_tx.
}
{
rewrite union_empty_r_L.
rewrite /pagetable_entries_excl_owned /pgt.
assert (currently_accessible_in_trans_memory_pages i trans' = ps_share βͺ currently_accessible_in_trans_memory_pages i trans) as Hrewrite'.
{
rewrite /currently_accessible_in_trans_memory_pages /trans'.
rewrite map_filter_insert_True.
2: { left;done. }
rewrite pages_in_trans_insert //.
apply map_filter_lookup_None. left;done.
}
rewrite Hrewrite'.
rewrite (union_comm_L ps_share _).
rewrite difference_difference_L.
rewrite big_sepS_sep //.
}
{
iExists (hpool β {[wh]}).
iSplit.
iPureIntro.
rewrite dom_insert_L.
rewrite union_assoc_L.
rewrite -Heq_hsall.
f_equal.
rewrite difference_union_L.
set_solver + Hin_wh.
rewrite big_sepM_insert;auto.
simpl. case_bool_decide as Hb;first done.
iFrame.
}
{
rewrite /transaction_pagetable_entries_transferred.
iApply (big_sepFM_lookup_None_False with "tran_pgt_transferred"); auto.
simpl. intros [_ H];inversion H.
}
{
rewrite /retrievable_transaction_transferred.
iDestruct (retri_split with "retri_share") as "[retri_share retri_share']".
iDestruct "retri" as "[retri1 retri2]".
iSplitL "retri1 retri_share".
iApply (big_sepFM_lookup_None_True with "retri1"); auto.
simpl;eauto.
iApply (big_sepFM_lookup_None_True with "retri2"); auto.
simpl;eauto.
iFrame.
}
{
rewrite /transaction_pagetable_entries_owned.
iApply (big_sepFM_lookup_None_True with "tran_pgt_owned"); auto.
simpl;eauto.
case_bool_decide.
simpl in H. done.
iFrame.
}
{
rewrite /retrieved_transaction_owned.
rewrite -big_sepFM_lookup_None_False;auto.
simpl. intro. destruct H;contradiction.
}
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[mem_rest $mem_acc]").
set_solver +.
rewrite -Hrewrite.
assert ((ps_acc βͺ (ps_share βͺ accessible_in_trans_memory_pages i trans)) = (ps_acc βͺ accessible_in_trans_memory_pages i trans)) as ->.
set_solver + Hsubseteq.
iFrame.
}
{
iApply (P_eq with "P"). done.
symmetry. apply except_insert_False_None. done. left;done.
intros.
destruct (decide (x = j)).
subst j.
split.
rewrite map_filter_insert_not' //=.
intros [? _]. done.
intros. rewrite H0 // in Hlookup_wh_None.
rewrite map_filter_insert_not' //=.
intros [_ ?]. done.
intros. rewrite H0 // in Hlookup_wh_None.
split.
rewrite map_filter_insert_not' //=.
intros [? _]. done.
intros. rewrite H0 // in Hlookup_wh_None.
rewrite map_filter_insert_not' //=.
intros [_ ?]. done.
intros. rewrite H0 // in Hlookup_wh_None.
}
}
{ (* at least one page is not exclusively owned by i (i.e. is involved in a transaction) *)
assert (β p, p β ps_share β§ p β pages_in_trans trans) as [p [Hin_p_share Hin_p_mem_in_trans]].
{ apply (not_subseteq_diff _ (ps_acc β {[p_rx; p_tx]}));auto. }
apply elem_of_pages_in_trans in Hin_p_mem_in_trans as [h [tran [Hlookup_tran Hin_p_tran]]].
iDestruct (big_sepM_lookup_acc with "trans") as "[[tran_tran pgt] Hacc_trans]";first exact Hlookup_tran.
iApply (mem_send_in_trans ai p h with "[PC mem_instr pgt_acc R0 R1 R2 tx mem_tx tran_tran]");iFrameAutoSolve.
exact Hdecode_hvc. simpl; reflexivity. lia. exact Heq_parse_tran. done. simpl; exact Hin_p_share. iFrame.
iNext. iIntros "(PC & mem_instr & pgt_acc & R0 & R1 & R2 & tx & mem_tx & tran_tran) _".
iDestruct ("Hacc_regs" $! (ai ^+ 1)%f with "[$ PC $ R0 $ R1 $ R2]") as (regs') "[%Htotal_regs' regs]".
iDestruct ("Hacc_mem_acc_tx" with "[$mem_instr]") as "mem_acc_tx".
iDestruct ("Hacc_trans" with "[$tran_tran $pgt]") as "trans".
iApply ("IH" $! _ ps_acc trans _ Htotal_rxs Htotal_regs' Hsubset_mb Hsubset_acc Hnin_rx Hnin_tx with "regs tx pgt_tx rx pgt_acc pgt_owned [fresh_handles trans]
tran_pgt_transferred retri rx_state other_rx tran_pgt_owned retri_owned [mem_rest mem_acc_tx mem_tx] P").
iExists hpool;by iFrame.
{
iDestruct (memory_pages_split_singleton' p_tx ps_acc with "[mem_acc_tx mem_tx]") as "mem_acc". set_solver + Hsubset_mb.
iSplitL "mem_acc_tx".
iExists mem_acc_tx;by iFrame "mem_acc_tx".
iExists mem_tx;by iFrame "mem_tx".
iApply (memory_pages_split_diff' _ ps_acc with "[$mem_rest $mem_acc]").
set_solver +.
}
}
Qed.
End ftlr_share.
|
[STATEMENT]
theorem (in SecurityInvariant_withOffendingFlows) ENFnrSR_offending_set:
"\<lbrakk> sinvar_all_edges_normal_form_not_refl_SR P \<rbrakk> \<Longrightarrow>
set_offending_flows G nP = (if sinvar G nP then
{}
else
{ {(e1,e2). (e1, e2) \<in> edges G \<and> e1 \<noteq> e2 \<and> \<not> P (nP e1) e1 (nP e2) e2} })"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. sinvar_all_edges_normal_form_not_refl_SR P \<Longrightarrow> set_offending_flows G nP = (if sinvar G nP then {} else {{(e1, e2). (e1, e2) \<in> edges G \<and> e1 \<noteq> e2 \<and> \<not> P (nP e1) e1 (nP e2) e2}})
[PROOF STEP]
by(auto dest: ENFnrSR_to_ENFsr simp: ENFsr_offending_set) |
{-# OPTIONS --without-K --rewriting #-}
open import HoTT
open import homotopy.CircleHSpace
open import homotopy.LoopSpaceCircle
import homotopy.Pi2HSusp as Pi2HSusp
open import homotopy.IterSuspensionStable
-- This summerizes all [Οβ SβΏ]
module homotopy.PinSn where
ΟS-SphereS-iso-β€ : β n β ΟS n (βSphere (S n)) βα΄³ β€-group
ΟS-SphereS-iso-β€ 0 =
ΟS 0 βSΒΉ
βα΄³β¨ unTrunc-iso Ξ©SΒΉ-group-structure β©
Ξ©^S-group 0 βSΒΉ
βα΄³β¨ Ξ©SΒΉ-iso-β€ β©
β€-group
βα΄³β
ΟS-SphereS-iso-β€ 1 =
ΟS 1 βSΒ²
βα΄³β¨ Pi2HSusp.Οβ-Susp βSΒΉ-hSpace β©
ΟS 0 βSΒΉ
βα΄³β¨ ΟS-SphereS-iso-β€ O β©
β€-group
βα΄³β
ΟS-SphereS-iso-β€ (S (S n)) =
ΟS (S (S n)) (βSphere (S (S (S n))))
βα΄³β¨ Susp^StableSucc.stable
(S n) (S n) (β€-ap-S $ β€-ap-S $ *2-increasing n)
(βSphere (S (S n))) {{Sphere-conn (S (S n))}} β©
ΟS (S n) (βSphere (S (S n)))
βα΄³β¨ ΟS-SphereS-iso-β€ (S n) β©
β€-group
βα΄³β
|
module Pragmas where
-- Check that Haskell code is parsed with the correct language pragmas
{-# FOREIGN AGDA2HS
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE LambdaCase #-}
#-}
{-# FOREIGN AGDA2HS
foo :: Bool -> a -> (a, Int)
foo = \ case
False -> (, 0)
True -> (, 1)
#-}
|
{-
This second-order equational theory was created from the following second-order syntax description:
$sig_string
-}
module $syn_name.Equality where
open import SOAS.Common
open import SOAS.Context
open import SOAS.Variable
open import SOAS.Families.Core
open import SOAS.Families.Build
open import SOAS.ContextMaps.Inductive
open import $syn_name.Signature
open import $syn_name.Syntax
open import SOAS.Metatheory.SecondOrder.Metasubstitution ${sig}:Syn
open import SOAS.Metatheory.SecondOrder.Equality ${sig}:Syn
private
variable
Ξ± Ξ² Ξ³ Ο : $type
Ξ Ξ Ξ : Ctx
infix 1 _βΉ_β’_ββ_
-- Axioms of equality
data _βΉ_β’_ββ_ : β π Ξ {Ξ±} β (π β· ${sig}) Ξ± Ξ β (π β· ${sig}) Ξ± Ξ β Set where
$axioms
open EqLogic _βΉ_β’_ββ_
open β-Reasoning
$derived_eqs
|
type $RR <class {@e1 i32, @e2 f32, @e3 f64}>
type $SS <class <$RR> {@f1 i32, @f2 i8, @f3 i8}>
type $TT <class {@e1 i32, @e2 f32, @e3 f64}>
type $UU <class <$RR> {@f1 i32, @f2 i8, @f3 i8}>
func &foo ( var %x <$SS>) void {
var %y <$UU>
dassign %y 0 ( dread agg %x 0 )
return () }
# EXEC: %irbuild Main.mpl
# EXEC: %irbuild Main.irb.mpl
# EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl
|
#include <boost/program_options.hpp>
#include <iostream>
#include "sampler.hpp"
#include "tiling.hpp"
namespace boostPO = boost::program_options;
int main(int argc, char** argv)
{
/* ARG PARSER *****************************************************/
std::string fn_rules;
std::string fn_bary;
std::string fn_offset;
std::string fn_out;
boostPO::variables_map vm;
boostPO::options_description desc("Allowed options");
desc.add_options()
("help,h",
"produce help message")
("rule,r",
boostPO::value<std::string>(&fn_rules)->required(),
"REQUIRED | subdivision rule filename")
("bary,b",
boostPO::value<std::string>(&fn_bary),
"barycenter offset filename (for each rule id)")
("offset,d",
boostPO::value<std::string>(&fn_offset),
"offset filename (for each structural indices)")
("out,o",
boostPO::value<std::string>(&fn_out),
"output filename")
;
try
{
boostPO::store(
boostPO::command_line_parser(argc, argv).
options(desc).run(), vm);
boostPO::notify(vm);
}
catch(boost::program_options::error& e)
{
std::cerr << e.what() << std::endl;
std::cout << desc << "\n";
exit(EXIT_FAILURE);
}
if(vm.count("help"))
{
std::cout << desc << "\n";
exit(EXIT_SUCCESS);
}
/* PROG ***********************************************************/
try
{
Sampler sampler(fn_rules, fn_bary, fn_offset);
//WriterFilePts write(fn_out);
//WriterVector write;
WriterEmpty write;
char ans;
float density = 4e6;
unsigned short int seed = 0;
float spaceScale = 0.21;
unsigned int speed[3][4] = {{0,0,0,0},{0,0,0,0},{0,0,0,0}};
unsigned int nbIter = 10;
for(int iter=-2; iter<1; ++iter)
{
switch(iter)
{
case -2: std::cout << "======== REF PT ==========" << std::endl; break;
case -1: std::cout << "======== BARY PT =========" << std::endl; break;
case 0: std::cout << "======= OFFSET PT ========" << std::endl; break;
}
std::cout << "==== Test Uniform Min ====" << std::endl;
for(int i=0; i<nbIter; ++i) speed[iter+2][0] += sampler.generateUniform(5, 0, iter, write, seed, spaceScale, true);
speed[iter+2][0] /= nbIter;
std::cout << "\n==== Test Uniform Max ====" << std::endl;
for(int i=0; i<nbIter; ++i) speed[iter+2][1] += sampler.generateUniform(5, 35, iter, write, seed, spaceScale, true);
speed[iter+2][1] /= nbIter;
std::cout << "\n==== Test Adaptive Min ====" << std::endl;
for(int i=0; i<nbIter; ++i) speed[iter+2][2] += sampler.generateAdaptive(&dFunc_linear, 0., 3440., iter, write, seed, spaceScale);
speed[iter+2][2] /= nbIter;
std::cout << "\n==== Test Adaptive Max ====" << std::endl;
for(int i=0; i<nbIter; ++i) speed[iter+2][3] += sampler.generateAdaptive(&dFunc_linear, 0., 124000., iter, write, seed, spaceScale);
speed[iter+2][3] /= nbIter;
std::cout << "===========================\n" << std::endl;
}
std::cout << "\n================================== RESUME ==================================" << std::endl;
std::cout << "(nb pt / s.)\t\tUniform\t\t\t\tAdaptive" << std::endl;
std::cout << "ref pt\t\t" << (float)speed[0][0] << " - " << (float)speed[0][1] << "\t" << (float)speed[0][2] << " - " << (float)speed[0][3] << std::endl;
std::cout << "bary pt\t\t" << (float)speed[1][0] << " - " << (float)speed[1][1] << "\t" << (float)speed[1][2] << " - " << (float)speed[1][3] << std::endl;
std::cout << "offset pt\t" << (float)speed[2][0] << " - " << (float)speed[2][1] << "\t" << (float)speed[2][2] << " - " << (float)speed[2][3] << std::endl;
std::cout << "============================================================================" << std::endl;
}
catch(const std::exception& e)
{
std::cerr << "Error : " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
|
From stdpp Require Import gmap.
From Perennial.Helpers Require Import Integers.
From Perennial.algebra Require Import big_sepM.
From Perennial.program_proof Require Import addr.addr_proof.
Lemma default_fmap `{Countable K} `{EqDecision K} {A B:Type} (m : option (gmap K A)) (f : A -> B) :
(default β
(fmap (fun bm => f <$> bm) m)) =
f <$> (default β
m).
Proof.
destruct m; simpl; eauto.
rewrite fmap_empty; eauto.
Qed.
Lemma filter_union_ignored {K A} `{EqDecision K} `{Countable K} (m m' : gmap K A) (P : K->Prop)
`{! β k, Decision (P k)} :
( β k a, m' !! k = Some a -> Β¬ P k ) ->
filter (Ξ» v, P (fst v)) m = filter (Ξ» v, P (fst v)) (m' βͺ m).
Proof.
intros.
apply map_eq; intros i.
destruct (decide (P i)).
2: { rewrite !map_filter_lookup_key_notin; eauto. }
rewrite map_filter_lookup_key_in; eauto.
rewrite map_filter_lookup_key_in; eauto.
rewrite lookup_union_r; eauto.
destruct (m' !! i) eqn:He; eauto.
exfalso. eapply H1; eauto.
Qed.
Lemma filter_union_gmap_addr_by_block_ignored {A} (m m' : gmap addr A) (P : u64->Prop)
`{! β k, Decision (P k)} :
( β k a, m' !! k = Some a -> Β¬ P (fst k) ) ->
filter (Ξ» v, P (fst v)) (gmap_addr_by_block m) = filter (Ξ» v, P (fst v)) (gmap_addr_by_block (m' βͺ m)).
Proof.
intros.
apply map_eq; intros i.
destruct (decide (P i)).
2: { rewrite ?map_filter_lookup_key_notin; eauto. }
rewrite map_filter_lookup_key_in; eauto.
rewrite map_filter_lookup_key_in; eauto.
rewrite /gmap_addr_by_block.
destruct (gmap_curry m !! i) eqn:He.
2: {
symmetry.
erewrite lookup_gmap_curry_None in He.
erewrite lookup_gmap_curry_None. intros j. specialize (He j).
specialize (H0 (i, j)). simpl in *.
rewrite lookup_union_r; eauto.
destruct (m' !! (i, j)) eqn:Hee; eauto. exfalso. eapply H0; eauto.
}
destruct (gmap_curry (m' βͺ m) !! i) eqn:He2.
2: {
exfalso.
erewrite lookup_gmap_curry_None in He2.
apply gmap_curry_non_empty in He as He'. apply map_choose in He'. destruct He' as [j [x He']].
specialize (He2 j). rewrite lookup_union_r in He2.
2: { destruct (m' !! (i, j)) eqn:Hee; eauto. exfalso. eapply H0; eauto. }
rewrite -lookup_gmap_curry in He2. rewrite He /= in He2. congruence.
}
f_equal.
apply map_eq.
intros j.
replace (g !! j) with (m !! (i, j)).
2: { rewrite -lookup_gmap_curry. rewrite He. done. }
replace (g0 !! j) with ((m' βͺ m) !! (i, j)).
2: { rewrite -lookup_gmap_curry. rewrite He2. done. }
rewrite lookup_union_r; eauto.
destruct (m' !! (i, j)) eqn:Hee; eauto. exfalso. eapply H0; eauto.
Qed.
|
#ifndef BOOST_NETWORK_MESSAGE_DIRECTIVES_REMOVE_HEADER_IPP_20111021
#define BOOST_NETWORK_MESSAGE_DIRECTIVES_REMOVE_HEADER_IPP_20111021
// Copyright 2011 Dean Michael Berris ([email protected]).
// Copyright 2011 Google, Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/network/message/directives/remove_header.hpp>
namespace boost { namespace network { namespace impl {
remove_header_directive::remove_header_directive(std::string const & header_name):
header_name_(header_name) {}
void remove_header_directive::operator() (message_base & msg) const {
msg.remove_headers(header_name_);
}
} /* impl */
} /* network */
} /* boost */
#endif /* BOOST_NETWORK_MESSAGE_DIRECTIVES_REMOVE_HEADER_IPP_20111021 */
|
Chinese medical philosophy holds that all life is sustained by the constant flow of an energy called βqiβ (pronounced βcheeβ). The qi of the body is connected to the qi of nature β illness occurs when the two are out of harmony. Acupuncture and Oriental medicine restore health by strengthening the bodyβs qi and enhancing its flow.
Chinese medical knowledge has been shaped by the experiences of thousands of practitioners over many centuries.
Schedule Your Appointment for Acupuncture ONLINE! |
\chapter{Appendix example}
This is an appendix
It shows up in the table of contents, but does not count towards the page count.
|
Require Import Category.Lib.
Require Import Category.Theory.Category.
Require Import Category.Theory.Functor.
Require Import Category.Structure.Cone.
Require Import Category.Structure.Limit.
Require Import Category.Structure.Terminal.
Require Import Category.Instance.Zero.
Generalizable All Variables.
Theorem Terminal_Limit (C : Category) (F : 0 βΆ C) :
Limit F β @Terminal C.
Proof.
split; intros.
- construct.
+ exact (vertex_obj[X]).
+ given (cone : Cone F). {
unshelve (refine {| vertex_obj := x |}); unshelve econstructor; intros.
- inversion x0.
- inversion x0.
}
destruct (@ump_limits _ _ _ X cone).
apply unique_obj.
+ given (cone : Cone F). {
unshelve (refine {| vertex_obj := x |}); unshelve econstructor; intros.
- inversion x0.
- inversion x0.
}
destruct (@ump_limits _ _ _ X cone).
pose proof (uniqueness f).
pose proof (uniqueness g).
rewrite <- X0, <- X1.
* reflexivity.
* intro x0; inversion x0.
* intro x0; inversion x0.
- construct.
+ construct; [ | unshelve econstructor ].
* exact terminal_obj.
* inversion x.
* inversion x.
+ simpl.
unshelve eexists.
* exact one.
* intros.
inversion x.
* intros.
apply one_unique.
Qed.
|
State Before: X Y : TopCat
f : X βΆ Y
β’ Epi f β Function.Surjective ((forget TopCat).map f) State After: X Y : TopCat
f : X βΆ Y
β’ Epi f β Epi ((forget TopCat).map f) Tactic: suffices Epi f β Epi ((forget TopCat).map f) by
rw [this, CategoryTheory.epi_iff_surjective] State Before: X Y : TopCat
f : X βΆ Y
β’ Epi f β Epi ((forget TopCat).map f) State After: case mp
X Y : TopCat
f : X βΆ Y
β’ Epi f β Epi ((forget TopCat).map f)
case mpr
X Y : TopCat
f : X βΆ Y
β’ Epi ((forget TopCat).map f) β Epi f Tactic: constructor State Before: X Y : TopCat
f : X βΆ Y
this : Epi f β Epi ((forget TopCat).map f)
β’ Epi f β Function.Surjective ((forget TopCat).map f) State After: no goals Tactic: rw [this, CategoryTheory.epi_iff_surjective] State Before: case mp
X Y : TopCat
f : X βΆ Y
β’ Epi f β Epi ((forget TopCat).map f) State After: case mp
X Y : TopCat
f : X βΆ Y
aβ : Epi f
β’ Epi ((forget TopCat).map f) Tactic: intro State Before: case mp
X Y : TopCat
f : X βΆ Y
aβ : Epi f
β’ Epi ((forget TopCat).map f) State After: no goals Tactic: infer_instance State Before: case mpr
X Y : TopCat
f : X βΆ Y
β’ Epi ((forget TopCat).map f) β Epi f State After: no goals Tactic: apply Functor.epi_of_epi_map |
import Mathlib.Tactic.Linarith
import Mathlib.Data.Rat.Init
import Mathlib.Data.Rat.Order
import Mathlib.Data.Int.Order.Basic
set_option linter.unusedVariables false
example [LinearOrderedCommRing Ξ±] {a b : Ξ±} (h : a < b) (w : b < a) : False := by
linarith
example {Ξ± : Type} (_inst : (a : Prop) β Decidable a) [LinearOrderedCommRing Ξ±]
{a b c : Ξ±}
(ha : a < 0)
(hb : Β¬b = 0)
(hc' : c = 0)
(h : (1 - a) * (b * b) β€ 0)
(hc : 0 β€ 0)
(w : -(a * -b * -b + b * -b + 0) = (1 - a) * (b * b))
(h : (1 - a) * (b * b) β€ 0) :
0 < 1 - a := by
linarith
example (e b c a v0 v1 : Rat) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) :
v0 + 5 + (v1 - 3) + (c - 2) = 10 := by
linarith
example [LinearOrderedCommRing Ξ±] (e b c a v0 v1 : Ξ±) (h1 : v0 = 5*a) (h2 : v1 = 3*b)
(h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by
linarith
example (h : (1 : β€) < 0) (g : Β¬ (37 : β€) < 42) (_k : True) (l : (-7 : β€) < 5): (3 : β€) < 7 := by
linarith [(rfl : 0 = 0)]
example (u v r s t : Rat) (h : 0 < u*(t*v + t*r + s)) : 0 < (t*(r + v) + s)*3*u := by
linarith
example (A B : Rat) (h : 0 < A * B) : 0 < 8*A*B := by
linarith
example (A B : Rat) (h : 0 < A * B) : 0 < A*8*B := by
linarith
example [LinearOrderedCommRing Ξ±] (x : Ξ±) : 0 β€ x := by
have h : 0 β€ x := sorry
linarith
example [LinearOrderedCommRing Ξ±] (x : Ξ±) : 0 β€ x := by
have h : 0 β€ x := sorry
linarith [h]
example [LinearOrderedCommRing Ξ±] (u v r s t : Ξ±) (h : 0 < u*(t*v + t*r + s)) :
0 < (t*(r + v) + s)*3*u := by linarith
example [LinearOrderedCommRing Ξ±] (A B : Ξ±) (h : 0 < A * B) : 0 < 8*A*B := by
linarith
-- Needs the `cancel_denoms` preprocessor, which in turn needs the `cancel_denoms` tactic ported.
section cancel_denoms
-- example (A B : Rat) (h : 0 < A * B) : 0 < A*B/8 := by
-- linarith
-- example (A B : Rat) (h : 0 < A * B) : 0 < A/8*B := by
-- linarith
-- example (Ξ΅ : Rat) (h1 : Ξ΅ > 0) : Ξ΅ / 2 + Ξ΅ / 3 + Ξ΅ / 7 < Ξ΅ :=
-- by linarith
-- example (x y z : Rat) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0)
-- (h3 : 12*y - z < 0) : False :=
-- by linarith
-- example (Ξ΅ : Rat) (h1 : Ξ΅ > 0) : Ξ΅ / 2 < Ξ΅ :=
-- by linarith
-- example (Ξ΅ : Rat) (h1 : Ξ΅ > 0) : Ξ΅ / 3 + Ξ΅ / 3 + Ξ΅ / 3 = Ξ΅ :=
-- by linarith
end cancel_denoms
example (a b c : Rat) (h2 : b + 2 > 3 + b) : False := by
linarith (config := {discharger := do Lean.Elab.Tactic.evalTactic (β`(tactic| ring))})
example (a b c : Rat) (h2 : b + 2 > 3 + b) : False := by
linarith
-- We haven't implemented `restrict_type` yet.
-- example (a b c : β) (x y : β€) (h1 : x β€ 3*y) (h2 : b + 2 > 3 + b) : false :=
-- by linarith (config := {restrict_type := β})
example (g v V c h : Rat) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0)
(h5 : 0 β€ c) (h6 : c < 1) : v β€ V := by
linarith
example (x y z : β€) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : False := by
linarith
example (x y z : β€) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) (h3 : 12*y - 4* z < 0) :
False := by
linarith
example (a b c : Rat) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : False := by
linarith
example (a b c : Rat) (h2 : b > 0) (h3 : Β¬ b β₯ 0) : False := by
linarith
example (x y z : Rat) (hx : x β€ 3*y) (h2 : y β€ 2*z) (h3 : x β₯ 6*z) : x = 3*y := by
linarith
example (x y z : β€) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) : Β¬ 12*y - 4* z < 0 := by
linarith
example (x y z : Rat) (hx : Β¬ x > 3*y) (h2 : Β¬ y > 2*z) (h3 : x β₯ 6*z) : x = 3*y := by
linarith
example (x y : Rat) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x β₯ 0)
(h'' : (6 + 3 * y) * y β₯ 0) : False := by
linarith
example (a : Rat) (ha : 0 β€ a) : 0 * 0 β€ 2 * a := by
linarith
example (x y : Rat) (h : x < y) : x β y := by linarith
example (x y : Rat) (h : x < y) : Β¬ x = y := by linarith
-- Check `linarith!` works as expected
example (x : Rat) : id x β₯ x := by
fail_if_success
linarith
linarith!
opaque Nat.prime : β β Prop
example (x y z : Rat) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0) (h3 : 12*y + (-4)* z < 0)
(h4 : Nat.prime 7) : False := by
linarith
example (x y z : Rat) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z))
(h3 : 12*y + (-4)* z < 0) (h4 : Nat.prime 7) : False := by
linarith
example (w x y z : β€) (h1 : 4*x + (-3)*y + 6*w β€ 0) (h2 : (-1)*x < 0) (h3 : y < 0) (h4 : w β₯ 0)
(h5 : Nat.prime x.natAbs) : False := by
linarith
section term_arguments
example (x : Rat) (hx : x > 0) (h : x.num < 0) : False := by
linarith [Rat.num_pos_iff_pos.mpr hx, h]
example (x : Rat) (hx : x > 0) (h : x.num < 0) : False := by
fail_if_success
linarith
fail_if_success
linarith only [h]
fail_if_success
linarith only [Rat.num_pos_iff_pos.mpr hx]
linarith only [Rat.num_pos_iff_pos.mpr hx, h]
end term_arguments
-- Check we use `exfalso` on non-comparison goals.
example (a b c : Rat) (h2 : b > 0) (h3 : b < 0) : Nat.prime 10 := by
linarith
example (a b c : Rat) (h2 : (2 : Rat) > 3) : a + b - c β₯ 3 :=
by linarith (config := {exfalso := false})
-- Verify that we split conjunctions in hypotheses.
example (x y : Rat)
(h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 β§ (x + 4) * x β₯ 0 β§ (6 + 3 * y) * y β₯ 0) : False :=
by
fail_if_success
linarith (config := {split_hypotheses := false})
linarith
example (h : 1 < 0) (g : Β¬ 37 < 42) (k : True) (l : (-7 : β€) < 5) : 3 < 7 := by
linarith [(rfl : 0 = 0)]
example (h : 1 < 0) : 3 = 7 := by
linarith [Int.zero_lt_one]
example (h1 : (1 : β) < 1) : False := by
linarith
example (a b c : β) : a + b β₯ a := by
linarith
example (a b i : β) (h1 : Β¬ a < i) (h2 : b < i) (h3 : a β€ b) : False := by
linarith
example (x y : β) (h : x < 3 * y) : True := by
zify at h
trivial
example : (Nat.cast 2 : β€) = 2 := Nat.cast_ofNat
example (x y z : β) (hx : x β€ 3*y) (h2 : y β€ 2*z) (h3 : x β₯ 6*z) : x = 3*y := by
linarith
example (a b c : β) : Β¬ a + b < a := by
linarith
example (n : β) (h1 : n β€ 3) (h2 : n > 2) : n = 3 := by
linarith
example (z : β) (hz : Β¬ z β₯ 2) (h2 : Β¬ z + 1 β€ 2) : False := by
linarith
example (z : β) (hz : Β¬ z β₯ 2) : z + 1 β€ 2 := by
linarith
example (i : β€) (hi : i > 5) : 2 * i + 3 > 11 := by
linarith
example (m : β) : m * m + m + (2 * m + 2) = m * m + m + (m + 1) + (m + 1) := by
linarith
example (mess : β β β) (S n : β) :
mess S + (n * mess S + n * 2 + 1) < n * mess S + mess S + (n * 2 + 2) := by
linarith
example (p n p' n' : β) (h : p + n' = p' + n) : n + p' = n' + p := by
linarith
-- example (a b c : β) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c := by
-- linarith
example (N : β) (n : β) (Hirrelevant : n > N) (A : Rat) (l : Rat) (h : A - l β€ -(A - l))
(h_1 : Β¬A β€ -A) (h_2 : Β¬l β€ -l) (h_3 : -(A - l) < 1) : A < l + 1 := by
linarith
-- example (d : Rat) (q n : β) (h1 : ((q : Rat) - 1)*n β₯ 0) (h2 : d = 2/3*(((q : Rat) - 1)*n)) :
-- d β€ ((q : Rat) - 1)*n := by
-- linarith
-- example (d : Rat) (q n : β) (h1 : ((q : Rat) - 1)*n β₯ 0) (h2 : d = 2/3*(((q : Rat) - 1)*n)) :
-- ((q : Rat) - 1)*n - d = 1/3 * (((q : Rat) - 1)*n) := by
-- linarith
-- example (x y z : β) (hx : x < 5) (hx2 : x > 5) (hy : y < 5000000000) (hz : z > 34*y) : false :=
-- by linarith only [hx, hx2]
-- example (x y z : β) (hx : x < 5) (hy : y < 5000000000) (hz : z > 34*y) : x β€ 5 :=
-- by linarith only [hx]
example (u v x y A B : β)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
u * y + v * x + u * v < 3 * A * B :=
by nlinarith
example (u v x y A B : β) : (0 < A) β (A β€ 1) β (1 β€ B)
β (x β€ B) β ( y β€ B)
β (0 β€ u ) β (0 β€ v )
β (u < A) β ( v < A)
β (u * y + v * x + u * v < 3 * A * B) := by
intros
nlinarith
example (u v x y A B : Rat)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
(0 <= A * (1 - A))
-> (0 <= A * (B - 1))
-> (0 < A * (A - u))
-> (0 <= (B - 1) * (A - u))
-> (0 <= (B - 1) * (A - v))
-> (0 <= (B - x) * v)
-> (0 <= (B - y) * u)
-> (0 <= u * (A - v))
->
u * y + v * x + u * v < 3 * A * B := by
intros
linarith
example (u v x y A B : Rat)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
(0 < A * A)
-> (0 <= A * (1 - A))
-> (0 <= A * (B - 1))
-> (0 <= A * (B - x))
-> (0 <= A * (B - y))
-> (0 <= A * u)
-> (0 <= A * v)
-> (0 < A * (A - u))
-> (0 < A * (A - v))
-> (0 <= (1 - A) * A)
-> (0 <= (1 - A) * (1 - A))
-> (0 <= (1 - A) * (B - 1))
-> (0 <= (1 - A) * (B - x))
-> (0 <= (1 - A) * (B - y))
-> (0 <= (1 - A) * u)
-> (0 <= (1 - A) * v)
-> (0 <= (1 - A) * (A - u))
-> (0 <= (1 - A) * (A - v))
-> (0 <= (B - 1) * A)
-> (0 <= (B - 1) * (1 - A))
-> (0 <= (B - 1) * (B - 1))
-> (0 <= (B - 1) * (B - x))
-> (0 <= (B - 1) * (B - y))
-> (0 <= (B - 1) * u)
-> (0 <= (B - 1) * v)
-> (0 <= (B - 1) * (A - u))
-> (0 <= (B - 1) * (A - v))
-> (0 <= (B - x) * A)
-> (0 <= (B - x) * (1 - A))
-> (0 <= (B - x) * (B - 1))
-> (0 <= (B - x) * (B - x))
-> (0 <= (B - x) * (B - y))
-> (0 <= (B - x) * u)
-> (0 <= (B - x) * v)
-> (0 <= (B - x) * (A - u))
-> (0 <= (B - x) * (A - v))
-> (0 <= (B - y) * A)
-> (0 <= (B - y) * (1 - A))
-> (0 <= (B - y) * (B - 1))
-> (0 <= (B - y) * (B - x))
-> (0 <= (B - y) * (B - y))
-> (0 <= (B - y) * u)
-> (0 <= (B - y) * v)
-> (0 <= (B - y) * (A - u))
-> (0 <= (B - y) * (A - v))
-> (0 <= u * A)
-> (0 <= u * (1 - A))
-> (0 <= u * (B - 1))
-> (0 <= u * (B - x))
-> (0 <= u * (B - y))
-> (0 <= u * u)
-> (0 <= u * v)
-> (0 <= u * (A - u))
-> (0 <= u * (A - v))
-> (0 <= v * A)
-> (0 <= v * (1 - A))
-> (0 <= v * (B - 1))
-> (0 <= v * (B - x))
-> (0 <= v * (B - y))
-> (0 <= v * u)
-> (0 <= v * v)
-> (0 <= v * (A - u))
-> (0 <= v * (A - v))
-> (0 < (A - u) * A)
-> (0 <= (A - u) * (1 - A))
-> (0 <= (A - u) * (B - 1))
-> (0 <= (A - u) * (B - x))
-> (0 <= (A - u) * (B - y))
-> (0 <= (A - u) * u)
-> (0 <= (A - u) * v)
-> (0 < (A - u) * (A - u))
-> (0 < (A - u) * (A - v))
-> (0 < (A - v) * A)
-> (0 <= (A - v) * (1 - A))
-> (0 <= (A - v) * (B - 1))
-> (0 <= (A - v) * (B - x))
-> (0 <= (A - v) * (B - y))
-> (0 <= (A - v) * u)
-> (0 <= (A - v) * v)
-> (0 < (A - v) * (A - u))
-> (0 < (A - v) * (A - v))
->
u * y + v * x + u * v < 3 * A * B := by
intros
linarith
-- TODO this needs the `cancelDenoms` preprocessor.
-- example (A B : β) : (0 < A) β (1 β€ B) β (0 < A / 8 * B) := by
-- intros
-- nlinarith
example (x y : β) : 0 β€ x ^2 + y ^2 := by
nlinarith
example (x y : β) : 0 β€ x*x + y*y := by
nlinarith
example (x y : β) : x = 0 β y = 0 β x*x + y*y = 0 := by
intros
nlinarith
lemma norm_eq_zero_iff {x y : β} : x * x + y * y = 0 β x = 0 β§ y = 0 := by
constructor
Β· intro
constructor <;>
nlinarith
Β· intro; nlinarith
lemma norm_zero_left {x y : β} (h1 : x * x + y * y = 0) : x = 0 := by
nlinarith
lemma norm_nonpos_right {x y : β} (h1 : x * x + y * y β€ 0) : y = 0 := by
nlinarith
lemma norm_nonpos_left (x y : β) (h1 : x * x + y * y β€ 0) : x = 0 := by
nlinarith
variable {E : Type _} [AddGroup E]
example (f : β€ β E) (h : 0 = f 0) : 1 β€ 2 := by nlinarith
example (a : E) (h : a = a) : 1 β€ 2 := by nlinarith
-- -- test that the apply bug doesn't affect linarith preprocessing
-- constant Ξ± : Type
-- variable [fact false] -- we work in an inconsistent context below
-- def leΞ± : Ξ± β Ξ± β Prop := Ξ» a b, β c : Ξ±, true
-- noncomputable instance : linear_ordered_field Ξ± :=
-- by refine_struct { le := leΞ± }; exact (fact.out false).elim
-- example (a : Ξ±) (ha : a < 2) : a β€ a :=
-- by linarith
example (p q r s t u v w : β) (h1 : p + u = q + t) (h2 : r + w = s + v) :
p * r + q * s + (t * w + u * v) = p * s + q * r + (t * v + u * w) :=
by nlinarith
-- -- Tests involving a norm, including that squares in a type where `sq_nonneg` does not apply
-- -- do not cause an exception
-- variables {R : Type _} [Ring R] (abs : R β β)
-- lemma abs_nonneg' : β r, 0 β€ abs r := (fact.out false).elim
-- example (t : R) (a b : β) (h : a β€ b) : abs (t^2) * a β€ abs (t^2) * b :=
-- by nlinarith [abs_nonneg' abs (t^2)]
-- example (t : R) (a b : β) (h : a β€ b) : a β€ abs (t^2) + b :=
-- by linarith [abs_nonneg' abs (t^2)]
-- example (t : R) (a b : β) (h : a β€ b) : abs t * a β€ abs t * b :=
-- by nlinarith [abs_nonneg' abs t]
-- constant T : Type
-- attribute [instance]
-- constant T_zero : ordered_ring T
-- namespace T
-- lemma zero_lt_one : (0 : T) < 1 := (fact.out false).elim
-- lemma works {a b : β} (hab : a β€ b) (h : b < a) : false :=
-- begin
-- linarith,
-- end
-- end T
-- example (a b c : β) (h : a β b) (h3 : b β c) (h2 : a β₯ b) : b β c :=
-- by linarith {split_ne := tt}
-- example (a b c : β) (h : a β b) (h2 : a β₯ b) (h3 : b β c) : a > b :=
-- by linarith {split_ne := tt}
example (x y : β) (hβ : 0 β€ y) (hβ : y β€ x) : y * x β€ x * x := by nlinarith
example (x y : β) (hβ : 0 β€ y) (hβ : y β€ x) : y * x β€ x ^ 2 := by nlinarith
axiom foo {x : Int} : 1 β€ x β 1 β€ x*x
lemma bar (x y: Int) (h : 0 β€ y β§ 1 β€ x) : 1 β€ y + x * x := by linarith [foo h.2]
-- -- issue #9822
-- lemma mytest (j : β) (h : 0 < j) : j-1 < j:= by linarith
example [LinearOrderedCommRing Ξ±] (h : β x : Ξ±, 0 β€ x) : True := by
cases' h with x h
have : 0 β€ x; Β· linarith
trivial
-- At one point, this failed, due to `mdata` interfering with `Expr.isEq`.
example (a : Int) : a = a := by
have h : True := True.intro
linarith
example (n : Nat) (h1 : Β¬n = 1) (h2 : n β₯ 1) : n β₯ 2 := by
by_contra h3
suffices n = 1 by exact h1 this
linarith
example (n : Nat) (h1 : Β¬n = 1) (h2 : n β₯ 1) : n β₯ 2 := by
have h4 : n β₯ 1 := h2
by_contra h3
suffices n = 1 by exact h1 this
linarith
|
print "Hello world!";
|
# -----------------------------------------------------------------------------
#
# Copyright (c) 2017 Sam Cox, Roberto Sommariva
#
# This file is part of the AtChem2 software package.
#
# This file is covered by the MIT license which can be found in the file
# LICENSE.md at the top level of the AtChem2 distribution.
#
# -----------------------------------------------------------------------------
## plotting tool for the AtChem2 model output
## --> R version
##
## ARGUMENT:
## - directory with the model output
##
## USAGE:
## Rscript --vanilla ./tools/plot/plot-atchem2.r ./model/output/
## ---------------------------------------------- ##
cmd_args <- commandArgs(trailingOnly = TRUE)
setwd(cmd_args[1])
getwd()
df1 <- read.table("speciesConcentrations.output", header=T)
df2 <- read.table("environmentVariables.output", header=T)
df3 <- read.table("photolysisRates.output", header=T)
df4 <- read.table("photolysisRatesParameters.output", header=T)
nc1 <- ncol(df1)
nc2 <- ncol(df2)
nc3 <- ncol(df3)
nc4 <- ncol(df4)
## ---------------------------- ##
cairo_pdf("atchem2_output.pdf", onefile=T, width=11, height=7)
## speciesConcentrations.output
par(mfrow=c(3,2))
for (i in 2:nc1) {
plot(df1[[1]], df1[[i]], type="l",
main=colnames(df1[i]), xlab="seconds", ylab="")
}
## environmentVariables.output
par(mfrow=c(3,2))
for (i in 2:nc2) {
plot(df2[[1]], df2[[i]], type="l",
main=colnames(df2[i]), xlab="seconds", ylab="")
}
## photolysisRates.output
par(mfrow=c(3,2))
for (i in 2:nc3) {
plot(df3[[1]], df3[[i]], type="l",
main=colnames(df3[i]), xlab="seconds", ylab="")
}
## photolysisRatesParameters.output
par(mfrow=c(3,2))
for (i in 2:nc4) {
plot(df4[[1]], df4[[i]], type="l",
main=colnames(df4[i]), xlab="seconds", ylab="")
}
dev.off()
## ---------------------------- ##
cat("\n===> atchem2_output.pdf created in directory:", cmd_args[1], "\n\n")
|
{- Support code -}
data Shape = ||| A triangle, with its base length and height
Triangle Double Double
| ||| A rectangle, with its length and height
Rectangle Double Double
| ||| A circle, with its radius
Circle Double
area : Shape -> Double
area (Triangle base height) = 0.5 * base * height
area (Rectangle length height) = length * height
area (Circle radius) = pi * radius * radius
data Picture = Primitive Shape
| Combine Picture Picture
| Rotate Double Picture
| Translate Double Double Picture
testPic1 : Picture
testPic1 = Combine (Primitive (Triangle 2 3))
(Primitive (Triangle 2 4))
testPic2 : Picture
testPic2 = Combine (Primitive (Rectangle 1 3))
(Primitive (Circle 4))
data Tree elem = Empty
| Node (Tree elem) elem (Tree elem)
%name Tree tree, tree1
insert : Ord elem => elem -> Tree elem -> Tree elem
insert x Empty = Node Empty x Empty
insert x orig@(Node left val right)
= case compare x val of
LT => Node (insert x left) val right
EQ => orig
GT => Node left val (insert x right)
{- Answers -}
{- 1 -}
listToTree : Ord a => List a -> Tree a
listToTree [] = Empty
listToTree (x :: xs) = insert x (listToTree xs)
{- 2 -}
treeToList : Tree a -> List a
treeToList Empty = []
treeToList (Node left val right) = treeToList left ++ val :: treeToList right
{- 3 -}
data Expr = Val Int
| Add Expr Expr
| Sub Expr Expr
| Mult Expr Expr
{- 4 -}
evaluate : Expr -> Int
evaluate (Val x) = x
evaluate (Add x y) = evaluate x + evaluate y
evaluate (Sub x y) = evaluate x - evaluate y
evaluate (Mult x y) = evaluate x * evaluate y
{- 5 -}
maxMaybe : Ord a => Maybe a -> Maybe a -> Maybe a
maxMaybe Nothing Nothing = Nothing
maxMaybe Nothing (Just x) = Just x
maxMaybe (Just x) Nothing = Just x
maxMaybe (Just x) (Just y) = Just (max x y)
{- 6 -}
biggestTriangle : Picture -> Maybe Double
biggestTriangle (Primitive tri@(Triangle x y)) = Just (area tri)
biggestTriangle (Primitive _) = Nothing
biggestTriangle (Combine x y) = maxMaybe (biggestTriangle x) (biggestTriangle y)
biggestTriangle (Rotate x pic) = biggestTriangle pic
biggestTriangle (Translate x y pic) = biggestTriangle pic
|
Formal statement is: lemma complex_cnj_mult [simp]: "cnj (x * y) = cnj x * cnj y" Informal statement is: The complex conjugate of a product is the product of the complex conjugates. |
% A simple template for LaTeX documents
%
% To produce pdf run:
% $ pdflatex paper.tex
%
\documentclass[10pt, twocolumn]{article}
%\documentclass[12pt]{article}
% Begin paragraphs with new line
\usepackage{parskip}
% Change margin size
\usepackage[margin=0.5in]{geometry}
% Graphics Example: (PDF's make for good plots)
\usepackage{graphicx}
% \centerline{\includegraphics{figure.pdf}}
% Allows hyperlinks
\usepackage{hyperref}
% Blocks of code
\usepackage{listings}
\lstset{basicstyle=\ttfamily, title=\lstname}
% Insert code like this. replace `plot.R` with file name.
% \lstinputlisting{plot.R}
% Monospaced fonts
%\usepackage{inconsolata}
% GNU \texttt{make} is a nice tool.
% Supports proof environment
\usepackage{amsthm}
% Allows writing \implies and align*
\usepackage{amsmath}
% Allows mathbb{R}
\usepackage{amsfonts}
% Numbers in scientific notation
\usepackage{siunitx}
% Use tables generated by pandas
\usepackage{booktabs}
% norm and infinity norm
\newcommand{\norm}[1]{\left\lVert#1\right\rVert}
\newcommand{\inorm}[1]{\left\lVert#1\right\rVert_\infty}
% Statistics essentials
\newcommand{\iid}{\text{ iid }}
\newcommand{\Expect}{\operatorname{E}}
\newcommand{\Var}{\operatorname{Var}}
\newcommand{\Cov}{\operatorname{Cov}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\textbf{Binomial}
$X \sim B(n, p)$
\[
p(k) = \binom{n}{k} p^k (1-p)^{n-k}
\qquad k = 0, 1, \dots, n
\]
$\Expect X = np, \quad \Var X = np(1-p)$
mgf: $M_X (t) = (pe^t + 1 - p)^n$
Beta is conjugate prior, Fisher info $I(p) = \frac{1}{p(1 - p)}$
\textbf{Poisson}
$X \sim P(\lambda)$
\[
p(k) = \frac{e^{-\lambda} \lambda^k}{k!}
\qquad k = 0, 1, \dots
\]
$\Expect X = \lambda, \quad \Var X = \lambda$
mgf: $M_X (t) = e^{\lambda (e^t -1)}$ Use recursive relation to compute
$\Expect(X_i)$.
Gamma is conjugate prior, Fisher info $I(\lambda) = \frac{1}{\lambda}$
\textbf{Normal}
$X \sim N(\mu, \Sigma)$, $\Sigma$ positive definite
\[
f(x) = \frac{\exp\{ - \frac{1}{2}(x - \mu)^T \Sigma^{-1} (x - \mu) \}}
{(2\pi)^{\frac{k}{2}} \sqrt{\det(\Sigma)}}
= \frac{1}{\sqrt{2 \pi} \sigma} e^{-\frac{(x - \mu)^2}{2
\sigma^2}}
\]
mgf: $M_X (t) = \exp (\mu' t + \frac{1}{2} t' \Sigma t)$
Normal is conj. prior, Fisher info $I(\mu, \sigma^2) =
[\begin{smallmatrix}
1 / \sigma^2 & 0 \\
0 & 1 / 2\sigma^4 \\
\end{smallmatrix}]$
\textbf{Beta}
$ X \sim \text{Beta}(\alpha, \beta)$
\[
f(x) = \frac{x^{\alpha-1}(1 - x)^{\beta-1}}{B(\alpha, \beta)}
\qquad 0 \leq x \leq 1
\]
$\Expect X = \frac{\alpha}{\alpha + \beta},
\quad \Var X = \frac{\alpha \beta}{(\alpha + \beta)^2 (\alpha + \beta + 1)}$
using the beta function:
\[
B(\alpha, \beta) =
\frac{\Gamma(\alpha) \Gamma(\beta)}{\Gamma(\alpha+ \beta)} =
\int_0^1 t^{\alpha -1} (1-t)^{\beta - 1}dt
\]
\textbf{Gamma}
$X \sim \text{Gamma}(\alpha, \beta)$
\[
f(x) = \frac{\beta^\alpha x^{\alpha-1} e^{-\beta x}}{\Gamma(\alpha)}
\qquad x > 0
\]
$\Expect X = \frac{\alpha}{\beta},
\quad \Var X = \frac{\alpha}{\beta^2}$
mgf: $M_X (t) = (1 - \frac{t}{\beta})^{-\alpha}, t < \beta$
$X \sim \text{Gamma}(\alpha, \beta) \iff \beta X \sim \text{Gamma}(\alpha, 1)$
$X_i \iid \text{Gamma}(\alpha_i, \beta)$, then
\[
\sum X_i \sim \text{Gamma}(\sum \alpha_i, \beta)
\]
Gamma function: $\Gamma(\alpha) = \int_0^\infty t^{\alpha-1} e^{-t} dt$.
$\Gamma(\frac{1}{2}) = \sqrt{\pi}$.
$\Gamma(\alpha + 1) = \alpha \Gamma(\alpha)$
$\Gamma(k) = (k-1)!$ for $k$ positive integer.
\textbf{Exponential}
Special case: $X \sim \text{Exp}(\lambda) \equiv \text{Gamma}(1, \lambda)$
$
f(x) = \lambda e^{-\lambda x},
\quad x > 0
\qquad \Expect X = \frac{1}{\lambda},
\quad \Var X = \frac{1}{\lambda ^2}
$
CDF $F(x) = 1 - e^{-\lambda x}$
\textbf{Chi square}
Special case: $X \sim \chi^2_n \equiv \text{Gamma}(\frac{n}{2}, \frac{1}{2})$
$
f(x) \propto x^{\frac{n}{2} - 1} e^{\frac{-x}{2}},
\quad x > 0
\qquad \Expect X = n,
\quad \Var X = 2n
$
Let $Z_i$ be iid $N(0, 1)$.
$\sum_{i=1}^n Z_i^2 \sim \chi^2_n$
Noncentral $\chi^2$. Let $Y \sim N(\mu, I)$ be an $n$ vector. Then
\[
\norm{Y}^2 \sim \chi^2_n(\norm{\mu}^2)
\]
\textbf{F}
\[
F(m, n) \equiv \frac{\frac{\chi^2_m}{m}}
{\frac{\chi^2_n}{n}}
\]
Where numerator and denominator are independent $\chi^2$.
\textbf{T}
\[
t(n) = \frac{N(0, 1)}
{\sqrt{\frac{\chi^2_n}{n}}}
\]
Where numerator and denominator are independent.
\vspace{0.2in}
\hrule
\textbf{Transformations} If $g$ 1:1 with continuous derivatives and nonzero
Jacobian, and $Y = g(X)$, then the density
\[
f_Y(y) = f_X(g^{-1}(y)) |J_{g^{-1}}(y)|
\]
For affine transformation $Y = AX + c$ then
\[
f_Y(y) = f_X(A^{-1}(y - c)) |\det A|^{-1}
\]
Moment generating functions determine distribution
\[
M_X(t) \equiv \Expect (e^{tX}),
\quad M_X'(0) = \Expect(X)
\]
$X_i$ independently distributed $\iff$
\[
M_{\sum X_i} (t) = \prod M_{X_i} (t)
\]
\textbf{Characteristic function}
\[
\phi(t) = \Expect (e^{i t^T X)}
= \Expect (\cos (t^T X)) + i \Expect(\sin(t^T X))
\]
Order statistics for sorted sample $X_{(1)}, \dots, X_{(n)}$ has pdf:
\[
n! \prod_{i=1}^n f(X_{(i)}) \quad I(X_{(1)} < \dots < X_{(n)})
\]
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section*{TODO - add measure theory}
\textbf{Jensen's Inequality} if $S \subset R^k$ convex and closed, $g$ convex on $S$, $P[X
\in S] = 1$, and $\Expect X$ is finite, then $\Expect X \in S$, $\Expect
g(X)$ exists, and
\[
\Expect g(X) \geq g(\Expect X)
\]
\textbf{Holder's Inequality} if $r, s > 1$ and $\frac{1}{r} + \frac{1}{s} =
1$ then
\[
\Expect |XY| \leq (\Expect |X|^r)^{\frac{1}{r}}(\Expect |X|^s)^{\frac{1}{s}}
\]
$T(X)$ Sufficient means the distribution of $X | T(X)$ does not depend on
$\theta$.
Factorization theorem: $T(x)$ is sufficient $\iff$
\[
f_{\theta}(x) = h(x) g(\theta, T(x))
\]
$L_x (\theta) = p_\theta (x) = p(x, \theta)$ likelihood is function of
$\theta$, density is function of $x$.
The likelihood ratio
\[
\lambda_x (\theta) = \frac{L_x (\theta)}{L_x (\theta_0)}
\]
is minimal sufficient. To show $T(x)$ is minimal sufficient show that it is
sufficient and a function of the likelihood $\lambda_x (\theta)$.
\textbf{Fisher information}
\[
I(\theta) = \Expect_\theta \left[ \frac{\partial}{\partial \theta}
\log L_X (\theta) \right]^2
= \Expect_\theta \left[ - \frac{\partial^2}{\partial \theta^2}
\log L_X (\theta) \right]
\]
$\text{bias } \hat{v} \equiv \Expect (\hat{v}) - v$
\[
MSE(\hat{v}) \equiv \Expect (\hat{v} - v)^2
= \Var (\hat{v}) + (\text{bias } \hat{v})^2
\]
\textbf{Rao-Blackwell} Let $S(X)$ be an unbiased point estimator for
$g(\theta)$. Conditioning on a sufficient statistic $T(X)$ reduces
variance.
\[
\Var_{\theta} (S(X)) \geq \Var_{\theta} (\Expect (S(X) | T(X)))
\]
Also holds for more general convex loss function $L$:
\[
R(\theta, S) \equiv \Expect_{\theta} L(\theta, S(X)) \geq
\Expect_{\theta} L(\theta, \Expect( S(X) | T(X)))
\]
\textbf{Completeness} $T(X)$ is complete if $\Expect g(T(X)) = 0$
implies $g = 0$ almost surely for all $\theta$.
\textbf{Cramer Rao Inequality} Let $g: \Theta \rightarrow R$. Suppose there
exists an unbiased estimator $U(X)$, $\Expect U(X) = g(\theta)$. Then
\[
\Var_\theta U(X) \geq
\left( \frac{\partial g(\theta)}{\partial \theta} \right)^T
I(\theta)^{-1}
\left( \frac{\partial g(\theta)}{\partial \theta} \right)
\]
Basu's Theorem - If $T(X)$ complete sufficient statistic and $A(X)$ is
ancillary then $A(X)$ and $T(X)$ are independent.
\textbf{Lehmann - Scheffe} Suppose $T(X)$ is complete sufficient. Then
there exists unique unbiased estimator $\Expect h(T(x))$ of $g(\theta) \in
R$ with smallest variance (MVUE).
\textbf{Exponential Families} $T(x)$ is natural sufficient statistic and is
complete sufficient if the $k$ parameter exponential family is full rank.
\[
p(x, \theta) = h(x) \exp \{ \eta(\theta)^T T(x) - B(\theta) \}
\]
Canonical form model indexed by $\eta$.
\[
q(x, \eta) = h(x) \exp \{ \eta^T T(x) - A(\eta) \}
\]
\[
\dot{A} (\eta) = \Expect_\eta (T(X)) \quad
\ddot{A} (\eta) = I(\eta) = \Var_\eta (T(X))
\]
Then moment generating function for $T(X)$ is
\[
M_{T(X)}(t) = \exp \{A(t + \eta) - A(\eta) \}
\]
Equivalent statements useful for GLM's such as $Y \sim N(X \beta,
\sigma_0^2 I)$, where $Z$ is $n \times p$:
1. $I(\beta) = \frac{1}{\sigma_0^2} X^T X$ positive definite
2. rank$(X) = p$
3. model is identifiable. More generally another equivalent statement is
$\Var (T(X)) = \ddot{A} (\eta)$ is positive definite.
\subsection*{Decision Theory}
\textbf{Decision rule} $\delta: \mathcal{X} \rightarrow \mathcal{A}$, where
$\delta \in \mathcal{D}$, the space of possible decision rules and
$\mathcal{A}$ is the action space.
\textbf{Loss function} $l: \Theta \times \mathcal{A} \rightarrow \mathbb{R}^+$
Posterior mean minimizes square error loss; median minimizes absolute loss.
\textbf{Risk function} $R: \Theta \times \mathcal{D} \rightarrow
\mathbb{R}^+$ expected loss for a particular value of $\theta$
\[
R(\theta, \delta) = \Expect_\theta l(\theta, \delta(X)) = \int
l(\theta, \delta(x)) \cdot p_\theta (x) dx
\]
Bayes setup:
\[
\pi(\theta | x) = \frac{p_\theta (x) \pi(\theta)}{m(x)}
\]
\textbf{Bayes decision rule} If there exists $\delta_\pi \in \mathcal{D}$
w.r.t prior $\pi$ such that
\[
r(\pi, \delta_\pi) = \inf_{\delta \in \mathcal{D}} r(\pi, \delta)
\]
To find Bayes rule minimize the posterior risk:
\[
\delta_\pi (x) = \min_{a \in \mathcal{A}} r_\pi (a | x)
\]
\textbf{Bayes risk} $r_\pi : \mathcal{D} \rightarrow
\mathbb{R}^+$ expected loss for fixed prior $\pi$
\[
r_\pi (\delta) = \Expect_\pi R(\theta, \delta)
= \int_\Theta R(\theta, \delta) \pi (d \theta)
= \int_\mathcal{X} r_\pi(\delta(x) | x) m(x) dx
\]
To find Bayes risk: 1) find the Bayes rule 2) compute the risk function 3)
take the expectation of the risk wrt prior $\pi$.
\textbf{Minimax} decision rule $\delta^*$ minimizes the worst case
scenario, satisfies
\[
\sup_{\theta} R(\theta, \delta^*) = \inf_{\delta} \sup_{\theta}
R(\theta, \delta)
\]
To show $\delta^*$ is minimax, first check for constant risk $R(\theta,
\delta^* = c$ for all $\theta$, then find a
prior $\pi$ such that $\delta^*$ is the Bayes rule. This $\pi$ is least
favorable. More generally can find
a sequence of priors $(\pi_k)$ such that the Bayes risk $r_{\pi_k}
(\delta_{\pi_k}) \rightarrow c$.
\newpage
\subsection*{Asymptotics}
\textbf{Almost Sure convergence}
\[
X_n \xrightarrow{a.s.} X \quad \text{means} \quad P(X_n \rightarrow X)
= 1
\]
Theorem: $\iff P(\sup_{m \geq n} |X_m - X| > \epsilon) \rightarrow 0
\quad \forall \epsilon > 0$.
\textbf{Convergence in Probability}
\[
X_n \xrightarrow{p} X
\]
means that $P( |X_n - X| > \epsilon ) \rightarrow 0$ for all $\epsilon > 0$.
\textbf{Generalized Chebychev Inequality}
Let $X$ be a r.v. and $g$ be a
nonnegative function increasing on the range of $X$. Then
\[
P(X \geq a) \leq \frac{\Expect g(X)}{g(a)}
\]
\textbf{Borel Cantelli Lemma}
\textbf{Hoeffding Inequality}
Let $X_1, \dots, X_n$ be independent (not necessarily iid) with $a_i \leq
X_i \leq b_i$ and $\Expect X_i = 0$. Then
\[
P \left( \sum_{i=1}^n X_i \geq \eta \right) \leq
\exp \left\{ -\frac{2\eta^2}{\sum_{i=1}^n (b_i - a_i)^2} \right\}
\]
\newpage
\subsection*{Multivariate Normal}
log likelihood for $k$ vector $x \sim N(\mu, \Sigma)$
\[
l_x = -\frac{k}{2} \log 2 \pi - \frac{1}{2}
\{ \log \det \Sigma + (x - \mu)^T \Sigma^{-1} (x - \mu) \}
\]
Stein's formula: $X \sim N(\mu, \sigma)$
\[
\Expect (g(X) (X - \mu)) = \sigma^2 \Expect(g'(X))
\]
assuming these expectations are finite.
$X \sim N(\mu, \Sigma)$, $A$ an $m \times n$ matrix,
then
\[
AX \sim N(A \mu, A \Sigma A^t)
\]
For $\Sigma$ full rank it's possible to transform between $Z \sim
N(0, I)$ and $X$:
\[
X = \Sigma^{1/2} Z + \mu \qquad Z = \Sigma^{-1/2} (X - \mu)
\]
In block matrix form:
\[
X =
\begin{bmatrix}
X_1 \\
X_2 \\
\end{bmatrix}
\sim N \left(
\begin{bmatrix}
\mu_1 \\
\mu_2 \\
\end{bmatrix}
,
\begin{bmatrix}
\Sigma_{11} & \Sigma_{12} \\
\Sigma_{21} & \Sigma_{22} \\
\end{bmatrix}
\right)
\]
Assuming $\Sigma_{11}$ is positive definite then the conditional
distribution
\[
X_2 | X_1 \sim N(\mu_2 + \Sigma_{21} \Sigma_{11}^{-1} (X_1 - \mu_1),
\Sigma_{22} - \Sigma_{21} \Sigma_{11}^{-1} \Sigma_{12})
\]
\subsection*{Conditional Distributions}
Conditional pdf:
\[
f_{X|Y}(x | y) \equiv \frac{f_{X, Y}(x, y)}{f_Y(y)}
\]
Iterated expectation:
\[
E(Y) = E(E(Y | X))
\]
Conditional variance formula:
\[
\Var(Y) = \Var(E(Y | X)) + E(\Var(Y | X))
\]
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection*{General Techniques}
Singular Value Decompostion (SVD) Any matrix $X$ can be written
\[
X = UDV^T
\]
with $U, V$ orthogonal, and $D$ diagonal.
Moore Penrose Psuedoinverse $A^+$ exists uniquely for every matrix $A$.
Projection matrix $P$ are symmetric and idempotent. They have eigenvalues
either 0 or 1.
\[
P = P^T \qquad P^2 = P
\]
Covariance of linear transformations
\[
Cov(Ay, Bx) = A Cov(y, x) B^T
\]
Invert $2 \times 2$ matrix:
$
A =
[\begin{smallmatrix}
a & b \\
c & d \\
\end{smallmatrix}]
$
\[
A^{-1} =
\frac{1}{\det (A)}
\begin{bmatrix}
d & -b \\
-c & a \\
\end{bmatrix}
\]
Sum identities:
\[
\sum_{k=0}^{\infty} p^k = \frac{p}{1 - p} \qquad
\sum_{k=0}^{\infty} k p^k = \frac{p}{(1 - p)^2} \qquad |p| < 1
\]
Integration by parts:
\[
\int uv' = uv - \int u'v
\]
Matrix / Vector differentiation
$\frac{\partial A^T \beta}{\partial \beta} = A$,
$\frac{\partial \beta^T A \beta}{\partial \beta} = (A + A^t) \beta =
2A\beta$ for $A$ symmetric.
$\frac{\partial}{\partial \theta_i} \log (|A|) =
tr( A^{-1} \frac{\partial A}{\partial \theta_i}$)
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection*{Linear Models}
Least Squares Principle
\[
\text{arg min}_\beta \norm{Y - X\beta}^2
\]
Normal Model
\[
Y = X\beta + \epsilon, \qquad \epsilon \sim N(0, \sigma^2 I)
\]
Normal Equations - Any $b$ satistfying this solves the least squares
\[
X^T X b = X^T y
\]
Gauss Markov Theorem - $\hat{\beta}$ is Best Linear Unbiased
Estimator (BLUE) of $\beta$.
\[
\hat{\beta} = (X^T X)^{-1} X^T y \sim N(\beta, \sigma^2 (X^T X)^{-1})
\]
Estimating the variance: $\frac{\norm{y - X \hat{\beta}}^2}{\sigma^2} \sim
\chi^2_{n-p}$.
\[
\hat{\sigma}^2 = \frac{\norm{y - X \hat{\beta}}^2}{n - p}
\]
Use t test for hypothesis testing and confidence intervals for the value of
a particular $\beta_j$ coefficient.
Let $w_{ii}$ be the $i$th diagonal entry of $(X^T X)^{-1}$.
\[
\frac{\beta_j - \beta_j^*}{\hat{\sigma} \sqrt{w_{ii}}} \sim t_{n-p}
\]
$1 - \alpha$ Confidence intervals for new observation $Y_h$ at $x_h$ and $E[Y_h]$:
\[
E[y_h] \approx \hat{y_h} \pm t(n-p, 1 - \frac{\alpha}{2}) \hat{\sigma}
\sqrt{x_h^T (X^T X)^{-1} x_h}
\]
\[
y_h \approx \hat{y_h} \pm t(n-p, 1 - \frac{\alpha}{2}) \hat{\sigma}
\sqrt{1 + x_h^T (X^T X)^{-1} x_h}
\]
Simultaneous (Working-Hotelling) confidence interval for $\Expect (y_h)$:
\[
\hat{y}_h \pm \sqrt{p F_{p, n - p, 1 - \alpha}} se\{ \hat{y}_h \}
\]
\[
\frac{(\hat{\beta} - \beta)^T X^T X (\hat{\beta} - \beta) /
p}{\hat{\sigma}^2}
\sim F_{p, n - p}
\]
General linear tests. Partition $\beta = (\beta_1, \beta_2)$ where $\beta_1$
is an $r$ vector and $\beta_2$ is $p - r$. Null hypothesis $H_0: \beta_2 =
\beta_2^*$ (often 0), and $H_a: \beta_2 \neq \beta_2^*$. Then
$SSE_r = \norm{y - X_2 \beta_2^* - X_1 \tilde{\beta_1}}^2$ is the sum of
squared error for the reduced model and
$SSE_f = \norm{y - X \hat{\beta}}^2$ is the squared sum of error for the
full model.
Under $H_0$:
\[
\frac{\frac{SSE_r - SSE_f}{p - r}}
{\frac{SSE_f}{n - p}}
\sim F_{p-r, n-p}
\]
Alternate forms of linear test, and testing a linear combination if $R\beta
= r$, for $R$ full rank $s \times p$ matrix.
\[
\frac{(R \hat{\beta} - r)^T (R(X^T X)^{-1} R^T)^{-1} (R \beta - r) / s}
{\hat{\sigma}^2} \sim F_{s, n-p}
\]
\subsection*{Model selection and diagnostics}
$SSTO = \sum_{i=1}^n (y_i - \bar{y}) = \norm{y - \bar{y} 1_n }^2
= \norm{(I - J)y}^2$
$SSR = \sum_{i=1}^n (\hat{y}_i - \bar{y}) = \norm{\hat{y} - \bar{y} 1_n}^2
= \norm{(H - P)y}^2$
$SSE = \sum_{i=1}^n (y_i - \hat{y}_i) = \norm{y - \hat{y}}^2
= \norm{(I - H)y}^2$
If the model contains the intercept in the column space of $X$ then $SSTO = SSR + SSE$.
$R^2 = 1 - \frac{SSE}{SSTO}$
Adjusted $R^2_a = 1 - \frac{SSE / (n-p)}{SSTO / (n-1)}$
$AIC = n \log SSE + 2p$
$BIC = n \log SSE + p \log n$
$Cp = \frac{SSE}{MSE} - (n - 2p)$
Residuals: $\hat{\epsilon}_i = y_i - \hat{y}_i$
Studentized residuals (\texttt{rstandard} in R):
\[
\gamma_i =
\frac{\hat{\epsilon}_i}{ s \{ \hat{\epsilon}_i \} } =
\frac{\hat{\epsilon}_i}{\hat{\sigma} \sqrt{1 - h_{ii}}}
\]
Prediction sum of squares (PRESS) is the same as leave one out cross
validation (LOOCV). Prediction error on $i$th observation is called deleted
residuals:
\[
y_i - \hat{y}_{i (-i)} = \frac{y_i - \hat{y}_i}{1 - H_{ii}}
\]
Works for ridge regression also, letting
$H = X(X^T X + \lambda I)^{-1} X^T$.
Studentized deleted residuals:
\[
t_i = \frac{\hat{\epsilon}_i}{\sqrt{MSE_{(-i)} (1 - h_{ii})}} \sim t_{n - p -1}
\]
Where $MSE_{(-i)} = SSE_{(-i)} / (n - 1 - p)$ and
$SSE_{(-i)} = SSE - \frac{\hat{\epsilon}_i}{1 - h_{ii}}$ can be used to
calculate without refitting model.
\subsection*{ANOVA}
Three principles of experimental design: 1) Replication 2) Randomization 3)
Blocking
One way ANOVA with $n$ total observations, $K$ groups:
{
\centering
\begin{tabular}{lll}
SS & & DF \\
SSTR & $\sum_{j=1}^K n_j (\bar{y_{j \cdot}} - \bar{y_{\cdot \cdot}})^2$ & K - 1 \\
SSE & $\sum_{i=1}^n (y_{ij} - \bar{y_{j \cdot}})^2$ & n - K \\
SSTO & $\sum_{i=1}^n (y_{ij} - \bar{y_{\cdot \cdot}})^2$ & n - 1
\end{tabular}
}
Contrasts are sums of the form $\Phi = \sum_{i=1}^K c_i \mu_i$ with
$\sum_{i=1}^K c_i = 0$.
Tukey's works for all pairwise contrasts.
Scheffe's and extended Tukey works for all contrasts.
Bonferroni's is for a limited number of pre specified contrasts.
\textbf{Ridge Regression} for $\lambda > 0$ solves
\[
\min_\beta ||Y - X\beta||^2 + \lambda ||\beta||^2
\]
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\textbf{Linear mixed models}
\[
y = X \beta + Z \alpha + \epsilon
\]
Standard assumptions:
$\Expect ( \alpha) = 0$, $\Expect ( \epsilon) = 0$,
$\Cov(\epsilon, \alpha) = 0$
$\alpha \sim N(0, G), \epsilon \sim N(0, R)$ are jointly normal.
Marginal model $y \sim N(X \beta, V)$ where $V = R + ZGZ'$.
The idea of reduced maximum likelihood (REML) is to first estimate the random components of the model.
This is done through a transformation of the data to create a new model
containing only the random components, and no fixed components.
Let $\xi = b' \beta + a' \alpha$ be a mixed effect. These are what we're
interested in estimating. We call them predictions rather than estimations
because we're predicting a random component.
BLUE - Best linear unbiased estimator,
$\tilde{\beta} = (X' V^{-1} X)^{-1} X' V^{-1} y$. This is the MLE of
$\beta$.
BP - Best predictor, $\Expect (\xi | y) = b' \beta + a' G Z' V^{-1} (y - X
\beta)$ a theoretical ideal that's
usually difficult or impossible to derive.
BLUP - Best linear predictor, which plugs in $\tilde{\beta}$ into BP.
EBLUP - Empirical best linear predictor, plugs in $\hat{\theta}$. This is
typically the one we compute and use.
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection*{Applied Lectures - 232B}
4 Jan - Matrix form for linear mixed model, assumptions
6 Jan - Examples mixed models, time series, non gaussian, marginal, max
likelihood estimation, REML
11 Jan - Lambs example, parametric bootstrap
13 Jan - Asymptotic covariance matrix of fixed effects $\hat{\beta}$,
computing examples
18 Jan - Holiday
20 Jan - Mixed model prediction, BP, BLUE, BLUP, example algebra in
discussion
25 Jan - Empirical BLUP, Fay Herriot model, jackknife
27 Jan - EBLUP for random effects, intro to GLM's
1 Feb - GLMM with several examples, Monte carlo and the E-M algorithm,
importance sampling
3 Feb - Rejection sampling, Markov Chain Monte Carlo (MCMC), Markov chain
convergence theorem, Gibb's Sampler
8 Feb - Gibbs Sampler, transition kernel, MCMC, threshold model, data
cloning
10 Feb - Midterm
\subsection*{Math Lectures - 231B}
4 Jan - Maximum likelihood, determining MLE
6 Jan - Normal examples MLE, constraints, MLE of pdf $f$ decreasing on $[0,
\infty)$.
11 Jan - MLE maximizing $\Expect l_X (\theta_0)$, KL divergence and
properties, M estimation
13 Jan - least squares and mean absolute deviation (MAD) as examples of m
estimators, existence and uniqueness theorems for optimization, review of
exponential families
18 Jan - Holiday
20 Jan - Existence and uniqueness of MLE for canonical and curved
exponential families, review convexity
25 Jan - Long proof of existence and uniqueness of MLE
27 Jan - Z estimation aka estimating equation estimation, method of
moments, gamma example, plug in principle
1 Feb - Asymptotics, modes of convergence and associated theorems,
Borel-Cantelli lemma, generalized Chebyshev
3 Feb - Hoeffding's inequality and proof, strong, weak, and uniform
consistency
8 Feb - Consistency theorem for MLE's in canonical exp families,
consistency of M estimator
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection*{Applied Lectures - 232A}
30 Nov - Outliers in x and y, leverage, DFFITS, cook's distance, influence
plot, add variable plot, robust regression
25 Nov - Model selection criteria, deleted residuals, forward and backward
selection in lab
23 Nov - BIC, AIC derivations, Mallow's cp, stepwise selection algorithms,
outliers and studentized residuals
18 Nov - F test with orthogonalized X, model selection criteria,
bootstrap t method in lab
16 Nov - Multicollinearity, Variance Inflation Factor,
ridge regression, bias variance tradeoff, AIC, BIC, cross validation, proof leave
one out cross validation formula for OLS
11 Nov - Holiday
9 Nov - Linear model with random $X$, transformations of $y$ and $X$, box
cox procedure, bootstrap with percentile-t and fixed $X$ sampling, weighted
least squares
4 Nov - Interaction plots for two way ANOVA with balanced design, Linear
models with random $X$
2 Nov - Midterm
28 Oct - Kronecker product formulae for two way ANOVA
26 Oct - Kronecker product 1 way ANOVA, decomposition of two way ANOVA,
noncentral $\chi^2$ distributions for ANOVA table SSA, SSB, SSAB
21 Oct - Tukey's method for pairwise contrasts, Bonferroni's method,
definition and properties of Kronecker product
\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection*{Math Lectures - 231A}
30 Nov - Bayesian inference, risk, decision rules, conjugate families,
Binomial, normal examples
25 Nov - Exponential families, GLM's, full rank exp families, decision
theory, Bayes risk
23 Nov - Fisher information, Cramer Rao inequality, Exponential families
and properties
18 Nov - Rao-Blackwell theorem, Lehmann-Scheffe theorem, UMVUE examples for
normal, uniform, Poisson, Fisher information
16 Nov - Minimal sufficiency, likelihood ratio, ancillary statistics,
completeness, Basu's theorem, loss functions
11 Nov - Holiday
9 Nov - Distribution of order statistics, factorization theorem, sufficient
statistics for Exponential families and uniform dist
4 Nov - Midterm
2 Nov - Location-scale families, invariance, ancillary and sufficient
statistics, order statistics, multinomial distribution
28 Oct - Transformation of discrete and continuous random variables,
Jacobian, examples with beta distributions, Dirichlet distribution
26 Oct - Jensen's and Holder's inequality, convex functions and sets,
products of normal random variables
21 Oct - Convolution formula, examples with Uniform, Gamma, Poisson,
marginal and conditional distributions for multivariate normal
\newpage
\subsection*{Problem Solving Strategies}
\textbf{Read the whole question}
Read carefully and do the right problem! If there's a hint, it should
probably be used. Early parts of a question can help for later parts, and later
parts occasionaly provide insight for earlier parts.
\textbf{First principles}
When in doubt, work from definitions.
\textbf{Look for Distributions}
Can the question be solved by knowing the distribution of some
quantity? Ex: $\sum (x_i - \bar{x})^2$ is $\chi^2_{n-1}$ for
$x_i \sim N(\mu, 1)$.
\textbf{Fast and correct algebra}
Better to write more than to make a simple algebra mistake.
Practice common manipulations so don't have to think about them
when testing.
\begin{table}[]
\centering
\caption{Problems in past 231 exams - Came from a brief glance at the
question statements. TODO- make second updated table after solving
questions that shows which techniques are used.}
\label{231problems}
\begin{tabular}{rl}
Binomial & ******* \\
Poisson & ****** \\
Uniform & ****** \\
Normal & ****** \\
Gamma & *** \\
Exponential & ** \\
Negative binomial & * \\
Beta & * \\
Geometric & * \\
MLE & ************* \\
asymptotic distribution & *********** \\
Bayes estimator / risk & ********** \\
UMVUE / Cramer-Rao & ********* \\
minimiax & ****** \\
UMP test & ****** \\
linear regression & ***** \\
likelihood ratio & **** \\
Wald's test & *** \\
sufficient statistic & ** \\
Hierarchical model & * \\
method of moments & * \\
hypothesis testing & * \\
order statistics & * \\
\end{tabular}
\end{table}
\end{document}
|
(* Adam Chlipalas heterogeneous list implementation (magic inside)
* Useful for De Bruijn indices
*)
Section hlist.
Variable A : Type.
Variable B : A -> Type.
Inductive hlist : list A -> Type :=
| HNil : hlist nil
| HCons : forall (x : A) (ls : list A), B x -> hlist ls -> hlist (x :: ls).
Variable elm : A.
Inductive member : list A -> Type :=
| HFirst : forall ls, member (elm :: ls)
| HNext : forall x ls, member ls -> member (x :: ls).
Fixpoint hget ls (mls : hlist ls) : member ls -> B elm :=
match mls with
| HNil
=> fun mem =>
match mem in member ls'
return (match ls' with
| nil => B elm
| _ :: _ => unit
end) with
| HFirst _ => tt
| HNext _ _ _ => tt
end
| HCons _ _ x mls'
=> fun mem =>
match mem in member ls'
return (match ls' with
| nil => Empty_set
| x' :: ls'' =>
B x' -> (member ls'' -> B elm)
-> B elm
end) with
| HFirst _ => fun x _ => x
| HNext _ _ mem' => fun _ get_mls' => get_mls' mem'
end x (hget mls')
end.
End hlist.
Arguments HNil [A B].
Arguments HCons [A B x ls].
Arguments HFirst [A elm ls].
Arguments HNext [A elm x ls]. |
| Scene2 with some more utilities
| Reva OpenGL demo program
| Andrew Price, 2006
context: ~app
needs callbacks
needs util/auxstack
needs math/floats
~floats
needs ui/gl needs ui/glu needs ui/glut
~gl
~app
variable tmpf32
2variable tmpf64
: f>32 tmpf32 f!4 tmpf32 @ ;
: f>64 tmpf64 f!8 tmpf64 2@ ;
: 3f f>32 f>32 f>32 rot rot swap ; | do 3 f>32s
: 3floats create f>32 f>32 f>32 , , , ; | Initialised vector of 3 32bit floats
: 4floats f>32 3floats , ; | Initialised vector of 4 32bit floats
: -f1 f1 fnegate ; | -1.0 on TOFS
0 variable, noargs
: blankargs " " ;
: windowtitle " GL Test -- Scene" ;
blankargs drop variable, blankargs*
500 variable, width
500 variable, height
f0 f0 f0 f1 4floats light_ambient drop
f1 f1 f1 f1 4floats light_diffuse drop
f1 f1 f1 f1 4floats light_specular drop
f1 f1 f1 f0 4floats light_position drop
variable mywindow
: init noargs blankargs* glutInit drop
GLUT_RGB GLUT_DOUBLE GLUT_DEPTH or or glutInitDisplayMode drop
width @ height @ glutInitWindowSize drop
100 100 glutInitWindowPosition drop
windowtitle drop glutCreateWindow mywindow !
GL_LIGHT0 GL_AMBIENT light_ambient glLightfv
GL_LIGHT0 GL_DIFFUSE light_diffuse glLightfv
GL_LIGHT0 GL_SPECULAR light_specular glLightfv
GL_LIGHT0 GL_POSITION light_position glLightfv
GL_LIGHTING glEnable
GL_LIGHT0 glEnable
GL_DEPTH_TEST glEnable
;
fvariable posx fvariable posy fvariable posz
-f1 0.75e0 f* posx f! 0.5e0 posy f! f0 posz f!
variable key
: HandleKey ( key x y -- )
| 3dup rot ." Key: " dup $ff and . ." (" emit ." ) x: " swap . ." y: " .
rot $ff and key ! 2drop key @
| ." Key " rot dup dup key ! emit 32 emit . . . cr
key @
case
'w of posy f@ 0.05e0 f+ posy f! endof | w
's of posy f@ 0.05e0 f- posy f! endof | s
'd of posx f@ 0.05e0 f+ posx f! endof | d
'a of posx f@ 0.05e0 f- posx f! endof | a
'q of posz f@ 0.05e0 f+ posz f! endof | q
'e of posz f@ 0.05e0 f- posz f! endof | e
27 of bye endof
endcase
glutPostRedisplay drop ; | ( key a b -- )
: HandleMouse ." Mouse " . . . . cr ;
: DrawScene | ." Draw" cr
GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT or glClear
GL_PROJECTION glMatrixMode
glLoadIdentity
-f1 2.5e0 f* f>64 2.5e0 f>64 -f1 2.5e0 f* f>64 2.5e0 f>64 -f1 10.0e0 f* f>64 10.0e0 f>64 glOrtho
GL_MODELVIEW glMatrixMode
glLoadIdentity
glPushMatrix
20.0e0 f1 f0 3f f0 f>32 glRotatef
glPushMatrix
posx f@ posy f@ posz f@ 3f glTranslatef
90.0e0 f>32 f1 f0 f0 3f glRotatef
0.275e0 f>64 0.85e0 f>64 30 30 glutSolidTorus
glPopMatrix
glPushMatrix
-f1 0.75e0 f* f>32 -f1 0.5e0 f* f>32 0.0e0 f>32 glTranslatef
270.0e0 f>32 f1 f>32 f0 f>32 f0 f>32 glRotatef
1.0e0 f>64 2.0e0 f>64 15 15 glutSolidCone
glPopMatrix
glPushMatrix
0.75e0 f>32 0.0e0 f>32 -f1 f>32 glTranslatef
| 1.0e0 f>64 30 30 glutSolidSphere
1.0e0 f>64 glutSolidTeapot
glPopMatrix
glPopMatrix
glFlush
glutSwapBuffers
;
: Reshape ( width height -- )
height ! width ! | ( width height -- )
0 0 width @ height @ glViewport ." Reshape " width @ . height @ . cr
GL_PROJECTION glMatrixMode
glLoadIdentity
-f1 2.5e0 f* f>64 2.5e0 f>64 -f1 2.5e0 f* f>64 2.5e0 f>64 -f1 10.0e0 f* f>64 10.0e0 f>64 glOrtho
GL_MODELVIEW glMatrixMode
glLoadIdentity
;
: SceneDrawer callback DrawScene ;
: KeyHandler callback 0 cb-param 1 cb-param 2 cb-param HandleKey ;
: MouseHandler callback HandleMouse ;
: ReshapeHandler callback 0 cb-param 1 cb-param Reshape ;
: setup-callbacks ['] SceneDrawer glutDisplayFunc drop ['] KeyHandler glutKeyboardFunc drop
['] MouseHandler glutMouseFunc drop ['] ReshapeHandler glutReshapeFunc drop ;
init setup-callbacks ." press ESC to quit" cr glutMainLoop drop
|
# Copyright 2020 Filippo Aleotti, Fabio Tosi, Li Zhang, Matteo Poggi, Stefano Mattoccia
#
# 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.
from __future__ import print_function
import argparse
import os
import cv2
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
from utils import general, tensor
from models import network_factory
from dataloader import augment
from torchvision import transforms
parser = argparse.ArgumentParser(description="Reversing the cycle: single shot")
# general
parser.add_argument("--gpu_ids", type=str, help="id(s) of the gpu to use", default="0")
parser.add_argument("--ckpt", help="path to checkpoint", required=True)
parser.add_argument("--maxdisp", type=int, default=192, help="maxium disparity")
parser.add_argument("--model", help="stereo network to use", required=True)
parser.add_argument(
"--left", type=str, help="path to left image(s) [space separated]", required=True
)
parser.add_argument(
"--right", type=str, help="path to right image(s) [space separated]", required=True
)
parser.add_argument(
"--seed", type=int, default=1, metavar="S", help="random seed (default: 1)"
)
# test
parser.add_argument("--final_h", type=int, default=384, help="height after pad in test")
parser.add_argument("--final_w", type=int, default=1280, help="width after pad in test")
parser.add_argument("--results", type=str, default="./artifacts", help="result folder")
parser.add_argument(
"--qualitative", action="store_true", help="save colored maps instead of 16bit"
)
parser.add_argument(
"--cmap",
type=str,
default="magma",
help="colormap to use",
choices=["magma", "gray", "jet", "kitti"],
)
parser.add_argument(
"--maxval", type=int, default=-1, help="max value in kitti colormap"
)
args = parser.parse_args()
gpus = general.parse_gpu_ids(args.gpu_ids)
args.cuda = len(gpus) > 0 and torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
def _parse(names):
"""Split a string with space separated valus.
Args:
Return:
a list where each element is a non-empty value of the original list
"""
imgs = names.split(" ")
imgs = [x.strip() for x in imgs if x.strip()]
return imgs
def run_single_shot(network):
""" Generate depth for a single (or a list of) example.
Args:
network: pre-trained stereo model
"""
test_params = {
"results": args.results,
"model": args.model,
"lefts": _parse(args.left),
"rights": _parse(args.right),
"qualitative": args.qualitative,
"maxval": args.maxval,
"cmap": args.cmap,
}
padding_params = {
"final_h": args.final_h,
"final_w": args.final_w,
}
network.eval()
transformation = augment.ComposeTransformation(
[
augment.ArrayToTensor(),
transforms.Normalize(mean=[0, 0, 0], std=[255, 255, 255]),
]
)
with tqdm(total=len(test_params["lefts"])) as pbar:
for (left_i, right_i) in zip(test_params["lefts"], test_params["rights"]):
if not os.path.exists(left_i):
print("missing left image:{}".format(left_i))
continue
if not os.path.exists(right_i):
print("missing right image:{}".format(right_i))
continue
left_img = cv2.imread(left_i)
right_img = cv2.imread(right_i)
if left_img.shape != right_img.shape:
raise ValueError("Left and right images have different shapes")
h, w, _ = left_img.shape
top_pad = padding_params["final_h"] - h
left_pad = padding_params["final_w"] - w
# add padding
left_img = np.lib.pad(
left_img, ((top_pad, 0), (0, left_pad), (0, 0)), mode="edge"
)
right_img = np.lib.pad(
right_img, ((top_pad, 0), (0, left_pad), (0, 0)), mode="edge"
)
# transorm to tensor
left = transformation(left_img)
right = transformation(right_img)
# create batch
left = torch.unsqueeze(left, 0)
right = torch.unsqueeze(right, 0)
name = "disp_" + os.path.basename(left_i)
if args.cuda:
# loading images on GPU
left = torch.FloatTensor(left).cuda()
right = torch.FloatTensor(right).cuda()
left, right = Variable(left), Variable(right)
# make prediction
with torch.no_grad():
output = network(left, right)
output = torch.squeeze(output)
output = torch.nn.functional.relu(output)
output = output.data.cpu().numpy()
extension = "." + name.split(".")[-1]
name = name.replace(extension, "")
# remove padding
if left_pad == 0:
final_output = output[top_pad:, :]
else:
final_output = output[top_pad:, :-left_pad]
if final_output.shape[0] != h or final_output.shape[1] != w:
raise ValueError("Problems in cropping final predictions")
destination = os.path.join(
test_params["results"], test_params["model"], "{}", name + ".png"
)
# saving predictions
if test_params["qualitative"]:
min_value = final_output.min()
max_value = final_output.max()
final_output = (final_output - min_value) / (max_value - min_value)
final_output *= 255.0
general.save_color(
destination.format("qualitative"),
final_output,
cmap=test_params["cmap"],
params={"maxval": test_params["maxval"]},
)
else:
general.save_kitti_disp(destination.format("16bit"), final_output)
pbar.update(1)
print("Done! Predictions saved in {} folder".format(test_params["results"]))
if __name__ == "__main__":
print("=> model: {}".format(args.model))
print("=> checkpoint: {}".format(args.ckpt))
if not os.path.exists(args.ckpt):
raise ValueError("Checkpoint not found!")
model = network_factory.get_network(args.model)(
{"maxdisp": args.maxdisp, "imagenet_pt": False}
)
if args.cuda:
print("=> selected gpu(s) with ids {}".format(*gpus))
model = nn.DataParallel(model)
model.cuda()
print(
"=> Number of model parameters: {}".format(
sum(p.numel() for p in model.parameters() if p.requires_grad)
)
)
state_dict = torch.load(args.ckpt)
model.load_state_dict(state_dict["state_dict"], strict=True)
print("EPOCHS: {}".format(state_dict["epoch"]))
run_single_shot(model)
|
# Unit test get_coef
# ==============================================================================
from pytest import approx
import numpy as np
import pandas as pd
from skforecast.ForecasterAutoreg import ForecasterAutoreg
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
def test_output_get_coef_when_regressor_is_LinearRegression():
'''
Test output of get_coef when regressor is LinearRegression with lags=3
and it is trained with y=pd.Series(np.arange(5)).
'''
forecaster = ForecasterAutoreg(LinearRegression(), lags=3)
forecaster.fit(y=pd.Series(np.arange(5)))
expected = pd.DataFrame({
'feature': ['lag_1', 'lag_2', 'lag_3'],
'coef': np.array([0.33333333, 0.33333333, 0.33333333])
})
results = forecaster.get_coef()
assert (results['feature'] == expected['feature']).all()
assert results['coef'].values == approx(expected['coef'].values)
def test_output_get_coef_when_regressor_is_RandomForest():
'''
Test output of get_coef when regressor is RandomForestRegressor with lags=3
and it is trained with y=pd.Series(np.arange(5)).
'''
forecaster = ForecasterAutoreg(RandomForestRegressor(n_estimators=1, max_depth=2), lags=3)
forecaster.fit(y=pd.Series(np.arange(5)))
expected = None
results = forecaster.get_coef()
assert results is expected |
[GOAL]
x : β
hx : x β€ 0
β’ expNegInvGlue x = 0
[PROOFSTEP]
simp [expNegInvGlue, hx]
[GOAL]
x : β
hx : 0 < x
β’ 0 < expNegInvGlue x
[PROOFSTEP]
simp [expNegInvGlue, not_le.2 hx, exp_pos]
[GOAL]
x : β
β’ 0 β€ expNegInvGlue x
[PROOFSTEP]
cases le_or_gt x 0 with
| inl h => exact ge_of_eq (zero_of_nonpos h)
| inr h => exact le_of_lt (pos_of_pos h)
[GOAL]
x : β
xβ : x β€ 0 β¨ x > 0
β’ 0 β€ expNegInvGlue x
[PROOFSTEP]
cases le_or_gt x 0 with
| inl h => exact ge_of_eq (zero_of_nonpos h)
| inr h => exact le_of_lt (pos_of_pos h)
[GOAL]
case inl
x : β
h : x β€ 0
β’ 0 β€ expNegInvGlue x
[PROOFSTEP]
| inl h => exact ge_of_eq (zero_of_nonpos h)
[GOAL]
case inl
x : β
h : x β€ 0
β’ 0 β€ expNegInvGlue x
[PROOFSTEP]
exact ge_of_eq (zero_of_nonpos h)
[GOAL]
case inr
x : β
h : x > 0
β’ 0 β€ expNegInvGlue x
[PROOFSTEP]
| inr h => exact le_of_lt (pos_of_pos h)
[GOAL]
case inr
x : β
h : x > 0
β’ 0 β€ expNegInvGlue x
[PROOFSTEP]
exact le_of_lt (pos_of_pos h)
[GOAL]
p : β[X]
β’ Tendsto (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x) (π 0) (π 0)
[PROOFSTEP]
simp only [expNegInvGlue, mul_ite, mul_zero]
[GOAL]
p : β[X]
β’ Tendsto (fun x => if x β€ 0 then 0 else Polynomial.eval xβ»ΒΉ p * exp (-xβ»ΒΉ)) (π 0) (π 0)
[PROOFSTEP]
refine tendsto_const_nhds.if ?_
[GOAL]
p : β[X]
β’ Tendsto (fun x => Polynomial.eval xβ»ΒΉ p * exp (-xβ»ΒΉ)) (π 0 β π {x | Β¬x β€ 0}) (π 0)
[PROOFSTEP]
simp only [not_le]
[GOAL]
p : β[X]
β’ Tendsto (fun x => Polynomial.eval xβ»ΒΉ p * exp (-xβ»ΒΉ)) (π 0 β π {x | 0 < x}) (π 0)
[PROOFSTEP]
have : Tendsto (fun x β¦ p.eval xβ»ΒΉ / exp xβ»ΒΉ) (π[>] 0) (π 0) := p.tendsto_div_exp_atTop.comp tendsto_inv_zero_atTop
[GOAL]
p : β[X]
this : Tendsto (fun x => Polynomial.eval xβ»ΒΉ p / exp xβ»ΒΉ) (π[Ioi 0] 0) (π 0)
β’ Tendsto (fun x => Polynomial.eval xβ»ΒΉ p * exp (-xβ»ΒΉ)) (π 0 β π {x | 0 < x}) (π 0)
[PROOFSTEP]
refine this.congr' <| mem_of_superset self_mem_nhdsWithin fun x hx β¦ ?_
[GOAL]
p : β[X]
this : Tendsto (fun x => Polynomial.eval xβ»ΒΉ p / exp xβ»ΒΉ) (π[Ioi 0] 0) (π 0)
x : β
hx : x β {x | 0 < x}
β’ x β {x | (fun x => Polynomial.eval xβ»ΒΉ p / exp xβ»ΒΉ = (fun x => Polynomial.eval xβ»ΒΉ p * exp (-xβ»ΒΉ)) x) x}
[PROOFSTEP]
simp [expNegInvGlue, hx.out.not_le, exp_neg, div_eq_mul_inv]
[GOAL]
p : β[X]
x : β
β’ HasDerivAt (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x)
(Polynomial.eval xβ»ΒΉ (X ^ 2 * (p - βderivative p)) * expNegInvGlue x) x
[PROOFSTEP]
rcases lt_trichotomy x 0 with hx | rfl | hx
[GOAL]
case inl
p : β[X]
x : β
hx : x < 0
β’ HasDerivAt (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x)
(Polynomial.eval xβ»ΒΉ (X ^ 2 * (p - βderivative p)) * expNegInvGlue x) x
[PROOFSTEP]
rw [zero_of_nonpos hx.le, mul_zero]
[GOAL]
case inl
p : β[X]
x : β
hx : x < 0
β’ HasDerivAt (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x) 0 x
[PROOFSTEP]
refine (hasDerivAt_const _ 0).congr_of_eventuallyEq ?_
[GOAL]
case inl
p : β[X]
x : β
hx : x < 0
β’ (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x) =αΆ [π x] fun x => 0
[PROOFSTEP]
filter_upwards [gt_mem_nhds hx] with y hy
[GOAL]
case h
p : β[X]
x : β
hx : x < 0
y : β
hy : y < 0
β’ Polynomial.eval yβ»ΒΉ p * expNegInvGlue y = 0
[PROOFSTEP]
rw [zero_of_nonpos hy.le, mul_zero]
[GOAL]
case inr.inl
p : β[X]
β’ HasDerivAt (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x)
(Polynomial.eval 0β»ΒΉ (X ^ 2 * (p - βderivative p)) * expNegInvGlue 0) 0
[PROOFSTEP]
rw [expNegInvGlue.zero, mul_zero, hasDerivAt_iff_tendsto_slope]
[GOAL]
case inr.inl
p : β[X]
β’ Tendsto (slope (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x) 0) (π[{0}αΆ] 0) (π 0)
[PROOFSTEP]
refine ((tendsto_polynomial_inv_mul_zero (p * X)).mono_left inf_le_left).congr fun x β¦ ?_
[GOAL]
case inr.inl
p : β[X]
x : β
β’ Polynomial.eval xβ»ΒΉ (p * X) * expNegInvGlue x = slope (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x) 0 x
[PROOFSTEP]
simp [slope_def_field, div_eq_mul_inv, mul_right_comm]
[GOAL]
case inr.inr
p : β[X]
x : β
hx : 0 < x
β’ HasDerivAt (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x)
(Polynomial.eval xβ»ΒΉ (X ^ 2 * (p - βderivative p)) * expNegInvGlue x) x
[PROOFSTEP]
have := ((p.hasDerivAt xβ»ΒΉ).mul (hasDerivAt_neg _).exp).comp x (hasDerivAt_inv hx.ne')
[GOAL]
case inr.inr
p : β[X]
x : β
hx : 0 < x
this :
HasDerivAt ((fun y => Polynomial.eval y p * exp (-y)) β Inv.inv)
((Polynomial.eval xβ»ΒΉ (βderivative p) * exp (-xβ»ΒΉ) + Polynomial.eval xβ»ΒΉ p * (exp (-xβ»ΒΉ) * -1)) * -(x ^ 2)β»ΒΉ) x
β’ HasDerivAt (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x)
(Polynomial.eval xβ»ΒΉ (X ^ 2 * (p - βderivative p)) * expNegInvGlue x) x
[PROOFSTEP]
convert this.congr_of_eventuallyEq _ using 1
[GOAL]
case h.e'_7
p : β[X]
x : β
hx : 0 < x
this :
HasDerivAt ((fun y => Polynomial.eval y p * exp (-y)) β Inv.inv)
((Polynomial.eval xβ»ΒΉ (βderivative p) * exp (-xβ»ΒΉ) + Polynomial.eval xβ»ΒΉ p * (exp (-xβ»ΒΉ) * -1)) * -(x ^ 2)β»ΒΉ) x
β’ Polynomial.eval xβ»ΒΉ (X ^ 2 * (p - βderivative p)) * expNegInvGlue x =
(Polynomial.eval xβ»ΒΉ (βderivative p) * exp (-xβ»ΒΉ) + Polynomial.eval xβ»ΒΉ p * (exp (-xβ»ΒΉ) * -1)) * -(x ^ 2)β»ΒΉ
[PROOFSTEP]
simp [expNegInvGlue, hx.not_le]
[GOAL]
case h.e'_7
p : β[X]
x : β
hx : 0 < x
this :
HasDerivAt ((fun y => Polynomial.eval y p * exp (-y)) β Inv.inv)
((Polynomial.eval xβ»ΒΉ (βderivative p) * exp (-xβ»ΒΉ) + Polynomial.eval xβ»ΒΉ p * (exp (-xβ»ΒΉ) * -1)) * -(x ^ 2)β»ΒΉ) x
β’ (x ^ 2)β»ΒΉ * (Polynomial.eval xβ»ΒΉ p - Polynomial.eval xβ»ΒΉ (βderivative p)) * exp (-xβ»ΒΉ) =
-((Polynomial.eval xβ»ΒΉ (βderivative p) * exp (-xβ»ΒΉ) + -(Polynomial.eval xβ»ΒΉ p * exp (-xβ»ΒΉ))) * (x ^ 2)β»ΒΉ)
[PROOFSTEP]
ring
[GOAL]
case inr.inr.convert_2
p : β[X]
x : β
hx : 0 < x
this :
HasDerivAt ((fun y => Polynomial.eval y p * exp (-y)) β Inv.inv)
((Polynomial.eval xβ»ΒΉ (βderivative p) * exp (-xβ»ΒΉ) + Polynomial.eval xβ»ΒΉ p * (exp (-xβ»ΒΉ) * -1)) * -(x ^ 2)β»ΒΉ) x
β’ (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x) =αΆ [π x] (fun y => Polynomial.eval y p * exp (-y)) β Inv.inv
[PROOFSTEP]
filter_upwards [lt_mem_nhds hx] with y hy
[GOAL]
case h
p : β[X]
x : β
hx : 0 < x
this :
HasDerivAt ((fun y => Polynomial.eval y p * exp (-y)) β Inv.inv)
((Polynomial.eval xβ»ΒΉ (βderivative p) * exp (-xβ»ΒΉ) + Polynomial.eval xβ»ΒΉ p * (exp (-xβ»ΒΉ) * -1)) * -(x ^ 2)β»ΒΉ) x
y : β
hy : 0 < y
β’ Polynomial.eval yβ»ΒΉ p * expNegInvGlue y = ((fun y => Polynomial.eval y p * exp (-y)) β Inv.inv) y
[PROOFSTEP]
simp [expNegInvGlue, hy.not_le]
[GOAL]
n : ββ
p : β[X]
β’ ContDiff β n fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
[PROOFSTEP]
apply contDiff_all_iff_nat.2 (fun m => ?_) n
[GOAL]
n : ββ
p : β[X]
m : β
β’ ContDiff β βm fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
[PROOFSTEP]
induction m generalizing p with
| zero => exact contDiff_zero.2 <| continuous_polynomial_eval_inv_mul _
| succ m ihm =>
refine contDiff_succ_iff_deriv.2 β¨differentiable_polynomial_eval_inv_mul _, ?_β©
convert ihm (X ^ 2 * (p - derivative (R := β) p)) using 2
exact (hasDerivAt_polynomial_eval_inv_mul p _).deriv
[GOAL]
n : ββ
p : β[X]
m : β
β’ ContDiff β βm fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
[PROOFSTEP]
induction m generalizing p with
| zero => exact contDiff_zero.2 <| continuous_polynomial_eval_inv_mul _
| succ m ihm =>
refine contDiff_succ_iff_deriv.2 β¨differentiable_polynomial_eval_inv_mul _, ?_β©
convert ihm (X ^ 2 * (p - derivative (R := β) p)) using 2
exact (hasDerivAt_polynomial_eval_inv_mul p _).deriv
[GOAL]
case zero
n : ββ
p : β[X]
β’ ContDiff β βNat.zero fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
[PROOFSTEP]
| zero => exact contDiff_zero.2 <| continuous_polynomial_eval_inv_mul _
[GOAL]
case zero
n : ββ
p : β[X]
β’ ContDiff β βNat.zero fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
[PROOFSTEP]
exact contDiff_zero.2 <| continuous_polynomial_eval_inv_mul _
[GOAL]
case succ
n : ββ
m : β
ihm : β (p : β[X]), ContDiff β βm fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
p : β[X]
β’ ContDiff β β(Nat.succ m) fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
[PROOFSTEP]
| succ m ihm =>
refine contDiff_succ_iff_deriv.2 β¨differentiable_polynomial_eval_inv_mul _, ?_β©
convert ihm (X ^ 2 * (p - derivative (R := β) p)) using 2
exact (hasDerivAt_polynomial_eval_inv_mul p _).deriv
[GOAL]
case succ
n : ββ
m : β
ihm : β (p : β[X]), ContDiff β βm fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
p : β[X]
β’ ContDiff β β(Nat.succ m) fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
[PROOFSTEP]
refine contDiff_succ_iff_deriv.2 β¨differentiable_polynomial_eval_inv_mul _, ?_β©
[GOAL]
case succ
n : ββ
m : β
ihm : β (p : β[X]), ContDiff β βm fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
p : β[X]
β’ ContDiff β (βm) (deriv fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x)
[PROOFSTEP]
convert ihm (X ^ 2 * (p - derivative (R := β) p)) using 2
[GOAL]
case h.e'_10.h
n : ββ
m : β
ihm : β (p : β[X]), ContDiff β βm fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x
p : β[X]
xβ : β
β’ deriv (fun x => Polynomial.eval xβ»ΒΉ p * expNegInvGlue x) xβ =
Polynomial.eval xββ»ΒΉ (X ^ 2 * (p - βderivative p)) * expNegInvGlue xβ
[PROOFSTEP]
exact (hasDerivAt_polynomial_eval_inv_mul p _).deriv
[GOAL]
n : ββ
β’ ContDiff β n expNegInvGlue
[PROOFSTEP]
simpa using contDiff_polynomial_eval_inv_mul 1
[GOAL]
x : β
h : 1 β€ x
β’ expNegInvGlue x = expNegInvGlue x + expNegInvGlue (1 - x)
[PROOFSTEP]
rw [zero_of_nonpos (sub_nonpos.2 h), add_zero]
[GOAL]
x : β
β’ smoothTransition x = 0 β x β€ 0
[PROOFSTEP]
simp only [smoothTransition, _root_.div_eq_zero_iff, (pos_denom x).ne', zero_iff_nonpos, or_false]
[GOAL]
x : β
β’ smoothTransition β(projIcc 0 1 (_ : 0 β€ 1) x) = smoothTransition x
[PROOFSTEP]
refine' congr_fun (IccExtend_eq_self zero_le_one smoothTransition (fun x hx => _) fun x hx => _) x
[GOAL]
case refine'_1
xβ x : β
hx : x < 0
β’ smoothTransition x = smoothTransition 0
[PROOFSTEP]
rw [smoothTransition.zero, zero_of_nonpos hx.le]
[GOAL]
case refine'_2
xβ x : β
hx : 1 < x
β’ smoothTransition x = smoothTransition 1
[PROOFSTEP]
rw [smoothTransition.one, one_of_one_le hx.le]
|
Require Import Events.
Require Import TraceModel.
Require Import Properties.
Require Import CommonST.
Require Import Robustdef.
Require Import Criteria.
Require Import Setoid.
Require Import ClassicalExtras.
Require Import Logic.ClassicalFacts.
Require Import TechnicalLemmas.
(** This file proves that R2RTP implies RTEP *)
(** *our assumptions *)
(**********************************************************)
Hypothesis input_totality_tgt : @input_totality tgt.
Hypothesis determinacy_src : @determinacy src.
Hypothesis tgt_sem : @semantics_safety_like tgt.
(**********************************************************)
Theorem R2rTP_RTIP : R2rTP -> RTIP.
Proof.
intros r2rpp. unfold RTIP. apply NNPP.
intros hf. rewrite not_forall_ex_not in hf. destruct hf as [P1 hf].
rewrite not_forall_ex_not in hf. destruct hf as [P2 hf].
rewrite not_imp in hf. destruct hf as [H1 hf].
unfold "β" in *.
rewrite not_forall_ex_not in hf. destruct hf as [Ct hf].
rewrite not_forall_ex_not in hf. destruct hf as [t hf].
rewrite not_imp in hf. destruct hf as [k1 k2].
specialize (r2rpp P1 P2 traces_match).
assert (Hsat : rsat2 P1 P2 traces_match).
{ intros C b1 b2 Hb1 Hb2. apply (H1 C b1) in Hb1.
unfold beh in Hb1.
now apply (determinacy_src (C [P2])). }
specialize (r2rpp Hsat Ct t); clear Hsat.
assert (H : forall t2, sem tgt (Ct [P2 β]) t2 -> traces_match t t2).
{ intros t2 H. now apply r2rpp. } clear r2rpp H1.
destruct (longest_in_psem tgt_sem (Ct [P2 β]) t k2) as [l [Hmt [Hpsem_m Hmax_m]]].
destruct Hpsem_m as [t2 [Hmt2 Hsem_t2]].
specialize (H t2 Hsem_t2). destruct H; try now subst.
destruct H as [ll [i1 [i2 [Hi1 [Hi2 [Hdiffi [Hpref1 Hpref2]]]]]]].
assert (psem (Ct [P2 β]) (ftbd (snoc ll i1))).
{ apply (input_totality_tgt (Ct [P2 β]) ll i2 i1); auto. now exists t2. }
assert (fpr (ftbd (snoc ll i1)) l) by now apply Hmax_m.
apply (fpr_pref_pref _ _ t2) in H0; auto.
destruct (same_ext (ftbd (snoc ll i1)) (ftbd (snoc ll i2)) t2); auto;
simpl in H1.
++ apply (list_snoc_pointwise ll ll i1 i2 i2 i2) in H1; auto.
inversion H1. congruence. now apply list_list_prefix_ref.
++ apply (list_snoc_pointwise ll ll i2 i1 i1 i1) in H1; auto.
inversion H1. congruence. now apply list_list_prefix_ref.
Qed.
Theorem R2rTP_RTEP : R2rTP -> RTEP.
Proof. intros H. apply RTIP_RTEP. exact (R2rTP_RTIP H). Qed.
|
(*
*
* Copyright 2017, Data61, CSIRO
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(DATA61_BSD)
*)
theory Corres_Method
imports Corres_UL SpecValid_R
begin
chapter \<open>Corres Methods\<close>
section \<open>Alternative split rules\<close>
text \<open>
These split rules provide much greater information about what is happening on each side
of the refinement.
\<close>
lemma corres_split_strongest:
assumes x: "corres_underlying sr nf nf' r' P P' a c"
assumes y: "\<And>rv rv'. r' rv rv' \<Longrightarrow> corres_underlying sr nf nf' r (R rv' rv) (R' rv rv') (b rv) (d rv')"
assumes "\<lbrace>\<lambda>s. (\<exists>s'. (s,s') \<in> sr \<and> Q' s') \<and> Q s\<rbrace> a \<lbrace>\<lambda>r s. \<forall>x. r' r x \<longrightarrow> (\<exists>s'. (s, s') \<in> sr) \<longrightarrow> R x r s\<rbrace>"
"\<lbrace>\<lambda>s'. (\<exists>s. (s, s') \<in> sr \<and> Q s) \<and> Q' s'\<rbrace> c \<lbrace>\<lambda>r s'. \<forall>x. r' x r \<longrightarrow> (\<exists>s. (s, s') \<in> sr) \<longrightarrow> R' x r s'\<rbrace>"
shows "corres_underlying sr nf nf' r (P and Q) (P' and Q') (a >>= (\<lambda>rv. b rv)) (c >>= (\<lambda>rv'. d rv'))"
using assms
apply -
apply (clarsimp simp: corres_underlying_def bind_def)
apply (clarsimp simp: Bex_def Ball_def valid_def)
by (safe, metis, meson+)
lemma corres_split_str:
assumes x: "corres_underlying sr nf nf' r' P P' a c"
assumes y: "\<And>rv rv'. r' rv rv' \<Longrightarrow> corres_underlying sr nf nf' r (R rv' rv) (R' rv rv') (b rv) (d rv')"
assumes z: "\<lbrace>Q\<rbrace> a \<lbrace>\<lambda>r s. \<forall>x. r' r x \<longrightarrow> R x r s\<rbrace>" "\<lbrace>Q'\<rbrace> c \<lbrace>\<lambda>r s. \<forall>x. r' x r \<longrightarrow> R' x r s\<rbrace>"
shows "corres_underlying sr nf nf' r (P and Q) (P' and Q') (a >>= (\<lambda>rv. b rv)) (c >>= (\<lambda>rv'. d rv'))"
apply (rule corres_split_strongest[OF x y])
using z
by (auto simp add: valid_def split: prod.splits)
lemma stronger_corres_guard_imp_str:
assumes x: "corres_underlying sr nf nf' r Q Q' f g"
assumes y: "\<And>s s'. \<lbrakk> P s; P' s'; (s, s') \<in> sr \<rbrakk> \<Longrightarrow> Q s \<and> Q' s'"
shows "corres_underlying sr nf nf' r P P' f g"
using x by (auto simp: y corres_underlying_def)
section \<open>Corres Method\<close>
text \<open>Handles structured decomposition of corres goals\<close>
named_theorems
corres_splits and
corres_simp and (* conservative simplification rules applied when no progress can be made *)
corres (* solving terminal corres subgoals *)
context begin
text \<open>Testing for schematic goal state\<close>
private definition "my_false s \<equiv> False"
private definition "my_false' s \<equiv> False"
private lemma corres_my_false: "corres_underlying sr nf nf' r my_false my_false' f f'"
by (simp add: my_false_def[abs_def] my_false'_def[abs_def])
private lemma corres_trivial:
"corres_underlying sr nf nf' r P P' f f' \<Longrightarrow> corres_underlying sr nf nf' r P P' f f'"
by simp
method check_corres = succeeds \<open>rule corres_trivial\<close>
private method corres_pre =
(check_corres, (fails \<open>rule corres_my_false\<close>, rule stronger_corres_guard_imp_str)?)
lemma corres_fold_dc:
"corres_underlying sr nf nf' dc P P' f f' \<Longrightarrow> corres_underlying sr nf nf' (\<lambda>_ _. True) P P' f f'"
by (simp add: dc_def[abs_def])
private method corres_fold_dc =
(match conclusion in
"corres_underlying _ _ _ (\<lambda>_ _. True) _ _ _ _" \<Rightarrow> \<open>rule corres_fold_dc\<close>)
method corres_once declares corres_splits corres corres_simp =
((check_corres,corres_fold_dc?,
#break "corres",
( determ \<open>rule corres\<close>
| (rule corres_splits, corres_once)
| (simp only: corres_simp, corres_once)
)))
method corres declares corres_splits corres corres_simp =
(corres_pre, (corres_once)+)[1]
end
lemma corres_when_str:
"\<lbrakk>G \<Longrightarrow> G' \<Longrightarrow> corres_underlying sr nf nf' dc P P' a c\<rbrakk>
\<Longrightarrow> corres_underlying sr nf nf' dc (K(G = G') and (\<lambda>x. G \<longrightarrow> P x)) (\<lambda>x. G' \<longrightarrow> P' x) (when G a) (when G' c)"
apply (simp add: corres_underlying_def)
apply (cases "G = G'"; cases G; simp)
by (clarsimp simp: return_def)
lemma corres_return_trivial:
"corres_underlying sr nf nf' dc (\<lambda>_. True) (\<lambda>_. True) (return ()) (return ())"
by simp
lemma corres_return_eq:
"corres_underlying sr nf nf' (op =) (\<lambda>_. True) (\<lambda>_. True) (return x) (return x)"
by simp
lemmas [corres_splits] =
corres_split_str
lemmas [corres] =
corres_when_str
corres_liftM2_simp[THEN iffD2]
corres_return_trivial
corres_return_eq
lemmas [corres_simp] =
fun_app_def comp_apply option.inject K_bind_def return_bind
Let_def
section \<open>Corresc - Corres over case statements\<close>
definition
"corres_underlyingL \<equiv> corres_underlying"
lemma wpc_helper_corres1:
"corres_underlyingL sr nf nf' r Q A f f' \<Longrightarrow> wpc_helper (P, P') (Q, Q') (corres_underlying sr nf nf' r P A f f')"
by (clarsimp simp: wpc_helper_def corres_underlyingL_def elim!: corres_guard_imp)
lemma wpc_helper_corres2:
"corres_underlying sr nf nf' r A Q f f' \<Longrightarrow> wpc_helper (P, P') (Q, Q') (corres_underlyingL sr nf nf' r A P f f')"
by (clarsimp simp: wpc_helper_def corres_underlyingL_def elim!: corres_guard_imp)
wpc_setup "\<lambda>f. corres_underlying sr nf nf' r P P' f f'" wpc_helper_corres1
wpc_setup "\<lambda>f'. corres_underlyingL sr nf nf' r P P' f f'" wpc_helper_corres2
lemma
wpc_contr_helper:
"A = B \<Longrightarrow> A = C \<Longrightarrow> B \<noteq> C \<Longrightarrow> P"
by blast
text \<open>
Generate quadratic blowup of the case statements on either side of refinement.
Attempt to discharge resulting contradictions.
\<close>
method corresc =
(check_corres, wpc; wpc; (solves \<open>rule FalseE, simp?, (erule (1) wpc_contr_helper, simp)?\<close>)?)[1]
section \<open>Corres Search - find symbolic execution path that allows a given rule to be applied\<close>
lemma corres_if_str:
"\<lbrakk>(G \<Longrightarrow> G' \<Longrightarrow> corres_underlying sr nf nf' r P P' a c); (\<not>G \<Longrightarrow> \<not>G' \<Longrightarrow> corres_underlying sr nf nf' r Q Q' b d)\<rbrakk>
\<Longrightarrow> corres_underlying sr nf nf' r (K(G = G') and (if G then P else Q)) (if G' then P' else Q') (if G then a else b)
(if G' then c else d)"
by (simp add: corres_underlying_def)
lemma corres_if_str_rev:
"\<lbrakk>(\<not> G \<Longrightarrow> G' \<Longrightarrow> corres_underlying sr nf nf' r P P' a c); (G \<Longrightarrow> \<not>G' \<Longrightarrow> corres_underlying sr nf nf' r Q Q' b d)\<rbrakk>
\<Longrightarrow> corres_underlying sr nf nf' r (K((\<not> G) = G') and (if G then Q else P)) (if G' then P' else Q') (if G then b else a)
(if G' then c else d)"
by (simp add: corres_underlying_def)
lemma corres_symb_exec_l_str:
assumes z: "\<And>rv. corres_underlying sr nf True r (Q rv) (P' rv) (x rv) y"
shows
"\<lbrakk>\<And>s. \<lbrace>PP s\<rbrace> m \<lbrace>\<lambda>_. op = s\<rbrace>; empty_fail m; no_fail P m; \<lbrace>R\<rbrace> m \<lbrace>Q\<rbrace>\<rbrakk>
\<Longrightarrow> corres_underlying sr nf True r (P and R and (\<lambda>s. \<forall>s'. s = s' \<longrightarrow> PP s s'))
(\<lambda>s'. (\<forall>s. (s, s') \<in> sr \<longrightarrow> (\<forall>rv. Q rv s \<longrightarrow> P' rv s'))) (m >>= x) y"
apply (insert z)
apply (clarsimp simp: corres_underlying_def bind_def valid_def empty_fail_def no_fail_def)
apply (drule_tac x=a in meta_spec)+
apply (drule_tac x=a in spec)+
by (auto split: prod.splits; fastforce)
lemma corres_symb_exec_r_str:
"\<lbrakk>\<And>rv. corres_underlying sr nf nf' r (P rv) (Q' rv) x (y rv);
\<And>s. \<lbrace>PP' s\<rbrace> m \<lbrace>\<lambda>r. op = s\<rbrace>; \<lbrace>P'\<rbrace> m \<lbrace>Q'\<rbrace>; nf' \<Longrightarrow> no_fail R m\<rbrakk>
\<Longrightarrow> corres_underlying sr nf nf' r (\<lambda>s'. (\<forall>s. (s', s) \<in> sr \<longrightarrow> (\<forall>rv. Q' rv s \<longrightarrow> P rv s'))) (P' and R and (\<lambda>s. \<forall>s'. s = s' \<longrightarrow> PP' s s')) x (m >>= y)"
apply (clarsimp simp: corres_underlying_def bind_def valid_def empty_fail_def no_fail_def)
by (auto split: prod.splits; fastforce)
context begin
private lemma corres_symb_exec_l_search:
"\<lbrakk>\<And>s. \<lbrace>PP s\<rbrace> m \<lbrace>\<lambda>_. op = s\<rbrace>; \<And>rv. corres_underlying sr nf True r (Q rv) P' (x rv) y;
empty_fail m; no_fail P m; \<lbrace>R\<rbrace> m \<lbrace>Q\<rbrace>\<rbrakk>
\<Longrightarrow> corres_underlying sr nf True r (P and R and (\<lambda>s. \<forall>s'. s = s' \<longrightarrow> PP s' s)) P' (m >>= x) y"
apply (rule corres_guard_imp)
apply (rule corres_symb_exec_l_str; assumption)
by auto
private lemma corres_symb_exec_r_search:
"\<lbrakk>\<And>s. \<lbrace>PP' s\<rbrace> m \<lbrace>\<lambda>r. op = s\<rbrace>; \<And>rv. corres_underlying sr nf nf' r P (Q' rv) x (y rv);
\<lbrace>P'\<rbrace> m \<lbrace>Q'\<rbrace>; nf' \<Longrightarrow> no_fail P' m\<rbrakk>
\<Longrightarrow> corres_underlying sr nf nf' r P (P' and (\<lambda>s. \<forall>s'. s = s' \<longrightarrow> PP' s' s)) x (m >>= y)"
apply (rule corres_guard_imp)
apply (rule corres_symb_exec_r_str; assumption)
by auto
private method corres_search_wp = solves \<open>((wp | wpc | simp)+)[1]\<close>
text \<open>
Depth-first search via symbolic execution of both left and right hand
sides, handling case statements and
potentially mismatched if statements. The find_goal
method handles searching each branch of case or if statements, while
we rely on backtracking to guess the order of left/right executions.
According to the above rules, a symbolic execution step can be taken
when the function can be shown to not modify the state. Questions
of wellformedness (i.e. empty_fail or no_fail) are deferred to the user
after the search concludes.
\<close>
private method corres_search_frame methods m uses search =
(#break "corres_search",
((corres?, corres_once corres: search)
| (corresc, find_goal \<open>m\<close>)[1]
| (rule corres_if_str, find_goal \<open>m\<close>)[1]
| (rule corres_if_str_rev, find_goal \<open>m\<close>)[1]
| (rule corres_symb_exec_l_search, corres_search_wp, m)
| (rule corres_symb_exec_r_search, corres_search_wp, m)))
text \<open>
Set up local context where we make sure we don't know how to
corres our given rule. The search is finished when we can only
make corres progress once we add our rule back in
\<close>
method corres_search uses search =
(use search[corres del] in
\<open>use in \<open>corres_search_frame \<open>corres_search search: search\<close> search: search\<close>\<close>)
end
chapter \<open>Misc Helper Lemmas\<close>
lemma corres_assert_assume_str:
"\<lbrakk> P' \<Longrightarrow> corres_underlying sr nf nf' r P Q f (g ()); \<And>s. Q s \<Longrightarrow> P' \<rbrakk> \<Longrightarrow>
corres_underlying sr nf nf' r P Q f (assert P' >>= g)"
by (auto simp: bind_def assert_def fail_def return_def
corres_underlying_def)
lemma corres_assert_str[corres]:
"corres_underlying sr nf nf' dc (%_. Q \<longrightarrow> P) (%_. Q) (assert P) (assert Q)"
by (auto simp add: corres_underlying_def return_def assert_def fail_def)
chapter \<open>Extra Stuff\<close>
section \<open>Named state rules\<close>
text \<open>This forms the bases of the a similar framework for spec_valid (i.e. induction proofs)\<close>
definition
"with_state P s \<equiv> \<lambda>s'. s = s' \<and> P s"
lemma corres_name_state:
assumes "\<And>s s'. (s,s') \<in> sr \<Longrightarrow> corres_underlying sr nf nf' r (with_state P s) (with_state P' s') f f'"
shows
"corres_underlying sr nf nf' r P P' f f'"
apply (insert assms)
apply (simp add: corres_underlying_def with_state_def)
by (fastforce split: prod.splits prod.split_asm)
lemma corres_name_state_pre:
assumes "corres_underlying sr nf nf' r (with_state Q s) (with_state Q' s') f f'"
"\<And>s. P s \<Longrightarrow> Q s" "\<And>s'. P' s' \<Longrightarrow> Q' s'"
shows
"corres_underlying sr nf nf' r (with_state P s) (with_state P' s') f f'"
apply (insert assms)
apply (simp add: corres_underlying_def with_state_def)
by (fastforce split: prod.splits prod.split_asm)
lemma corres_drop_state:
assumes "corres_underlying sr nf nf' r P P' f f'"
shows "corres_underlying sr nf nf' r (with_state P s) (with_state P' s') f f'"
apply (rule corres_guard_imp)
apply (rule assms)
by (auto simp add: with_state_def)
lemma corres_split_named:
assumes x: "(s, s') \<in> sr \<Longrightarrow> corres_underlying sr nf nf' r' (with_state P s) (with_state P' s') a c"
assumes y: "\<And>ss ss' rv rv'. r' rv rv' \<Longrightarrow> (rv,ss) \<in> fst (a s) \<Longrightarrow> (rv',ss') \<in> fst (c s') \<Longrightarrow>
(ss,ss') \<in> sr \<Longrightarrow>
corres_underlying sr nf nf' r (with_state (R rv' rv) ss) (with_state (R' rv rv') ss') (b rv) (d rv')"
assumes "(s,s') \<in> sr \<Longrightarrow> Q' s' \<Longrightarrow> s \<turnstile> \<lbrace>Q\<rbrace> a \<lbrace>\<lambda>r s. (\<exists>s'' r''. r' r r'' \<and> (s,s'') \<in> sr \<and> (r'',s'') \<in> fst (c s')) \<longrightarrow> (\<forall>r''. r' r r'' \<longrightarrow> R r'' r s)\<rbrace>"
"(s,s') \<in> sr \<Longrightarrow> Q s \<Longrightarrow> s' \<turnstile> \<lbrace>Q'\<rbrace> c \<lbrace>\<lambda>r s'. \<forall>x. r' x r \<longrightarrow> (\<exists>s. (s,s') \<in> sr) \<longrightarrow> R' x r s'\<rbrace>"
shows "corres_underlying sr nf nf' r (with_state (P and Q) s) (with_state (P' and Q') s') (a >>= (\<lambda>rv. b rv)) (c >>= (\<lambda>rv'. d rv'))"
using assms
apply -
apply (clarsimp simp: corres_underlying_def bind_def with_state_def)
apply (clarsimp simp: Bex_def Ball_def valid_def spec_valid_def)
by meson
end
|
import tactic.induction
import data.int.basic
import data.set.basic
import .base .point
noncomputable theory
open_locale classical
-----
lemma dist_self {a : Point} : dist a a = 0 :=
begin
change int.to_nat _ = 0,
simp_rw [sub_self, abs_zero, max_self], refl,
end
lemma eq_zero_left_of_max_eq_zero {a b : β€}
(h : (max (|a|) (|b|)).to_nat = 0) : a = 0 :=
begin
by_contra hβ,
replace hβ := lt_max_of_lt_left (abs_pos.mpr hβ),
replace hβ : int.to_nat 0 < (max (|a|) (|b|)).to_nat,
{ rw int.to_nat_lt_to_nat; assumption },
rw h at hβ, cases hβ,
end
lemma eq_zero_right_of_max_eq_zero {a b : β€}
(h : (max (|a|) (|b|)).to_nat = 0) : b = 0 :=
by { rw max_comm at h, exact eq_zero_left_of_max_eq_zero h }
lemma eq_zero_of_max_eq_zero {a b : β€}
(h : (max (|a|) (|b|)).to_nat = 0) : a = 0 β§ b = 0 :=
β¨eq_zero_left_of_max_eq_zero h, eq_zero_right_of_max_eq_zero hβ©
lemma dist_eq_zero_iff {a b : Point} : dist a b = 0 β a = b :=
begin
split; intro h,
{ obtain β¨hβ, hββ© := eq_zero_of_max_eq_zero h,
rw sub_eq_zero at hβ hβ, ext; assumption },
{ subst h, exact dist_self },
end
lemma dist_coe_int {a b : Point} :
(dist a b : β€) = max (|a.x - b.x|) (|a.y - b.y|) :=
begin
rw [dist, int.to_nat_eq_max, max_def, if_pos],
rw max_def, split_ifs; apply abs_nonneg,
end
lemma triangle_aux {a b x y : β€} :
|a + b| β€ max (|a|) x + max (|b|) y :=
begin
calc |a + b| β€ |a| + |b| : abs_add _ _
... β€ max (|a|) x + |b| : add_le_add_right (le_max_left _ _) _
... β€ max (|a|) x + max (|b|) y : add_le_add_left (le_max_left _ _) _
end
lemma dist_triangle {a b c : Point} :
dist a c β€ dist a b + dist b c :=
begin
zify, simp_rw [dist_coe_int, max_le_iff], split,
{ have h := @triangle_aux (a.x - b.x) (b.x - c.x) (|a.y - b.y|) (|b.y - c.y|),
simp at h, exact h },
{ have h := @triangle_aux (a.y - b.y) (b.y - c.y) (|a.x - b.x|) (|b.x - c.x|),
simp [max_comm] at h, exact h },
end
lemma dist_comm {a b : Point} : dist a b = dist b a :=
by { simp_rw dist, congr' 2; apply abs_sub_comm }
lemma dist_le_iff_zify {a b : Point} {d : β} :
dist a b β€ d β max (|a.x - b.x|) (|a.y - b.y|) β€ d :=
by { simp [dist] }
lemma dist_le_iff {a b : Point} {d : β} :
dist a b β€ d β |a.x - b.x| β€ d β§ |a.y - b.y| β€ d :=
by simp [dist_le_iff_zify]
lemma dist_le_set_finite {c : Point} {d : β} :
{p : Point | dist p c β€ d}.finite :=
begin
simp_rw dist_le_iff, apply set_finite_of_set_equiv_finite Point_equiv_prod.symm,
convert_to {p : β€ Γ β€ | (|p.1 - c.x|) β€ d β§ (|p.2 - c.y|) β€ d}.finite,
{ rw set.ext_iff, intro p, change _ β§ _ β _ β§ _, rw iff_iff_eq,
congr; rw Point_equiv_symm_apply },
apply @set.finite.prod β€ β€ {x : β€ | |x - c.x| β€ βd} {y : β€ | |y - c.y| β€ βd};
exact abs_sub_le_finite,
end |
The Conseil scolaire catholique de Providence ( CSC Providence ) represents the two French Catholic schools in the city , Saint @-@ FranΓ§ois @-@ Xavier and Saint @-@ Thomas @-@ d 'Aquin , while the Conseil scolaire Viamonde operates two French public schools , the elementary Γcole Les Rapides and the secondary Γcole <unk> Franco @-@ Jeunesse . There are also two independent Christian elementary schools in Sarnia β Sarnia Christian School and Temple Christian Academy .
|
[STATEMENT]
lemma bitOR_integer_unfold [code]:
"x OR y =
(if x = 0 then y
else if x = - 1 then - 1
else Bit_integer (bin_rest_integer x OR bin_rest_integer y) (bin_last_integer x \<or> bin_last_integer y))"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. x OR y = (if x = 0 then y else if x = - 1 then - 1 else Bit_integer (bin_rest_integer x OR bin_rest_integer y) (bin_last_integer x \<or> bin_last_integer y))
[PROOF STEP]
by transfer
(auto simp add: algebra_simps
or_int_rec [of _ \<open>_ * 2\<close>] or_int_rec [of _ \<open>1 + _ * 2\<close>] or_int_rec [of \<open>1 + _ * 2\<close>]
elim!: evenE oddE) |
% This is the main LaTeX file which is used to produce the Biopython
% Tutorial documentation.
%
% If you just want to read the documentation, you can pick up ready-to-go
% copies in both pdf and html format from:
%
% http://biopython.org/DIST/docs/tutorial/Tutorial.html
% http://biopython.org/DIST/docs/tutorial/Tutorial.pdf
%
% If you want to typeset the documentation, you'll need a standard TeX/LaTeX
% distribution (I use teTeX, which works great for me on Unix platforms).
% Additionally, you need HeVeA (or at least hevea.sty), which can be
% found at:
%
% http://pauillac.inria.fr/~maranget/hevea/index.html
%
% You will also need the pictures included in the document, some of
% which are UMLish diagrams created by Dia
% (http://www.lysator.liu.se/~alla/dia/dia.html).
% These diagrams are available from Biopython git in the original dia
% format, which you can easily save as .png format using Dia itself.
% They are also checked in as the png files, so if you make
% modifications to the original dia files, the png files should also be
% changed.
%
% Once you're all set, you should be able to generate pdf by running:
%
% pdflatex Tutorial.tex (to generate the first draft)
% pdflatex Tutorial.tex (to get the cross references right)
% pdflatex Tutorial.tex (to get the table of contents right)
%
% To generate the html, you'll need HeVeA installed. You should be
% able to just run:
%
% hevea -fix Tutorial.tex
%
% However, on older versions of hevea you may first need to remove the
% Tutorial.aux file generated by LaTeX, then run hevea twice to get
% the references right.
%
% If you want to typeset this and have problems, please report them
% at [email protected], and we'll try to get things resolved. We
% always love to have people interested in the documentation!
\documentclass{report}
\usepackage{url}
\usepackage{fullpage}
\usepackage{hevea}
\usepackage{graphicx}
% make everything have section numbers
\setcounter{secnumdepth}{4}
% Make links between references
\usepackage{hyperref}
\newif\ifpdf
\ifx\pdfoutput\undefined
\pdffalse
\else
\pdfoutput=1
\pdftrue
\fi
\ifpdf
\hypersetup{colorlinks=true, hyperindex=true, citecolor=red, urlcolor=blue}
\fi
\begin{document}
\begin{htmlonly}
\title{Biopython Tutorial and Cookbook}
\end{htmlonly}
\begin{latexonly}
\title{
%Hack to get the logo on the PDF front page:
\includegraphics[width=\textwidth]{images/biopython.jpg}\\
%Hack to get some white space using a blank line:
~\\
Biopython Tutorial and Cookbook}
\end{latexonly}
\author{Jeff Chang, Brad Chapman, Iddo Friedberg, Thomas Hamelryck, \\
Michiel de Hoon, Peter Cock, Tiago Antao, Eric Talevich, Bartek Wilczy\'{n}ski}
\date{Last Update -- 22 March 2013 (Biopython 1.61+)}
%Hack to get the logo at the start of the HTML front page:
%(hopefully this isn't going to be too wide for most people)
\begin{rawhtml}
<P ALIGN="center">
<IMG ALIGN="center" SRC="images/biopython.jpg" TITLE="Biopython Logo" ALT="[Biopython Logo]" width="1024" height="288" />
</p>
\end{rawhtml}
\maketitle
\tableofcontents
\chapter{Introduction}
\label{chapter:introduction}
\section{What is Biopython?}
The Biopython Project is an international association of developers of freely available Python (\url{http://www.python.org}) tools for computational molecular biology. Python is an object oriented, interpreted, flexible language that is becoming increasingly popular for scientific computing. Python is easy to learn, has a very clear syntax and can easily be extended with modules written in C, C++ or FORTRAN.
The Biopython web site (\url{http://www.biopython.org}) provides
an online resource for modules, scripts, and web links for developers
of Python-based software for bioinformatics use and research. Basically,
the goal of Biopython is to make it as easy as possible to use Python
for bioinformatics by creating high-quality, reusable modules and
classes. Biopython features include parsers for various Bioinformatics
file formats (BLAST, Clustalw, FASTA, Genbank,...), access to online
services (NCBI, Expasy,...), interfaces to common and not-so-common
programs (Clustalw, DSSP, MSMS...), a standard sequence class, various
clustering modules, a KD tree data structure etc. and even documentation.
Basically, we just like to program in Python and want to make it as easy as possible to use Python for bioinformatics by creating high-quality, reusable modules and scripts.
\section{What can I find in the Biopython package}
The main Biopython releases have lots of functionality, including:
\begin{itemize}
\item The ability to parse bioinformatics files into Python utilizable data structures, including support for the following formats:
\begin{itemize}
\item Blast output -- both from standalone and WWW Blast
\item Clustalw
\item FASTA
\item GenBank
\item PubMed and Medline
\item ExPASy files, like Enzyme and Prosite
\item SCOP, including `dom' and `lin' files
\item UniGene
\item SwissProt
\end{itemize}
\item Files in the supported formats can be iterated over record by record or indexed and accessed via a Dictionary interface.
\item Code to deal with popular on-line bioinformatics destinations such as:
\begin{itemize}
\item NCBI -- Blast, Entrez and PubMed services
\item ExPASy -- Swiss-Prot and Prosite entries, as well as Prosite searches
\end{itemize}
\item Interfaces to common bioinformatics programs such as:
\begin{itemize}
\item Standalone Blast from NCBI
\item Clustalw alignment program
\item EMBOSS command line tools
\end{itemize}
\item A standard sequence class that deals with sequences, ids on sequences, and sequence features.
\item Tools for performing common operations on sequences, such as translation, transcription and weight calculations.
\item Code to perform classification of data using k Nearest Neighbors, Naive Bayes or Support Vector Machines.
\item Code for dealing with alignments, including a standard way to create and deal with substitution matrices.
\item Code making it easy to split up parallelizable tasks into separate processes.
\item GUI-based programs to do basic sequence manipulations, translations, BLASTing, etc.
\item Extensive documentation and help with using the modules, including this file, on-line wiki documentation, the web site, and the mailing list.
\item Integration with BioSQL, a sequence database schema also supported by the BioPerl and BioJava projects.
\end{itemize}
We hope this gives you plenty of reasons to download and start using Biopython!
\section{Installing Biopython}
All of the installation information for Biopython was separated from
this document to make it easier to keep updated.
The short version is go to our downloads page (\url{http://biopython.org/wiki/Download}),
download and install the listed dependencies, then download and install Biopython.
Biopython runs on many platforms (Windows, Mac, and on the various flavors of Linux and Unix).
For Windows we provide pre-compiled click-and-run installers, while for Unix and other
operating systems you must install from source as described in the included README file.
This is usually as simple as the standard commands:
\begin{verbatim}
python setup.py build
python setup.py test
sudo python setup.py install
\end{verbatim}
\noindent (You can in fact skip the build and test, and go straight to the install --
but its better to make sure everything seems to be working.)
The longer version of our installation instructions covers
installation of Python, Biopython dependencies and Biopython itself.
It is available in PDF
(\url{http://biopython.org/DIST/docs/install/Installation.pdf})
and HTML formats
(\url{http://biopython.org/DIST/docs/install/Installation.html}).
\section{Frequently Asked Questions (FAQ)}
\begin{enumerate}
\item \emph{How do I cite Biopython in a scientific publication?} \\
Please cite our application note \cite[Cock \textit{et al.}, 2009]{cock2009}
as the main Biopython reference.
In addition, please cite any publications from the following list if appropriate, in particular as a reference for specific modules within Biopython (more information can be found on our website):
\begin{itemize}
\item For the official project announcement: \cite[Chapman and Chang, 2000]{chapman2000};
\item For \verb+Bio.PDB+: \cite[Hamelryck and Manderick, 2003]{hamelryck2003a};
\item For \verb+Bio.Cluster+: \cite[De Hoon \textit{et al.}, 2004]{dehoon2004};
\item For \verb+Bio.Graphics.GenomeDiagram+: \cite[Pritchard \textit{et al.}, 2006]{pritchard2006};
\item For \verb+Bio.Phylo+ and \verb+Bio.Phylo.PAML+: \cite[Talevich \textit{et al.}, 2012]{talevich2012};
\item For the FASTQ file format as supported in Biopython, BioPerl, BioRuby, BioJava, and EMBOSS: \cite[Cock \textit{et al.}, 2010]{cock2010}.
\end{itemize}
\item \emph{How should I capitalize ``Biopython''? Is ``BioPython'' OK?} \\
The correct capitalization is ``Biopython'', not ``BioPython'' (even though
that would have matched BioPerl, BioJava and BioRuby).
\item \emph{How do I find out what version of Biopython I have installed?} \\
Use this:
\begin{verbatim}
>>> import Bio
>>> print Bio.__version__
...
\end{verbatim}
If the ``\verb|import Bio|'' line fails, Biopython is not installed.
If the second line fails, your version is very out of date.
If the version string ends with a plus, you don't have an official
release, but a snapshot of the in development code.
\item \emph{Where is the latest version of this document?}\\
If you download a Biopython source code archive, it will include the
relevant version in both HTML and PDF formats. The latest published
version of this document (updated at each release) is online:
\begin{itemize}
\item \url{http://biopython.org/DIST/docs/tutorial/Tutorial.html}
\item \url{http://biopython.org/DIST/docs/tutorial/Tutorial.pdf}
\end{itemize}
If you are using the very latest unreleased code from our repository
you can find copies of the in-progress tutorial here:
\begin{itemize}
\item \url{http://biopython.org/DIST/docs/tutorial/Tutorial-dev.html}
\item \url{http://biopython.org/DIST/docs/tutorial/Tutorial-dev.pdf}
\end{itemize}
\item \emph{Which ``Numerical Python'' do I need?} \\
For Biopython 1.48 or earlier, you needed the old Numeric module.
For Biopython 1.49 onwards, you need the newer NumPy instead.
Both Numeric and NumPy can be installed on the same machine fine.
See also: \url{http://numpy.scipy.org/}
\item \emph{Why is the} \verb|Seq| \emph{object missing the (back) transcription \& translation methods described in this Tutorial?} \\
You need Biopython 1.49 or later. Alternatively, use the \verb|Bio.Seq| module functions described in Section~\ref{sec:seq-module-functions}.
\item \emph{Why is the} \verb|Seq| \emph{object missing the upper \& lower methods described in this Tutorial?} \\
You need Biopython 1.53 or later. Alternatively, use \verb|str(my_seq).upper()| to get an upper case string.
If you need a Seq object, try \verb|Seq(str(my_seq).upper())| but be careful about blindly re-using the same alphabet.
\item \emph{Why doesn't the} \verb|Seq| \emph{object translation method support the} \verb|cds| \emph{option described in this Tutorial?} \\
You need Biopython 1.51 or later.
\item \emph{Why doesn't} \verb|Bio.SeqIO| \emph{work? It imports fine but there is no parse function etc.} \\
You need Biopython 1.43 or later. Older versions did contain some related code under the \verb|Bio.SeqIO| name which has since been removed - and this is why the import ``works''.
\item \emph{Why doesn't} \verb|Bio.SeqIO.read()| \emph{work? The module imports fine but there is no read function!} \\
You need Biopython 1.45 or later. Or, use \texttt{Bio.SeqIO.parse(...).next()} instead.
\item \emph{Why isn't} \verb|Bio.AlignIO| \emph{present? The module import fails!} \\
You need Biopython 1.46 or later.
\item \emph{What file formats do} \verb|Bio.SeqIO| \emph{and} \verb|Bio.AlignIO| \emph{read and write?} \\
Check the built in docstrings (\texttt{from Bio import SeqIO}, then \texttt{help(SeqIO)}), or see \url{http://biopython.org/wiki/SeqIO} and \url{http://biopython.org/wiki/AlignIO} on the wiki for the latest listing.
\item \emph{Why don't the } \verb|Bio.SeqIO| \emph{and} \verb|Bio.AlignIO| \emph{input functions let me provide a sequence alphabet?} \\
You need Biopython 1.49 or later.
\item \emph{Why won't the } \verb|Bio.SeqIO| \emph{and} \verb|Bio.AlignIO| \emph{functions} \verb|parse|\emph{,} \verb|read| \emph{and} \verb|write| \emph{take filenames? They insist on handles!} \\
You need Biopython 1.54 or later, or just use handles explicitly (see Section~\ref{sec:appendix-handles}).
It is especially important to remember to close output handles explicitly after writing your data.
\item \emph{Why won't the } \verb|Bio.SeqIO.write()| \emph{and} \verb|Bio.AlignIO.write()| \emph{functions accept a single record or alignment? They insist on a list or iterator!} \\
You need Biopython 1.54 or later, or just wrap the item with \verb|[...]| to create a list of one element.
\item \emph{Why doesn't} \verb|str(...)| \emph{give me the full sequence of a} \verb|Seq| \emph{object?} \\
You need Biopython 1.45 or later. Alternatively, rather than \verb|str(my_seq)|, use \verb|my_seq.tostring()| (which will also work on recent versions of Biopython).
\item \emph{Why doesn't} \verb|Bio.Blast| \emph{work with the latest plain text NCBI blast output?} \\
The NCBI keep tweaking the plain text output from the BLAST tools, and keeping our parser up to date is/was an ongoing struggle.
If you aren't using the latest version of Biopython, you could try upgrading.
However, we (and the NCBI) recommend you use the XML output instead, which is designed to be read by a computer program.
\item \emph{Why doesn't} \verb|Bio.Entrez.read()| \emph{work? The module imports fine but there is no read function!} \\
You need Biopython 1.46 or later.
\item \emph{Why doesn't} \verb|Bio.Entrez.parse()| \emph{work? The module imports fine but there is no parse function!} \\
You need Biopython 1.52 or later.
\item \emph{Why has my script using} \verb|Bio.Entrez.efetch()| \emph{stopped working?} \\
This could be due to NCBI changes in February 2012 introducing EFetch 2.0.
First, they changed the default return modes - you probably want to add \verb|retmode="text"| to
your call.
Second, they are now stricter about how to provide a list of IDs -- Biopython 1.59 onwards
turns a list into a comma separated string automatically.
\item \emph{Why doesn't} \verb|Bio.Blast.NCBIWWW.qblast()| \emph{give the same results as the NCBI BLAST website?} \\
You need to specify the same options -- the NCBI often adjust the default settings on the website,
and they do not match the QBLAST defaults anymore. Check things like the gap penalties and expectation threshold.
\item \emph{Why doesn't} \verb|Bio.Blast.NCBIXML.read()| \emph{work? The module imports but there is no read function!} \\
You need Biopython 1.50 or later. Or, use \texttt{Bio.Blast.NCBIXML.parse(...).next()} instead.
\item \emph{Why doesn't my} \verb|SeqRecord| \emph{object have a} \verb|letter_annotations| \emph{attribute?} \\
Per-letter-annotation support was added in Biopython 1.50.
\item \emph{Why can't I slice my} \verb|SeqRecord| \emph{to get a sub-record?} \\
You need Biopython 1.50 or later.
\item \emph{Why can't I add} \verb|SeqRecord| \emph{objects together?} \\
You need Biopython 1.53 or later.
\item \emph{Why doesn't} \verb|Bio.SeqIO.convert()| \emph{or} \verb|Bio.AlignIO.convert()| \emph{work? The modules import fine but there is no convert function!} \\
You need Biopython 1.52 or later. Alternatively, combine the \verb|parse| and \verb|write|
functions as described in this tutorial (see Sections~\ref{sec:SeqIO-conversion} and~\ref{sec:converting-alignments}).
\item \emph{Why doesn't} \verb|Bio.SeqIO.index()| \emph{work? The module imports fine but there is no index function!} \\
You need Biopython 1.52 or later.
\item \emph{Why doesn't} \verb|Bio.SeqIO.index_db()| \emph{work? The module imports fine but there is no \texttt{index\_db} function!} \\
You need Biopython 1.57 or later (and a Python with SQLite3 support).
\item \emph{Where is the} \verb|MultipleSeqAlignment| \emph{object? The} \verb|Bio.Align| \emph{module imports fine but this class isn't there!} \\
You need Biopython 1.54 or later. Alternatively, the older \verb|Bio.Align.Generic.Alignment| class supports some of its functionality, but using this is now discouraged.
\item \emph{Why can't I run command line tools directly from the application wrappers?} \\
You need Biopython 1.55 or later. Alternatively, use the Python \verb|subprocess| module directly.
\item \emph{I looked in a directory for code, but I couldn't find the code that does something. Where's it hidden?} \\
One thing to know is that we put code in \verb|__init__.py| files. If you are not used to looking for code in this file this can be confusing. The reason we do this is to make the imports easier for users. For instance, instead of having to do a ``repetitive'' import like \verb|from Bio.GenBank import GenBank|, you can just use \verb|from Bio import GenBank|.
\item \emph{Why does the code from CVS seem out of date?} \\
In late September 2009, just after the release of Biopython 1.52, we switched from using CVS to git, a distributed version control system. The old CVS server will remain available as a static and read only backup, but if you want to grab the latest code, you'll need to use git instead. See our website for more details.
\end{enumerate}
\noindent For more general questions, the Python FAQ pages \url{http://www.python.org/doc/faq/} may be useful.
\chapter{Quick Start -- What can you do with Biopython?}
\label{chapter:quick-start}
This section is designed to get you started quickly with Biopython, and to give a general overview of what is available and how to use it. All of the examples in this section assume that you have some general working knowledge of Python, and that you have successfully installed Biopython on your system. If you think you need to brush up on your Python, the main Python web site provides quite a bit of free documentation to get started with (\url{http://www.python.org/doc/}).
Since much biological work on the computer involves connecting with databases on the internet, some of the examples will also require a working internet connection in order to run.
Now that that is all out of the way, let's get into what we can do with Biopython.
\section{General overview of what Biopython provides}
As mentioned in the introduction, Biopython is a set of libraries to provide the ability to deal with ``things'' of interest to biologists working on the computer. In general this means that you will need to have at least some programming experience (in Python, of course!) or at least an interest in learning to program. Biopython's job is to make your job easier as a programmer by supplying reusable libraries so that you can focus on answering your specific question of interest, instead of focusing on the internals of parsing a particular file format (of course, if you want to help by writing a parser that doesn't exist and contributing it to Biopython, please go ahead!). So Biopython's job is to make you happy!
One thing to note about Biopython is that it often provides multiple ways of ``doing the same thing.'' Things have improved in recent releases, but this can still be frustrating as in Python there should ideally be one right way to do something. However, this can also be a real benefit because it gives you lots of flexibility and control over the libraries. The tutorial helps to show you the common or easy ways to do things so that you can just make things work. To learn more about the alternative possibilities, look in the Cookbook (Chapter~\ref{chapter:cookbook}, this has some cools tricks and tips), the Advanced section (Chapter~\ref{chapter:advanced}), the built in ``docstrings'' (via the Python help command, or the \href{http://biopython.org/DIST/docs/api/}{API documentation}) or ultimately the code itself.
\section{Working with sequences}
\label{sec:sequences}
Disputably (of course!), the central object in bioinformatics is the sequence. Thus, we'll start with a quick introduction to the Biopython mechanisms for dealing with sequences, the \verb|Seq| object, which we'll discuss in more detail in Chapter~\ref{chapter:Bio.Seq}.
Most of the time when we think about sequences we have in my mind a string of letters like `\verb|AGTACACTGGT|'. You can create such \verb|Seq| object with this sequence as follows - the ``\verb+>>>+'' represents the Python prompt followed by what you would type in:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> my_seq = Seq("AGTACACTGGT")
>>> my_seq
Seq('AGTACACTGGT', Alphabet())
>>> print my_seq
AGTACACTGGT
>>> my_seq.alphabet
Alphabet()
\end{verbatim}
What we have here is a sequence object with a \emph{generic} alphabet - reflecting the fact we have \emph{not} specified if this is a DNA or protein sequence (okay, a protein with a lot of Alanines, Glycines, Cysteines and Threonines!). We'll talk more about alphabets in Chapter~\ref{chapter:Bio.Seq}.
In addition to having an alphabet, the \verb|Seq| object differs from the Python string in the methods it supports. You can't do this with a plain string:
%cont-doctest
\begin{verbatim}
>>> my_seq
Seq('AGTACACTGGT', Alphabet())
>>> my_seq.complement()
Seq('TCATGTGACCA', Alphabet())
>>> my_seq.reverse_complement()
Seq('ACCAGTGTACT', Alphabet())
\end{verbatim}
The next most important class is the \verb|SeqRecord| or Sequence Record. This holds a sequence (as a \verb|Seq| object) with additional annotation including an identifier, name and description. The \verb|Bio.SeqIO| module for reading and writing sequence file formats works with \verb|SeqRecord| objects, which will be introduced below and covered in more detail by Chapter~\ref{chapter:Bio.SeqIO}.
This covers the basic features and uses of the Biopython sequence class.
Now that you've got some idea of what it is like to interact with the Biopython libraries, it's time to delve into the fun, fun world of dealing with biological file formats!
\section{A usage example}
\label{sec:orchids}
Before we jump right into parsers and everything else to do with Biopython, let's set up an example to motivate everything we do and make life more interesting. After all, if there wasn't any biology in this tutorial, why would you want you read it?
Since I love plants, I think we're just going to have to have a plant based example (sorry to all the fans of other organisms out there!). Having just completed a recent trip to our local greenhouse, we've suddenly developed an incredible obsession with Lady Slipper Orchids (if you wonder why, have a look at some \href{http://www.flickr.com/search/?q=lady+slipper+orchid&s=int&z=t}{Lady Slipper Orchids photos on Flickr}, or try a \href{http://images.google.com/images?q=lady%20slipper%20orchid}{Google Image Search}).
Of course, orchids are not only beautiful to look at, they are also extremely interesting for people studying evolution and systematics. So let's suppose we're thinking about writing a funding proposal to do a molecular study of Lady Slipper evolution, and would like to see what kind of research has already been done and how we can add to that.
% Brad's links to Millicent Orchids are dead now (March 2007)
% http://www.millicentorchids.com/greenhouse/images/papesq01.jpg
% http://www.millicentorchids.com/greenhouse/indexphoto.htm
After a little bit of reading up we discover that the Lady Slipper Orchids are in the Orchidaceae family and the Cypripedioideae sub-family and are made up of 5 genera: \emph{Cypripedium}, \emph{Paphiopedilum}, \emph{Phragmipedium}, \emph{Selenipedium} and \emph{Mexipedium}.
That gives us enough to get started delving for more information. So, let's look at how the Biopython tools can help us. We'll start with sequence parsing in Section~\ref{sec:sequence-parsing}, but the orchids will be back later on as well - for example we'll search PubMed for papers about orchids and extract sequence data from GenBank in Chapter~\ref{chapter:entrez}, extract data from Swiss-Prot from certain orchid proteins in Chapter~\ref{chapter:swiss_prot}, and work with ClustalW multiple sequence alignments of orchid proteins in Section~\ref{sec:align_clustal}.
\section{Parsing sequence file formats}
\label{sec:sequence-parsing}
A large part of much bioinformatics work involves dealing with the many types of file formats designed to hold biological data. These files are loaded with interesting biological data, and a special challenge is parsing these files into a format so that you can manipulate them with some kind of programming language. However the task of parsing these files can be frustrated by the fact that the formats can change quite regularly, and that formats may contain small subtleties which can break even the most well designed parsers.
We are now going to briefly introduce the \verb|Bio.SeqIO| module -- you can find out more in Chapter~\ref{chapter:Bio.SeqIO}. We'll start with an online search for our friends, the lady slipper orchids. To keep this introduction simple, we're just using the NCBI website by hand. Let's just take a look through the nucleotide databases at NCBI, using an Entrez online search (\url{http://www.ncbi.nlm.nih.gov:80/entrez/query.fcgi?db=Nucleotide}) for everything mentioning the text Cypripedioideae (this is the subfamily of lady slipper orchids).
When this tutorial was originally written, this search gave us only 94 hits, which we saved as a FASTA formatted text file and as a GenBank formatted text file (files \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{\tt ls\_orchid.fasta} and \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{\tt ls\_orchid.gbk}, also included with the Biopython source code under {\tt docs/tutorial/examples/}).
% The GenBank version is actually new - it was created by filtering out the original 94 hits from the
% latest search of over 400 hits.
If you run the search today, you'll get hundreds of results! When following the tutorial, if you want to see the same list of genes, just download the two files above or copy them from \verb|docs/examples/| in the Biopython source code. In Section~\ref{sec:connecting-with-biological-databases} we will look at how to do a search like this from within Python.
\subsection{Simple FASTA parsing example}
\label{sec:fasta-parsing}
If you open the lady slipper orchids FASTA file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{\tt ls\_orchid.fasta} in your favourite text editor, you'll see that the file starts like this:
\begin{verbatim}
>gi|2765658|emb|Z78533.1|CIZ78533 C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA
CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGGAATAAACGATCGAGTG
AATCCGGAGGACCGGTGTACTCAGCTCACCGGGGGCATTGCTCCCGTGGTGACCCTGATTTGTTGTTGGG
...
\end{verbatim}
It contains 94 records, each has a line starting with ``\verb+>+'' (greater-than symbol) followed by the sequence on one or more lines. Now try this in Python:
\begin{verbatim}
from Bio import SeqIO
for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
print seq_record.id
print repr(seq_record.seq)
print len(seq_record)
\end{verbatim}
\noindent You should get something like this on your screen:
\begin{verbatim}
gi|2765658|emb|Z78533.1|CIZ78533
Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', SingleLetterAlphabet())
740
...
gi|2765564|emb|Z78439.1|PBZ78439
Seq('CATTGTTGAGATCACATAATAATTGATCGAGTTAATCTGGAGGATCTGTTTACT...GCC', SingleLetterAlphabet())
592
\end{verbatim}
Notice that the FASTA format does not specify the alphabet, so \verb|Bio.SeqIO| has defaulted to the rather generic \verb|SingleLetterAlphabet()| rather than something DNA specific.
\subsection{Simple GenBank parsing example}
Now let's load the GenBank file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{\tt ls\_orchid.gbk} instead - notice that the code to do this is almost identical to the snippet used above for the FASTA file - the only difference is we change the filename and the format string:
\begin{verbatim}
from Bio import SeqIO
for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"):
print seq_record.id
print repr(seq_record.seq)
print len(seq_record)
\end{verbatim}
\noindent This should give:
\begin{verbatim}
Z78533.1
Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
740
...
Z78439.1
Seq('CATTGTTGAGATCACATAATAATTGATCGAGTTAATCTGGAGGATCTGTTTACT...GCC', IUPACAmbiguousDNA())
592
\end{verbatim}
This time \verb|Bio.SeqIO| has been able to choose a sensible alphabet, IUPAC Ambiguous DNA. You'll also notice that a shorter string has been used as the \verb|seq_record.id| in this case.
\subsection{I love parsing -- please don't stop talking about it!}
Biopython has a lot of parsers, and each has its own little special niches based on the sequence format it is parsing and all of that. Chapter~\ref{chapter:Bio.SeqIO} covers \verb|Bio.SeqIO| in more detail, while Chapter~\ref{chapter:Bio.AlignIO} introduces \verb|Bio.AlignIO| for sequence alignments.
While the most popular file formats have parsers integrated into \verb|Bio.SeqIO| and/or \verb|Bio.AlignIO|, for some of the rarer and unloved file formats there is either no parser at all, or an old parser which has not been linked in yet.
Please also check the wiki pages \url{http://biopython.org/wiki/SeqIO} and \url{http://biopython.org/wiki/AlignIO} for the latest information, or ask on the mailing list. The wiki pages should include an up to date list of supported file types, and some additional examples.
The next place to look for information about specific parsers and how to do cool things with them is in the Cookbook (Chapter~\ref{chapter:cookbook} of this Tutorial). If you don't find the information you are looking for, please consider helping out your poor overworked documentors and submitting a cookbook entry about it! (once you figure out how to do it, that is!)
\section{Connecting with biological databases}
\label{sec:connecting-with-biological-databases}
One of the very common things that you need to do in bioinformatics is extract information from biological databases. It can be quite tedious to access these databases manually, especially if you have a lot of repetitive work to do. Biopython attempts to save you time and energy by making some on-line databases available from Python scripts. Currently, Biopython has code to extract information from the following databases:
\begin{itemize}
\item \href{http://www.ncbi.nlm.nih.gov/Entrez/}{Entrez} (and \href{http://www.ncbi.nlm.nih.gov/PubMed/}{PubMed}) from the NCBI -- See Chapter~\ref{chapter:entrez}.
\item \href{http://www.expasy.org/}{ExPASy} -- See Chapter~\ref{chapter:swiss_prot}.
\item \href{http://scop.mrc-lmb.cam.ac.uk/scop/}{SCOP} -- See the \verb|Bio.SCOP.search()| function.
\end{itemize}
The code in these modules basically makes it easy to write Python code that interact with the CGI scripts on these pages, so that you can get results in an easy to deal with format. In some cases, the results can be tightly integrated with the Biopython parsers to make it even easier to extract information.
\section{What to do next}
Now that you've made it this far, you hopefully have a good understanding of the basics of Biopython and are ready to start using it for doing useful work. The best thing to do now is finish reading this tutorial, and then if you want start snooping around in the source code, and looking at the automatically generated documentation.
Once you get a picture of what you want to do, and what libraries in Biopython will do it, you should take a peak at the Cookbook (Chapter~\ref{chapter:cookbook}), which may have example code to do something similar to what you want to do.
If you know what you want to do, but can't figure out how to do it, please feel free to post questions to the main Biopython list (see \url{http://biopython.org/wiki/Mailing_lists}). This will not only help us answer your question, it will also allow us to improve the documentation so it can help the next person do what you want to do.
Enjoy the code!
\chapter{Sequence objects}
\label{chapter:Bio.Seq}
Biological sequences are arguably the central object in Bioinformatics, and in this chapter we'll introduce the Biopython mechanism for dealing with sequences, the \verb|Seq| object.
Chapter~\ref{chapter:SeqRecord} will introduce the related \verb|SeqRecord| object, which combines the sequence information with any annotation, used again in Chapter~\ref{chapter:Bio.SeqIO} for Sequence Input/Output.
Sequences are essentially strings of letters like \verb|AGTACACTGGT|, which seems very natural since this is the most common way that sequences are seen in biological file formats.
There are two important differences between \verb|Seq| objects and standard Python strings.
First of all, they have different methods. Although the \verb|Seq| object supports many of the same methods as a plain string, its \verb|translate()| method differs by doing biological translation, and there are also additional biologically relevant methods like \verb|reverse_complement()|.
Secondly, the \verb|Seq| object has an important attribute, \verb|alphabet|, which is an object describing what the individual characters making up the sequence string ``mean'', and how they should be interpreted. For example, is \verb|AGTACACTGGT| a DNA sequence, or just a protein sequence that happens to be rich in Alanines, Glycines, Cysteines
and Threonines?
\section{Sequences and Alphabets}
The alphabet object is perhaps the important thing that makes the \verb|Seq| object more than just a string. The currently available alphabets for Biopython are defined in the \verb|Bio.Alphabet| module. We'll use the IUPAC alphabets (\url{http://www.chem.qmw.ac.uk/iupac/}) here to deal with some of our favorite objects: DNA, RNA and Proteins.
\verb|Bio.Alphabet.IUPAC| provides basic definitions for proteins, DNA and RNA, but additionally provides the ability to extend and customize the basic definitions. For instance, for proteins, there is a basic IUPACProtein class, but there is an additional ExtendedIUPACProtein class providing for the additional elements ``U'' (or ``Sec'' for selenocysteine) and ``O'' (or ``Pyl'' for pyrrolysine), plus the ambiguous symbols ``B'' (or ``Asx'' for asparagine or aspartic acid), ``Z'' (or ``Glx'' for glutamine or glutamic acid), ``J'' (or ``Xle'' for leucine isoleucine) and ``X'' (or ``Xxx'' for an unknown amino acid). For DNA you've got choices of IUPACUnambiguousDNA, which provides for just the basic letters, IUPACAmbiguousDNA (which provides for ambiguity letters for every possible situation) and ExtendedIUPACDNA, which allows letters for modified bases. Similarly, RNA can be represented by IUPACAmbiguousRNA or IUPACUnambiguousRNA.
The advantages of having an alphabet class are two fold. First, this gives an idea of the type of information the Seq object contains. Secondly, this provides a means of constraining the information, as a means of type checking.
Now that we know what we are dealing with, let's look at how to utilize this class to do interesting work.
You can create an ambiguous sequence with the default generic alphabet like this:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> my_seq = Seq("AGTACACTGGT")
>>> my_seq
Seq('AGTACACTGGT', Alphabet())
>>> my_seq.alphabet
Alphabet()
\end{verbatim}
However, where possible you should specify the alphabet explicitly when creating your sequence objects - in this case an unambiguous DNA alphabet object:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq("AGTACACTGGT", IUPAC.unambiguous_dna)
>>> my_seq
Seq('AGTACACTGGT', IUPACUnambiguousDNA())
>>> my_seq.alphabet
IUPACUnambiguousDNA()
\end{verbatim}
Unless of course, this really is an amino acid sequence:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_prot = Seq("AGTACACTGGT", IUPAC.protein)
>>> my_prot
Seq('AGTACACTGGT', IUPACProtein())
>>> my_prot.alphabet
IUPACProtein()
\end{verbatim}
\section{Sequences act like strings}
In many ways, we can deal with Seq objects as if they were normal Python strings, for example getting the length, or iterating over the elements:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq("GATCG", IUPAC.unambiguous_dna)
>>> for index, letter in enumerate(my_seq):
... print index, letter
0 G
1 A
2 T
3 C
4 G
>>> print len(my_seq)
5
\end{verbatim}
You can access elements of the sequence in the same way as for strings (but remember, Python counts from zero!):
%cont-doctest
\begin{verbatim}
>>> print my_seq[0] #first letter
G
>>> print my_seq[2] #third letter
T
>>> print my_seq[-1] #last letter
G
\end{verbatim}
The \verb|Seq| object has a \verb|.count()| method, just like a string.
Note that this means that like a Python string, this gives a
\emph{non-overlapping} count:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> "AAAA".count("AA")
2
>>> Seq("AAAA").count("AA")
2
\end{verbatim}
\noindent For some biological uses, you may actually want an overlapping count
(i.e. $3$ in this trivial example). When searching for single letters, this
makes no difference:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq('GATCGATGGGCCTATATAGGATCGAAAATCGC', IUPAC.unambiguous_dna)
>>> len(my_seq)
32
>>> my_seq.count("G")
9
>>> 100 * float(my_seq.count("G") + my_seq.count("C")) / len(my_seq)
46.875
\end{verbatim}
While you could use the above snippet of code to calculate a GC\%, note that the \verb|Bio.SeqUtils| module has several GC functions already built. For example:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> from Bio.SeqUtils import GC
>>> my_seq = Seq('GATCGATGGGCCTATATAGGATCGAAAATCGC', IUPAC.unambiguous_dna)
>>> GC(my_seq)
46.875
\end{verbatim}
\noindent Note that using the \verb|Bio.SeqUtils.GC()| function should automatically cope with mixed case sequences and the ambiguous nucleotide S which means G or C.
Also note that just like a normal Python string, the \verb|Seq| object is in some ways ``read-only''. If you need to edit your sequence, for example simulating a point mutation, look at the Section~\ref{sec:mutable-seq} below which talks about the \verb|MutableSeq| object.
\section{Slicing a sequence}
A more complicated example, let's get a slice of the sequence:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq("GATCGATGGGCCTATATAGGATCGAAAATCGC", IUPAC.unambiguous_dna)
>>> my_seq[4:12]
Seq('GATGGGCC', IUPACUnambiguousDNA())
\end{verbatim}
Two things are interesting to note. First, this follows the normal conventions for Python strings. So the first element of the sequence is 0 (which is normal for computer science, but not so normal for biology). When you do a slice the first item is included (i.e.~4 in this case) and the last is excluded (12 in this case), which is the way things work in Python, but of course not necessarily the way everyone in the world would expect. The main goal is to stay consistent with what Python does.
The second thing to notice is that the slice is performed on the sequence data string, but the new object produced is another \verb|Seq| object which retains the alphabet information from the original \verb|Seq| object.
Also like a Python string, you can do slices with a start, stop and \emph{stride} (the step size, which defaults to one). For example, we can get the first, second and third codon positions of this DNA sequence:
%cont-doctest
\begin{verbatim}
>>> my_seq[0::3]
Seq('GCTGTAGTAAG', IUPACUnambiguousDNA())
>>> my_seq[1::3]
Seq('AGGCATGCATC', IUPACUnambiguousDNA())
>>> my_seq[2::3]
Seq('TAGCTAAGAC', IUPACUnambiguousDNA())
\end{verbatim}
Another stride trick you might have seen with a Python string is the use of a -1 stride to reverse the string. You can do this with a \verb|Seq| object too:
%cont-doctest
\begin{verbatim}
>>> my_seq[::-1]
Seq('CGCTAAAAGCTAGGATATATCCGGGTAGCTAG', IUPACUnambiguousDNA())
\end{verbatim}
\section{Turning Seq objects into strings}
\label{sec:seq-to-string}
If you really do just need a plain string, for example to write to a file, or insert into a database, then this is very easy to get:
%cont-doctest
\begin{verbatim}
>>> str(my_seq)
'GATCGATGGGCCTATATAGGATCGAAAATCGC'
\end{verbatim}
Since calling \verb|str()| on a \verb|Seq| object returns the full sequence as a string,
you often don't actually have to do this conversion explicitly.
Python does this automatically with a print statement:
%cont-doctest
\begin{verbatim}
>>> print my_seq
GATCGATGGGCCTATATAGGATCGAAAATCGC
\end{verbatim}
You can also use the \verb|Seq| object directly with a \verb|%s| placeholder when using the Python string formatting or interpolation operator (\verb|%|):
%cont-doctest
\begin{verbatim}
>>> fasta_format_string = ">Name\n%s\n" % my_seq
>>> print fasta_format_string
>Name
GATCGATGGGCCTATATAGGATCGAAAATCGC
<BLANKLINE>
\end{verbatim}
\noindent This line of code constructs a simple FASTA format record (without worrying about line wrapping).
Section~\ref{sec:SeqRecord-format} describes a neat way to get a FASTA formatted
string from a \verb|SeqRecord| object, while the more general topic of reading and
writing FASTA format sequence files is covered in Chapter~\ref{chapter:Bio.SeqIO}.
\emph{NOTE:} If you are using Biopython 1.44 or older, using \verb|str(my_seq)|
will give just a truncated representation. Instead use \verb|my_seq.tostring()|
(which is still available in the current Biopython releases for backwards compatibility):
%cont-doctest
\begin{verbatim}
>>> my_seq.tostring()
'GATCGATGGGCCTATATAGGATCGAAAATCGC'
\end{verbatim}
\section{Concatenating or adding sequences}
Naturally, you can in principle add any two Seq objects together - just like you can with Python strings to concatenate them. However, you can't add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence:
%doctest
\begin{verbatim}
>>> from Bio.Alphabet import IUPAC
>>> from Bio.Seq import Seq
>>> protein_seq = Seq("EVRNAK", IUPAC.protein)
>>> dna_seq = Seq("ACGT", IUPAC.unambiguous_dna)
>>> protein_seq + dna_seq
Traceback (most recent call last):
...
TypeError: Incompatible alphabets IUPACProtein() and IUPACUnambiguousDNA()
\end{verbatim}
If you \emph{really} wanted to do this, you'd have to first give both sequences generic alphabets:
%cont-doctest
\begin{verbatim}
>>> from Bio.Alphabet import generic_alphabet
>>> protein_seq.alphabet = generic_alphabet
>>> dna_seq.alphabet = generic_alphabet
>>> protein_seq + dna_seq
Seq('EVRNAKACGT', Alphabet())
\end{verbatim}
Here is an example of adding a generic nucleotide sequence to an unambiguous IUPAC DNA sequence, resulting in an ambiguous nucleotide sequence:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_nucleotide
>>> from Bio.Alphabet import IUPAC
>>> nuc_seq = Seq("GATCGATGC", generic_nucleotide)
>>> dna_seq = Seq("ACGT", IUPAC.unambiguous_dna)
>>> nuc_seq
Seq('GATCGATGC', NucleotideAlphabet())
>>> dna_seq
Seq('ACGT', IUPACUnambiguousDNA())
>>> nuc_seq + dna_seq
Seq('GATCGATGCACGT', NucleotideAlphabet())
\end{verbatim}
\section{Changing case}
Python strings have very useful \verb|upper| and \verb|lower| methods for changing the case.
As of Biopython 1.53, the \verb|Seq| object gained similar methods which are alphabet aware.
For example,
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> dna_seq = Seq("acgtACGT", generic_dna)
>>> dna_seq
Seq('acgtACGT', DNAAlphabet())
>>> dna_seq.upper()
Seq('ACGTACGT', DNAAlphabet())
>>> dna_seq.lower()
Seq('acgtacgt', DNAAlphabet())
\end{verbatim}
These are useful for doing case insensitive matching:
%cont-doctest
\begin{verbatim}
>>> "GTAC" in dna_seq
False
>>> "GTAC" in dna_seq.upper()
True
\end{verbatim}
Note that strictly speaking the IUPAC alphabets are for upper case
sequences only, thus:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> dna_seq = Seq("ACGT", IUPAC.unambiguous_dna)
>>> dna_seq
Seq('ACGT', IUPACUnambiguousDNA())
>>> dna_seq.lower()
Seq('acgt', DNAAlphabet())
\end{verbatim}
\section{Nucleotide sequences and (reverse) complements}
\label{sec:seq-reverse-complement}
For nucleotide sequences, you can easily obtain the complement or reverse
complement of a \verb|Seq| object using its built-in methods:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq("GATCGATGGGCCTATATAGGATCGAAAATCGC", IUPAC.unambiguous_dna)
>>> my_seq
Seq('GATCGATGGGCCTATATAGGATCGAAAATCGC', IUPACUnambiguousDNA())
>>> my_seq.complement()
Seq('CTAGCTACCCGGATATATCCTAGCTTTTAGCG', IUPACUnambiguousDNA())
>>> my_seq.reverse_complement()
Seq('GCGATTTTCGATCCTATATAGGCCCATCGATC', IUPACUnambiguousDNA())
\end{verbatim}
As mentioned earlier, an easy way to just reverse a \verb|Seq| object (or a
Python string) is slice it with -1 step:
%cont-doctest
\begin{verbatim}
>>> my_seq[::-1]
Seq('CGCTAAAAGCTAGGATATATCCGGGTAGCTAG', IUPACUnambiguousDNA())
\end{verbatim}
In all of these operations, the alphabet property is maintained. This is very
useful in case you accidentally end up trying to do something weird like take
the (reverse)complement of a protein sequence:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> protein_seq = Seq("EVRNAK", IUPAC.protein)
>>> protein_seq.complement()
Traceback (most recent call last):
...
ValueError: Proteins do not have complements!
\end{verbatim}
The example in Section~\ref{sec:SeqIO-reverse-complement} combines the \verb|Seq|
object's reverse complement method with \verb|Bio.SeqIO| for sequence input/output.
\section{Transcription}
Before talking about transcription, I want to try and clarify the strand issue.
Consider the following (made up) stretch of double stranded DNA which
encodes a short peptide:
\begin{tabular}{rcl}
\\
& {\small DNA coding strand (aka Crick strand, strand $+1$)} & \\
5' & \texttt{ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG} & 3' \\
& \texttt{|||||||||||||||||||||||||||||||||||||||} & \\
3' & \texttt{TACCGGTAACATTACCCGGCGACTTTCCCACGGGCTATC} & 5' \\
& {\small DNA template strand (aka Watson strand, strand $-1$)} & \\
\\
& {\LARGE $|$} &\\
& Transcription & \\
& {\LARGE $\downarrow$} &\\
\\
5' & \texttt{AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG} & 3' \\
& {\small Single stranded messenger RNA} & \\
\\
\end{tabular}
The actual biological transcription process works from the template strand, doing a reverse complement (TCAG $\rightarrow$ CUGA) to give the mRNA. However, in Biopython and bioinformatics in general, we typically work directly with the coding strand because this means we can get the mRNA sequence just by switching T $\rightarrow$ U.
Now let's actually get down to doing a transcription in Biopython. First, let's create \verb|Seq| objects for the coding and template DNA strands:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG", IUPAC.unambiguous_dna)
>>> coding_dna
Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
>>> template_dna = coding_dna.reverse_complement()
>>> template_dna
Seq('CTATCGGGCACCCTTTCAGCGGCCCATTACAATGGCCAT', IUPACUnambiguousDNA())
\end{verbatim}
\noindent These should match the figure above - remember by convention nucleotide sequences are normally read from the 5' to 3' direction, while in the figure the template strand is shown reversed.
Now let's transcribe the coding strand into the corresponding mRNA, using the \verb|Seq| object's built in \verb|transcribe| method:
%cont-doctest
\begin{verbatim}
>>> coding_dna
Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
>>> messenger_rna = coding_dna.transcribe()
>>> messenger_rna
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
\end{verbatim}
\noindent As you can see, all this does is switch T $\rightarrow$ U, and adjust the alphabet.
If you do want to do a true biological transcription starting with the template strand, then this becomes a two-step process:
%cont-doctest
\begin{verbatim}
>>> template_dna.reverse_complement().transcribe()
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
\end{verbatim}
The \verb|Seq| object also includes a back-transcription method for going from the mRNA to the coding strand of the DNA. Again, this is a simple U $\rightarrow$ T substitution and associated change of alphabet:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG", IUPAC.unambiguous_rna)
>>> messenger_rna
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
>>> messenger_rna.back_transcribe()
Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
\end{verbatim}
\emph{Note:} The \verb|Seq| object's \verb|transcribe| and \verb|back_transcribe| methods
were added in Biopython 1.49. For older releases you would have to use the \verb|Bio.Seq|
module's functions instead, see Section~\ref{sec:seq-module-functions}.
\section{Translation}
\label{sec:translation}
Sticking with the same example discussed in the transcription section above,
now let's translate this mRNA into the corresponding protein sequence - again taking
advantage of one of the \verb|Seq| object's biological methods:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> messenger_rna = Seq("AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG", IUPAC.unambiguous_rna)
>>> messenger_rna
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
>>> messenger_rna.translate()
Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))
\end{verbatim}
You can also translate directly from the coding strand DNA sequence:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG", IUPAC.unambiguous_dna)
>>> coding_dna
Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())
>>> coding_dna.translate()
Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))
\end{verbatim}
You should notice in the above protein sequences that in addition to the end stop character, there is an internal stop as well. This was a deliberate choice of example, as it gives an excuse to talk about some optional arguments, including different translation tables (Genetic Codes).
The translation tables available in Biopython are based on those \href{http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi}{from the NCBI} (see the next section of this tutorial). By default, translation will use the \emph{standard} genetic code (NCBI table id 1).
Suppose we are dealing with a mitochondrial sequence. We need to tell the translation function to use the relevant genetic code instead:
%cont-doctest
\begin{verbatim}
>>> coding_dna.translate(table="Vertebrate Mitochondrial")
Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))
\end{verbatim}
You can also specify the table using the NCBI table number which is shorter, and often included in the feature annotation of GenBank files:
%cont-doctest
\begin{verbatim}
>>> coding_dna.translate(table=2)
Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))
\end{verbatim}
Now, you may want to translate the nucleotides up to the first in frame stop codon,
and then stop (as happens in nature):
%cont-doctest
\begin{verbatim}
>>> coding_dna.translate()
Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))
>>> coding_dna.translate(to_stop=True)
Seq('MAIVMGR', IUPACProtein())
>>> coding_dna.translate(table=2)
Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))
>>> coding_dna.translate(table=2, to_stop=True)
Seq('MAIVMGRWKGAR', IUPACProtein())
\end{verbatim}
\noindent Notice that when you use the \verb|to_stop| argument, the stop codon itself
is not translated - and the stop symbol is not included at the end of your protein
sequence.
You can even specify the stop symbol if you don't like the default asterisk:
%cont-doctest
\begin{verbatim}
>>> coding_dna.translate(table=2, stop_symbol="@")
Seq('MAIVMGRWKGAR@', HasStopCodon(IUPACProtein(), '@'))
\end{verbatim}
Now, suppose you have a complete coding sequence CDS, which is to say a
nucleotide sequence (e.g. mRNA -- after any splicing) which is a whole number
of codons (i.e. the length is a multiple of three), commences with a start
codon, ends with a stop codon, and has no internal in-frame stop codons.
In general, given a complete CDS, the default translate method will do what
you want (perhaps with the \verb|to_stop| option). However, what if your
sequence uses a non-standard start codon? This happens a lot in bacteria --
for example the gene yaaX in \texttt{E. coli} K12:
%TODO - handle line wrapping in doctest?
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> gene = Seq("GTGAAAAAGATGCAATCTATCGTACTCGCACTTTCCCTGGTTCTGGTCGCTCCCATGGCA" + \
... "GCACAGGCTGCGGAAATTACGTTAGTCCCGTCAGTAAAATTACAGATAGGCGATCGTGAT" + \
... "AATCGTGGCTATTACTGGGATGGAGGTCACTGGCGCGACCACGGCTGGTGGAAACAACAT" + \
... "TATGAATGGCGAGGCAATCGCTGGCACCTACACGGACCGCCGCCACCGCCGCGCCACCAT" + \
... "AAGAAAGCTCCTCATGATCATCACGGCGGTCATGGTCCAGGCAAACATCACCGCTAA",
... generic_dna)
>>> gene.translate(table="Bacterial")
Seq('VKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HR*',
HasStopCodon(ExtendedIUPACProtein(), '*')
>>> gene.translate(table="Bacterial", to_stop=True)
Seq('VKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HHR',
ExtendedIUPACProtein())
\end{verbatim}
\noindent In the bacterial genetic code \texttt{GTG} is a valid start codon,
and while it does \emph{normally} encode Valine, if used as a start codon it
should be translated as methionine. This happens if you tell Biopython your
sequence is a complete CDS:
%TODO - handle line wrapping in doctest?
\begin{verbatim}
>>> gene.translate(table="Bacterial", cds=True)
Seq('MKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HHR',
ExtendedIUPACProtein())
\end{verbatim}
In addition to telling Biopython to translate an alternative start codon as
methionine, using this option also makes sure your sequence really is a valid
CDS (you'll get an exception if not).
The example in Section~\ref{sec:SeqIO-translate} combines the \verb|Seq| object's
translate method with \verb|Bio.SeqIO| for sequence input/output.
\section{Translation Tables}
In the previous sections we talked about the \verb|Seq| object translation method (and mentioned the equivalent function in the \verb|Bio.Seq| module -- see
Section~\ref{sec:seq-module-functions}).
Internally these use codon table objects derived from the NCBI information at
\url{ftp://ftp.ncbi.nlm.nih.gov/entrez/misc/data/gc.prt}, also shown on
\url{http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi} in a much more readable layout.
As before, let's just focus on two choices: the Standard translation table, and the
translation table for Vertebrate Mitochondrial DNA.
%doctest
\begin{verbatim}
>>> from Bio.Data import CodonTable
>>> standard_table = CodonTable.unambiguous_dna_by_name["Standard"]
>>> mito_table = CodonTable.unambiguous_dna_by_name["Vertebrate Mitochondrial"]
\end{verbatim}
Alternatively, these tables are labeled with ID numbers 1 and 2, respectively:
%cont-doctest
\begin{verbatim}
>>> from Bio.Data import CodonTable
>>> standard_table = CodonTable.unambiguous_dna_by_id[1]
>>> mito_table = CodonTable.unambiguous_dna_by_id[2]
\end{verbatim}
You can compare the actual tables visually by printing them:
%TODO - handle <BLANKLINE> automatically in doctest?
\begin{verbatim}
>>> print standard_table
Table 1 Standard, SGC0
| T | C | A | G |
--+---------+---------+---------+---------+--
T | TTT F | TCT S | TAT Y | TGT C | T
T | TTC F | TCC S | TAC Y | TGC C | C
T | TTA L | TCA S | TAA Stop| TGA Stop| A
T | TTG L(s)| TCG S | TAG Stop| TGG W | G
--+---------+---------+---------+---------+--
C | CTT L | CCT P | CAT H | CGT R | T
C | CTC L | CCC P | CAC H | CGC R | C
C | CTA L | CCA P | CAA Q | CGA R | A
C | CTG L(s)| CCG P | CAG Q | CGG R | G
--+---------+---------+---------+---------+--
A | ATT I | ACT T | AAT N | AGT S | T
A | ATC I | ACC T | AAC N | AGC S | C
A | ATA I | ACA T | AAA K | AGA R | A
A | ATG M(s)| ACG T | AAG K | AGG R | G
--+---------+---------+---------+---------+--
G | GTT V | GCT A | GAT D | GGT G | T
G | GTC V | GCC A | GAC D | GGC G | C
G | GTA V | GCA A | GAA E | GGA G | A
G | GTG V | GCG A | GAG E | GGG G | G
--+---------+---------+---------+---------+--
\end{verbatim}
\noindent and:
\begin{verbatim}
>>> print mito_table
Table 2 Vertebrate Mitochondrial, SGC1
| T | C | A | G |
--+---------+---------+---------+---------+--
T | TTT F | TCT S | TAT Y | TGT C | T
T | TTC F | TCC S | TAC Y | TGC C | C
T | TTA L | TCA S | TAA Stop| TGA W | A
T | TTG L | TCG S | TAG Stop| TGG W | G
--+---------+---------+---------+---------+--
C | CTT L | CCT P | CAT H | CGT R | T
C | CTC L | CCC P | CAC H | CGC R | C
C | CTA L | CCA P | CAA Q | CGA R | A
C | CTG L | CCG P | CAG Q | CGG R | G
--+---------+---------+---------+---------+--
A | ATT I(s)| ACT T | AAT N | AGT S | T
A | ATC I(s)| ACC T | AAC N | AGC S | C
A | ATA M(s)| ACA T | AAA K | AGA Stop| A
A | ATG M(s)| ACG T | AAG K | AGG Stop| G
--+---------+---------+---------+---------+--
G | GTT V | GCT A | GAT D | GGT G | T
G | GTC V | GCC A | GAC D | GGC G | C
G | GTA V | GCA A | GAA E | GGA G | A
G | GTG V(s)| GCG A | GAG E | GGG G | G
--+---------+---------+---------+---------+--
\end{verbatim}
You may find these following properties useful -- for example if you are trying
to do your own gene finding:
%cont-doctest
\begin{verbatim}
>>> mito_table.stop_codons
['TAA', 'TAG', 'AGA', 'AGG']
>>> mito_table.start_codons
['ATT', 'ATC', 'ATA', 'ATG', 'GTG']
>>> mito_table.forward_table["ACG"]
'T'
\end{verbatim}
\section{Comparing Seq objects}
\label{sec:seq-comparison}
Sequence comparison is actually a very complicated topic, and there is no easy
way to decide if two sequences are equal. The basic problem is the meaning of
the letters in a sequence are context dependent - the letter ``A'' could be part
of a DNA, RNA or protein sequence. Biopython uses alphabet objects as part of
each \verb|Seq| object to try and capture this information - so comparing two
\verb|Seq| objects means considering both the sequence strings \emph{and} the
alphabets.
For example, you might argue that the two DNA \verb|Seq| objects
\texttt{Seq("ACGT", IUPAC.unambiguous\_dna)} and
\texttt{Seq("ACGT", IUPAC.ambiguous\_dna)} should be equal, even though
they do have different alphabets. Depending on the context this could be
important.
This gets worse -- suppose you think \texttt{Seq("ACGT",
IUPAC.unambiguous\_dna)} and \texttt{Seq("ACGT")} (i.e. the default generic
alphabet) should be equal. Then, logically, \texttt{Seq("ACGT", IUPAC.protein)}
and \texttt{Seq("ACGT")} should also be equal. Now, in logic if $A=B$ and
$B=C$, by transitivity we expect $A=C$. So for logical consistency we'd
require \texttt{Seq("ACGT", IUPAC.unambiguous\_dna)} and \texttt{Seq("ACGT",
IUPAC.protein)} to be equal -- which most people would agree is just not right.
This transitivity problem would also have implications for using \verb|Seq|
objects as Python dictionary keys.
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> seq1 = Seq("ACGT", IUPAC.unambiguous_dna)
>>> seq2 = Seq("ACGT", IUPAC.unambiguous_dna)
\end{verbatim}
So, what does Biopython do? Well, the equality test is the default for Python
objects -- it tests to see if they are the same object in memory. This is a
very strict test:
%TODO - silence FutureWarning from this doctest?
\begin{verbatim}
>>> seq1 == seq2
False
>>> seq1 == seq1
True
\end{verbatim}
If you actually want to do this, you can be more explicit by using the Python
\verb|id| function,
%cont-doctest
\begin{verbatim}
>>> id(seq1) == id(seq2)
False
>>> id(seq1) == id(seq1)
True
\end{verbatim}
Now, in every day use, your sequences will probably all have the same
alphabet, or at least all be the same type of sequence (all DNA, all RNA, or
all protein). What you probably want is to just compare the sequences as
strings -- so do this explicitly:
%cont-doctest
\begin{verbatim}
>>> str(seq1) == str(seq2)
True
>>> str(seq1) == str(seq1)
True
\end{verbatim}
\noindent As an extension to this, while you can use a Python dictionary with
\verb|Seq| objects as keys, it is generally more useful to use the sequence a
string for the key. See also Section~\ref{sec:seq-to-string}.
\section{MutableSeq objects}
\label{sec:mutable-seq}
Just like the normal Python string, the \verb|Seq| object is ``read only'', or in Python terminology, immutable. Apart from wanting the \verb|Seq| object to act like a string, this is also a useful default since in many biological applications you want to ensure you are not changing your sequence data:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq("GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA", IUPAC.unambiguous_dna)
\end{verbatim}
Observe what happens if you try to edit the sequence:
%TODO - This is not a doctest as Python 2.4 output omits the object name.
\begin{verbatim}
>>> my_seq[5] = "G"
Traceback (most recent call last):
...
TypeError: 'Seq' object does not support item assignment
\end{verbatim}
However, you can convert it into a mutable sequence (a \verb|MutableSeq| object) and do pretty much anything you want with it:
%cont-doctest
\begin{verbatim}
>>> mutable_seq = my_seq.tomutable()
>>> mutable_seq
MutableSeq('GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA', IUPACUnambiguousDNA())
\end{verbatim}
Alternatively, you can create a \verb|MutableSeq| object directly from a string:
%doctest
\begin{verbatim}
>>> from Bio.Seq import MutableSeq
>>> from Bio.Alphabet import IUPAC
>>> mutable_seq = MutableSeq("GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA", IUPAC.unambiguous_dna)
\end{verbatim}
Either way will give you a sequence object which can be changed:
%cont-doctest
\begin{verbatim}
>>> mutable_seq
MutableSeq('GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA', IUPACUnambiguousDNA())
>>> mutable_seq[5] = "C"
>>> mutable_seq
MutableSeq('GCCATCGTAATGGGCCGCTGAAAGGGTGCCCGA', IUPACUnambiguousDNA())
>>> mutable_seq.remove("T")
>>> mutable_seq
MutableSeq('GCCACGTAATGGGCCGCTGAAAGGGTGCCCGA', IUPACUnambiguousDNA())
>>> mutable_seq.reverse()
>>> mutable_seq
MutableSeq('AGCCCGTGGGAAAGTCGCCGGGTAATGCACCG', IUPACUnambiguousDNA())
\end{verbatim}
Do note that unlike the \verb|Seq| object, the \verb|MutableSeq| object's methods like \verb|reverse_complement()| and \verb|reverse()| act in-situ!
An important technical difference between mutable and immutable objects in Python means that you can't use a \verb|MutableSeq| object as a dictionary key, but you can use a Python string or a \verb|Seq| object in this way.
Once you have finished editing your a \verb|MutableSeq| object, it's easy to get back to a read-only \verb|Seq| object should you need to:
%cont-doctest
\begin{verbatim}
>>> new_seq = mutable_seq.toseq()
>>> new_seq
Seq('AGCCCGTGGGAAAGTCGCCGGGTAATGCACCG', IUPACUnambiguousDNA())
\end{verbatim}
You can also get a string from a \verb|MutableSeq| object just like from a \verb|Seq| object (Section~\ref{sec:seq-to-string}).
\section{UnknownSeq objects}
The \verb|UnknownSeq| object is a subclass of the basic \verb|Seq| object
and its purpose is to represent a
sequence where we know the length, but not the actual letters making it up.
You could of course use a normal \verb|Seq| object in this situation, but it wastes
rather a lot of memory to hold a string of a million ``N'' characters when you could
just store a single letter ``N'' and the desired length as an integer.
%doctest
\begin{verbatim}
>>> from Bio.Seq import UnknownSeq
>>> unk = UnknownSeq(20)
>>> unk
UnknownSeq(20, alphabet = Alphabet(), character = '?')
>>> print unk
????????????????????
>>> len(unk)
20
\end{verbatim}
You can of course specify an alphabet, meaning for nucleotide sequences
the letter defaults to ``N'' and for proteins ``X'', rather than just ``?''.
%cont-doctest
\begin{verbatim}
>>> from Bio.Seq import UnknownSeq
>>> from Bio.Alphabet import IUPAC
>>> unk_dna = UnknownSeq(20, alphabet=IUPAC.ambiguous_dna)
>>> unk_dna
UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')
>>> print unk_dna
NNNNNNNNNNNNNNNNNNNN
\end{verbatim}
You can use all the usual \verb|Seq| object methods too, note these give back
memory saving \verb|UnknownSeq| objects where appropriate as you might expect:
%cont-doctest
\begin{verbatim}
>>> unk_dna
UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')
>>> unk_dna.complement()
UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')
>>> unk_dna.reverse_complement()
UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')
>>> unk_dna.transcribe()
UnknownSeq(20, alphabet = IUPACAmbiguousRNA(), character = 'N')
>>> unk_protein = unk_dna.translate()
>>> unk_protein
UnknownSeq(6, alphabet = ProteinAlphabet(), character = 'X')
>>> print unk_protein
XXXXXX
>>> len(unk_protein)
6
\end{verbatim}
You may be able to find a use for the \verb|UnknownSeq| object in your own
code, but it is more likely that you will first come across them in a
\verb|SeqRecord| object created by \verb|Bio.SeqIO|
(see Chapter~\ref{chapter:Bio.SeqIO}).
Some sequence file formats don't always include the actual sequence, for
example GenBank and EMBL files may include a list of features but for the
sequence just present the contig information. Alternatively, the QUAL files
used in sequencing work hold quality scores but they \emph{never} contain a
sequence -- instead there is a partner FASTA file which \emph{does} have the
sequence.
\section{Working with directly strings}
\label{sec:seq-module-functions}
To close this chapter, for those you who \emph{really} don't want to use the sequence
objects (or who prefer a functional programming style to an object orientated one),
there are module level functions in \verb|Bio.Seq| will accept plain Python strings,
\verb|Seq| objects (including \verb|UnknownSeq| objects) or \verb|MutableSeq| objects:
%doctest
\begin{verbatim}
>>> from Bio.Seq import reverse_complement, transcribe, back_transcribe, translate
>>> my_string = "GCTGTTATGGGTCGTTGGAAGGGTGGTCGTGCTGCTGGTTAG"
>>> reverse_complement(my_string)
'CTAACCAGCAGCACGACCACCCTTCCAACGACCCATAACAGC'
>>> transcribe(my_string)
'GCUGUUAUGGGUCGUUGGAAGGGUGGUCGUGCUGCUGGUUAG'
>>> back_transcribe(my_string)
'GCTGTTATGGGTCGTTGGAAGGGTGGTCGTGCTGCTGGTTAG'
>>> translate(my_string)
'AVMGRWKGGRAAG*'
\end{verbatim}
\noindent You are, however, encouraged to work with \verb|Seq| objects by default.
\chapter{Sequence annotation objects}
\label{chapter:SeqRecord}
Chapter~\ref{chapter:Bio.Seq} introduced the sequence classes. Immediately ``above'' the \verb|Seq| class is the Sequence Record or \verb|SeqRecord| class, defined in the \verb|Bio.SeqRecord| module. This class allows higher level features such as identifiers and features (as \verb|SeqFeature| objects) to be associated with the sequence, and is used throughout the sequence input/output interface \verb|Bio.SeqIO| described fully in Chapter~\ref{chapter:Bio.SeqIO}.
If you are only going to be working with simple data like FASTA files, you can probably skip this chapter
for now. If on the other hand you are going to be using richly annotated sequence data, say from GenBank
or EMBL files, this information is quite important.
While this chapter should cover most things to do with the \verb|SeqRecord| and \verb|SeqFeature| objects in this chapter, you may also want to read the \verb|SeqRecord| wiki page (\url{http://biopython.org/wiki/SeqRecord}), and the built in documentation (also online -- \href{http://biopython.org/DIST/docs/api/Bio.SeqRecord.SeqRecord-class.html}{SeqRecord} and \href{http://biopython.org/DIST/docs/api/Bio.SeqFeature.SeqFeature-class.html}{SeqFeature}):
\begin{verbatim}
>>> from Bio.SeqRecord import SeqRecord
>>> help(SeqRecord)
...
\end{verbatim}
\section{The SeqRecord object}
\label{sec:SeqRecord}
The \verb|SeqRecord| (Sequence Record) class is defined in the \verb|Bio.SeqRecord| module. This class allows higher level features such as identifiers and features to be associated with a sequence (see Chapter~\ref{chapter:Bio.Seq}), and is the basic data type for the \verb|Bio.SeqIO| sequence input/output interface (see Chapter~\ref{chapter:Bio.SeqIO}).
The \verb|SeqRecord| class itself is quite simple, and offers the following information as attributes:
\begin{description}
\item[.seq] -- The sequence itself, typically a \verb|Seq| object.
\item[.id] -- The primary ID used to identify the sequence -- a string. In most cases this is something like an accession number.
\item[.name] -- A ``common'' name/id for the sequence -- a string. In some cases this will be the same as the accession number, but it could also be a clone name. I think of this as being analogous to the LOCUS id in a GenBank record.
\item[.description] -- A human readable description or expressive name for the sequence -- a string.
\item[.letter\_annotations] -- Holds per-letter-annotations using a (restricted) dictionary of additional information about the letters in the sequence. The keys are the name of the information, and the information is contained in the value as a Python sequence (i.e. a list, tuple or string) with the same length as the sequence itself. This is often used for quality scores (e.g. Section~\ref{sec:FASTQ-filtering-example}) or secondary structure information (e.g. from Stockholm/PFAM alignment files).
\item[.annotations] -- A dictionary of additional information about the sequence. The keys are the name of the information, and the information is contained in the value. This allows the addition of more ``unstructured'' information to the sequence.
\item[.features] -- A list of \verb|SeqFeature| objects with more structured information about the features on a sequence (e.g. position of genes on a genome, or domains on a protein sequence). The structure of sequence features is described below in Section~\ref{sec:seq_features}.
\item[.dbxrefs] - A list of database cross-references as strings.
\end{description}
\section{Creating a SeqRecord}
Using a \verb|SeqRecord| object is not very complicated, since all of the
information is presented as attributes of the class. Usually you won't create
a \verb|SeqRecord| ``by hand'', but instead use \verb|Bio.SeqIO| to read in a
sequence file for you (see Chapter~\ref{chapter:Bio.SeqIO} and the examples
below). However, creating \verb|SeqRecord| can be quite simple.
\subsection{SeqRecord objects from scratch}
To create a \verb|SeqRecord| at a minimum you just need a \verb|Seq| object:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> simple_seq = Seq("GATC")
>>> from Bio.SeqRecord import SeqRecord
>>> simple_seq_r = SeqRecord(simple_seq)
\end{verbatim}
Additionally, you can also pass the id, name and description to the initialization function, but if not they will be set as strings indicating they are unknown, and can be modified subsequently:
%cont-doctest
\begin{verbatim}
>>> simple_seq_r.id
'<unknown id>'
>>> simple_seq_r.id = "AC12345"
>>> simple_seq_r.description = "Made up sequence I wish I could write a paper about"
>>> print simple_seq_r.description
Made up sequence I wish I could write a paper about
>>> simple_seq_r.seq
Seq('GATC', Alphabet())
\end{verbatim}
Including an identifier is very important if you want to output your \verb|SeqRecord| to a file. You would normally include this when creating the object:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> simple_seq = Seq("GATC")
>>> from Bio.SeqRecord import SeqRecord
>>> simple_seq_r = SeqRecord(simple_seq, id="AC12345")
\end{verbatim}
As mentioned above, the \verb|SeqRecord| has an dictionary attribute \verb|annotations|. This is used
for any miscellaneous annotations that doesn't fit under one of the other more specific attributes.
Adding annotations is easy, and just involves dealing directly with the annotation dictionary:
%cont-doctest
\begin{verbatim}
>>> simple_seq_r.annotations["evidence"] = "None. I just made it up."
>>> print simple_seq_r.annotations
{'evidence': 'None. I just made it up.'}
>>> print simple_seq_r.annotations["evidence"]
None. I just made it up.
\end{verbatim}
Working with per-letter-annotations is similar, \verb|letter_annotations| is a
dictionary like attribute which will let you assign any Python sequence (i.e.
a string, list or tuple) which has the same length as the sequence:
%cont-doctest
\begin{verbatim}
>>> simple_seq_r.letter_annotations["phred_quality"] = [40,40,38,30]
>>> print simple_seq_r.letter_annotations
{'phred_quality': [40, 40, 38, 30]}
>>> print simple_seq_r.letter_annotations["phred_quality"]
[40, 40, 38, 30]
\end{verbatim}
The \verb|dbxrefs| and \verb|features| attributes are just Python lists, and
should be used to store strings and \verb|SeqFeature| objects (discussed later
in this chapter) respectively.
%TODO - Update this to show passing in the annotations etc to __init__ ?
\subsection{SeqRecord objects from FASTA files}
This example uses a fairly large FASTA file containing the whole sequence for \textit{Yersinia pestis biovar Microtus} str. 91001 plasmid pPCP1, originally downloaded from the NCBI. This file is included with the Biopython unit tests under the GenBank folder, or online \href{http://biopython.org/SRC/biopython/Tests/GenBank/NC_005816.fna}{\texttt{NC\_005816.fna}} from our website.
The file starts like this - and you can check there is only one record present (i.e. only one line starting with a greater than symbol):
\begin{verbatim}
>gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... pPCP1, complete sequence
TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGGGGGTAATCTGCTCTCC
...
\end{verbatim}
Back in Chapter~\ref{chapter:quick-start} you will have seen the function \verb|Bio.SeqIO.parse(...)|
used to loop over all the records in a file as \verb|SeqRecord| objects. The \verb|Bio.SeqIO| module
has a sister function for use on files which contain just one record which we'll use here (see Chapter~\ref{chapter:Bio.SeqIO} for details):
%TODO - line wrapping for doctest?
\begin{verbatim}
>>> from Bio import SeqIO
>>> record = SeqIO.read("NC_005816.fna", "fasta")
>>> record
SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
SingleLetterAlphabet()), id='gi|45478711|ref|NC_005816.1|', name='gi|45478711|ref|NC_005816.1|',
description='gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... sequence',
dbxrefs=[])
\end{verbatim}
Now, let's have a look at the key attributes of this \verb|SeqRecord|
individually -- starting with the \verb|seq| attribute which gives you a
\verb|Seq| object:
\begin{verbatim}
>>> record.seq
Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', SingleLetterAlphabet())
\end{verbatim}
\noindent Here \verb|Bio.SeqIO| has defaulted to a generic alphabet, rather
than guessing that this is DNA. If you know in advance what kind of sequence
your FASTA file contains, you can tell \verb|Bio.SeqIO| which alphabet to use
(see Chapter~\ref{chapter:Bio.SeqIO}).
Next, the identifiers and description:
\begin{verbatim}
>>> record.id
'gi|45478711|ref|NC_005816.1|'
>>> record.name
'gi|45478711|ref|NC_005816.1|'
>>> record.description
'gi|45478711|ref|NC_005816.1| Yersinia pestis biovar Microtus ... pPCP1, complete sequence'
\end{verbatim}
As you can see above, the first word of the FASTA record's title line (after
removing the greater than symbol) is used for both the \verb|id| and
\verb|name| attributes. The whole title line (after removing the greater than
symbol) is used for the record description. This is deliberate, partly for
backwards compatibility reasons, but it also makes sense if you have a FASTA
file like this:
\begin{verbatim}
>Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1
TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGGGGGTAATCTGCTCTCC
...
\end{verbatim}
Note that none of the other annotation attributes get populated when reading a
FASTA file:
\begin{verbatim}
>>> record.dbxrefs
[]
>>> record.annotations
{}
>>> record.letter_annotations
{}
>>> record.features
[]
\end{verbatim}
In this case our example FASTA file was from the NCBI, and they have a fairly well defined set of conventions for formatting their FASTA lines. This means it would be possible to parse this information and extract the GI number and accession for example. However, FASTA files from other sources vary, so this isn't possible in general.
\subsection{SeqRecord objects from GenBank files}
As in the previous example, we're going to look at the whole sequence for \textit{Yersinia pestis biovar Microtus} str. 91001 plasmid pPCP1, originally downloaded from the NCBI, but this time as a GenBank file.
Again, this file is included with the Biopython unit tests under the GenBank folder, or online \href{http://biopython.org/SRC/biopython/Tests/GenBank/NC_005816.gb}{\texttt{NC\_005816.gb}} from our website.
This file contains a single record (i.e. only one LOCUS line) and starts:
\begin{verbatim}
LOCUS NC_005816 9609 bp DNA circular BCT 21-JUL-2008
DEFINITION Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete
sequence.
ACCESSION NC_005816
VERSION NC_005816.1 GI:45478711
PROJECT GenomeProject:10638
...
\end{verbatim}
Again, we'll use \verb|Bio.SeqIO| to read this file in, and the code is almost identical to that for used above for the FASTA file (see Chapter~\ref{chapter:Bio.SeqIO} for details):
\begin{verbatim}
>>> from Bio import SeqIO
>>> record = SeqIO.read("NC_005816.gb", "genbank")
>>> record
SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
dbxrefs=['Project:10638'])
\end{verbatim}
You should be able to spot some differences already! But taking the attributes individually,
the sequence string is the same as before, but this time \verb|Bio.SeqIO| has been able to automatically assign a more specific alphabet (see Chapter~\ref{chapter:Bio.SeqIO} for details):
\begin{verbatim}
>>> record.seq
Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG', IUPACAmbiguousDNA())
\end{verbatim}
The \verb|name| comes from the LOCUS line, while the \verb|id| includes the version suffix.
The description comes from the DEFINITION line:
\begin{verbatim}
>>> record.id
'NC_005816.1'
>>> record.name
'NC_005816'
>>> record.description
'Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.'
\end{verbatim}
GenBank files don't have any per-letter annotations:
\begin{verbatim}
>>> record.letter_annotations
{}
\end{verbatim}
Most of the annotations information gets recorded in the \verb|annotations| dictionary, for example:
\begin{verbatim}
>>> len(record.annotations)
11
>>> record.annotations["source"]
'Yersinia pestis biovar Microtus str. 91001'
\end{verbatim}
The \verb|dbxrefs| list gets populated from any PROJECT or DBLINK lines:
\begin{verbatim}
>>> record.dbxrefs
['Project:10638']
\end{verbatim}
Finally, and perhaps most interestingly, all the entries in the features table (e.g. the genes or CDS features) get recorded as \verb|SeqFeature| objects in the \verb|features| list.
\begin{verbatim}
>>> len(record.features)
29
\end{verbatim}
\noindent We'll talk about \verb|SeqFeature| objects next, in
Section~\ref{sec:seq_features}.
\section{Feature, location and position objects}
\label{sec:seq_features}
\subsection{SeqFeature objects}
Sequence features are an essential part of describing a sequence. Once you get beyond the sequence itself, you need some way to organize and easily get at the more ``abstract'' information that is known about the sequence. While it is probably impossible to develop a general sequence feature class that will cover everything, the Biopython \verb|SeqFeature| class attempts to encapsulate as much of the information about the sequence as possible. The design is heavily based on the GenBank/EMBL feature tables, so if you understand how they look, you'll probably have an easier time grasping the structure of the Biopython classes.
The key idea about each \verb|SeqFeature| object is to describe a region on a parent sequence, typically a \verb|SeqRecord| object. That region is described with a location object, typically a range between two positions (see Section~\ref{sec:locations} below).
The \verb|SeqFeature| class has a number of attributes, so first we'll list them and their general features, and then later in the chapter work through examples to show how this applies to a real life example. The attributes of a SeqFeature are:
\begin{description}
\item[.type] -- This is a textual description of the type of feature (for instance, this will be something like `CDS' or `gene').
\item[.location] -- The location of the \verb|SeqFeature| on the sequence
that you are dealing with, see Section~\ref{sec:locations} below. The
\verb|SeqFeature| delegates much of its functionality to the location
object, and includes a number of shortcut attributes for properties
of the location:
\begin{description}
\item[.ref] -- shorthand for \verb|.location.ref| -- any (different)
reference sequence the location is referring to. Usually just None.
\item[.ref\_db] -- shorthand for \verb|.location.ref_db| -- specifies
the database any identifier in \verb|.ref| refers to. Usually just None.
\item[.strand] -- shorthand for \verb|.location.strand| -- the strand on
the sequence that the feature is located on. For double stranded nucleotide
sequence this may either be $1$ for the top strand, $-1$ for the bottom
strand, $0$ if the strand is important but is unknown, or \texttt{None}
if it doesn't matter. This is None for proteins, or single stranded sequences.
\end{description}
\item[.qualifiers] -- This is a Python dictionary of additional information about the feature. The key is some kind of terse one-word description of what the information contained in the value is about, and the value is the actual information. For example, a common key for a qualifier might be ``evidence'' and the value might be ``computational (non-experimental).'' This is just a way to let the person who is looking at the feature know that it has not be experimentally (i.~e.~in a wet lab) confirmed. Note that other the value will be a list of strings (even when there is only one string). This is a reflection of the feature tables in GenBank/EMBL files.
\item[.sub\_features] -- This used to be used to represent features with complicated locations like `joins' in GenBank/EMBL files. This has been deprecated with the introduction of the \verb|CompoundLocation| object, and should now be ignored.
\end{description}
\subsection{Positions and locations}
\label{sec:locations}
The key idea about each \verb|SeqFeature| object is to describe a
region on a parent sequence, for which we use a location object,
typically describing a range between two positions. Two try to
clarify the terminology we're using:
\begin{description}
\item[position] -- This refers to a single position on a sequence,
which may be fuzzy or not. For instance, 5, 20, \verb|<100| and
\verb|>200| are all positions.
\item[location] -- A location is region of sequence bounded by
some positions. For instance 5..20 (i.~e.~5 to 20) is a location.
\end{description}
I just mention this because sometimes I get confused between the two.
\subsubsection{FeatureLocation object}
Unless you work with eukaryotic genes, most \verb|SeqFeature| locations are
extremely simple - you just need start and end coordinates and a strand.
That's essentially all the basic \verb|FeatureLocation| object does.
%TODO -- add example here
In practise of course, things can be more complicated. First of all
we have to handle compound locations made up of several regions.
Secondly, the positions themselves may be fuzzy (inexact).
\subsubsection{CompoundLocation object}
Biopython 1.62 introduced the \verb|CompoundLocation| as part of
a restructuring of how complex locations made up of multiple regions
are represented.
The main usage is for handling `join' locations in EMBL/GenBank files.
%TODO -- add example here
\subsubsection{Fuzzy Positions}
So far we've only used simple positions. One complication in dealing
with feature locations comes in the positions themselves.
In biology many times things aren't entirely certain
(as much as us wet lab biologists try to make them certain!). For
instance, you might do a dinucleotide priming experiment and discover
that the start of mRNA transcript starts at one of two sites. This
is very useful information, but the complication comes in how to
represent this as a position. To help us deal with this, we have
the concept of fuzzy positions. Basically there are several types
of fuzzy positions, so we have five classes do deal with them:
\begin{description}
\item[ExactPosition] -- As its name suggests, this class represents a position which is specified as exact along the sequence. This is represented as just a number, and you can get the position by looking at the \verb|position| attribute of the object.
\item[BeforePosition] -- This class represents a fuzzy position
that occurs prior to some specified site. In GenBank/EMBL notation,
this is represented as something like \verb|`<13'|, signifying that
the real position is located somewhere less than 13. To get
the specified upper boundary, look at the \verb|position|
attribute of the object.
\item[AfterPosition] -- Contrary to \verb|BeforePosition|, this
class represents a position that occurs after some specified site.
This is represented in GenBank as \verb|`>13'|, and like
\verb|BeforePosition|, you get the boundary number by looking
at the \verb|position| attribute of the object.
\item[WithinPosition] -- Occasionally used for GenBank/EMBL locations,
this class models a position which occurs somewhere between two
specified nucleotides. In GenBank/EMBL notation, this would be
represented as `(1.5)', to represent that the position is somewhere
within the range 1 to 5. To get the information in this class you
have to look at two attributes. The \verb|position| attribute
specifies the lower boundary of the range we are looking at, so in
our example case this would be one. The \verb|extension| attribute
specifies the range to the higher boundary, so in this case it
would be 4. So \verb|object.position| is the lower boundary and
\verb|object.position + object.extension| is the upper boundary.
\item[OneOfPosition] -- Occasionally used for GenBank/EMBL locations,
this class deals with a position where several possible values exist,
for instance you could use this if the start codon was unclear and
there where two candidates for the start of the gene. Alternatively,
that might be handled explicitly as two related gene features.
\item[UnknownPosition] -- This class deals with a position of unknown
location. This is not used in GenBank/EMBL, but corresponds to the `?'
feature coordinate used in UniProt.
\end{description}
Here's an example where we create a location with fuzzy end points:
%doctest
\begin{verbatim}
>>> from Bio import SeqFeature
>>> start_pos = SeqFeature.AfterPosition(5)
>>> end_pos = SeqFeature.BetweenPosition(9, left=8, right=9)
>>> my_location = SeqFeature.FeatureLocation(start_pos, end_pos)
\end{verbatim}
Note that the details of some of the fuzzy-locations changed in Biopython 1.59,
in particular for BetweenPosition and WithinPosition you must now make it explicit
which integer position should be used for slicing etc. For a start position this
is generally the lower (left) value, while for an end position this would generally
be the higher (right) value.
If you print out a \verb|FeatureLocation| object, you can get a nice representation of the information:
%cont-doctest
\begin{verbatim}
>>> print my_location
[>5:(8^9)]
\end{verbatim}
We can access the fuzzy start and end positions using the start and end attributes of the location:
%cont-doctest
\begin{verbatim}
>>> my_location.start
AfterPosition(5)
>>> print my_location.start
>5
>>> my_location.end
BetweenPosition(9, left=8, right=9)
>>> print my_location.end
(8^9)
\end{verbatim}
If you don't want to deal with fuzzy positions and just want numbers,
they are actually subclasses of integers so should work like integers:
%cont-doctest
\begin{verbatim}
>>> int(my_location.start)
5
>>> int(my_location.end)
9
\end{verbatim}
For compatibility with older versions of Biopython you can ask for the
\verb|nofuzzy_start| and \verb|nofuzzy_end| attributes of the location
which are plain integers:
%cont-doctest
\begin{verbatim}
>>> my_location.nofuzzy_start
5
>>> my_location.nofuzzy_end
9
\end{verbatim}
Notice that this just gives you back the position attributes of the fuzzy locations.
Similarly, to make it easy to create a position without worrying about fuzzy positions, you can just pass in numbers to the \verb|FeaturePosition| constructors, and you'll get back out \verb|ExactPosition| objects:
%cont-doctest
\begin{verbatim}
>>> exact_location = SeqFeature.FeatureLocation(5, 9)
>>> print exact_location
[5:9]
>>> exact_location.start
ExactPosition(5)
>>> int(exact_location.start)
5
>>> exact_location.nofuzzy_start
5
\end{verbatim}
That is most of the nitty gritty about dealing with fuzzy positions in Biopython.
It has been designed so that dealing with fuzziness is not that much more
complicated than dealing with exact positions, and hopefully you find that true!
\subsubsection{Location testing}
You can use the Python keyword \verb|in| with a \verb|SeqFeature| or location
object to see if the base/residue for a parent coordinate is within the
feature/location or not.
For example, suppose you have a SNP of interest and you want to know which
features this SNP is within, and lets suppose this SNP is at index 4350
(Python counting!). Here is a simple brute force solution where we just
check all the features one by one in a loop:
%doctest ../Tests/GenBank
\begin{verbatim}
>>> from Bio import SeqIO
>>> my_snp = 4350
>>> record = SeqIO.read("NC_005816.gb", "genbank")
>>> for feature in record.features:
... if my_snp in feature:
... print feature.type, feature.qualifiers.get('db_xref')
...
source ['taxon:229193']
gene ['GeneID:2767712']
CDS ['GI:45478716', 'GeneID:2767712']
\end{verbatim}
Note that gene and CDS features from GenBank or EMBL files defined with joins
are the union of the exons -- they do not cover any introns.
%TODO - Add join example
\subsection{Sequence described by a feature or location}
A \verb|SeqFeature| or location object doesn't directly contain a sequence, instead the location (see Section~\ref{sec:locations}) describes how to get this from the parent sequence. For example consider a (short) gene sequence with location 5:18 on the reverse strand, which in GenBank/EMBL notation using 1-based counting would be \texttt{complement(6..18)}, like this:
%doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> example_parent = Seq("ACCGAGACGGCAAAGGCTAGCATAGGTATGAGACTTCCTTCCTGCCAGTGCTGAGGAACTGGGAGCCTAC")
>>> example_feature = SeqFeature(FeatureLocation(5, 18), type="gene", strand=-1)
\end{verbatim}
You could take the parent sequence, slice it to extract 5:18, and then take the reverse complement.
If you are using Biopython 1.59 or later, the feature location's start and end are integer like so this works:
%cont-doctest
\begin{verbatim}
>>> feature_seq = example_parent[example_feature.location.start:example_feature.location.end].reverse_complement()
>>> print feature_seq
AGCCTTTGCCGTC
\end{verbatim}
This is a simple example so this isn't too bad -- however once you have to deal with compound features (joins) this is rather messy. Instead, the \verb|SeqFeature| object has an \verb|extract| method to take care of all this:
%cont-doctest
\begin{verbatim}
>>> feature_seq = example_feature.extract(example_parent)
>>> print feature_seq
AGCCTTTGCCGTC
\end{verbatim}
The length of a \verb|SeqFeature| or location matches
that of the region of sequence it describes.
%cont-doctest
\begin{verbatim}
>>> print example_feature.extract(example_parent)
AGCCTTTGCCGTC
>>> print len(example_feature.extract(example_parent))
13
>>> print len(example_feature)
13
>>> print len(example_feature.location)
13
\end{verbatim}
For simple \verb|FeatureLocation| objects the length is just
the difference between the start and end positions. However,
for a \verb|CompoundLocation| the length is the sum of the
constituent regions.
\section{References}
Another common annotation related to a sequence is a reference to a journal or other published work dealing with the sequence. We have a fairly simple way of representing a Reference in Biopython -- we have a \verb|Bio.SeqFeature.Reference| class that stores the relevant information about a reference as attributes of an object.
The attributes include things that you would expect to see in a reference like \verb|journal|, \verb|title| and \verb|authors|. Additionally, it also can hold the \verb|medline_id| and \verb|pubmed_id| and a \verb|comment| about the reference. These are all accessed simply as attributes of the object.
A reference also has a \verb|location| object so that it can specify a particular location on the sequence that the reference refers to. For instance, you might have a journal that is dealing with a particular gene located on a BAC, and want to specify that it only refers to this position exactly. The \verb|location| is a potentially fuzzy location, as described in section~\ref{sec:locations}.
Any reference objects are stored as a list in the \verb|SeqRecord| object's \verb|annotations| dictionary under the key ``references''.
That's all there is too it. References are meant to be easy to deal with, and hopefully general enough to cover lots of usage cases.
\section{The format method}
\label{sec:SeqRecord-format}
The \verb|format()| method of the \verb|SeqRecord| class gives a string
containing your record formatted using one of the output file formats
supported by \verb|Bio.SeqIO|, such as FASTA:
\begin{verbatim}
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_protein
record = SeqRecord(Seq("MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD" \
+"GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK" \
+"NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM" \
+"SSAC", generic_protein),
id="gi|14150838|gb|AAK54648.1|AF376133_1",
description="chalcone synthase [Cucumis sativus]")
print record.format("fasta")
\end{verbatim}
\noindent which should give:
\begin{verbatim}
>gi|14150838|gb|AAK54648.1|AF376133_1 chalcone synthase [Cucumis sativus]
MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD
GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK
NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM
SSAC
\end{verbatim}
This \verb|format| method takes a single mandatory argument, a lower case string which is
supported by \verb|Bio.SeqIO| as an output format (see Chapter~\ref{chapter:Bio.SeqIO}).
However, some of the file formats \verb|Bio.SeqIO| can write to \emph{require} more than
one record (typically the case for multiple sequence alignment formats), and thus won't
work via this \verb|format()| method. See also Section~\ref{sec:Bio.SeqIO-and-StringIO}.
\section{Slicing a SeqRecord}
\label{sec:SeqRecord-slicing}
You can slice a \verb|SeqRecord|, to give you a new \verb|SeqRecord| covering just
part of the sequence. What is important
here is that any per-letter annotations are also sliced, and any features which fall
completely within the new sequence are preserved (with their locations adjusted).
For example, taking the same GenBank file used earlier:
%doctest ../Tests/GenBank
\begin{verbatim}
>>> from Bio import SeqIO
>>> record = SeqIO.read("NC_005816.gb", "genbank")
\end{verbatim}
%TODO - support line wrapping in doctest
\begin{verbatim}
>>> record
SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
dbxrefs=['Project:10638'])
\end{verbatim}
%cont-doctest
\begin{verbatim}
>>> len(record)
9609
>>> len(record.features)
41
\end{verbatim}
For this example we're going to focus in on the \verb|pim| gene, \verb|YP_pPCP05|.
If you have a look at the GenBank file directly you'll find this gene/CDS has
location string \texttt{4343..4780}, or in Python counting \texttt{4342:4780}.
From looking at the file you can work out that these are the twelfth and
thirteenth entries in the file, so in Python zero-based counting they are
entries $11$ and $12$ in the \texttt{features} list:
%cont-doctest
\begin{verbatim}
>>> print record.features[20]
type: gene
location: [4342:4780](+)
qualifiers:
Key: db_xref, Value: ['GeneID:2767712']
Key: gene, Value: ['pim']
Key: locus_tag, Value: ['YP_pPCP05']
<BLANKLINE>
\end{verbatim}
%This one is truncated so can't use for doctest
\begin{verbatim}
>>> print record.features[21]
type: CDS
location: [4342:4780](+)
qualifiers:
Key: codon_start, Value: ['1']
Key: db_xref, Value: ['GI:45478716', 'GeneID:2767712']
Key: gene, Value: ['pim']
Key: locus_tag, Value: ['YP_pPCP05']
Key: note, Value: ['similar to many previously sequenced pesticin immunity ...']
Key: product, Value: ['pesticin immunity protein']
Key: protein_id, Value: ['NP_995571.1']
Key: transl_table, Value: ['11']
Key: translation, Value: ['MGGGMISKLFCLALIFLSSSGLAEKNTYTAKDILQNLELNTFGNSLSH...']
\end{verbatim}
Let's slice this parent record from 4300 to 4800 (enough to include the \verb|pim|
gene/CDS), and see how many features we get:
%cont-doctest
\begin{verbatim}
>>> sub_record = record[4300:4800]
\end{verbatim}
%TODO - Line wrapping for doctest?
\begin{verbatim}
>>> sub_record
SeqRecord(seq=Seq('ATAAATAGATTATTCCAAATAATTTATTTATGTAAGAACAGGATGGGAGGGGGA...TTA',
IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
dbxrefs=[])
\end{verbatim}
%cont-doctest
\begin{verbatim}
>>> len(sub_record)
500
>>> len(sub_record.features)
2
\end{verbatim}
Our sub-record just has two features, the gene and CDS entries for \verb|YP_pPCP05|:
%cont-doctest
\begin{verbatim}
>>> print sub_record.features[0]
type: gene
location: [42:480](+)
qualifiers:
Key: db_xref, Value: ['GeneID:2767712']
Key: gene, Value: ['pim']
Key: locus_tag, Value: ['YP_pPCP05']
<BLANKLINE>
\end{verbatim}
\begin{verbatim}
>>> print sub_record.features[20]
type: CDS
location: [42:480](+)
qualifiers:
Key: codon_start, Value: ['1']
Key: db_xref, Value: ['GI:45478716', 'GeneID:2767712']
Key: gene, Value: ['pim']
Key: locus_tag, Value: ['YP_pPCP05']
Key: note, Value: ['similar to many previously sequenced pesticin immunity ...']
Key: product, Value: ['pesticin immunity protein']
Key: protein_id, Value: ['NP_995571.1']
Key: transl_table, Value: ['11']
Key: translation, Value: ['MGGGMISKLFCLALIFLSSSGLAEKNTYTAKDILQNLELNTFGNSLSH...']
\end{verbatim}
\noindent Notice that their locations have been adjusted to reflect the new parent sequence!
While Biopython has done something sensible and hopefully intuitive with the features
(and any per-letter annotation), for the other annotation it is impossible to know if
this still applies to the sub-sequence or not. To avoid guessing, the \texttt{annotations}
and \texttt{dbxrefs} are omitted from the sub-record, and it is up to you to transfer
any relevant information as appropriate.
%cont-doctest
\begin{verbatim}
>>> sub_record.annotations
{}
>>> sub_record.dbxrefs
[]
\end{verbatim}
The same point could be made about the record \texttt{id}, \texttt{name}
and \texttt{description}, but for practicality these are preserved:
%cont-doctest
\begin{verbatim}
>>> sub_record.id
'NC_005816.1'
>>> sub_record.name
'NC_005816'
>>> sub_record.description
'Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.'
\end{verbatim}
\noindent This illustrates the problem nicely though, our new sub-record is
\emph{not} the complete sequence of the plasmid, so the description is wrong!
Let's fix this and then view the sub-record as a reduced GenBank file using
the \texttt{format} method described above in Section~\ref{sec:SeqRecord-format}:
\begin{verbatim}
>>> sub_record.description = "Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, partial."
>>> print sub_record.format("genbank")
...
\end{verbatim}
See Sections~\ref{sec:FASTQ-slicing-off-primer}
and~\ref{sec:FASTQ-slicing-off-adaptor} for some FASTQ examples where the
per-letter annotations (the read quality scores) are also sliced.
\section{Adding SeqRecord objects}
\label{sec:SeqRecord-addition}
You can add \verb|SeqRecord| objects together, giving a new \verb|SeqRecord|.
What is important here is that any common
per-letter annotations are also added, all the features are preserved (with their
locations adjusted), and any other common annotation is also kept (like the id, name
and description).
For an example with per-letter annotation, we'll use the first record in a
FASTQ file. Chapter~\ref{chapter:Bio.SeqIO} will explain the \verb|SeqIO| functions:
%doctest ../Tests/Quality
\begin{verbatim}
>>> from Bio import SeqIO
>>> record = SeqIO.parse("example.fastq", "fastq").next()
>>> len(record)
25
>>> print record.seq
CCCTTCTTGTCTTCAGCGTTTCTCC
\end{verbatim}
%TODO - doctest wrapping
\begin{verbatim}
>>> print record.letter_annotations["phred_quality"]
[26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26,
26, 26, 26, 23, 23]
\end{verbatim}
\noindent Let's suppose this was Roche 454 data, and that from other information
you think the \texttt{TTT} should be only \texttt{TT}. We can make a new edited
record by first slicing the \verb|SeqRecord| before and after the ``extra''
third \texttt{T}:
%cont-doctest
\begin{verbatim}
>>> left = record[:20]
>>> print left.seq
CCCTTCTTGTCTTCAGCGTT
>>> print left.letter_annotations["phred_quality"]
[26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26]
>>> right = record[21:]
>>> print right.seq
CTCC
>>> print right.letter_annotations["phred_quality"]
[26, 26, 23, 23]
\end{verbatim}
\noindent Now add the two parts together:
%cont-doctest
\begin{verbatim}
>>> edited = left + right
>>> len(edited)
24
>>> print edited.seq
CCCTTCTTGTCTTCAGCGTTCTCC
\end{verbatim}
\begin{verbatim}
>>> print edited.letter_annotations["phred_quality"]
[26, 26, 18, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 22, 26, 26, 26, 26,
26, 26, 23, 23]
\end{verbatim}
\noindent Easy and intuitive? We hope so! You can make this shorter with just:
%cont-doctest
\begin{verbatim}
>>> edited = record[:20] + record[21:]
\end{verbatim}
Now, for an example with features, we'll use a GenBank file.
Suppose you have a circular genome:
%doctest ../Tests/GenBank
\begin{verbatim}
>>> from Bio import SeqIO
>>> record = SeqIO.read("NC_005816.gb", "genbank")
\end{verbatim}
%TODO - doctest wrapping
\begin{verbatim}
>>> record
SeqRecord(seq=Seq('TGTAACGAACGGTGCAATAGTGATCCACACCCAACGCCTGAAATCAGATCCAGG...CTG',
IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
dbxrefs=['Project:10638'])
\end{verbatim}
%cont-doctest
\begin{verbatim}
>>> len(record)
9609
>>> len(record.features)
41
>>> record.dbxrefs
['Project:58037']
\end{verbatim}
%TODO - doctest wrapping
\begin{verbatim}
>>> record.annotations.keys()
['comment', 'sequence_version', 'source', 'taxonomy', 'keywords', 'references',
'accessions', 'data_file_division', 'date', 'organism', 'gi']
\end{verbatim}
You can shift the origin like this:
%cont-doctest
\begin{verbatim}
>>> shifted = record[2000:] + record[:2000]
\end{verbatim}
%TODO - doctest wrapping
\begin{verbatim}
>>> shifted
SeqRecord(seq=Seq('GATACGCAGTCATATTTTTTACACAATTCTCTAATCCCGACAAGGTCGTAGGTC...GGA',
IUPACAmbiguousDNA()), id='NC_005816.1', name='NC_005816',
description='Yersinia pestis biovar Microtus str. 91001 plasmid pPCP1, complete sequence.',
dbxrefs=[])
\end{verbatim}
%cont-doctest
\begin{verbatim}
>>> len(shifted)
9609
\end{verbatim}
Note that this isn't perfect in that some annotation like the database cross references
and one of the features (the source feature) have been lost:
%cont-doctest
\begin{verbatim}
>>> len(shifted.features)
40
>>> shifted.dbxrefs
[]
>>> shifted.annotations.keys()
[]
\end{verbatim}
This is because the \verb|SeqRecord| slicing step is cautious in what annotation
it preserves (erroneously propagating annotation can cause major problems). If
you want to keep the database cross references or the annotations dictionary,
this must be done explicitly:
\begin{verbatim}
>>> shifted.dbxrefs = record.dbxrefs[:]
>>> shifted.annotations = record.annotations.copy()
>>> shifted.dbxrefs
['Project:10638']
>>> shifted.annotations.keys()
['comment', 'sequence_version', 'source', 'taxonomy', 'keywords', 'references',
'accessions', 'data_file_division', 'date', 'organism', 'gi']
\end{verbatim}
Also note that in an example like this, you should probably change the record
identifiers since the NCBI references refer to the \emph{original} unmodified
sequence.
\section{Reverse-complementing SeqRecord objects}
\label{sec:SeqRecord-reverse-complement}
One of the new features in Biopython 1.57 was the \verb|SeqRecord| object's
\verb|reverse_complement| method. This tries to balance easy of use with worries
about what to do with the annotation in the reverse complemented record.
For the sequence, this uses the Seq object's reverse complement method. Any
features are transferred with the location and strand recalculated. Likewise
any per-letter-annotation is also copied but reversed (which makes sense for
typical examples like quality scores). However, transfer of most annotation
is problematical.
For instance, if the record ID was an accession, that accession should not really
apply to the reverse complemented sequence, and transferring the identifier by
default could easily cause subtle data corruption in downstream analysis.
Therefore by default, the \verb|SeqRecord|'s id, name, description, annotations
and database cross references are all \emph{not} transferred by default.
The \verb|SeqRecord| object's \verb|reverse_complement| method takes a number
of optional arguments corresponding to properties of the record. Setting these
arguments to \verb|True| means copy the old values, while \verb|False| means
drop the old values and use the default value. You can alternatively provide
the new desired value instead.
Consider this example record:
%doctest ../Tests/GenBank
\begin{verbatim}
>>> from Bio import SeqIO
>>> record = SeqIO.read("NC_005816.gb", "genbank")
>>> print record.id, len(record), len(record.features), len(record.dbxrefs), len(record.annotations)
NC_005816.1 9609 41 1 11
\end{verbatim}
Here we take the reverse complement and specify a new identifier -- but notice
how most of the annotation is dropped (but not the features):
%cont-doctest
\begin{verbatim}
>>> rc = record.reverse_complement(id="TESTING")
>>> print rc.id, len(rc), len(rc.features), len(rc.dbxrefs), len(rc.annotations)
TESTING 9609 41 0 0
\end{verbatim}
\chapter{Sequence Input/Output}
\label{chapter:Bio.SeqIO}
In this chapter we'll discuss in more detail the \verb|Bio.SeqIO| module, which was briefly introduced in Chapter~\ref{chapter:quick-start} and also used in Chapter~\ref{chapter:SeqRecord}. This aims to provide a simple interface for working with assorted sequence file formats in a uniform way.
See also the \verb|Bio.SeqIO| wiki page (\url{http://biopython.org/wiki/SeqIO}), and the built in documentation (also \href{http://biopython.org/DIST/docs/api/Bio.SeqIO-module.html}{online}):
\begin{verbatim}
>>> from Bio import SeqIO
>>> help(SeqIO)
...
\end{verbatim}
The ``catch'' is that you have to work with \verb|SeqRecord| objects (see Chapter~\ref{chapter:SeqRecord}), which contain a \verb|Seq| object (see Chapter~\ref{chapter:Bio.Seq}) plus annotation like an identifier and description.
\section{Parsing or Reading Sequences}
\label{sec:Bio.SeqIO-input}
The workhorse function \verb|Bio.SeqIO.parse()| is used to read in sequence data as SeqRecord objects. This function expects two arguments:
\begin{enumerate}
\item The first argument is a {\it handle} to read the data from, or a filename. A handle is typically a file opened for reading, but could be the output from a command line program, or data downloaded from the internet (see Section~\ref{sec:SeqIO_Online}). See Section~\ref{sec:appendix-handles} for more about handles.
\item The second argument is a lower case string specifying sequence format -- we don't try and guess the file format for you! See \url{http://biopython.org/wiki/SeqIO} for a full listing of supported formats.
\end{enumerate}
\noindent There is an optional argument \verb|alphabet| to specify the alphabet to be used. This is useful for file formats like FASTA where otherwise \verb|Bio.SeqIO| will default to a generic alphabet.
The \verb|Bio.SeqIO.parse()| function returns an {\it iterator} which gives \verb|SeqRecord| objects. Iterators are typically used in a for loop as shown below.
Sometimes you'll find yourself dealing with files which contain only a single record. For this situation use the function \verb|Bio.SeqIO.read()| which takes the same arguments. Provided there is one and only one record in the file, this is returned as a \verb|SeqRecord| object. Otherwise an exception is raised.
\subsection{Reading Sequence Files}
In general \verb|Bio.SeqIO.parse()| is used to read in sequence files as \verb|SeqRecord| objects, and is typically used with a for loop like this:
\begin{verbatim}
from Bio import SeqIO
for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
print seq_record.id
print repr(seq_record.seq)
print len(seq_record)
\end{verbatim}
The above example is repeated from the introduction in Section~\ref{sec:sequence-parsing}, and will load the orchid DNA sequences in the FASTA format file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{ls\_orchid.fasta}. If instead you wanted to load a GenBank format file like \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{ls\_orchid.gbk} then all you need to do is change the filename and the format string:
\begin{verbatim}
from Bio import SeqIO
for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"):
print seq_record.id
print seq_record.seq
print len(seq_record)
\end{verbatim}
Similarly, if you wanted to read in a file in another file format, then assuming \verb|Bio.SeqIO.parse()| supports it you would just need to change the format string as appropriate, for example ``swiss'' for SwissProt files or ``embl'' for EMBL text files. There is a full listing on the wiki page (\url{http://biopython.org/wiki/SeqIO}) and in the built in documentation (also \href{http://biopython.org/DIST/docs/api/Bio.SeqIO-module.html}{online}).
Another very common way to use a Python iterator is within a list comprehension (or
a generator expression). For example, if all you wanted to extract from the file was
a list of the record identifiers we can easily do this with the following list comprehension:
\begin{verbatim}
>>> from Bio import SeqIO
>>> identifiers = [seq_record.id for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank")]
>>> identifiers
['Z78533.1', 'Z78532.1', 'Z78531.1', 'Z78530.1', 'Z78529.1', 'Z78527.1', ..., 'Z78439.1']
\end{verbatim}
\noindent There are more examples using \verb|SeqIO.parse()| in a list
comprehension like this in Section~\ref{seq:sequence-parsing-plus-pylab}
(e.g. for plotting sequence lengths or GC\%).
\subsection{Iterating over the records in a sequence file}
In the above examples, we have usually used a for loop to iterate over all the records one by one. You can use the for loop with all sorts of Python objects (including lists, tuples and strings) which support the iteration interface.
The object returned by \verb|Bio.SeqIO| is actually an iterator which returns \verb|SeqRecord| objects. You get to see each record in turn, but once and only once. The plus point is that an iterator can save you memory when dealing with large files.
Instead of using a for loop, can also use the \verb|.next()| method of an iterator to step through the entries, like this:
\begin{verbatim}
from Bio import SeqIO
record_iterator = SeqIO.parse("ls_orchid.fasta", "fasta")
first_record = record_iterator.next()
print first_record.id
print first_record.description
second_record = record_iterator.next()
print second_record.id
print second_record.description
\end{verbatim}
Note that if you try and use \verb|.next()| and there are no more results, you'll get the special \verb|StopIteration| exception.
One special case to consider is when your sequence files have multiple records, but you only want the first one. In this situation the following code is very concise:
\begin{verbatim}
from Bio import SeqIO
first_record = SeqIO.parse("ls_orchid.gbk", "genbank").next()
\end{verbatim}
A word of warning here -- using the \verb|.next()| method like this will silently ignore any additional records in the file.
If your files have {\it one and only one} record, like some of the online examples later in this chapter, or a GenBank file for a single chromosome, then use the new \verb|Bio.SeqIO.read()| function instead.
This will check there are no extra unexpected records present.
\subsection{Getting a list of the records in a sequence file}
In the previous section we talked about the fact that \verb|Bio.SeqIO.parse()| gives you a \verb|SeqRecord| iterator, and that you get the records one by one. Very often you need to be able to access the records in any order. The Python \verb|list| data type is perfect for this, and we can turn the record iterator into a list of \verb|SeqRecord| objects using the built-in Python function \verb|list()| like so:
\begin{verbatim}
from Bio import SeqIO
records = list(SeqIO.parse("ls_orchid.gbk", "genbank"))
print "Found %i records" % len(records)
print "The last record"
last_record = records[-1] #using Python's list tricks
print last_record.id
print repr(last_record.seq)
print len(last_record)
print "The first record"
first_record = records[0] #remember, Python counts from zero
print first_record.id
print repr(first_record.seq)
print len(first_record)
\end{verbatim}
\noindent Giving:
\begin{verbatim}
Found 94 records
The last record
Z78439.1
Seq('CATTGTTGAGATCACATAATAATTGATCGAGTTAATCTGGAGGATCTGTTTACT...GCC', IUPACAmbiguousDNA())
592
The first record
Z78533.1
Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
740
\end{verbatim}
You can of course still use a for loop with a list of \verb|SeqRecord| objects. Using a list is much more flexible than an iterator (for example, you can determine the number of records from the length of the list), but does need more memory because it will hold all the records in memory at once.
\subsection{Extracting data}
The \verb|SeqRecord| object and its annotation structures are described more fully in
Chapter~\ref{chapter:SeqRecord}. As an example of how annotations are stored, we'll look at the output from parsing the first record in the GenBank file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{ls\_orchid.gbk}.
\begin{verbatim}
from Bio import SeqIO
record_iterator = SeqIO.parse("ls_orchid.gbk", "genbank")
first_record = record_iterator.next()
print first_record
\end{verbatim}
\noindent That should give something like this:
\begin{verbatim}
ID: Z78533.1
Name: Z78533
Description: C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA.
Number of features: 5
/sequence_version=1
/source=Cypripedium irapeanum
/taxonomy=['Eukaryota', 'Viridiplantae', 'Streptophyta', ..., 'Cypripedium']
/keywords=['5.8S ribosomal RNA', '5.8S rRNA gene', ..., 'ITS1', 'ITS2']
/references=[...]
/accessions=['Z78533']
/data_file_division=PLN
/date=30-NOV-2006
/organism=Cypripedium irapeanum
/gi=2765658
Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGG...CGC', IUPACAmbiguousDNA())
\end{verbatim}
This gives a human readable summary of most of the annotation data for the \verb|SeqRecord|.
For this example we're going to use the \verb|.annotations| attribute which is just a Python dictionary.
The contents of this annotations dictionary were shown when we printed the record above.
You can also print them out directly:
\begin{verbatim}
print first_record.annotations
\end{verbatim}
\noindent Like any Python dictionary, you can easily get a list of the keys:
\begin{verbatim}
print first_record.annotations.keys()
\end{verbatim}
\noindent or values:
\begin{verbatim}
print first_record.annotations.values()
\end{verbatim}
In general, the annotation values are strings, or lists of strings. One special case is any references in the file get stored as reference objects.
Suppose you wanted to extract a list of the species from the \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{ls\_orchid.gbk} GenBank file. The information we want, \emph{Cypripedium irapeanum}, is held in the annotations dictionary under `source' and `organism', which we can access like this:
\begin{verbatim}
>>> print first_record.annotations["source"]
Cypripedium irapeanum
\end{verbatim}
\noindent or:
\begin{verbatim}
>>> print first_record.annotations["organism"]
Cypripedium irapeanum
\end{verbatim}
In general, `organism' is used for the scientific name (in Latin, e.g. \textit{Arabidopsis thaliana}),
while `source' will often be the common name (e.g. thale cress). In this example, as is often the case,
the two fields are identical.
Now let's go through all the records, building up a list of the species each orchid sequence is from:
\begin{verbatim}
from Bio import SeqIO
all_species = []
for seq_record in SeqIO.parse("ls_orchid.gbk", "genbank"):
all_species.append(seq_record.annotations["organism"])
print all_species
\end{verbatim}
Another way of writing this code is to use a list comprehension:
\begin{verbatim}
from Bio import SeqIO
all_species = [seq_record.annotations["organism"] for seq_record in \
SeqIO.parse("ls_orchid.gbk", "genbank")]
print all_species
\end{verbatim}
\noindent In either case, the result is:
% Try and keep this example output line short enough to fit on one page of PDF output:
\begin{verbatim}
['Cypripedium irapeanum', 'Cypripedium californicum', ..., 'Paphiopedilum barbatum']
\end{verbatim}
Great. That was pretty easy because GenBank files are annotated in a standardised way.
Now, let's suppose you wanted to extract a list of the species from a FASTA file, rather than the GenBank file. The bad news is you will have to write some code to extract the data you want from the record's description line - if the information is in the file in the first place! Our example FASTA format file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{ls\_orchid.fasta} starts like this:
\begin{verbatim}
>gi|2765658|emb|Z78533.1|CIZ78533 C.irapeanum 5.8S rRNA gene and ITS1 and ITS2 DNA
CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGATGAGACCGTGGAATAAACGATCGAGTG
AATCCGGAGGACCGGTGTACTCAGCTCACCGGGGGCATTGCTCCCGTGGTGACCCTGATTTGTTGTTGGG
...
\end{verbatim}
You can check by hand, but for every record the species name is in the description line as the second word. This means if we break up each record's \verb|.description| at the spaces, then the species is there as field number one (field zero is the record identifier). That means we can do this:
\begin{verbatim}
from Bio import SeqIO
all_species = []
for seq_record in SeqIO.parse("ls_orchid.fasta", "fasta"):
all_species.append(seq_record.description.split()[1])
print all_species
\end{verbatim}
\noindent This gives:
\begin{verbatim}
['C.irapeanum', 'C.californicum', 'C.fasciculatum', 'C.margaritaceum', ..., 'P.barbatum']
\end{verbatim}
The concise alternative using list comprehensions would be:
\begin{verbatim}
from Bio import SeqIO
all_species == [seq_record.description.split()[1] for seq_record in \
SeqIO.parse("ls_orchid.fasta", "fasta")]
print all_species
\end{verbatim}
In general, extracting information from the FASTA description line is not very nice.
If you can get your sequences in a well annotated file format like GenBank or EMBL,
then this sort of annotation information is much easier to deal with.
\section{Parsing sequences from compressed files}
\label{sec:SeqIO_compressed}
In the previous section, we looked at parsing sequence data from a file.
Instead of using a filename, you can give \verb|Bio.SeqIO| a handle
(see Section~\ref{sec:appendix-handles}), and in this section
we'll use handles to parse sequence from compressed files.
As you'll have seen above, we can use \verb|Bio.SeqIO.read()| or
\verb|Bio.SeqIO.parse()| with a filename - for instance this quick
example calculates the total length of the sequences in a multiple
record GenBank file using a generator expression:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> print sum(len(r) for r in SeqIO.parse("ls_orchid.gbk", "gb"))
67518
\end{verbatim}
\noindent
Here we use a file handle instead, using the \verb|with| statement
(Python 2.5 or later) to close the handle automatically:
%This doctest won't work on Python 2.5, even with the __future__ import. Odd.
\begin{verbatim}
>>> from __future__ import with_statement #Needed on Python 2.5
>>> from Bio import SeqIO
>>> with open("ls_orchid.gbk") as handle:
... print sum(len(r) for r in SeqIO.parse(handle, "gb"))
67518
\end{verbatim}
\noindent
Or, the old fashioned way where you manually close the handle:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> handle = open("ls_orchid.gbk")
>>> print sum(len(r) for r in SeqIO.parse(handle, "gb"))
67518
>>> handle.close()
\end{verbatim}
Now, suppose we have a gzip compressed file instead? These are very
commonly used on Linux. We can use Python's \verb|gzip| module to open
the compressed file for reading - which gives us a handle object:
%This doctest fails on Python 3, http://bugs.python.org/issue13989
\begin{verbatim}
>>> import gzip
>>> from Bio import SeqIO
>>> handle = gzip.open("ls_orchid.gbk.gz", "r")
>>> print sum(len(r) for r in SeqIO.parse(handle, "gb"))
67518
>>> handle.close()
\end{verbatim}
Similarly if we had a bzip2 compressed file (sadly the function name isn't
quite as consistent):
%This doctest fails on Python 3
\begin{verbatim}
>>> import bz2
>>> from Bio import SeqIO
>>> handle = bz2.BZ2File("ls_orchid.gbk.bz2", "r")
>>> print sum(len(r) for r in SeqIO.parse(handle, "gb"))
67518
>>> handle.close()
\end{verbatim}
\noindent
If you are using Python 2.7 or later, the \verb|with|-version works for
gzip and bz2 as well. Unfortunately this is broken on older versions of
Python (\href{http://bugs.python.org/issue3860}{Issue 3860}) and you'd
get an \verb|AttributeError| about \verb|__exit__| being missing.
There is a gzip (GNU Zip) variant called BGZF (Blocked GNU Zip Format),
which can be treated like an ordinary gzip file for reading, but has
advantages for random access later which we'll talk about later in
Section~\ref{sec:SeqIO-index-bgzf}.
\section{Parsing sequences from the net}
\label{sec:SeqIO_Online}
In the previous sections, we looked at parsing sequence data from a file
(using a filename or handle), and from compressed files (using a handle).
Here we'll use \verb|Bio.SeqIO| with another type of handle, a network
connection, to download and parse sequences from the internet.
Note that just because you \emph{can} download sequence data and parse it into
a \verb|SeqRecord| object in one go doesn't mean this is a good idea.
In general, you should probably download sequences \emph{once} and save them to
a file for reuse.
\subsection{Parsing GenBank records from the net}
\label{sec:SeqIO_GenBank_Online}
Section~\ref{sec:efetch} talks about the Entrez EFetch interface in more detail,
but for now let's just connect to the NCBI and get a few \textit{Opuntia} (prickly-pear)
sequences from GenBank using their GI numbers.
First of all, let's fetch just one record. If you don't care about the
annotations and features downloading a FASTA file is a good choice as these
are compact. Now remember, when you expect the handle to contain one and
only one record, use the \verb|Bio.SeqIO.read()| function:
\begin{verbatim}
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "[email protected]"
handle = Entrez.efetch(db="nucleotide", rettype="fasta", retmode="text", id="6273291")
seq_record = SeqIO.read(handle, "fasta")
handle.close()
print "%s with %i features" % (seq_record.id, len(seq_record.features))
\end{verbatim}
\noindent Expected output:
\begin{verbatim}
gi|6273291|gb|AF191665.1|AF191665 with 0 features
\end{verbatim}
The NCBI will also let you ask for the file in other formats, in particular as
a GenBank file. Until Easter 2009, the Entrez EFetch API let you use ``genbank''
as the return type, however the NCBI now insist on using the official
return types of ``gb'' (or ``gp'' for proteins) as described on
\href{http://www.ncbi.nlm.nih.gov/entrez/query/static/efetchseq_help.html}
{EFetch for Sequence and other Molecular Biology Databases}.
As a result, in Biopython 1.50 onwards, we support ``gb'' as an
alias for ``genbank'' in \verb|Bio.SeqIO|.
\begin{verbatim}
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "[email protected]"
handle = Entrez.efetch(db="nucleotide", rettype="gb", retmode="text", id="6273291")
seq_record = SeqIO.read(handle, "gb") #using "gb" as an alias for "genbank"
handle.close()
print "%s with %i features" % (seq_record.id, len(seq_record.features))
\end{verbatim}
\noindent The expected output of this example is:
\begin{verbatim}
AF191665.1 with 3 features
\end{verbatim}
\noindent Notice this time we have three features.
Now let's fetch several records. This time the handle contains multiple records,
so we must use the \verb|Bio.SeqIO.parse()| function:
\begin{verbatim}
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "[email protected]"
handle = Entrez.efetch(db="nucleotide", rettype="gb", retmode="text", \
id="6273291,6273290,6273289")
for seq_record in SeqIO.parse(handle, "gb"):
print seq_record.id, seq_record.description[:50] + "..."
print "Sequence length %i," % len(seq_record),
print "%i features," % len(seq_record.features),
print "from: %s" % seq_record.annotations["source"]
handle.close()
\end{verbatim}
\noindent That should give the following output:
\begin{verbatim}
AF191665.1 Opuntia marenae rpl16 gene; chloroplast gene for c...
Sequence length 902, 3 features, from: chloroplast Opuntia marenae
AF191664.1 Opuntia clavata rpl16 gene; chloroplast gene for c...
Sequence length 899, 3 features, from: chloroplast Grusonia clavata
AF191663.1 Opuntia bradtiana rpl16 gene; chloroplast gene for...
Sequence length 899, 3 features, from: chloroplast Opuntia bradtianaa
\end{verbatim}
See Chapter~\ref{chapter:entrez} for more about the \verb|Bio.Entrez| module, and make sure to read about the NCBI guidelines for using Entrez (Section~\ref{sec:entrez-guidelines}).
\subsection{Parsing SwissProt sequences from the net}
\label{sec:SeqIO_ExPASy_and_SwissProt}
Now let's use a handle to download a SwissProt file from ExPASy,
something covered in more depth in Chapter~\ref{chapter:swiss_prot}.
As mentioned above, when you expect the handle to contain one and only one record,
use the \verb|Bio.SeqIO.read()| function:
\begin{verbatim}
from Bio import ExPASy
from Bio import SeqIO
handle = ExPASy.get_sprot_raw("O23729")
seq_record = SeqIO.read(handle, "swiss")
handle.close()
print seq_record.id
print seq_record.name
print seq_record.description
print repr(seq_record.seq)
print "Length %i" % len(seq_record)
print seq_record.annotations["keywords"]
\end{verbatim}
\noindent Assuming your network connection is OK, you should get back:
\begin{verbatim}
O23729
CHS3_BROFI
RecName: Full=Chalcone synthase 3; EC=2.3.1.74; AltName: Full=Naringenin-chalcone synthase 3;
Seq('MAPAMEEIRQAQRAEGPAAVLAIGTSTPPNALYQADYPDYYFRITKSEHLTELK...GAE', ProteinAlphabet())
Length 394
['Acyltransferase', 'Flavonoid biosynthesis', 'Transferase']
\end{verbatim}
\section{Sequence files as Dictionaries}
We're now going to introduce three related functions in the \verb|Bio.SeqIO|
module which allow dictionary like random access to a multi-sequence file.
There is a trade off here between flexibility and memory usage. In summary:
\begin{itemize}
\item \verb|Bio.SeqIO.to_dict()| is the most flexible but also the most
memory demanding option (see Section~\ref{SeqIO:to_dict}). This is basically
a helper function to build a normal Python \verb|dictionary| with each entry
held as a \verb|SeqRecord| object in memory, allowing you to modify the
records.
\item \verb|Bio.SeqIO.index()| is a useful middle ground, acting like a
read only dictionary and parsing sequences into \verb|SeqRecord| objects
on demand (see Section~\ref{sec:SeqIO-index}).
\item \verb|Bio.SeqIO.index_db()| also acts like a read only dictionary
but stores the identifiers and file offsets in a file on disk (as an
SQLite3 database), meaning it has very low memory requirements (see
Section~\ref{sec:SeqIO-index-db}), but will be a little bit slower.
\end{itemize}
See the discussion for an broad overview
(Section~\ref{sec:SeqIO-indexing-discussion}).
\subsection{Sequence files as Dictionaries -- In memory}
\label{SeqIO:to_dict}
The next thing that we'll do with our ubiquitous orchid files is to show how
to index them and access them like a database using the Python \verb|dictionary|
data type (like a hash in Perl). This is very useful for moderately large files
where you only need to access certain elements of the file, and makes for a nice
quick 'n dirty database. For dealing with larger files where memory becomes a
problem, see Section~\ref{sec:SeqIO-index} below.
You can use the function \verb|Bio.SeqIO.to_dict()| to make a SeqRecord dictionary
(in memory). By default this will use each record's identifier (i.e. the \verb|.id|
attribute) as the key. Let's try this using our GenBank file:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.gbk", "genbank"))
\end{verbatim}
There is just one required argument for \verb|Bio.SeqIO.to_dict()|, a list or
generator giving \verb|SeqRecord| objects. Here we have just used the output
from the \verb|SeqIO.parse| function. As the name suggests, this returns a
Python dictionary.
Since this variable \verb|orchid_dict| is an ordinary Python dictionary, we can look at all of the keys we have available:
%cont-doctest
\begin{verbatim}
>>> len(orchid_dict)
94
\end{verbatim}
%Can't use following for doctest due to abbreviation
\begin{verbatim}
>>> print orchid_dict.keys()
['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
\end{verbatim}
If you really want to, you can even look at all the records at once:
\begin{verbatim}
>>> orchid_dict.values() #lots of output!
...
\end{verbatim}
We can access a single \verb|SeqRecord| object via the keys and manipulate the object as normal:
%cont-doctest
\begin{verbatim}
>>> seq_record = orchid_dict["Z78475.1"]
>>> print seq_record.description
P.supardii 5.8S rRNA gene and ITS1 and ITS2 DNA.
>>> print repr(seq_record.seq)
Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGTTGAGATCACAT...GGT', IUPACAmbiguousDNA())
\end{verbatim}
So, it is very easy to create an in memory ``database'' of our GenBank records. Next we'll try this for the FASTA file instead.
Note that those of you with prior Python experience should all be able to construct a dictionary like this ``by hand''. However, typical dictionary construction methods will not deal with the case of repeated keys very nicely. Using the \verb|Bio.SeqIO.to_dict()| will explicitly check for duplicate keys, and raise an exception if any are found.
\subsubsection{Specifying the dictionary keys}
\label{seq:seqio-todict-functionkey}
Using the same code as above, but for the FASTA file instead:
\begin{verbatim}
from Bio import SeqIO
orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.fasta", "fasta"))
print orchid_dict.keys()
\end{verbatim}
\noindent This time the keys are:
\begin{verbatim}
['gi|2765596|emb|Z78471.1|PDZ78471', 'gi|2765646|emb|Z78521.1|CCZ78521', ...
..., 'gi|2765613|emb|Z78488.1|PTZ78488', 'gi|2765583|emb|Z78458.1|PHZ78458']
\end{verbatim}
You should recognise these strings from when we parsed the FASTA file earlier in Section~\ref{sec:fasta-parsing}. Suppose you would rather have something else as the keys - like the accession numbers. This brings us nicely to \verb|SeqIO.to_dict()|'s optional argument \verb|key_function|, which lets you define what to use as the dictionary key for your records.
First you must write your own function to return the key you want (as a string) when given a \verb|SeqRecord| object. In general, the details of function will depend on the sort of input records you are dealing with. But for our orchids, we can just split up the record's identifier using the ``pipe'' character (the vertical line) and return the fourth entry (field three):
\begin{verbatim}
def get_accession(record):
""""Given a SeqRecord, return the accession number as a string.
e.g. "gi|2765613|emb|Z78488.1|PTZ78488" -> "Z78488.1"
"""
parts = record.id.split("|")
assert len(parts) == 5 and parts[0] == "gi" and parts[2] == "emb"
return parts[3]
\end{verbatim}
\noindent Then we can give this function to the \verb|SeqIO.to_dict()| function to use in building the dictionary:
\begin{verbatim}
from Bio import SeqIO
orchid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.fasta", "fasta"), key_function=get_accession)
print orchid_dict.keys()
\end{verbatim}
\noindent Finally, as desired, the new dictionary keys:
\begin{verbatim}
>>> print orchid_dict.keys()
['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
\end{verbatim}
\noindent Not too complicated, I hope!
\subsubsection{Indexing a dictionary using the SEGUID checksum}
To give another example of working with dictionaries of \verb|SeqRecord| objects, we'll use the SEGUID checksum function. This is a relatively recent checksum, and collisions should be very rare (i.e. two different sequences with the same checksum), an improvement on the CRC64 checksum.
Once again, working with the orchids GenBank file:
\begin{verbatim}
from Bio import SeqIO
from Bio.SeqUtils.CheckSum import seguid
for record in SeqIO.parse("ls_orchid.gbk", "genbank"):
print record.id, seguid(record.seq)
\end{verbatim}
\noindent This should give:
\begin{verbatim}
Z78533.1 JUEoWn6DPhgZ9nAyowsgtoD9TTo
Z78532.1 MN/s0q9zDoCVEEc+k/IFwCNF2pY
...
Z78439.1 H+JfaShya/4yyAj7IbMqgNkxdxQ
\end{verbatim}
Now, recall the \verb|Bio.SeqIO.to_dict()| function's \verb|key_function| argument expects a function which turns a \verb|SeqRecord| into a string. We can't use the \verb|seguid()| function directly because it expects to be given a \verb|Seq| object (or a string). However, we can use Python's \verb|lambda| feature to create a ``one off'' function to give to \verb|Bio.SeqIO.to_dict()| instead:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> from Bio.SeqUtils.CheckSum import seguid
>>> seguid_dict = SeqIO.to_dict(SeqIO.parse("ls_orchid.gbk", "genbank"),
... lambda rec : seguid(rec.seq))
>>> record = seguid_dict["MN/s0q9zDoCVEEc+k/IFwCNF2pY"]
>>> print record.id
Z78532.1
>>> print record.description
C.californicum 5.8S rRNA gene and ITS1 and ITS2 DNA.
\end{verbatim}
\noindent That should have retrieved the record {\tt Z78532.1}, the second entry in the file.
\subsection{Sequence files as Dictionaries -- Indexed files}
%\subsection{Indexing really large files}
\label{sec:SeqIO-index}
As the previous couple of examples tried to illustrate, using
\verb|Bio.SeqIO.to_dict()| is very flexible. However, because it holds
everything in memory, the size of file you can work with is limited by your
computer's RAM. In general, this will only work on small to medium files.
For larger files you should consider
\verb|Bio.SeqIO.index()|, which works a little differently. Although
it still returns a dictionary like object, this does \emph{not} keep
\emph{everything} in memory. Instead, it just records where each record
is within the file -- when you ask for a particular record, it then parses
it on demand.
As an example, let's use the same GenBank file as before:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> orchid_dict = SeqIO.index("ls_orchid.gbk", "genbank")
>>> len(orchid_dict)
94
\end{verbatim}
%Following is abbr.
\begin{verbatim}
>>> orchid_dict.keys()
['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
\end{verbatim}
%cont-doctest
\begin{verbatim}
>>> seq_record = orchid_dict["Z78475.1"]
>>> print seq_record.description
P.supardii 5.8S rRNA gene and ITS1 and ITS2 DNA.
>>> seq_record.seq
Seq('CGTAACAAGGTTTCCGTAGGTGAACCTGCGGAAGGATCATTGTTGAGATCACAT...GGT', IUPACAmbiguousDNA())
\end{verbatim}
\noindent Note that \verb|Bio.SeqIO.index()| won't take a handle,
but only a filename. There are good reasons for this, but it is a little
technical. The second argument is the file format (a lower case string as
used in the other \verb|Bio.SeqIO| functions). You can use many other
simple file formats, including FASTA and FASTQ files (see the example in
Section~\ref{sec:fastq-indexing}). However, alignment
formats like PHYLIP or Clustal are not supported. Finally as an optional
argument you can supply an alphabet, or a key function.
Here is the same example using the FASTA file - all we change is the
filename and the format name:
\begin{verbatim}
>>> from Bio import SeqIO
>>> orchid_dict = SeqIO.index("ls_orchid.fasta", "fasta")
>>> len(orchid_dict)
94
>>> orchid_dict.keys()
['gi|2765596|emb|Z78471.1|PDZ78471', 'gi|2765646|emb|Z78521.1|CCZ78521', ...
..., 'gi|2765613|emb|Z78488.1|PTZ78488', 'gi|2765583|emb|Z78458.1|PHZ78458']
\end{verbatim}
\subsubsection{Specifying the dictionary keys}
\label{seq:seqio-index-functionkey}
Suppose you want to use the same keys as before? Much like with the
\verb|Bio.SeqIO.to_dict()| example in Section~\ref{seq:seqio-todict-functionkey},
you'll need to write a tiny function to map from the FASTA identifier
(as a string) to the key you want:
\begin{verbatim}
def get_acc(identifier):
""""Given a SeqRecord identifier string, return the accession number as a string.
e.g. "gi|2765613|emb|Z78488.1|PTZ78488" -> "Z78488.1"
"""
parts = identifier.split("|")
assert len(parts) == 5 and parts[0] == "gi" and parts[2] == "emb"
return parts[3]
\end{verbatim}
\noindent Then we can give this function to the \verb|Bio.SeqIO.index()|
function to use in building the dictionary:
\begin{verbatim}
>>> from Bio import SeqIO
>>> orchid_dict = SeqIO.index("ls_orchid.fasta", "fasta", key_function=get_acc)
>>> print orchid_dict.keys()
['Z78484.1', 'Z78464.1', 'Z78455.1', 'Z78442.1', 'Z78532.1', 'Z78453.1', ..., 'Z78471.1']
\end{verbatim}
\noindent Easy when you know how?
\subsubsection{Getting the raw data for a record}
\label{sec:seqio-index-getraw}
The dictionary-like object from \verb|Bio.SeqIO.index()| gives you each
entry as a \verb|SeqRecord| object. However, it is sometimes useful to
be able to get the original raw data straight from the file. For this
use the \verb|get_raw()| method which takes a
single argument (the record identifier) and returns a string (extracted
from the file without modification).
A motivating example is extracting a subset of a records from a large
file where either \verb|Bio.SeqIO.write()| does not (yet) support the
output file format (e.g. the plain text SwissProt file format) or
where you need to preserve the text exactly (e.g. GenBank or EMBL
output from Biopython does not yet preserve every last bit of
annotation).
Let's suppose you have download the whole of UniProt in the plain
text SwissPort file format from their FTP site
(\url{ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.dat.gz})
and uncompressed it as the file \verb|uniprot_sprot.dat|, and you
want to extract just a few records from it:
\begin{verbatim}
>>> from Bio import SeqIO
>>> uniprot = SeqIO.index("uniprot_sprot.dat", "swiss")
>>> handle = open("selected.dat", "w")
>>> for acc in ["P33487", "P19801", "P13689", "Q8JZQ5", "Q9TRC7"]:
... handle.write(uniprot.get_raw(acc))
>>> handle.close()
\end{verbatim}
There is a longer example in Section~\ref{sec:SeqIO-sort} using the
\verb|SeqIO.index()| function to sort a large sequence file (without
loading everything into memory at once).
\subsection{Sequence files as Dictionaries -- Database indexed files}
\label{sec:SeqIO-index-db}
Biopython 1.57 introduced an alternative, \verb|Bio.SeqIO.index_db()|, which
can work on even extremely large files since it stores the record information
as a file on disk (using an SQLite3 database) rather than in memory. Also,
you can index multiple files together (providing all the record identifiers
are unique).
The \verb|Bio.SeqIO.index()| function takes three required arguments:
\begin{itemize}
\item Index filename, we suggest using something ending \texttt{.idx}.
This index file is actually an SQLite3 database.
\item List of sequence filenames to index (or a single filename)
\item File format (lower case string as used in the rest of the
\verb|SeqIO| module).
\end{itemize}
As an example, consider the GenBank flat file releases from the NCBI FTP site,
\url{ftp://ftp.ncbi.nih.gov/genbank/}, which are gzip compressed GenBank files.
As of GenBank release $182$, there are $16$ files making up the viral sequences,
\texttt{gbvrl1.seq}, \ldots, \texttt{gbvrl16.seq}, containing in total almost
one million records. You can index them like this:
\begin{verbatim}
>>> from Bio import SeqIO
>>> files = ["gbvrl%i.seq" % (i+1) for i in range(16)]
>>> gb_vrl = SeqIO.index_db("gbvrl.idx", files, "genbank")
>>> print "%i sequences indexed" % len(gb_vrl)
958086 sequences indexed
\end{verbatim}
That takes about two minutes to run on my machine. If you rerun it then the
index file (here \texttt{gbvrl.idx}) is reloaded in under a second. You can
use the index as a read only Python dictionary - without having to worry
about which file the sequence comes from, e.g.
\begin{verbatim}
>>> print gb_vrl["GQ333173.1"].description
HIV-1 isolate F12279A1 from Uganda gag protein (gag) gene, partial cds.
\end{verbatim}
\subsubsection{Getting the raw data for a record}
Just as with the \verb|Bio.SeqIO.index()| function discussed above in
Section~\ref{sec:seqio-index-getraw}, the dictionary like object also lets you
get at the raw text of each record:
\begin{verbatim}
>>> print gb_vrl.get_raw("GQ333173.1")
LOCUS GQ333173 459 bp DNA linear VRL 21-OCT-2009
DEFINITION HIV-1 isolate F12279A1 from Uganda gag protein (gag) gene, partial
cds.
ACCESSION GQ333173
...
//
\end{verbatim}
\subsection{Indexing compressed files}
\label{sec:SeqIO-index-bgzf}
Very often when you are indexing a sequence file it can be quite large -- so
you may want to compress it on disk. Unfortunately efficient random access
is difficult with the more common file formats like gzip and bzip2. In this
setting, BGZF (Blocked GNU Zip Format) can be very helpful. This is a variant
of gzip (and can be decompressed using standard gzip tools) popularised by
the BAM file format, \href{http://samtools.sourceforge.net/}{samtools}, and
\href{http://samtools.sourceforge.net/tabix.shtml}{tabix}.
To create a BGZF compressed file you can use the command line tool \verb|bgzip|
which comes with samtools. In our examples we use a filename extension
\verb|*.bgz|, so they can be distinguished from normal gzipped files (named
\verb|*.gz|). You can also use the \verb|Bio.bgzf| module to read and write
BGZF files from within Python.
The \verb|Bio.SeqIO.index()| and \verb|Bio.SeqIO.index_db()| can both be
used with BGZF compressed files. For example, if you started with an
uncompressed GenBank file:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> orchid_dict = SeqIO.index("ls_orchid.gbk", "genbank")
>>> len(orchid_dict)
94
\end{verbatim}
You could compress this (while keeping the original file) at the command
line using the following command -- but don't worry, the compressed file
is already included with the other example files:
\begin{verbatim}
$ bgzip -c ls_orchid.gbk > ls_orchid.gbk.bgz
\end{verbatim}
You can use the compressed file in exactly the same way:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> orchid_dict = SeqIO.index("ls_orchid.gbk.bgz", "genbank")
>>> len(orchid_dict)
94
\end{verbatim}
\noindent
or:
%Don't use doctest as would have to clean up the *.idx file
\begin{verbatim}
>>> from Bio import SeqIO
>>> orchid_dict = SeqIO.index_db("ls_orchid.gbk.bgz.idx", "ls_orchid.gbk.bgz", "genbank")
>>> len(orchid_dict)
94
\end{verbatim}
The \verb|SeqIO| indexing automatically detects the BGZF compression. Note
that you can't use the same index file for the uncompressed and compressed files.
\subsection{Discussion}
\label{sec:SeqIO-indexing-discussion}
So, which of these methods should you use and why? It depends on what you are
trying to do (and how much data you are dealing with). However, in general
picking \verb|Bio.SeqIO.index()| is a good starting point. If you are dealing
with millions of records, multiple files, or repeated analyses, then look at
\verb|Bio.SeqIO.index_db()|.
Reasons to choose \verb|Bio.SeqIO.to_dict()| over either
\verb|Bio.SeqIO.index()| or \verb|Bio.SeqIO.index_db()| boil down to a need
for flexibility despite its high memory needs. The advantage of storing the
\verb|SeqRecord| objects in memory is they can be changed, added to, or
removed at will. In addition to the downside of high memory consumption,
indexing can also take longer because all the records must be fully parsed.
Both \verb|Bio.SeqIO.index()| and \verb|Bio.SeqIO.index_db()| only parse
records on demand. When indexing, they scan the file once looking for the
start of each record and do as little work as possible to extract the
identifier.
Reasons to choose \verb|Bio.SeqIO.index()| over \verb|Bio.SeqIO.index_db()|
include:
\begin{itemize}
\item Faster to build the index (more noticeable in simple file formats)
\item Slightly faster access as SeqRecord objects (but the difference is only
really noticeable for simple to parse file formats).
\item Can use any immutable Python object as the dictionary keys (e.g. a
tuple of strings, or a frozen set) not just strings.
\item Don't need to worry about the index database being out of date if the
sequence file being indexed has changed.
\end{itemize}
Reasons to choose \verb|Bio.SeqIO.index_db()| over \verb|Bio.SeqIO.index()|
include:
\begin{itemize}
\item Not memory limited -- this is already important with files from second
generation sequencing where 10s of millions of sequences are common, and
using \verb|Bio.SeqIO.index()| can require more than 4GB of RAM and therefore
a 64bit version of Python.
\item Because the index is kept on disk, it can be reused. Although building
the index database file takes longer, if you have a script which will be
rerun on the same datafiles in future, this could save time in the long run.
\item Indexing multiple files together
\item The \verb|get_raw()| method can be much faster, since for most file
formats the length of each record is stored as well as its offset.
\end{itemize}
\section{Writing Sequence Files}
We've talked about using \verb|Bio.SeqIO.parse()| for sequence input (reading files), and now we'll look at \verb|Bio.SeqIO.write()| which is for sequence output (writing files). This is a function taking three arguments: some \verb|SeqRecord| objects, a handle or filename to write to, and a sequence format.
Here is an example, where we start by creating a few \verb|SeqRecord| objects the hard way (by hand, rather than by loading them from a file):
\begin{verbatim}
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import generic_protein
rec1 = SeqRecord(Seq("MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD" \
+"GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK" \
+"NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM" \
+"SSAC", generic_protein),
id="gi|14150838|gb|AAK54648.1|AF376133_1",
description="chalcone synthase [Cucumis sativus]")
rec2 = SeqRecord(Seq("YPDYYFRITNREHKAELKEKFQRMCDKSMIKKRYMYLTEEILKENPSMCEYMAPSLDARQ" \
+"DMVVVEIPKLGKEAAVKAIKEWGQ", generic_protein),
id="gi|13919613|gb|AAK33142.1|",
description="chalcone synthase [Fragaria vesca subsp. bracteata]")
rec3 = SeqRecord(Seq("MVTVEEFRRAQCAEGPATVMAIGTATPSNCVDQSTYPDYYFRITNSEHKVELKEKFKRMC" \
+"EKSMIKKRYMHLTEEILKENPNICAYMAPSLDARQDIVVVEVPKLGKEAAQKAIKEWGQP" \
+"KSKITHLVFCTTSGVDMPGCDYQLTKLLGLRPSVKRFMMYQQGCFAGGTVLRMAKDLAEN" \
+"NKGARVLVVCSEITAVTFRGPNDTHLDSLVGQALFGDGAAAVIIGSDPIPEVERPLFELV" \
+"SAAQTLLPDSEGAIDGHLREVGLTFHLLKDVPGLISKNIEKSLVEAFQPLGISDWNSLFW" \
+"IAHPGGPAILDQVELKLGLKQEKLKATRKVLSNYGNMSSACVLFILDEMRKASAKEGLGT" \
+"TGEGLEWGVLFGFGPGLTVETVVLHSVAT", generic_protein),
id="gi|13925890|gb|AAK49457.1|",
description="chalcone synthase [Nicotiana tabacum]")
my_records = [rec1, rec2, rec3]
\end{verbatim}
\noindent Now we have a list of \verb|SeqRecord| objects, we'll write them to a FASTA format file:
\begin{verbatim}
from Bio import SeqIO
SeqIO.write(my_records, "my_example.faa", "fasta")
\end{verbatim}
\noindent And if you open this file in your favourite text editor it should look like this:
\begin{verbatim}
>gi|14150838|gb|AAK54648.1|AF376133_1 chalcone synthase [Cucumis sativus]
MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD
GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK
NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM
SSAC
>gi|13919613|gb|AAK33142.1| chalcone synthase [Fragaria vesca subsp. bracteata]
YPDYYFRITNREHKAELKEKFQRMCDKSMIKKRYMYLTEEILKENPSMCEYMAPSLDARQ
DMVVVEIPKLGKEAAVKAIKEWGQ
>gi|13925890|gb|AAK49457.1| chalcone synthase [Nicotiana tabacum]
MVTVEEFRRAQCAEGPATVMAIGTATPSNCVDQSTYPDYYFRITNSEHKVELKEKFKRMC
EKSMIKKRYMHLTEEILKENPNICAYMAPSLDARQDIVVVEVPKLGKEAAQKAIKEWGQP
KSKITHLVFCTTSGVDMPGCDYQLTKLLGLRPSVKRFMMYQQGCFAGGTVLRMAKDLAEN
NKGARVLVVCSEITAVTFRGPNDTHLDSLVGQALFGDGAAAVIIGSDPIPEVERPLFELV
SAAQTLLPDSEGAIDGHLREVGLTFHLLKDVPGLISKNIEKSLVEAFQPLGISDWNSLFW
IAHPGGPAILDQVELKLGLKQEKLKATRKVLSNYGNMSSACVLFILDEMRKASAKEGLGT
TGEGLEWGVLFGFGPGLTVETVVLHSVAT
\end{verbatim}
Suppose you wanted to know how many records the \verb|Bio.SeqIO.write()| function wrote to the handle?
If your records were in a list you could just use \verb|len(my_records)|, however you can't do that when your records come from a generator/iterator. The \verb|Bio.SeqIO.write()| function returns the number of \verb|SeqRecord| objects written to the file.
\emph{Note} - If you tell the \verb|Bio.SeqIO.write()| function to write to a file that already exists, the old file will be overwritten without any warning.
\subsection{Round trips}
Some people like their parsers to be ``round-tripable'', meaning if you read in
a file and write it back out again it is unchanged. This requires that the parser
must extract enough information to reproduce the original file \emph{exactly}.
\verb|Bio.SeqIO| does \emph{not} aim to do this.
As a trivial example, any line wrapping of the sequence data in FASTA files is
allowed. An identical \verb|SeqRecord| would be given from parsing the following
two examples which differ only in their line breaks:
\begin{verbatim}
>YAL068C-7235.2170 Putative promoter sequence
TACGAGAATAATTTCTCATCATCCAGCTTTAACACAAAATTCGCACAGTTTTCGTTAAGA
GAACTTAACATTTTCTTATGACGTAAATGAAGTTTATATATAAATTTCCTTTTTATTGGA
>YAL068C-7235.2170 Putative promoter sequence
TACGAGAATAATTTCTCATCATCCAGCTTTAACACAAAATTCGCA
CAGTTTTCGTTAAGAGAACTTAACATTTTCTTATGACGTAAATGA
AGTTTATATATAAATTTCCTTTTTATTGGA
\end{verbatim}
To make a round-tripable FASTA parser you would need to keep track of where the
sequence line breaks occurred, and this extra information is usually pointless.
Instead Biopython uses a default line wrapping of $60$ characters on output.
The same problem with white space applies in many other file formats too.
Another issue in some cases is that Biopython does not (yet) preserve every
last bit of annotation (e.g. GenBank and EMBL).
Occasionally preserving the original layout (with any quirks it may have) is
important. See Section~\ref{sec:seqio-index-getraw} about the \verb|get_raw()|
method of the \verb|Bio.SeqIO.index()| dictionary-like object for one potential
solution.
\subsection{Converting between sequence file formats}
\label{sec:SeqIO-conversion}
In previous example we used a list of \verb|SeqRecord| objects as input to the \verb|Bio.SeqIO.write()| function, but it will also accept a \verb|SeqRecord| iterator like we get from \verb|Bio.SeqIO.parse()| -- this lets us do file conversion by combining these two functions.
For this example we'll read in the GenBank format file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.gbk}{ls\_orchid.gbk} and write it out in FASTA format:
\begin{verbatim}
from Bio import SeqIO
records = SeqIO.parse("ls_orchid.gbk", "genbank")
count = SeqIO.write(records, "my_example.fasta", "fasta")
print "Converted %i records" % count
\end{verbatim}
Still, that is a little bit complicated. So, because file conversion is such a
common task, there is a helper function letting you replace that with just:
\begin{verbatim}
from Bio import SeqIO
count = SeqIO.convert("ls_orchid.gbk", "genbank", "my_example.fasta", "fasta")
print "Converted %i records" % count
\end{verbatim}
The \verb|Bio.SeqIO.convert()| function will take handles \emph{or} filenames.
Watch out though -- if the output file already exists, it will overwrite it!
To find out more, see the built in help:
\begin{verbatim}
>>> from Bio import SeqIO
>>> help(SeqIO.convert)
...
\end{verbatim}
In principle, just by changing the filenames and the format names, this code
could be used to convert between any file formats available in Biopython.
However, writing some formats requires information (e.g. quality scores) which
other files formats don't contain. For example, while you can turn a FASTQ
file into a FASTA file, you can't do the reverse. See also
Sections~\ref{sec:SeqIO-fastq-conversion} and~\ref{sec:SeqIO-fasta-qual-conversion}
in the cookbook chapter which looks at inter-converting between different FASTQ formats.
Finally, as an added incentive for using the \verb|Bio.SeqIO.convert()| function
(on top of the fact your code will be shorter), doing it this way may also be
faster! The reason for this is the convert function can take advantage of
several file format specific optimisations and tricks.
\subsection{Converting a file of sequences to their reverse complements}
\label{sec:SeqIO-reverse-complement}
Suppose you had a file of nucleotide sequences, and you wanted to turn it into a file containing their reverse complement sequences. This time a little bit of work is required to transform the \verb|SeqRecord| objects we get from our input file into something suitable for saving to our output file.
To start with, we'll use \verb|Bio.SeqIO.parse()| to load some nucleotide
sequences from a file, then print out their reverse complements using
the \verb|Seq| object's built in \verb|.reverse_complement()| method (see Section~\ref{sec:seq-reverse-complement}):
\begin{verbatim}
>>> from Bio import SeqIO
>>> for record in SeqIO.parse("ls_orchid.gbk", "genbank"):
... print record.id
... print record.seq.reverse_complement()
\end{verbatim}
Now, if we want to save these reverse complements to a file, we'll need to make \verb|SeqRecord| objects.
We can use the \verb|SeqRecord| object's built in \verb|.reverse_complement()| method (see Section~\ref{sec:SeqRecord-reverse-complement}) but we must decide how to name our new records.
This is an excellent place to demonstrate the power of list comprehensions which make a list in memory:
%doctest examples
\begin{verbatim}
>>> from Bio import SeqIO
>>> records = [rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
... for rec in SeqIO.parse("ls_orchid.fasta", "fasta")]
>>> len(records)
94
\end{verbatim}
\noindent Now list comprehensions have a nice trick up their sleeves, you can add a conditional statement:
%cont-doctest examples
\begin{verbatim}
>>> records = [rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
... for rec in SeqIO.parse("ls_orchid.fasta", "fasta") if len(rec)<700]
>>> len(records)
18
\end{verbatim}
That would create an in memory list of reverse complement records where the sequence length was under 700 base pairs. However, we can do exactly the same with a generator expression - but with the advantage that this does not create a list of all the records in memory at once:
%cont-doctest examples
\begin{verbatim}
>>> records = (rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
... for rec in SeqIO.parse("ls_orchid.fasta", "fasta") if len(rec)<700)
\end{verbatim}
As a complete example:
%not a doctest as would have to remove the output file
\begin{verbatim}
>>> from Bio import SeqIO
>>> records = (rec.reverse_complement(id="rc_"+rec.id, description = "reverse complement") \
... for rec in SeqIO.parse("ls_orchid.fasta", "fasta") if len(rec)<700)
>>> SeqIO.write(records, "rev_comp.fasta", "fasta")
18
\end{verbatim}
There is a related example in Section~\ref{sec:SeqIO-translate}, translating each
record in a FASTA file from nucleotides to amino acids.
\subsection{Getting your SeqRecord objects as formatted strings}
\label{sec:Bio.SeqIO-and-StringIO}
Suppose that you don't really want to write your records to a file or handle -- instead you want a string containing the records in a particular file format. The \verb|Bio.SeqIO| interface is based on handles, but Python has a useful built in module which provides a string based handle.
For an example of how you might use this, let's load in a bunch of \verb|SeqRecord| objects from our orchids GenBank file, and create a string containing the records in FASTA format:
\begin{verbatim}
from Bio import SeqIO
from StringIO import StringIO
records = SeqIO.parse("ls_orchid.gbk", "genbank")
out_handle = StringIO()
SeqIO.write(records, out_handle, "fasta")
fasta_data = out_handle.getvalue()
print fasta_data
\end{verbatim}
This isn't entirely straightforward the first time you see it! On the bright side, for the special case where you would like a string containing a \emph{single} record in a particular file format, use the the \verb|SeqRecord| class' \verb|format()| method (see Section~\ref{sec:SeqRecord-format}).
Note that although we don't encourage it, you \emph{can} use the \verb|format()| method to write to a file, for example something like this:
\begin{verbatim}
from Bio import SeqIO
out_handle = open("ls_orchid_long.tab", "w")
for record in SeqIO.parse("ls_orchid.gbk", "genbank"):
if len(record) > 100:
out_handle.write(record.format("tab"))
out_handle.close()
\end{verbatim}
\noindent While this style of code will work for a simple sequential file format like FASTA or the simple tab separated format used here, it will \emph{not} work for more complex or interlaced file formats. This is why we still recommend using \verb|Bio.SeqIO.write()|, as in the following example:
\begin{verbatim}
from Bio import SeqIO
records = (rec for rec in SeqIO.parse("ls_orchid.gbk", "genbank") if len(rec) > 100)
SeqIO.write(records, "ls_orchid.tab", "tab")
\end{verbatim}
\noindent Making a single call to \verb|SeqIO.write(...)| is also much quicker than
multiple calls to the \verb|SeqRecord.format(...)| method.
\chapter{Multiple Sequence Alignment objects}
\label{chapter:Bio.AlignIO}
This chapter is about Multiple Sequence Alignments, by which we mean a collection of
multiple sequences which have been aligned together -- usually with the insertion of gap
characters, and addition of leading or trailing gaps -- such that all the sequence
strings are the same length. Such an alignment can be regarded as a matrix of letters,
where each row is held as a \verb|SeqRecord| object internally.
We will introduce the \verb|MultipleSeqAlignment| object which holds this kind of data,
and the \verb|Bio.AlignIO| module for reading and writing them as various file formats
(following the design of the \verb|Bio.SeqIO| module from the previous chapter).
Note that both \verb|Bio.SeqIO| and \verb|Bio.AlignIO| can read and write sequence
alignment files. The appropriate choice will depend largely on what you want to do
with the data.
The final part of this chapter is about our command line wrappers for common multiple
sequence alignment tools like ClustalW and MUSCLE.
\section{Parsing or Reading Sequence Alignments}
We have two functions for reading in sequence alignments, \verb|Bio.AlignIO.read()| and \verb|Bio.AlignIO.parse()| which following the convention introduced in \verb|Bio.SeqIO| are for files containing one or multiple alignments respectively.
Using \verb|Bio.AlignIO.parse()| will return an {\it iterator} which gives \verb|MultipleSeqAlignment| objects. Iterators are typically used in a for loop. Examples of situations where you will have multiple different alignments include resampled alignments from the PHYLIP tool \verb|seqboot|, or multiple pairwise alignments from the EMBOSS tools \verb|water| or \verb|needle|, or Bill Pearson's FASTA tools.
However, in many situations you will be dealing with files which contain only a single alignment. In this case, you should use the \verb|Bio.AlignIO.read()| function which returns a single \verb|MultipleSeqAlignment| object.
Both functions expect two mandatory arguments:
\begin{enumerate}
\item The first argument is a {\it handle} to read the data from, typically an open file (see Section~\ref{sec:appendix-handles}), or a filename.
\item The second argument is a lower case string specifying the alignment format. As in \verb|Bio.SeqIO| we don't try and guess the file format for you! See \url{http://biopython.org/wiki/AlignIO} for a full listing of supported formats.
\end{enumerate}
\noindent There is also an optional \verb|seq_count| argument which is discussed in Section~\ref{sec:AlignIO-count-argument} below for dealing with ambiguous file formats which may contain more than one alignment.
A further optional \verb|alphabet| argument allowing you to specify the expected alphabet. This can be useful as many alignment file formats do not explicitly label the sequences as RNA, DNA or protein -- which means \verb|Bio.AlignIO| will default to using a generic alphabet.
\subsection{Single Alignments}
As an example, consider the following annotation rich protein alignment in the PFAM or Stockholm file format:
\begin{verbatim}
# STOCKHOLM 1.0
#=GS COATB_BPIKE/30-81 AC P03620.1
#=GS COATB_BPIKE/30-81 DR PDB; 1ifl ; 1-52;
#=GS Q9T0Q8_BPIKE/1-52 AC Q9T0Q8.1
#=GS COATB_BPI22/32-83 AC P15416.1
#=GS COATB_BPM13/24-72 AC P69541.1
#=GS COATB_BPM13/24-72 DR PDB; 2cpb ; 1-49;
#=GS COATB_BPM13/24-72 DR PDB; 2cps ; 1-49;
#=GS COATB_BPZJ2/1-49 AC P03618.1
#=GS Q9T0Q9_BPFD/1-49 AC Q9T0Q9.1
#=GS Q9T0Q9_BPFD/1-49 DR PDB; 1nh4 A; 1-49;
#=GS COATB_BPIF1/22-73 AC P03619.2
#=GS COATB_BPIF1/22-73 DR PDB; 1ifk ; 1-50;
COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA
#=GR COATB_BPIKE/30-81 SS -HHHHHHHHHHHHHH--HHHHHHHH--HHHHHHHHHHHHHHHHHHHHH----
Q9T0Q8_BPIKE/1-52 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA
COATB_BPI22/32-83 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA
COATB_BPM13/24-72 AEGDDP...AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
#=GR COATB_BPM13/24-72 SS ---S-T...CHCHHHHCCCCTCCCTTCHHHHHHHHHHHHHHHHHHHHCTT--
COATB_BPZJ2/1-49 AEGDDP...AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA
Q9T0Q9_BPFD/1-49 AEGDDP...AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
#=GR Q9T0Q9_BPFD/1-49 SS ------...-HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH--
COATB_BPIF1/22-73 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA
#=GR COATB_BPIF1/22-73 SS XX-HHHH--HHHHHH--HHHHHHH--HHHHHHHHHHHHHHHHHHHHHHH---
#=GC SS_cons XHHHHHHHHHHHHHHHCHHHHHHHHCHHHHHHHHHHHHHHHHHHHHHHHC--
#=GC seq_cons AEssss...AptAhDSLpspAT-hIu.sWshVsslVsAsluIKLFKKFsSKA
//
\end{verbatim}
This is the seed alignment for the Phage\_Coat\_Gp8 (PF05371) PFAM entry, downloaded from a now out of date release of PFAM from \url{http://pfam.sanger.ac.uk/}. We can load this file as follows (assuming it has been saved to disk as ``PF05371\_seed.sth'' in the current working directory):
%doctest examples
\begin{verbatim}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
\end{verbatim}
\noindent This code will print out a summary of the alignment:
%cont-doctest
\begin{verbatim}
>>> print alignment
SingleLetterAlphabet() alignment with 7 rows and 52 columns
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRL...SKA COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
\end{verbatim}
You'll notice in the above output the sequences have been truncated. We could instead write our own code to format this as we please by iterating over the rows as \verb|SeqRecord| objects:
%doctest examples
\begin{verbatim}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> print "Alignment length %i" % alignment.get_alignment_length()
Alignment length 52
>>> for record in alignment:
... print "%s - %s" % (record.seq, record.id)
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73
\end{verbatim}
You could also use the alignment object's \verb|format| method to show it in a particular file format -- see Section~\ref{sec:alignment-format-method} for details.
Did you notice in the raw file above that several of the sequences include database cross-references to the PDB and the associated known secondary structure? Try this:
%cont-doctest
\begin{verbatim}
>>> for record in alignment:
... if record.dbxrefs:
... print record.id, record.dbxrefs
COATB_BPIKE/30-81 ['PDB; 1ifl ; 1-52;']
COATB_BPM13/24-72 ['PDB; 2cpb ; 1-49;', 'PDB; 2cps ; 1-49;']
Q9T0Q9_BPFD/1-49 ['PDB; 1nh4 A; 1-49;']
COATB_BPIF1/22-73 ['PDB; 1ifk ; 1-50;']
\end{verbatim}
\noindent To have a look at all the sequence annotation, try this:
\begin{verbatim}
>>> for record in alignment:
... print record
\end{verbatim}
Sanger provide a nice web interface at \url{http://pfam.sanger.ac.uk/family?acc=PF05371} which will actually let you download this alignment in several other formats. This is what the file looks like in the FASTA file format:
\begin{verbatim}
>COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA
>Q9T0Q8_BPIKE/1-52
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA
>COATB_BPI22/32-83
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA
>COATB_BPM13/24-72
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
>COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA
>Q9T0Q9_BPFD/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA
>COATB_BPIF1/22-73
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA
\end{verbatim}
\noindent Note the website should have an option about showing gaps as periods (dots) or dashes, we've shown dashes above. Assuming you download and save this as file ``PF05371\_seed.faa'' then you can load it with almost exactly the same code:
\begin{verbatim}
from Bio import AlignIO
alignment = AlignIO.read("PF05371_seed.faa", "fasta")
print alignment
\end{verbatim}
All that has changed in this code is the filename and the format string. You'll get the same output as before, the sequences and record identifiers are the same.
However, as you should expect, if you check each \verb|SeqRecord| there is no annotation nor database cross-references because these are not included in the FASTA file format.
Note that rather than using the Sanger website, you could have used \verb|Bio.AlignIO| to convert the original Stockholm format file into a FASTA file yourself (see below).
With any supported file format, you can load an alignment in exactly the same way just by changing the format string. For example, use ``phylip'' for PHYLIP files, ``nexus'' for NEXUS files or ``emboss'' for the alignments output by the EMBOSS tools. There is a full listing on the wiki page (\url{http://biopython.org/wiki/AlignIO}) and in the built in documentation (also \href{http://biopython.org/DIST/docs/api/Bio.AlignIO-module.html}{online}):
\begin{verbatim}
>>> from Bio import AlignIO
>>> help(AlignIO)
...
\end{verbatim}
\subsection{Multiple Alignments}
The previous section focused on reading files containing a single alignment. In general however, files can contain more than one alignment, and to read these files we must use the \verb|Bio.AlignIO.parse()| function.
Suppose you have a small alignment in PHYLIP format:
\begin{verbatim}
5 6
Alpha AACAAC
Beta AACCCC
Gamma ACCAAC
Delta CCACCA
Epsilon CCAAAC
\end{verbatim}
If you wanted to bootstrap a phylogenetic tree using the PHYLIP tools, one of the steps would be to create a set of many resampled alignments using the tool \verb|bootseq|. This would give output something like this, which has been abbreviated for conciseness:
\begin{verbatim}
5 6
Alpha AAACCA
Beta AAACCC
Gamma ACCCCA
Delta CCCAAC
Epsilon CCCAAA
5 6
Alpha AAACAA
Beta AAACCC
Gamma ACCCAA
Delta CCCACC
Epsilon CCCAAA
5 6
Alpha AAAAAC
Beta AAACCC
Gamma AACAAC
Delta CCCCCA
Epsilon CCCAAC
...
5 6
Alpha AAAACC
Beta ACCCCC
Gamma AAAACC
Delta CCCCAA
Epsilon CAAACC
\end{verbatim}
If you wanted to read this in using \verb|Bio.AlignIO| you could use:
\begin{verbatim}
from Bio import AlignIO
alignments = AlignIO.parse("resampled.phy", "phylip")
for alignment in alignments:
print alignment
print
\end{verbatim}
\noindent This would give the following output, again abbreviated for display:
\begin{verbatim}
SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAACCA Alpha
AAACCC Beta
ACCCCA Gamma
CCCAAC Delta
CCCAAA Epsilon
SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAACAA Alpha
AAACCC Beta
ACCCAA Gamma
CCCACC Delta
CCCAAA Epsilon
SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAAAAC Alpha
AAACCC Beta
AACAAC Gamma
CCCCCA Delta
CCCAAC Epsilon
...
SingleLetterAlphabet() alignment with 5 rows and 6 columns
AAAACC Alpha
ACCCCC Beta
AAAACC Gamma
CCCCAA Delta
CAAACC Epsilon
\end{verbatim}
As with the function \verb|Bio.SeqIO.parse()|, using \verb|Bio.AlignIO.parse()| returns an iterator.
If you want to keep all the alignments in memory at once, which will allow you to access them in any order, then turn the iterator into a list:
\begin{verbatim}
from Bio import AlignIO
alignments = list(AlignIO.parse("resampled.phy", "phylip"))
last_align = alignments[-1]
first_align = alignments[0]
\end{verbatim}
\subsection{Ambiguous Alignments}
\label{sec:AlignIO-count-argument}
Many alignment file formats can explicitly store more than one alignment, and the division between each alignment is clear. However, when a general sequence file format has been used there is no such block structure. The most common such situation is when alignments have been saved in the FASTA file format. For example consider the following:
\begin{verbatim}
>Alpha
ACTACGACTAGCTCAG--G
>Beta
ACTACCGCTAGCTCAGAAG
>Gamma
ACTACGGCTAGCACAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Beta
ACTACCGCTAGCTCAGAAG
>Gamma
ACTACGGCTAGCACAGAAG
\end{verbatim}
\noindent This could be a single alignment containing six sequences (with repeated identifiers). Or, judging from the identifiers, this is probably two different alignments each with three sequences, which happen to all have the same length.
What about this next example?
\begin{verbatim}
>Alpha
ACTACGACTAGCTCAG--G
>Beta
ACTACCGCTAGCTCAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Gamma
ACTACGGCTAGCACAGAAG
>Alpha
ACTACGACTAGCTCAGG--
>Delta
ACTACGGCTAGCACAGAAG
\end{verbatim}
\noindent Again, this could be a single alignment with six sequences. However this time based on the identifiers we might guess this is three pairwise alignments which by chance have all got the same lengths.
This final example is similar:
\begin{verbatim}
>Alpha
ACTACGACTAGCTCAG--G
>XXX
ACTACCGCTAGCTCAGAAG
>Alpha
ACTACGACTAGCTCAGG
>YYY
ACTACGGCAAGCACAGG
>Alpha
--ACTACGAC--TAGCTCAGG
>ZZZ
GGACTACGACAATAGCTCAGG
\end{verbatim}
\noindent In this third example, because of the differing lengths, this cannot be treated as a single alignment containing all six records. However, it could be three pairwise alignments.
Clearly trying to store more than one alignment in a FASTA file is not ideal. However, if you are forced to deal with these as input files \verb|Bio.AlignIO| can cope with the most common situation where all the alignments have the same number of records.
One example of this is a collection of pairwise alignments, which can be produced by the EMBOSS tools \verb|needle| and \verb|water| -- although in this situation, \verb|Bio.AlignIO| should be able to understand their native output using ``emboss'' as the format string.
To interpret these FASTA examples as several separate alignments, we can use \verb|Bio.AlignIO.parse()| with the optional \verb|seq_count| argument which specifies how many sequences are expected in each alignment (in these examples, 3, 2 and 2 respectively).
For example, using the third example as the input data:
\begin{verbatim}
for alignment in AlignIO.parse(handle, "fasta", seq_count=2):
print "Alignment length %i" % alignment.get_alignment_length()
for record in alignment:
print "%s - %s" % (record.seq, record.id)
print
\end{verbatim}
\noindent giving:
\begin{verbatim}
Alignment length 19
ACTACGACTAGCTCAG--G - Alpha
ACTACCGCTAGCTCAGAAG - XXX
Alignment length 17
ACTACGACTAGCTCAGG - Alpha
ACTACGGCAAGCACAGG - YYY
Alignment length 21
--ACTACGAC--TAGCTCAGG - Alpha
GGACTACGACAATAGCTCAGG - ZZZ
\end{verbatim}
Using \verb|Bio.AlignIO.read()| or \verb|Bio.AlignIO.parse()| without the \verb|seq_count| argument would give a single alignment containing all six records for the first two examples. For the third example, an exception would be raised because the lengths differ preventing them being turned into a single alignment.
If the file format itself has a block structure allowing \verb|Bio.AlignIO| to determine the number of sequences in each alignment directly, then the \verb|seq_count| argument is not needed. If it is supplied, and doesn't agree with the file contents, an error is raised.
Note that this optional \verb|seq_count| argument assumes each alignment in the file has the same number of sequences. Hypothetically you may come across stranger situations, for example a FASTA file containing several alignments each with a different number of sequences -- although I would love to hear of a real world example of this. Assuming you cannot get the data in a nicer file format, there is no straight forward way to deal with this using \verb|Bio.AlignIO|. In this case, you could consider reading in the sequences themselves using \verb|Bio.SeqIO| and batching them together to create the alignments as appropriate.
\section{Writing Alignments}
We've talked about using \verb|Bio.AlignIO.read()| and \verb|Bio.AlignIO.parse()| for alignment input (reading files), and now we'll look at \verb|Bio.AlignIO.write()| which is for alignment output (writing files). This is a function taking three arguments: some \verb|MultipleSeqAlignment| objects (or for backwards compatibility the obsolete \verb|Alignment| objects), a handle or filename to write to, and a sequence format.
Here is an example, where we start by creating a few \verb|MultipleSeqAlignment| objects the hard way (by hand, rather than by loading them from a file).
Note we create some \verb|SeqRecord| objects to construct the alignment from.
\begin{verbatim}
from Bio.Alphabet import generic_dna
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment
align1 = MultipleSeqAlignment([
SeqRecord(Seq("ACTGCTAGCTAG", generic_dna), id="Alpha"),
SeqRecord(Seq("ACT-CTAGCTAG", generic_dna), id="Beta"),
SeqRecord(Seq("ACTGCTAGDTAG", generic_dna), id="Gamma"),
])
align2 = MultipleSeqAlignment([
SeqRecord(Seq("GTCAGC-AG", generic_dna), id="Delta"),
SeqRecord(Seq("GACAGCTAG", generic_dna), id="Epsilon"),
SeqRecord(Seq("GTCAGCTAG", generic_dna), id="Zeta"),
])
align3 = MultipleSeqAlignment([
SeqRecord(Seq("ACTAGTACAGCTG", generic_dna), id="Eta"),
SeqRecord(Seq("ACTAGTACAGCT-", generic_dna), id="Theta"),
SeqRecord(Seq("-CTACTACAGGTG", generic_dna), id="Iota"),
])
my_alignments = [align1, align2, align3]
\end{verbatim}
\noindent Now we have a list of \verb|Alignment| objects, we'll write them to a PHYLIP format file:
\begin{verbatim}
from Bio import AlignIO
AlignIO.write(my_alignments, "my_example.phy", "phylip")
\end{verbatim}
\noindent And if you open this file in your favourite text editor it should look like this:
\begin{verbatim}
3 12
Alpha ACTGCTAGCT AG
Beta ACT-CTAGCT AG
Gamma ACTGCTAGDT AG
3 9
Delta GTCAGC-AG
Epislon GACAGCTAG
Zeta GTCAGCTAG
3 13
Eta ACTAGTACAG CTG
Theta ACTAGTACAG CT-
Iota -CTACTACAG GTG
\end{verbatim}
Its more common to want to load an existing alignment, and save that, perhaps after some simple manipulation like removing certain rows or columns.
Suppose you wanted to know how many alignments the \verb|Bio.AlignIO.write()| function wrote to the handle? If your alignments were in a list like the example above, you could just use \verb|len(my_alignments)|, however you can't do that when your records come from a generator/iterator. Therefore the \verb|Bio.AlignIO.write()| function returns the number of alignments written to the file.
\emph{Note} - If you tell the \verb|Bio.AlignIO.write()| function to write to a file that already exists, the old file will be overwritten without any warning.
\subsection{Converting between sequence alignment file formats}
\label{sec:converting-alignments}
Converting between sequence alignment file formats with \verb|Bio.AlignIO| works
in the same way as converting between sequence file formats with \verb|Bio.SeqIO|
(Section~\ref{sec:SeqIO-conversion}). We load generally the alignment(s) using
\verb|Bio.AlignIO.parse()| and then save them using the \verb|Bio.AlignIO.write()|
-- or just use the \verb|Bio.AlignIO.convert()| helper function.
For this example, we'll load the PFAM/Stockholm format file used earlier and save it as a Clustal W format file:
\begin{verbatim}
from Bio import AlignIO
count = AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.aln", "clustal")
print "Converted %i alignments" % count
\end{verbatim}
Or, using \verb|Bio.AlignIO.parse()| and \verb|Bio.AlignIO.write()|:
\begin{verbatim}
from Bio import AlignIO
alignments = AlignIO.parse("PF05371_seed.sth", "stockholm")
count = AlignIO.write(alignments, "PF05371_seed.aln", "clustal")
print "Converted %i alignments" % count
\end{verbatim}
The \verb|Bio.AlignIO.write()| function expects to be given multiple alignment objects. In the example above we gave it the alignment iterator returned by \verb|Bio.AlignIO.parse()|.
In this case, we know there is only one alignment in the file so we could have used \verb|Bio.AlignIO.read()| instead, but notice we have to pass this alignment to \verb|Bio.AlignIO.write()| as a single element list:
\begin{verbatim}
from Bio import AlignIO
alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
AlignIO.write([alignment], "PF05371_seed.aln", "clustal")
\end{verbatim}
Either way, you should end up with the same new Clustal W format file ``PF05371\_seed.aln'' with the following content:
\begin{verbatim}
CLUSTAL X (1.81) multiple sequence alignment
COATB_BPIKE/30-81 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSS
Q9T0Q8_BPIKE/1-52 AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVS
COATB_BPI22/32-83 DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSS
COATB_BPM13/24-72 AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTS
COATB_BPZJ2/1-49 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFAS
Q9T0Q9_BPFD/1-49 AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTS
COATB_BPIF1/22-73 FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVS
COATB_BPIKE/30-81 KA
Q9T0Q8_BPIKE/1-52 RA
COATB_BPI22/32-83 KA
COATB_BPM13/24-72 KA
COATB_BPZJ2/1-49 KA
Q9T0Q9_BPFD/1-49 KA
COATB_BPIF1/22-73 RA
\end{verbatim}
Alternatively, you could make a PHYLIP format file which we'll name ``PF05371\_seed.phy'':
\begin{verbatim}
from Bio import AlignIO
AlignIO.convert("PF05371_seed.sth", "stockholm", "PF05371_seed.phy", "phylip")
\end{verbatim}
This time the output looks like this:
\begin{verbatim}
7 52
COATB_BPIK AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS
Q9T0Q8_BPI AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS
COATB_BPI2 DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS
COATB_BPM1 AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
COATB_BPZJ AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS
Q9T0Q9_BPF AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
COATB_BPIF FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS
KA
RA
KA
KA
KA
KA
RA
\end{verbatim}
One of the big handicaps of the PHYLIP alignment file format is that the sequence identifiers are strictly truncated at ten characters. In this example, as you can see the resulting names are still unique - but they are not very readable. In this particular case, there is no clear way to compress the identifiers, but for the sake of argument you may want to assign your own names or numbering system. This following bit of code manipulates the record identifiers before saving the output:
\begin{verbatim}
from Bio import AlignIO
alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
name_mapping = {}
for i, record in enumerate(alignment):
name_mapping[i] = record.id
record.id = "seq%i" % i
print name_mapping
AlignIO.write([alignment], "PF05371_seed.phy", "phylip")
\end{verbatim}
\noindent This code used a Python dictionary to record a simple mapping from the new sequence system to the original identifier:
\begin{verbatim}
{0: 'COATB_BPIKE/30-81', 1: 'Q9T0Q8_BPIKE/1-52', 2: 'COATB_BPI22/32-83', ...}
\end{verbatim}
\noindent Here is the new PHYLIP format output:
\begin{verbatim}
7 52
seq0 AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIRLFKKFSS
seq1 AEPNAATNYA TEAMDSLKTQ AIDLISQTWP VVTTVVVAGL VIKLFKKFVS
seq2 DGTSTATSYA TEAMNSLKTQ ATDLIDQTWP VVTSVAVAGL AIRLFKKFSS
seq3 AEGDDP---A KAAFNSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
seq4 AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFAS
seq5 AEGDDP---A KAAFDSLQAS ATEYIGYAWA MVVVIVGATI GIKLFKKFTS
seq6 FAADDATSQA KAAFDSLTAQ ATEMSGYAWA LVVLVVGATV GIKLFKKFVS
KA
RA
KA
KA
KA
KA
RA
\end{verbatim}
\noindent In general, because of the identifier limitation, working with PHYLIP file formats shouldn't be your first choice. Using the PFAM/Stockholm format on the other hand allows you to record a lot of additional annotation too.
\subsection{Getting your alignment objects as formatted strings}
\label{sec:alignment-format-method}
The \verb|Bio.AlignIO| interface is based on handles, which means if you want to get your alignment(s) into a string in a particular file format you need to do a little bit more work (see below).
However, you will probably prefer to take advantage of the alignment object's \verb|format()| method.
This takes a single mandatory argument, a lower case string which is supported by \verb|Bio.AlignIO| as an output format. For example:
\begin{verbatim}
from Bio import AlignIO
alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
print alignment.format("clustal")
\end{verbatim}
As described in Section~\ref{sec:SeqRecord-format}), the \verb|SeqRecord| object has a similar method using output formats supported by \verb|Bio.SeqIO|.
Internally the \verb|format()| method is using the \verb|StringIO| string based handle and calling
\verb|Bio.AlignIO.write()|. You can do this in your own code if for example you are using an
older version of Biopython:
\begin{verbatim}
from Bio import AlignIO
from StringIO import StringIO
alignments = AlignIO.parse("PF05371_seed.sth", "stockholm")
out_handle = StringIO()
AlignIO.write(alignments, out_handle, "clustal")
clustal_data = out_handle.getvalue()
print clustal_data
\end{verbatim}
\section{Manipulating Alignments}
\label{sec:manipulating-alignments}
Now that we've covered loading and saving alignments, we'll look at what else you can do
with them.
\subsection{Slicing alignments}
First of all, in some senses the alignment objects act like a Python \verb|list| of
\verb|SeqRecord| objects (the rows). With this model in mind hopefully the actions
of \verb|len()| (the number of rows) and iteration (each row as a \verb|SeqRecord|)
make sense:
%doctest examples
\begin{verbatim}
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> print "Number of rows: %i" % len(alignment)
Number of rows: 7
>>> for record in alignment:
... print "%s - %s" % (record.seq, record.id)
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA - COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA - Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA - COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA - COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA - Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA - COATB_BPIF1/22-73
\end{verbatim}
You can also use the list-like \verb|append| and \verb|extend| methods to add
more rows to the alignment (as \verb|SeqRecord| objects). Keeping the list
metaphor in mind, simple slicing of the alignment should also make sense -
it selects some of the rows giving back another alignment object:
%cont-doctest
\begin{verbatim}
>>> print alignment
SingleLetterAlphabet() alignment with 7 rows and 52 columns
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRL...SKA COATB_BPIKE/30-81
AEPNAATNYATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKL...SRA Q9T0Q8_BPIKE/1-52
DGTSTATSYATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRL...SKA COATB_BPI22/32-83
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
>>> print alignment[3:7]
SingleLetterAlphabet() alignment with 4 rows and 52 columns
AEGDDP---AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPM13/24-72
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA COATB_BPZJ2/1-49
AEGDDP---AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKL...SKA Q9T0Q9_BPFD/1-49
FAADDATSQAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKL...SRA COATB_BPIF1/22-73
\end{verbatim}
What if you wanted to select by column? Those of you who have used the NumPy
matrix or array objects won't be surprised at this - you use a double index.
%cont-doctest
\begin{verbatim}
>>> print alignment[2,6]
T
\end{verbatim}
\noindent Using two integer indices pulls out a single letter, short hand for this:
%cont-doctest
\begin{verbatim}
>>> print alignment[2].seq[6]
T
\end{verbatim}
You can pull out a single column as a string like this:
%cont-doctest
\begin{verbatim}
>>> print alignment[:,6]
TTT---T
\end{verbatim}
You can also select a range of columns. For example, to pick out those same
three rows we extracted earlier, but take just their first six columns:
%cont-doctest
\begin{verbatim}
>>> print alignment[3:6,:6]
SingleLetterAlphabet() alignment with 3 rows and 6 columns
AEGDDP COATB_BPM13/24-72
AEGDDP COATB_BPZJ2/1-49
AEGDDP Q9T0Q9_BPFD/1-49
\end{verbatim}
Leaving the first index as \verb|:| means take all the rows:
%cont-doctest
\begin{verbatim}
>>> print alignment[:,:6]
SingleLetterAlphabet() alignment with 7 rows and 6 columns
AEPNAA COATB_BPIKE/30-81
AEPNAA Q9T0Q8_BPIKE/1-52
DGTSTA COATB_BPI22/32-83
AEGDDP COATB_BPM13/24-72
AEGDDP COATB_BPZJ2/1-49
AEGDDP Q9T0Q9_BPFD/1-49
FAADDA COATB_BPIF1/22-73
\end{verbatim}
This brings us to a neat way to remove a section. Notice columns
7, 8 and 9 which are gaps in three of the seven sequences:
%cont-doctest
\begin{verbatim}
>>> print alignment[:,6:9]
SingleLetterAlphabet() alignment with 7 rows and 3 columns
TNY COATB_BPIKE/30-81
TNY Q9T0Q8_BPIKE/1-52
TSY COATB_BPI22/32-83
--- COATB_BPM13/24-72
--- COATB_BPZJ2/1-49
--- Q9T0Q9_BPFD/1-49
TSQ COATB_BPIF1/22-73
\end{verbatim}
\noindent Again, you can slice to get everything after the ninth column:
%cont-doctest
\begin{verbatim}
>>> print alignment[:,9:]
SingleLetterAlphabet() alignment with 7 rows and 43 columns
ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
ATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
ATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83
AKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72
AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
AKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
AKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
\end{verbatim}
\noindent Now, the interesting thing is that addition of alignment objects works
by column. This lets you do this as a way to remove a block of columns:
%cont-doctest
\begin{verbatim}
>>> edited = alignment[:,:6] + alignment[:,9:]
>>> print edited
SingleLetterAlphabet() alignment with 7 rows and 49 columns
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83
AEGDDPAKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
\end{verbatim}
Another common use of alignment addition would be to combine alignments for
several different genes into a meta-alignment. Watch out though - the identifiers
need to match up (see Section~\ref{sec:SeqRecord-addition} for how adding
\verb|SeqRecord| objects works). You may find it helpful to first sort the
alignment rows alphabetically by id:
%cont-doctest
\begin{verbatim}
>>> edited.sort()
>>> print edited
SingleLetterAlphabet() alignment with 7 rows and 49 columns
DGTSTAATEAMNSLKTQATDLIDQTWPVVTSVAVAGLAIRLFKKFSSKA COATB_BPI22/32-83
FAADDAAKAAFDSLTAQATEMSGYAWALVVLVVGATVGIKLFKKFVSRA COATB_BPIF1/22-73
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIRLFKKFSSKA COATB_BPIKE/30-81
AEGDDPAKAAFNSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA COATB_BPM13/24-72
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFASKA COATB_BPZJ2/1-49
AEPNAAATEAMDSLKTQAIDLISQTWPVVTTVVVAGLVIKLFKKFVSRA Q9T0Q8_BPIKE/1-52
AEGDDPAKAAFDSLQASATEYIGYAWAMVVVIVGATIGIKLFKKFTSKA Q9T0Q9_BPFD/1-49
\end{verbatim}
\noindent Note that you can only add two alignments together if they
have the same number of rows.
\subsection{Alignments as arrays}
Depending on what you are doing, it can be more useful to turn the alignment
object into an array of letters -- and you can do this with NumPy:
%doctest examples lib:numpy
\begin{verbatim}
>>> import numpy as np
>>> from Bio import AlignIO
>>> alignment = AlignIO.read("PF05371_seed.sth", "stockholm")
>>> align_array = np.array([list(rec) for rec in alignment], np.character)
>>> align_array.shape
(7, 52)
\end{verbatim}
If you will be working heavily with the columns, you can tell NumPy to store
the array by column (as in Fortran) rather then its default of by row (as in C):
\begin{verbatim}
>>> align_array = np.array([list(rec) for rec in alignment], np.character, order="F")
\end{verbatim}
Note that this leaves the original Biopython alignment object and the NumPy array
in memory as separate objects - editing one will not update the other!
\section{Alignment Tools}
\label{sec:alignment-tools}
There are \emph{lots} of algorithms out there for aligning sequences, both pairwise alignments
and multiple sequence alignments. These calculations are relatively slow, and you generally
wouldn't want to write such an algorithm in Python. Instead, you can use Biopython to invoke
a command line tool on your behalf. Normally you would:
\begin{enumerate}
\item Prepare an input file of your unaligned sequences, typically this will be a FASTA file
which you might create using \verb|Bio.SeqIO| (see Chapter~\ref{chapter:Bio.SeqIO}).
\item Call the command line tool to process this input file, typically via one of Biopython's
command line wrappers (which we'll discuss here).
\item Read the output from the tool, i.e. your aligned sequences, typically using
\verb|Bio.AlignIO| (see earlier in this chapter).
\end{enumerate}
All the command line wrappers we're going to talk about in this chapter follow the same style.
You create a command line object specifying the options (e.g. the input filename and the
output filename), then invoke this command line via a Python operating system call (e.g.
using the \texttt{subprocess} module).
Most of these wrappers are defined in the \verb|Bio.Align.Applications| module:
\begin{verbatim}
>>> import Bio.Align.Applications
>>> dir(Bio.Align.Applications)
...
['ClustalwCommandline', 'DialignCommandline', 'MafftCommandline', 'MuscleCommandline',
'PrankCommandline', 'ProbconsCommandline', 'TCoffeeCommandline' ...]
\end{verbatim}
\noindent (Ignore the entries starting with an underscore -- these have
special meaning in Python.)
The module \verb|Bio.Emboss.Applications| has wrappers for some of the
\href{http://emboss.sourceforge.net/}{EMBOSS suite}, including
\texttt{needle} and \texttt{water}, which are described below in
Section~\ref{seq:emboss-needle-water}, and wrappers for the EMBOSS
packaged versions of the PHYLIP tools (which EMBOSS refer to as one
of their EMBASSY packages - third party tools with an EMBOSS style
interface).
We won't explore all these alignment tools here in the section, just a
sample, but the same principles apply.
\subsection{ClustalW}
\label{sec:align_clustal}
ClustalW is a popular command line tool for multiple sequence alignment
(there is also a graphical interface called ClustalX). Biopython's
\verb|Bio.Align.Applications| module has a wrapper for this alignment tool
(and several others).
Before trying to use ClustalW from within Python, you should first try running
the ClustalW tool yourself by hand at the command line, to familiarise
yourself the other options. You'll find the Biopython wrapper is very
faithful to the actual command line API:
\begin{verbatim}
>>> from Bio.Align.Applications import ClustalwCommandline
>>> help(ClustalwCommandline)
...
\end{verbatim}
For the most basic usage, all you need is to have a FASTA input file, such as
\href{http://biopython.org/DIST/docs/tutorial/examples/opuntia.fasta}{opuntia.fasta}
(available online or in the Doc/examples subdirectory of the Biopython source
code). This is a small FASTA file containing seven prickly-pear DNA sequences
(from the cactus family \textit{Opuntia}).
By default ClustalW will generate an alignment and guide tree file with names
based on the input FASTA file, in this case \texttt{opuntia.aln} and
\texttt{opuntia.dnd}, but you can override this or make it explicit:
%doctest
\begin{verbatim}
>>> from Bio.Align.Applications import ClustalwCommandline
>>> cline = ClustalwCommandline("clustalw2", infile="opuntia.fasta")
>>> print cline
clustalw2 -infile=opuntia.fasta
\end{verbatim}
Notice here we have given the executable name as \texttt{clustalw2},
indicating we have version two installed, which has a different filename to
version one (\texttt{clustalw}, the default). Fortunately both versions
support the same set of arguments at the command line (and indeed, should be
functionally identical).
You may find that even though you have ClustalW installed, the above command
doesn't work -- you may get a message about ``command not found'' (especially
on Windows). This indicated that the ClustalW executable is not on your PATH
(an environment variable, a list of directories to be searched). You can
either update your PATH setting to include the location of your copy of
ClustalW tools (how you do this will depend on your OS), or simply type in
the full path of the tool. For example:
%doctest
\begin{verbatim}
>>> import os
>>> from Bio.Align.Applications import ClustalwCommandline
>>> clustalw_exe = r"C:\Program Files\new clustal\clustalw2.exe"
>>> clustalw_cline = ClustalwCommandline(clustalw_exe, infile="opuntia.fasta")
\end{verbatim}
%Don't run it in the doctest
\begin{verbatim}
>>> assert os.path.isfile(clustalw_exe), "Clustal W executable missing"
>>> stdout, stderr = clustalw_cline()
\end{verbatim}
\noindent Remember, in Python strings \verb|\n| and \verb|\t| are by default
interpreted as a new line and a tab -- which is why we're put a letter
``r'' at the start for a raw string that isn't translated in this way.
This is generally good practice when specifying a Windows style file name.
Internally this uses the
\verb|subprocess| module which is now the recommended way to run another
program in Python. This replaces older options like the \verb|os.system()|
and the \verb|os.popen*| functions.
Now, at this point it helps to know about how command line tools ``work''.
When you run a tool at the command line, it will often print text output
directly to screen. This text can be captured or redirected, via
two ``pipes'', called standard output (the normal results) and standard
error (for error messages and debug messages). There is also standard
input, which is any text fed into the tool. These names get shortened
to stdin, stdout and stderr. When the tool finishes, it has a return
code (an integer), which by convention is zero for success.
When you run the command line tool like this via the Biopython wrapper,
it will wait for it to finish, and check the return code. If this is
non zero (indicating an error), an exception is raised. The wrapper
then returns two strings, stdout and stderr.
In the case of ClustalW, when run at the command line all the important
output is written directly to the output files. Everything normally printed to
screen while you wait (via stdout or stderr) is boring and can be
ignored (assuming it worked).
What we care about are the two output files, the alignment and the guide
tree. We didn't tell ClustalW what filenames to use, but it defaults to
picking names based on the input file. In this case the output should be
in the file \verb|opuntia.aln|.
You should be able to work out how to read in the alignment using
\verb|Bio.AlignIO| by now:
\begin{verbatim}
>>> from Bio import AlignIO
>>> align = AlignIO.read("opuntia.aln", "clustal")
>>> print align
SingleLetterAlphabet() alignment with 7 rows and 906 columns
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191
\end{verbatim}
In case you are interested (and this is an aside from the main thrust of this
chapter), the \texttt{opuntia.dnd} file ClustalW creates is just a standard
Newick tree file, and \verb|Bio.Phylo| can parse these:
\begin{verbatim}
>>> from Bio import Phylo
>>> tree = Phylo.read("opuntia.dnd", "newick")
>>> Phylo.draw_ascii(tree)
_______________ gi|6273291|gb|AF191665.1|AF191665
__________________________|
| | ______ gi|6273290|gb|AF191664.1|AF191664
| |__|
| |_____ gi|6273289|gb|AF191663.1|AF191663
|
_|_________________ gi|6273287|gb|AF191661.1|AF191661
|
|__________ gi|6273286|gb|AF191660.1|AF191660
|
| __ gi|6273285|gb|AF191659.1|AF191659
|___|
| gi|6273284|gb|AF191658.1|AF191658
\end{verbatim}
\noindent Chapter \ref{sec:Phylo} covers Biopython's support for phylogenetic trees in more
depth.
\subsection{MUSCLE}
MUSCLE is a more recent multiple sequence alignment tool than ClustalW, and
Biopython also has a wrapper for it under the \verb|Bio.Align.Applications|
module. As before, we recommend you try using MUSCLE from the command line before
trying it from within Python, as the Biopython wrapper is very faithful to the
actual command line API:
\begin{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> help(MuscleCommandline)
...
\end{verbatim}
For the most basic usage, all you need is to have a FASTA input file, such as
\href{http://biopython.org/DIST/docs/tutorial/examples/opuntia.fasta}{opuntia.fasta}
(available online or in the Doc/examples subdirectory of the Biopython source
code). You can then tell MUSCLE to read in this FASTA file, and write the
alignment to an output file:
%doctest
\begin{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.txt")
>>> print cline
muscle -in opuntia.fasta -out opuntia.txt
\end{verbatim}
Note that MUSCLE uses ``-in'' and ``-out'' but in Biopython we have to use
``input'' and ``out'' as the keyword arguments or property names. This is
because ``in'' is a reserved word in Python.
By default MUSCLE will output the alignment as a FASTA file (using gapped
sequences). The \verb|Bio.AlignIO| module should be able to read this
alignment using \texttt{format="fasta"}.
You can also ask for ClustalW-like output:
%doctest
\begin{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clw=True)
>>> print cline
muscle -in opuntia.fasta -out opuntia.aln -clw
\end{verbatim}
Or, strict ClustalW output where the original ClustalW header line is
used for maximum compatibility:
%doctest
\begin{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> cline = MuscleCommandline(input="opuntia.fasta", out="opuntia.aln", clwstrict=True)
>>> print cline
muscle -in opuntia.fasta -out opuntia.aln -clwstrict
\end{verbatim}
\noindent The \verb|Bio.AlignIO| module should be able to read these alignments
using \texttt{format="clustal"}.
MUSCLE can also output in GCG MSF format (using the \texttt{msf} argument), but
Biopython can't currently parse that, or using HTML which would give a human
readable web page (not suitable for parsing).
You can also set the other optional parameters, for example the maximum number
of iterations. See the built in help for details.
You would then run MUSCLE command line string as described above for
ClustalW, and parse the output using \verb|Bio.AlignIO| to get an
alignment object.
\subsection{MUSCLE using stdout}
Using a MUSCLE command line as in the examples above will write the alignment
to a file. This means there will be no important information written to the
standard out (stdout) or standard error (stderr) handles. However, by default
MUSCLE will write the alignment to standard output (stdout). We can take
advantage of this to avoid having a temporary output file! For example:
%doctest
\begin{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> print muscle_cline
muscle -in opuntia.fasta
\end{verbatim}
If we run this via the wrapper, we get back the output as a string. In order
to parse this we can use \verb|StringIO| to turn it into a handle.
Remember that MUSCLE defaults to using FASTA as the output format:
\begin{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> stdout, stderr = muscle_cline()
>>> from StringIO import StringIO
>>> from Bio import AlignIO
>>> align = AlignIO.read(StringIO(stdout), "fasta")
>>> print align
SingleLetterAlphabet() alignment with 7 rows and 906 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191664
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191661
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658
\end{verbatim}
The above approach is fairly simple, but if you are dealing with very large output
text the fact that all of stdout and stderr is loaded into memory as a string can
be a potential drawback. Using the \verb|subprocess| module we can work directly
with handles instead:
\begin{verbatim}
>>> import subprocess
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(input="opuntia.fasta")
>>> child = subprocess.Popen(str(muscle_cline),
... stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... shell=(sys.platform!="win32"))
>>> from Bio import AlignIO
>>> align = AlignIO.read(child.stdout, "fasta")
>>> print align
SingleLetterAlphabet() alignment with 7 rows and 906 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191663
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191665
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191664
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191661
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191660
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191659
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191658
\end{verbatim}
\subsection{MUSCLE using stdin and stdout}
We don't actually \emph{need} to have our FASTA input sequences prepared in a file,
because by default MUSCLE will read in the input sequence from standard input!
Note this is a bit more advanced and fiddly, so don't bother with this technique
unless you need to.
First, we'll need some unaligned sequences in memory as \verb|SeqRecord| objects.
For this demonstration I'm going to use a filtered version of the original FASTA
file (using a generator expression), taking just six of the seven sequences:
%doctest
\begin{verbatim}
>>> from Bio import SeqIO
>>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
\end{verbatim}
Then we create the MUSCLE command line, leaving the input and output to their
defaults (stdin and stdout). I'm also going to ask for strict ClustalW format
as for the output.
%doctest
\begin{verbatim}
>>> from Bio.Align.Applications import MuscleCommandline
>>> muscle_cline = MuscleCommandline(clwstrict=True)
>>> print muscle_cline
muscle -clwstrict
\end{verbatim}
Now for the fiddly bits using the \verb|subprocess| module, stdin and stdout:
\begin{verbatim}
>>> import subprocess
>>> import sys
>>> child = subprocess.Popen(str(cline),
... stdin=subprocess.PIPE,
... stdout=subprocess.PIPE,
... stderr=subprocess.PIPE,
... shell=(sys.platform!="win32"))
\end{verbatim}
That should start MUSCLE, but it will be sitting waiting for its FASTA input
sequences, which we must supply via its stdin handle:
\begin{verbatim}
>>> SeqIO.write(records, child.stdin, "fasta")
6
>>> child.stdin.close()
\end{verbatim}
After writing the six sequences to the handle, MUSCLE will still be waiting
to see if that is all the FASTA sequences or not -- so we must signal that
this is all the input data by closing the handle. At that point MUSCLE should
start to run, and we can ask for the output:
\begin{verbatim}
>>> from Bio import AlignIO
>>> align = AlignIO.read(child.stdout, "clustal")
>>> print align
SingleLetterAlphabet() alignment with 6 rows and 900 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF19166
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF19165
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF19165
\end{verbatim}
Wow! There we are with a new alignment of just the six records, without having created
a temporary FASTA input file, or a temporary alignment output file. However, a word of
caution: Dealing with errors with this style of calling external programs is much more
complicated.
It also becomes far harder to diagnose problems, because you can't try running MUSCLE
manually outside of Biopython (because you don't have the input file to supply).
There can also be subtle cross platform issues (e.g. Windows versus Linux), and how
you run your script can have an impact (e.g. at the command line, from IDLE or an
IDE, or as a GUI script). These are all generic Python issues though, and not
specific to Biopython.
If you find working directly with \texttt{subprocess} like this scary, there is an
alternative. If you execute the tool with \texttt{muscle\_cline()} you can supply
any standard input as a big string, \texttt{muscle\_cline(stdin=...)}. So,
provided your data isn't very big, you can prepare the FASTA input in memory as
a string using \texttt{StringIO} (see Section~\ref{sec:appendix-handles}):
%doctest
\begin{verbatim}
>>> from Bio import SeqIO
>>> records = (r for r in SeqIO.parse("opuntia.fasta", "fasta") if len(r) < 900)
>>> from StringIO import StringIO
>>> handle = StringIO()
>>> SeqIO.write(records, handle, "fasta")
6
>>> data = handle.getvalue()
\end{verbatim}
\noindent You can then run the tool and parse the alignment as follows:
%not a doctest as can't assume the MUSCLE binary is present
\begin{verbatim}
>>> stdout, stderr = muscle_cline(stdin=data)
>>> from Bio import AlignIO
>>> align = AlignIO.read(StringIO(stdout), "clustal")
>>> print align
SingleLetterAlphabet() alignment with 6 rows and 900 columns
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF19166
TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF19166
TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF19166
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF19165
TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF19165
\end{verbatim}
You might find this easier, but it does require more memory (RAM) for the strings
used for the input FASTA and output Clustal formatted data.
\subsection{EMBOSS needle and water}
\label{seq:emboss-needle-water}
The \href{http://emboss.sourceforge.net/}{EMBOSS} suite includes the \texttt{water} and
\texttt{needle} tools for Smith-Waterman algorithm local alignment, and Needleman-Wunsch
global alignment. The tools share the same style interface, so switching between the two
is trivial -- we'll just use \texttt{needle} here.
Suppose you want to do a global pairwise alignment between two sequences, prepared in
FASTA format as follows:
\begin{verbatim}
>HBA_HUMAN
MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHG
KKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTP
AVHASLDKFLASVSTVLTSKYR
\end{verbatim}
\noindent in a file \texttt{alpha.fasta}, and secondly in a file \texttt{beta.fasta}:
\begin{verbatim}
>HBB_HUMAN
MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLSTPDAVMGNPK
VKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFG
KEFTPPVQAAYQKVVAGVANALAHKYH
\end{verbatim}
Let's start by creating a complete \texttt{needle} command line object in one go:
%doctest
\begin{verbatim}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> needle_cline = NeedleCommandline(asequence="alpha.faa", bsequence="beta.faa",
... gapopen=10, gapextend=0.5, outfile="needle.txt")
>>> print needle_cline
needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5
\end{verbatim}
Why not try running this by hand at the command prompt? You should see it does a
pairwise comparison and records the output in the file \texttt{needle.txt} (in the
default EMBOSS alignment file format).
Even if you have EMBOSS installed, running this command may not work -- you
might get a message about ``command not found'' (especially on Windows). This
probably means that the EMBOSS tools are not on your PATH environment
variable. You can either update your PATH setting, or simply tell Biopython
the full path to the tool, for example:
%doctest
\begin{verbatim}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> needle_cline = NeedleCommandline(r"C:\EMBOSS\needle.exe",
... asequence="alpha.faa", bsequence="beta.faa",
... gapopen=10, gapextend=0.5, outfile="needle.txt")
\end{verbatim}
\noindent Remember in Python that for a default string \verb|\n| or \verb|\t| means a
new line or a tab -- which is why we're put a letter ``r'' at the start for a raw string.
At this point it might help to try running the EMBOSS tools yourself by hand at the
command line, to familiarise yourself the other options and compare them to the
Biopython help text:
\begin{verbatim}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> help(NeedleCommandline)
...
\end{verbatim}
Note that you can also specify (or change or look at) the settings like this:
%doctest
\begin{verbatim}
>>> from Bio.Emboss.Applications import NeedleCommandline
>>> needle_cline = NeedleCommandline()
>>> needle_cline.asequence="alpha.faa"
>>> needle_cline.bsequence="beta.faa"
>>> needle_cline.gapopen=10
>>> needle_cline.gapextend=0.5
>>> needle_cline.outfile="needle.txt"
>>> print needle_cline
needle -outfile=needle.txt -asequence=alpha.faa -bsequence=beta.faa -gapopen=10 -gapextend=0.5
>>> print needle_cline.outfile
needle.txt
\end{verbatim}
Next we want to use Python to run this command for us. As explained above,
for full control, we recommend you use the built in Python \texttt{subprocess}
module, but for simple usage the wrapper object usually suffices:
\begin{verbatim}
>>> stdout, stderr = needle_cline()
>>> print stdout + stderr
Needleman-Wunsch global alignment of two sequences
\end{verbatim}
Next we can load the output file with \verb|Bio.AlignIO| as
discussed earlier in this chapter, as the \texttt{emboss} format:
\begin{verbatim}
>>> from Bio import AlignIO
>>> align = AlignIO.read("needle.txt", "emboss")
>>> print align
SingleLetterAlphabet() alignment with 2 rows and 149 columns
MV-LSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTY...KYR HBA_HUMAN
MVHLTPEEKSAVTALWGKV--NVDEVGGEALGRLLVVYPWTQRF...KYH HBB_HUMAN
\end{verbatim}
In this example, we told EMBOSS to write the output to a file, but you
\emph{can} tell it to write the output to stdout instead (useful if you
don't want a temporary output file to get rid of -- use
\texttt{stdout=True} rather than the \texttt{outfile} argument), and
also to read \emph{one} of the one of the inputs from stdin (e.g.
\texttt{asequence="stdin"}, much like in the MUSCLE example in the
section above).
This has only scratched the surface of what you can do with \texttt{needle}
and \texttt{water}. One useful trick is that the second file can contain
multiple sequences (say five), and then EMBOSS will do five pairwise
alignments.
Note - Biopython includes its own pairwise alignment code in the \verb|Bio.pairwise2|
module (written in C for speed, but with a pure Python fallback available too). This
doesn't work with alignment objects, so we have not covered it within this chapter.
See the module's docstring (built in help) for details.
\chapter{BLAST}
\label{chapter:blast}
Hey, everybody loves BLAST right? I mean, geez, how can get it get any easier to do comparisons between one of your sequences and every other sequence in the known world? But, of course, this section isn't about how cool BLAST is, since we already know that. It is about the problem with BLAST -- it can be really difficult to deal with the volume of data generated by large runs, and to automate BLAST runs in general.
Fortunately, the Biopython folks know this only too well, so they've developed lots of tools for dealing with BLAST and making things much easier. This section details how to use these tools and do useful things with them.
Dealing with BLAST can be split up into two steps, both of which can be done from within Biopython.
Firstly, running BLAST for your query sequence(s), and getting some output.
Secondly, parsing the BLAST output in Python for further analysis.
Your first introduction to running BLAST was probably via the NCBI web-service.
In fact, there are lots of ways you can run BLAST, which can be categorised several ways.
The most important distinction is running BLAST locally (on your own machine),
and running BLAST remotely (on another machine, typically the NCBI servers).
We're going to start this chapter by invoking the NCBI online BLAST service
from within a Python script.
\emph{NOTE}: The following Chapter~\ref{chapter:searchio} describes
\verb|Bio.SearchIO|, an \emph{experimental} module in Biopython. We
intend this to ultimately replace the older \verb|Bio.Blast| module, as it
provides a more general framework handling other related sequence
searching tools as well. However, until that is declared stable, for
production code please continue to use the \verb|Bio.Blast| module
for dealing with NCBI BLAST.
\section{Running BLAST over the Internet}
\label{sec:running-www-blast}
We use the function \verb|qblast()| in the \verb|Bio.Blast.NCBIWWW| module
call the online version of BLAST. This has three non-optional arguments:
\begin{itemize}
\item The first argument is the blast program to use for the search, as a
lower case string. The options and descriptions of the programs are
available at \url{http://www.ncbi.nlm.nih.gov/BLAST/blast_program.shtml}.
Currently \verb|qblast| only works with blastn, blastp, blastx, tblast
and tblastx.
\item The second argument specifies the databases to search against. Again,
the options for this are available on the NCBI web pages at
\url{http://www.ncbi.nlm.nih.gov/BLAST/blast_databases.shtml}.
\item The third argument is a string containing your query sequence. This
can either be the sequence itself, the sequence in fasta format,
or an identifier like a GI number.
\end{itemize}
The \verb|qblast| function also take a number of other option arguments
which are basically analogous to the different parameters you can set
on the BLAST web page. We'll just highlight a few of them here:
\begin{itemize}
\item The \verb|qblast| function can return the BLAST results in various
formats, which you can choose with the optional \verb|format_type| keyword:
\verb|"HTML"|, \verb|"Text"|, \verb|"ASN.1"|, or \verb|"XML"|.
The default is \verb|"XML"|, as that is the format expected by the parser,
described in section~\ref{sec:parsing-blast} below.
\item The argument \verb|expect| sets the expectation or e-value threshold.
\end{itemize}
For more about the optional BLAST arguments, we refer you to the NCBI's own
documentation, or that built into Biopython:
\begin{verbatim}
>>> from Bio.Blast import NCBIWWW
>>> help(NCBIWWW.qblast)
...
\end{verbatim}
Note that the default settings on the NCBI BLAST website are not quite
the same as the defaults on QBLAST. If you get different results, you'll
need to check the parameters (e.g. the expectation value threshold and
the gap values).
For example, if you have a nucleotide sequence you want to search against
the nucleotide database (nt) using BLASTN, and you know the GI number of your
query sequence, you can use:
\begin{verbatim}
>>> from Bio.Blast import NCBIWWW
>>> result_handle = NCBIWWW.qblast("blastn", "nt", "8332116")
\end{verbatim}
Alternatively, if we have our query sequence already in a FASTA formatted
file, we just need to open the file and read in this record as a string,
and use that as the query argument:
\begin{verbatim}
>>> from Bio.Blast import NCBIWWW
>>> fasta_string = open("m_cold.fasta").read()
>>> result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)
\end{verbatim}
We could also have read in the FASTA file as a \verb|SeqRecord| and then
supplied just the sequence itself:
\begin{verbatim}
>>> from Bio.Blast import NCBIWWW
>>> from Bio import SeqIO
>>> record = SeqIO.read(open("m_cold.fasta"), format="fasta")
>>> result_handle = NCBIWWW.qblast("blastn", "nt", record.seq)
\end{verbatim}
Supplying just the sequence means that BLAST will assign an identifier
for your sequence automatically. You might prefer to use the
\verb|SeqRecord| object's format method to make a fasta string
(which will include the existing identifier):
\begin{verbatim}
>>> from Bio.Blast import NCBIWWW
>>> from Bio import SeqIO
>>> record = SeqIO.read(open("m_cold.fasta"), format="fasta")
>>> result_handle = NCBIWWW.qblast("blastn", "nt", record.format("fasta"))
\end{verbatim}
This approach makes more sense if you have your sequence(s) in a
non-FASTA file format which you can extract using \verb|Bio.SeqIO|
(see Chapter~\ref{chapter:Bio.SeqIO}).
Whatever arguments you give the \verb|qblast()| function, you should
get back your results in a handle object (by default in XML format).
The next step would be to parse the XML output into Python objects
representing the search results (Section~\ref{sec:parsing-blast}),
but you might want to save a local copy of the output file first.
I find this especially useful when debugging my code that extracts
info from the BLAST results (because re-running the online search
is slow and wastes the NCBI computer time).
\label{sec:saving-blast-output}
We need to be a bit careful since we can use \verb|result_handle.read()| to
read the BLAST output only once -- calling \verb|result_handle.read()| again
returns an empty string.
\begin{verbatim}
>>> save_file = open("my_blast.xml", "w")
>>> save_file.write(result_handle.read())
>>> save_file.close()
>>> result_handle.close()
\end{verbatim}
After doing this, the results are in the file \verb|my_blast.xml| and the
original handle has had all its data extracted (so we closed it). However,
the \verb|parse| function of the BLAST parser (described
in~\ref{sec:parsing-blast}) takes a file-handle-like object, so
we can just open the saved file for input:
\begin{verbatim}
>>> result_handle = open("my_blast.xml")
\end{verbatim}
Now that we've got the BLAST results back into a handle again, we are ready
to do something with them, so this leads us right into the parsing section
(see Section~\ref{sec:parsing-blast} below). You may want to jump ahead to
that now \ldots.
\section{Running BLAST locally}
\label{sec:running-local-blast}
\subsection{Introduction}
Running BLAST locally (as opposed to over the internet, see
Section~\ref{sec:running-www-blast}) has at least major two advantages:
\begin{itemize}
\item Local BLAST may be faster than BLAST over the internet;
\item Local BLAST allows you to make your own database to search for sequences against.
\end{itemize}
Dealing with proprietary or unpublished sequence data can be another reason to run BLAST
locally. You may not be allowed to redistribute the sequences, so submitting them to the
NCBI as a BLAST query would not be an option.
Unfortunately, there are some major drawbacks too -- installing all the bits and getting
it setup right takes some effort:
\begin{itemize}
\item Local BLAST requires command line tools to be installed.
\item Local BLAST requires (large) BLAST databases to be setup (and potentially kept up to date).
\end{itemize}
\noindent
To further confuse matters there are at least four different standalone BLAST packages,
and there are also other tools which can produce imitation BLAST output files, such as BLAT.
\subsection{Standalone NCBI ``legacy'' BLAST}
\href{http://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=Download}
{NCBI ``legacy'' BLAST} included command line tools \verb|blastall|, \verb|blastpgp| and
\verb|rpsblast|. This was the most widely used standalone BLAST tool up until its replacement
BLAST+ was released by the NCBI.
The \verb|Bio.Blast.Applications| module has wrappers for the ``legacy'' NCBI BLAST tools
like \verb|blastall|, \verb|blastpgp| and \verb|rpsblast|, and there are also helper
functions in \verb|Bio.Blast.NCBIStandalone|. These are now considered obsolete, and will
be deprecated and eventually removed from Biopython as people move over to the replacement
BLAST+ suite.
To try and avoid confusion, we will not cover calling these old tools from Biopython
in this tutorial. Have a look at the older edition of this tutorial included with
Biopython 1.52 if you are curious (look at the Tutorial PDF or HTML file in the Doc
directory within \texttt{biopython-1.52.tar.gz} or \texttt{biopython-1.52.zip}).
\subsection{Standalone NCBI BLAST+}
\href{http://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=Download}
{NCBI ``new'' BLAST+} was released in 2009. This replaces the old NCBI ``legacy'' BLAST
package. The \verb|Bio.Blast.Applications| module has wrappers for these ``new'' tools
like \verb|blastn|, \verb|blastp|, \verb|blastx|, \verb|tblastn|, \verb|tblastx|
(which all used to be handled by \verb|blastall|), \verb|psiblast|
(replacing \verb|blastpgp|) and \verb|rpsblast| and \verb|rpstblastn|
(which replace the old \verb|rpsblast|).
We don't include a wrapper for the \verb|makeblastdb| used in BLAST+ to build a
local BLAST database from FASTA file, nor the equivalent tool \verb|formatdb| in
``legacy'' BLAST.
This section will show briefly how to use these tools from within Python. If you have
already read or tried the alignment tool examples in Section~\ref{sec:alignment-tools}
this should all seem quite straightforward. First, we construct a command line string
(as you would type in at the command line prompt if running standalone BLAST by hand).
Then we can execute this command from within Python.
For example, taking a FASTA file of gene nucleotide sequences, you might want to
run a BLASTX (translation) search against the non-redundant (NR) protein database.
Assuming you (or your systems administrator) has downloaded and installed the NR
database, you might run:
\begin{verbatim}
blastx -query opuntia.fasta -db nr -out opuntia.xml -evalue 0.001 -outfmt 5
\end{verbatim}
This should run BLASTX against the NR database, using an expectation cut-off value
of $0.001$ and produce XML output to the specified file (which we can then parse).
On my computer this takes about six minutes - a good reason to save the output
to a file so you and repeat any analysis as needed.
From within Biopython we can use the NCBI BLASTX wrapper from the
\verb|Bio.Blast.Applications| module to build the command line string,
and run it:
\begin{verbatim}
>>> from Bio.Blast.Applications import NcbiblastxCommandline
>>> help(NcbiblastxCommandline)
...
>>> blastx_cline = NcbiblastxCommandline(query="opuntia.fasta", db="nr", evalue=0.001,
... outfmt=5, out="opuntia.xml")
>>> blastx_cline
NcbiblastxCommandline(cmd='blastx', out='opuntia.xml', outfmt=5, query='opuntia.fasta',
db='nr', evalue=0.001)
>>> print blastx_cline
blastx -out opuntia.xml -outfmt 5 -query opuntia.fasta -db nr -evalue 0.001
>>> stdout, stderr = blastx_cline()
\end{verbatim}
In this example there shouldn't be any output from BLASTX to the terminal,
so stdout and stderr should be empty. You may want to check the output file
\verb|opuntia.xml| has been created.
As you may recall from earlier examples in the tutorial, the \verb|opuntia.fasta|
contains seven sequences, so the BLAST XML output should contain multiple results.
Therefore use \verb|Bio.Blast.NCBIXML.parse()| to parse it as described below in
Section~\ref{sec:parsing-blast}.
\subsection{WU-BLAST and AB-BLAST}
You may also come across \href{http://blast.wustl.edu/}{Washington University BLAST}
(WU-BLAST), and its successor, \href{http://blast.advbiocomp.com}{Advanced Biocomputing
BLAST} (AB-BLAST, released in 2009, not free/open source). These packages include
the command line tools \verb|wu-blastall| and \verb|ab-blastall|.
Biopython does not currently provide wrappers for calling these tools, but should be able
to parse any NCBI compatible output from them.
\section{Parsing BLAST output}
\label{sec:parsing-blast}
As mentioned above, BLAST can generate output in various formats, such as
XML, HTML, and plain text. Originally, Biopython had parsers for BLAST
plain text and HTML output, as these were the only output formats offered
at the time. Unfortunately, the BLAST output in these formats kept changing,
each time breaking the Biopython parsers. Our HTML BLAST parser has been
removed, but the plain text BLAST parser is still available (see
Section~\ref{sec:parsing-blast-deprecated}). Use it at your own risk,
it may or may not work, depending on which BLAST version you're using.
As keeping up with changes in BLAST
became a hopeless endeavor, especially with users running different BLAST
versions, we now recommend to parse the output in XML format, which can be
generated by recent versions of BLAST. Not only is the XML output more stable
than the plain text and HTML output, it is also much easier to parse
automatically, making Biopython a whole lot more stable.
You can get BLAST output in XML format in various ways. For the parser, it
doesn't matter how the output was generated, as long as it is in the XML format.
\begin{itemize}
\item You can use Biopython to run BLAST over the internet, as described in
section~\ref{sec:running-www-blast}.
\item You can use Biopython to run BLAST locally, as described in
section~\ref{sec:running-local-blast}.
\item You can do the BLAST search yourself on the NCBI site through your
web browser, and then save the results. You need to choose XML as the format
in which to receive the results, and save the final BLAST page you get
(you know, the one with all of the interesting results!) to a file.
\item You can also run BLAST locally without using Biopython, and save
the output in a file. Again, you need to choose XML as the format in which
to receive the results.
\end{itemize}
The important point is that you do not have to use Biopython
scripts to fetch the data in order to be able to parse it.
Doing things in one of these ways, you then need to get a handle
to the results. In Python, a handle is just a nice general way of
describing input to any info source so that the info can be retrieved
using \verb|read()| and \verb|readline()| functions
(see Section~{sec:appendix-handles}).
If you followed the code above for interacting with BLAST through a
script, then you already have \verb|result_handle|, the handle to the
BLAST results. For example, using a GI number to do an online search:
\begin{verbatim}
>>> from Bio.Blast import NCBIWWW
>>> result_handle = NCBIWWW.qblast("blastn", "nt", "8332116")
\end{verbatim}
If instead you ran BLAST some other way, and have the
BLAST output (in XML format) in the file \verb|my_blast.xml|, all you
need to do is to open the file for reading:
\begin{verbatim}
>>> result_handle = open("my_blast.xml")
\end{verbatim}
Now that we've got a handle, we are ready to parse the output. The
code to parse it is really quite small. If you expect a single
BLAST result (i.e. you used a single query):
\begin{verbatim}
>>> from Bio.Blast import NCBIXML
>>> blast_record = NCBIXML.read(result_handle)
\end{verbatim}
\noindent or, if you have lots of results (i.e. multiple query sequences):
\begin{verbatim}
>>> from Bio.Blast import NCBIXML
>>> blast_records = NCBIXML.parse(result_handle)
\end{verbatim}
Just like \verb|Bio.SeqIO| and \verb|Bio.AlignIO|
(see Chapters~\ref{chapter:Bio.SeqIO} and~\ref{chapter:Bio.AlignIO}),
we have a pair of input functions, \verb|read| and \verb|parse|, where
\verb|read| is for when you have exactly one object, and \verb|parse|
is an iterator for when you can have lots of objects -- but instead of
getting \verb|SeqRecord| or \verb|MultipleSeqAlignment| objects, we
get BLAST record objects.
To be able to handle the situation where the BLAST file may be huge,
containing thousands of results, \verb|NCBIXML.parse()| returns an
iterator. In plain English, an iterator allows you to step through
the BLAST output, retrieving BLAST records one by one for each BLAST
search result:
\begin{verbatim}
>>> from Bio.Blast import NCBIXML
>>> blast_records = NCBIXML.parse(result_handle)
>>> blast_record = blast_records.next()
# ... do something with blast_record
>>> blast_record = blast_records.next()
# ... do something with blast_record
>>> blast_record = blast_records.next()
# ... do something with blast_record
>>> blast_record = blast_records.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
# No further records
\end{verbatim}
Or, you can use a \verb|for|-loop:
\begin{verbatim}
>>> for blast_record in blast_records:
... # Do something with blast_record
\end{verbatim}
Note though that you can step through the BLAST records only once.
Usually, from each BLAST record you would save the information that
you are interested in. If you want to save all returned BLAST records,
you can convert the iterator into a list:
\begin{verbatim}
>>> blast_records = list(blast_records)
\end{verbatim}
Now you can access each BLAST record in the list with an index as usual.
If your BLAST file is huge though, you may run into memory problems trying to
save them all in a list.
Usually, you'll be running one BLAST search at a time. Then, all you need
to do is to pick up the first (and only) BLAST record in \verb|blast_records|:
\begin{verbatim}
>>> from Bio.Blast import NCBIXML
>>> blast_records = NCBIXML.parse(result_handle)
>>> blast_record = blast_records.next()
\end{verbatim}
\noindent or more elegantly:
\begin{verbatim}
>>> from Bio.Blast import NCBIXML
>>> blast_record = NCBIXML.read(result_handle)
\end{verbatim}
I guess by now you're wondering what is in a BLAST record.
\section{The BLAST record class}
A BLAST Record contains everything you might ever want to extract from the
BLAST output. Right now we'll just show
an example of how to get some info out of the BLAST report, but if you
want something in particular that is not described here, look at the
info on the record class in detail, and take a gander into the code or
automatically generated documentation -- the docstrings have lots of
good info about what is stored in each piece of information.
To continue with our example, let's just print out some summary info
about all hits in our blast report greater than a particular
threshold. The following code does this:
\begin{verbatim}
>>> E_VALUE_THRESH = 0.04
>>> for alignment in blast_record.alignments:
... for hsp in alignment.hsps:
... if hsp.expect < E_VALUE_THRESH:
... print '****Alignment****'
... print 'sequence:', alignment.title
... print 'length:', alignment.length
... print 'e value:', hsp.expect
... print hsp.query[0:75] + '...'
... print hsp.match[0:75] + '...'
... print hsp.sbjct[0:75] + '...'
\end{verbatim}
This will print out summary reports like the following:
\begin{verbatim}
****Alignment****
sequence: >gb|AF283004.1|AF283004 Arabidopsis thaliana cold acclimation protein WCOR413-like protein
alpha form mRNA, complete cds
length: 783
e value: 0.034
tacttgttgatattggatcgaacaaactggagaaccaacatgctcacgtcacttttagtcccttacatattcctc...
||||||||| | ||||||||||| || |||| || || |||||||| |||||| | | |||||||| ||| ||...
tacttgttggtgttggatcgaaccaattggaagacgaatatgctcacatcacttctcattccttacatcttcttc...
\end{verbatim}
Basically, you can do anything you want to with the info in the BLAST
report once you have parsed it. This will, of course, depend on what
you want to use it for, but hopefully this helps you get started on
doing what you need to do!
An important consideration for extracting information from a BLAST report is the type of objects that the information is stored in. In Biopython, the parsers return \verb|Record| objects, either \verb|Blast| or \verb|PSIBlast| depending on what you are parsing. These objects are defined in \verb|Bio.Blast.Record| and are quite complete.
Here are my attempts at UML class diagrams for the \verb|Blast| and \verb|PSIBlast| record classes. If you are good at UML and see mistakes/improvements that can be made, please let me know. The Blast class diagram is shown in Figure~\ref{fig:blastrecord}.
\begin{htmlonly}
\label{fig:blastrecord}
\imgsrc[width=650, height=750]{images/BlastRecord.png}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/BlastRecord.png}
\caption{Class diagram for the Blast Record class representing all of the info in a BLAST report}
\label{fig:blastrecord}
\end{figure}
\end{latexonly}
The PSIBlast record object is similar, but has support for the rounds that are used in the iteration steps of PSIBlast. The class diagram for PSIBlast is shown in Figure~\ref{fig:psiblastrecord}.
\begin{htmlonly}
\label{fig:psiblastrecord}
\imgsrc[width=650, height=750]{images/PSIBlastRecord.png}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/PSIBlastRecord.png}
\caption{Class diagram for the PSIBlast Record class.}
\label{fig:psiblastrecord}
\end{figure}
\end{latexonly}
\section{Deprecated BLAST parsers}
\label{sec:parsing-blast-deprecated}
Older versions of Biopython had parsers for BLAST output in plain text or HTML
format. Over the years, we discovered that it is very hard to maintain these
parsers in working order. Basically, any small change to the BLAST output in
newly released BLAST versions tends to cause the plain text and HTML parsers
to break. We therefore recommend parsing BLAST output in XML format, as
described in section~\ref{sec:parsing-blast}.
Depending on which BLAST versions or programs you're using, our plain text BLAST parser may or may not work. Use it at your own risk!
\subsection{Parsing plain-text BLAST output}
The plain text BLAST parser is located in \verb|Bio.Blast.NCBIStandalone|.
As with the XML parser, we need to have a handle object that we can pass to the parser. The handle must implement the \verb|readline()| method and do this properly. The common ways to get such a handle are to either use the provided \verb|blastall| or \verb|blastpgp| functions to run the local blast, or to run a local blast via the command line, and then do something like the following:
\begin{verbatim}
>>> result_handle = open("my_file_of_blast_output.txt")
\end{verbatim}
Well, now that we've got a handle (which we'll call \verb|result_handle|),
we are ready to parse it. This can be done with the following code:
\begin{verbatim}
>>> from Bio.Blast import NCBIStandalone
>>> blast_parser = NCBIStandalone.BlastParser()
>>> blast_record = blast_parser.parse(result_handle)
\end{verbatim}
This will parse the BLAST report into a Blast Record class (either a Blast or a PSIBlast record, depending on what you are parsing) so that you can extract the information from it. In our case, let's just use print out a quick summary of all of the alignments greater than some threshold value.
\begin{verbatim}
>>> E_VALUE_THRESH = 0.04
>>> for alignment in blast_record.alignments:
... for hsp in alignment.hsps:
... if hsp.expect < E_VALUE_THRESH:
... print '****Alignment****'
... print 'sequence:', alignment.title
... print 'length:', alignment.length
... print 'e value:', hsp.expect
... print hsp.query[0:75] + '...'
... print hsp.match[0:75] + '...'
... print hsp.sbjct[0:75] + '...'
\end{verbatim}
If you also read the section~\ref{sec:parsing-blast} on parsing BLAST XML output, you'll notice that the above code is identical to what is found in that section. Once you parse something into a record class you can deal with it independent of the format of the original BLAST info you were parsing. Pretty snazzy!
Sure, parsing one record is great, but I've got a BLAST file with tons of records -- how can I parse them all? Well, fear not, the answer lies in the very next section.
\subsection{Parsing a plain-text BLAST file full of BLAST runs}
We can do this using the blast iterator. To set up an iterator, we first set up a parser, to parse our blast reports in Blast Record objects:
\begin{verbatim}
>>> from Bio.Blast import NCBIStandalone
>>> blast_parser = NCBIStandalone.BlastParser()
\end{verbatim}
Then we will assume we have a handle to a bunch of blast records, which we'll call \verb|result_handle|. Getting a handle is described in full detail above in the blast parsing sections.
Now that we've got a parser and a handle, we are ready to set up the iterator with the following command:
\begin{verbatim}
>>> blast_iterator = NCBIStandalone.Iterator(result_handle, blast_parser)
\end{verbatim}
The second option, the parser, is optional. If we don't supply a parser, then the iterator will just return the raw BLAST reports one at a time.
Now that we've got an iterator, we start retrieving blast records (generated by our parser) using \verb|next()|:
\begin{verbatim}
>>> blast_record = blast_iterator.next()
\end{verbatim}
Each call to next will return a new record that we can deal with. Now we can iterate through this records and generate our old favorite, a nice little blast report:
\begin{verbatim}
>>> for blast_record in blast_iterator:
... E_VALUE_THRESH = 0.04
... for alignment in blast_record.alignments:
... for hsp in alignment.hsps:
... if hsp.expect < E_VALUE_THRESH:
... print '****Alignment****'
... print 'sequence:', alignment.title
... print 'length:', alignment.length
... print 'e value:', hsp.expect
... if len(hsp.query) > 75:
... dots = '...'
... else:
... dots = ''
... print hsp.query[0:75] + dots
... print hsp.match[0:75] + dots
... print hsp.sbjct[0:75] + dots
\end{verbatim}
%Notice that \verb|b_iterator.next()| will return \verb|None| when it runs out of records to parse, so it is easy to iterate through the entire file with a while loop that checks for the existence of a record.
The iterator allows you to deal with huge blast records without any memory problems, since things are read in one at a time. I have parsed tremendously huge files without any problems using this.
%TODO - Remove this or update it for BLAST XML parser
\subsection{Finding a bad record somewhere in a huge plain-text BLAST file}
One really ugly problem that happens to me is that I'll be parsing a huge blast file for a while, and the parser will bomb out with a ValueError. This is a serious problem, since you can't tell if the ValueError is due to a parser problem, or a problem with the BLAST. To make it even worse, you have no idea where the parse failed, so you can't just ignore the error, since this could be ignoring an important data point.
We used to have to make a little script to get around this problem, but the \verb|Bio.Blast| module now includes a \verb|BlastErrorParser| which really helps make this easier. The \verb|BlastErrorParser| works very similar to the regular \verb|BlastParser|, but it adds an extra layer of work by catching ValueErrors that are generated by the parser, and attempting to diagnose the errors.
Let's take a look at using this parser -- first we define the file we are going to parse and the file to write the problem reports to:
\begin{verbatim}
>>> import os
>>> blast_file = os.path.join(os.getcwd(), "blast_out", "big_blast.out")
>>> error_file = os.path.join(os.getcwd(), "blast_out", "big_blast.problems")
\end{verbatim}
Now we want to get a \verb|BlastErrorParser|:
\begin{verbatim}
>>> from Bio.Blast import NCBIStandalone
>>> error_handle = open(error_file, "w")
>>> blast_error_parser = NCBIStandalone.BlastErrorParser(error_handle)
\end{verbatim}
Notice that the parser take an optional argument of a handle. If a handle is passed, then the parser will write any blast records which generate a ValueError to this handle. Otherwise, these records will not be recorded.
Now we can use the \verb|BlastErrorParser| just like a regular blast parser. Specifically, we might want to make an iterator that goes through our blast records one at a time and parses them with the error parser:
\begin{verbatim}
>>> result_handle = open(blast_file)
>>> iterator = NCBIStandalone.Iterator(result_handle, blast_error_parser)
\end{verbatim}
We can read these records one a time, but now we can catch and deal with errors that are due to problems with Blast (and not with the parser itself):
\begin{verbatim}
>>> try:
... next_record = iterator.next()
... except NCBIStandalone.LowQualityBlastError, info:
... print "LowQualityBlastError detected in id %s" % info[1]
\end{verbatim}
The \verb|.next()| method is normally called indirectly via a \verb|for|-loop.
Right now the \verb|BlastErrorParser| can generate the following errors:
\begin{itemize}
\item \verb|ValueError| -- This is the same error generated by the regular BlastParser, and is due to the parser not being able to parse a specific file. This is normally either due to a bug in the parser, or some kind of discrepancy between the version of BLAST you are using and the versions the parser is able to handle.
\item \verb|LowQualityBlastError| -- When BLASTing a sequence that is of really bad quality (for example, a short sequence that is basically a stretch of one nucleotide), it seems that Blast ends up masking out the entire sequence and ending up with nothing to parse. In this case it will produce a truncated report that causes the parser to generate a ValueError. \verb|LowQualityBlastError| is reported in these cases. This error returns an info item with the following information:
\begin{itemize}
\item \verb|item[0]| -- The error message
\item \verb|item[1]| -- The id of the input record that caused the error. This is really useful if you want to record all of the records that are causing problems.
\end{itemize}
\end{itemize}
As mentioned, with each error generated, the BlastErrorParser will write the offending record to the specified \verb|error_handle|. You can then go ahead and look and these and deal with them as you see fit. Either you will be able to debug the parser with a single blast report, or will find out problems in your blast runs. Either way, it will definitely be a useful experience!
Hopefully the \verb|BlastErrorParser| will make it much easier to debug and deal with large Blast files.
\section{Dealing with PSI-BLAST}
You can run the standalone version of PSI-BLAST (the legacy NCBI command line
tool \verb|blastpgp|, or its replacement \verb|psiblast|) using the wrappers
in \verb|Bio.Blast.Applications| module.
At the time of writing, the NCBI do not appear to support tools running a
PSI-BLAST search via the internet.
Note that the \verb|Bio.Blast.NCBIXML| parser can read the XML output from
current versions of PSI-BLAST, but information like which sequences in each
iteration is new or reused isn't present in the XML file.
If you care about this information you may have more joy with the plain text
output and the \verb|PSIBlastParser| in \verb|Bio.Blast.NCBIStandalone|.
\section{Dealing with RPS-BLAST}
You can run the standalone version of RPS-BLAST (either the legacy NCBI
command line tool \verb|rpsblast|, or its replacement with the same name)
using the wrappers in \verb|Bio.Blast.Applications| module.
At the time of writing, the NCBI do not appear to support tools running an
RPS-BLAST search via the internet.
You can use the \verb|Bio.Blast.NCBIXML| parser to read the XML output from
current versions of RPS-BLAST.
\chapter{BLAST and other sequence search tools (\textit{experimental code})}
\label{chapter:searchio}
\emph{WARNING}: This chapter of the Tutorial describes an \emph{experimental}
module in Biopython. It is being included in Biopython and documented
here in the tutorial in a pre-final state to allow a period of feedback
and refinement before we declare it stable. Until then the details will
probably change, and any scripts using the current \verb|Bio.SearchIO|
would need to be updated. Please keep this in mind! For stable code
working with NCBI BLAST, please continue to use Bio.Blast described
in the preceding Chapter~\ref{chapter:blast}.
Biological sequence identification is an integral part of bioinformatics.
Several tools are available for this, each with their own algorithms and
approaches, such as BLAST (arguably the most popular), FASTA, HMMER, and many
more. In general, these tools usually use your sequence to search a database of
potential matches. With the growing number of known sequences (hence the
growing number of potential matches), interpreting the results becomes
increasingly hard as there could be hundreds or even thousands of potential
matches. Naturally, manual interpretation of these searches' results is out of
the question. Moreover, you often need to work with several sequence search
tools, each with its own statistics, conventions, and output format. Imagine how
daunting it would be when you need to work with multiple sequences using
multiple search tools.
We know this too well ourselves, which is why we created the \verb|Bio.SearchIO|
submodule in Biopython. \verb|Bio.SearchIO| allows you to extract information
from your search results in a convenient way, while also dealing with the
different standards and conventions used by different search tools.
The name \verb|SearchIO| is a homage to BioPerl's module of the same name.
In this chapter, we'll go through the main features of \verb|Bio.SearchIO| to
show what it can do for you. We'll use two popular search tools along the way:
BLAST and BLAT. They are used merely for illustrative purposes, and you should
be able to adapt the workflow to any other search tools supported by
\verb|Bio.SearchIO| in a breeze. You're very welcome to follow along with the
search output files we'll be using. The BLAST output file can be downloaded
\href{http://biopython.org/SRC/Tests/Tutorial/my_blast.xml}{here},
and the BLAT output file
\href{http://biopython.org/SRC/Tests/Tutorial/my_blat.psl}{here}.
Both output files were generated using this sequence:
\begin{verbatim}
>mystery_seq
CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
\end{verbatim}
The BLAST result is an XML file generated using \verb|blastn| against the NCBI
\verb|refseq_rna| database. For BLAT, the sequence database was the February 2009
\verb|hg19| human genome draft and the output format is PSL.
We'll start from an introduction to the \verb|Bio.SearchIO| object model. The
model is the representation of your search results, thus it is core to
\verb|Bio.SearchIO| itself. After that, we'll check out the main functions in
\verb|Bio.SearchIO| that you may often use.
Now that we're all set, let's go to the first step: introducing the core
object model.
\section{The SearchIO object model}
\label{sec:searchio-model}
Despite the wildly differing output styles among many sequence search tools,
it turns out that their underlying concept is similar:
\begin{itemize}
\item The output file may contain results from one or more search queries.
\item In each search query, you will see one or more hits from the given
search database.
\item In each database hit, you will see one or more regions containing the
actual sequence alignment between your query sequence and the database
sequence.
\item Some programs like BLAT or Exonerate may further split these regions into
several alignment fragments (or blocks in BLAT and possibly exons in
exonerate). This is not something you always see, as programs like BLAST and
HMMER do not do this.
\end{itemize}
Realizing this generality, we decided use it as base for creating the
\verb|Bio.SearchIO| object model. The object model consists of a nested
hierarchy of Python objects, each one representing one concept outlined above.
These objects are:
\begin{itemize}
\item \verb|QueryResult|, to represent a single search query.
\item \verb|Hit|, to represent a single database hit. \verb|Hit| objects are
contained within \verb|QueryResult| and in each \verb|QueryResult| there is
zero or more \verb|Hit| objects.
\item \verb|HSP| (short for high-scoring pair), to represent region(s) of
significant alignments between query and hit sequences. \verb|HSP| objects
are contained within \verb|Hit| objects and each \verb|Hit| has one or more
\verb|HSP| objects.
\item \verb|HSPFragment|, to represent a single contiguous alignment between
query and hit sequences. \verb|HSPFragment| objects are contained within
\verb|HSP| objects. Most sequence search tools like BLAST and HMMER unify
\verb|HSP| and \verb|HSPFragment| objects as each \verb|HSP| will only have
a single \verb|HSPFragment|. However there are tools like BLAT and Exonerate
that produce \verb|HSP| containing multiple \verb|HSPFragment|. Don't worry
if this seems a tad confusing now, we'll elaborate more on these two objects
later on.
\end{itemize}
These four objects are the ones you will interact with when you use
\verb|Bio.SearchIO|. They are created using one of the main \verb|Bio.SearchIO|
methods: \verb|read|, \verb|parse|, \verb|index|, or \verb|index_db|. The
details of these methods are provided in later sections. For this section, we'll
only be using read and parse. These functions behave similarly to their
\verb|Bio.SeqIO| and \verb|Bio.AlignIO| counterparts:
\begin{itemize}
\item \verb|read| is used for search output files with a single query and
returns a \verb|QueryResult| object
\item \verb|parse| is used for search output files with multiple queries and
returns a generator that yields \verb|QueryResult| objects
\end{itemize}
With that settled, let's start probing each \verb|Bio.SearchIO| object,
beginning with \verb|QueryResult|.
\subsection{QueryResult}
\label{sec:searchio-qresult}
The QueryResult object represents a single search query and contains zero or
more Hit objects. Let's see what it looks like using the BLAST file we have:
%doctest ../Doc/examples
\begin{verbatim}
>>> from Bio import SearchIO
>>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
>>> print blast_qresult
Program: blastn (2.2.27+)
Query: 42291 (61)
mystery_seq
Target: refseq_rna
Hits: ---- ----- ----------------------------------------------------------
# # HSP ID + description
---- ----- ----------------------------------------------------------
0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52...
1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA...
2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ...
3 2 gi|301171322|ref|NR_035857.1| Pan troglodytes microRNA...
4 1 gi|301171267|ref|NR_035851.1| Pan troglodytes microRNA...
5 2 gi|262205330|ref|NR_030198.1| Homo sapiens microRNA 52...
6 1 gi|262205302|ref|NR_030191.1| Homo sapiens microRNA 51...
7 1 gi|301171259|ref|NR_035850.1| Pan troglodytes microRNA...
8 1 gi|262205451|ref|NR_030222.1| Homo sapiens microRNA 51...
9 2 gi|301171447|ref|NR_035871.1| Pan troglodytes microRNA...
10 1 gi|301171276|ref|NR_035852.1| Pan troglodytes microRNA...
11 1 gi|262205290|ref|NR_030188.1| Homo sapiens microRNA 51...
12 1 gi|301171354|ref|NR_035860.1| Pan troglodytes microRNA...
13 1 gi|262205281|ref|NR_030186.1| Homo sapiens microRNA 52...
14 2 gi|262205298|ref|NR_030190.1| Homo sapiens microRNA 52...
15 1 gi|301171394|ref|NR_035865.1| Pan troglodytes microRNA...
16 1 gi|262205429|ref|NR_030218.1| Homo sapiens microRNA 51...
17 1 gi|262205423|ref|NR_030217.1| Homo sapiens microRNA 52...
18 1 gi|301171401|ref|NR_035866.1| Pan troglodytes microRNA...
19 1 gi|270133247|ref|NR_032574.1| Macaca mulatta microRNA ...
20 1 gi|262205309|ref|NR_030193.1| Homo sapiens microRNA 52...
21 2 gi|270132717|ref|NR_032716.1| Macaca mulatta microRNA ...
22 2 gi|301171437|ref|NR_035870.1| Pan troglodytes microRNA...
23 2 gi|270133306|ref|NR_032587.1| Macaca mulatta microRNA ...
24 2 gi|301171428|ref|NR_035869.1| Pan troglodytes microRNA...
25 1 gi|301171211|ref|NR_035845.1| Pan troglodytes microRNA...
26 2 gi|301171153|ref|NR_035838.1| Pan troglodytes microRNA...
27 2 gi|301171146|ref|NR_035837.1| Pan troglodytes microRNA...
28 2 gi|270133254|ref|NR_032575.1| Macaca mulatta microRNA ...
29 2 gi|262205445|ref|NR_030221.1| Homo sapiens microRNA 51...
~~~
97 1 gi|356517317|ref|XM_003527287.1| PREDICTED: Glycine ma...
98 1 gi|297814701|ref|XM_002875188.1| Arabidopsis lyrata su...
99 1 gi|397513516|ref|XM_003827011.1| PREDICTED: Pan panisc...
\end{verbatim}
We've just begun to scratch the surface of the object model, but you can see that
there's already some useful information. By invoking \verb|print| on the
\verb|QueryResult| object, you can see:
\begin{itemize}
\item The program name and version (blastn version 2.2.27+)
\item The query ID, description, and its sequence length (ID is 42291,
description is `mystery\_seq', and it is 61 nucleotides long)
\item The target database to search against (refseq\_rna)
\item A quick overview of the resulting hits. For our query sequence, there are
100 potential hits (numbered 0--99 in the table). For each hit, we can also see
how many HSPs it contains, its ID, and a snippet of its description. Notice
here that \verb|Bio.SearchIO| truncates the hit table overview, by showing
only hits numbered 0--29, and then 97--99.
\end{itemize}
Now let's check our BLAT results using the same procedure as above:
%cont-doctest
\begin{verbatim}
>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
>>> print blat_qresult
Program: blat (<unknown version>)
Query: mystery_seq (61)
<unknown description>
Target: <unknown target>
Hits: ---- ----- ----------------------------------------------------------
# # HSP ID + description
---- ----- ----------------------------------------------------------
0 17 chr19 <unknown description>
\end{verbatim}
You'll immediately notice that there are some differences. Some of these are
caused by the way PSL format stores its details, as you'll see. The rest are
caused by the genuine program and target database differences between our BLAST
and BLAT searches:
\begin{itemize}
\item The program name and version. \verb|Bio.SearchIO| knows that the program
is BLAT, but in the output file there is no information regarding the
program version so it defaults to `<unknown version>'.
\item The query ID, description, and its sequence length. Notice here that these
details are slightly different from the ones we saw in BLAST. The ID is
`mystery\_seq' instead of 42991, there is no known description, but the query
length is still 61. This is actually a difference introduced by the file
formats themselves. BLAST sometimes creates its own query IDs and uses your
original ID as the sequence description.
\item The target database is not known, as it is not stated in the BLAT output
file.
\item And finally, the list of hits we have is completely different. Here, we
see that our query sequence only hits the `chr19' database entry, but in it
we see 17 HSP regions. This should not be surprising however, given that we
are using a different program, each with its own target database.
\end{itemize}
All the details you saw when invoking the \verb|print| method can be accessed
individually using Python's object attribute access notation (a.k.a. the dot
notation). There are also other format-specific attributes that you can access
using the same method.
%cont-doctest
\begin{verbatim}
>>> print "%s %s" % (blast_qresult.program, blast_qresult.version)
blastn 2.2.27+
>>> print "%s %s" % (blat_qresult.program, blat_qresult.version)
blat <unknown version>
>>> blast_qresult.param_evalue_threshold # blast-xml specific
10.0
\end{verbatim}
For a complete list of accessible attributes, you can check each format-specific
documentation. Here are the ones
\href{http://biopython.org/DIST/docs/api/Bio.SearchIO.BlastIO-module.html}{for BLAST}
and for
\href{http://biopython.org/DIST/docs/api/Bio.SearchIO.BlatIO-module.html}{BLAT}.
Having looked at using \verb|print| on \verb|QueryResult| objects, let's drill
down deeper. What exactly is a \verb|QueryResult|? In terms of Python objects,
\verb|QueryResult| is a hybrid between a list and a dictionary. In other words,
it is a container object with all the convenient features of lists and
dictionaries.
Like Python lists and dictionaries, \verb|QueryResult| objects are iterable.
Each iteration returns a \verb|Hit| object:
\begin{verbatim}
>>> for hit in blast_qresult:
... hit
Hit(id='gi|262205317|ref|NR_030195.1|', query_id='42291', 1 hsps)
Hit(id='gi|301171311|ref|NR_035856.1|', query_id='42291', 1 hsps)
Hit(id='gi|270133242|ref|NR_032573.1|', query_id='42291', 1 hsps)
Hit(id='gi|301171322|ref|NR_035857.1|', query_id='42291', 2 hsps)
Hit(id='gi|301171267|ref|NR_035851.1|', query_id='42291', 1 hsps)
...
\end{verbatim}
To check how many items (hits) a \verb|QueryResult| has, you can simply invoke
Python's \verb|len| method:
%cont-doctest
\begin{verbatim}
>>> len(blast_qresult)
100
>>> len(blat_qresult)
1
\end{verbatim}
Like Python lists, you can retrieve items (hits) from a \verb|QueryResult| using
the slice notation:
%cont-doctest
\begin{verbatim}
>>> blast_qresult[0] # retrieves the top hit
Hit(id='gi|262205317|ref|NR_030195.1|', query_id='42291', 1 hsps)
>>> blast_qresult[-1] # retrieves the last hit
Hit(id='gi|397513516|ref|XM_003827011.1|', query_id='42291', 1 hsps)
\end{verbatim}
To retrieve multiple hits, you can slice \verb|QueryResult| objects using the
slice notation as well. In this case, the slice will return a new
\verb|QueryResult| object containing only the sliced hits:
%cont-doctest
\begin{verbatim}
>>> blast_slice = blast_qresult[:3] # slices the first three hits
>>> print blast_slice
Program: blastn (2.2.27+)
Query: 42291 (61)
mystery_seq
Target: refseq_rna
Hits: ---- ----- ----------------------------------------------------------
# # HSP ID + description
---- ----- ----------------------------------------------------------
0 1 gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 52...
1 1 gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA...
2 1 gi|270133242|ref|NR_032573.1| Macaca mulatta microRNA ...
\end{verbatim}
Like Python dictionaries, you can also retrieve hits using the hit's ID. This is
particularly useful if you know a given hit ID exists within a search query
results:
%cont-doctest
\begin{verbatim}
>>> blast_qresult['gi|262205317|ref|NR_030195.1|']
Hit(id='gi|262205317|ref|NR_030195.1|', query_id='42291', 1 hsps)
\end{verbatim}
You can also get a full list of \verb|Hit| objects using \verb|hits| and a full
list of \verb|Hit| IDs using \verb|hit_keys|:
\begin{verbatim}
>>> blast_qresult.hits
[...] # list of all hits
>>> blast_qresult.hit_keys
[...] # list of all hit IDs
\end{verbatim}
What if you just want to check whether a particular hit is present in the query
results? You can do a simple Python membership test using the \verb|in| keyword:
%cont-doctest
\begin{verbatim}
>>> 'gi|262205317|ref|NR_030195.1|' in blast_qresult
True
>>> 'gi|262205317|ref|NR_030194.1|' in blast_qresult
False
\end{verbatim}
Sometimes, knowing whether a hit is present is not enough; you also want to know
the rank of the hit. Here, the \verb|index| method comes to the rescue:
%cont-doctest
\begin{verbatim}
>>> blast_qresult.index('gi|301171437|ref|NR_035870.1|')
22
\end{verbatim}
Remember that we're using Python's indexing style here, which is zero-based.
This means our hit above is ranked at no. 23, not 22.
Also, note that the hit rank you see here is based on the native hit ordering
present in the original search output file. Different search tools may order
these hits based on different criteria.
If the native hit ordering doesn't suit your taste, you can use the \verb|sort|
method of the \verb|QueryResult| object. It is very similar to Python's
\verb|list.sort| method, with the addition of an option to create a new sorted
\verb|QueryResult| object or not.
Here is an example of using \verb|QueryResult.sort| to sort the hits based on
each hit's full sequence length. For this particular sort, we'll set the
\verb|in_place| flag to \verb|False| so that sorting will return a new
\verb|QueryResult| object and leave our initial object unsorted. We'll also set
the \verb|reverse| flag to \verb|True| so that we sort in descending order.
%cont-doctest
\begin{verbatim}
>>> for hit in blast_qresult[:5]: # id and sequence length of the first five hits
... print hit.id, hit.seq_len
...
gi|262205317|ref|NR_030195.1| 61
gi|301171311|ref|NR_035856.1| 60
gi|270133242|ref|NR_032573.1| 85
gi|301171322|ref|NR_035857.1| 86
gi|301171267|ref|NR_035851.1| 80
>>> sort_key = lambda hit: hit.seq_len
>>> sorted_qresult = blast_qresult.sort(key=sort_key, reverse=True, in_place=False)
>>> for hit in sorted_qresult[:5]:
... print hit.id, hit.seq_len
...
gi|397513516|ref|XM_003827011.1| 6002
gi|390332045|ref|XM_776818.2| 4082
gi|390332043|ref|XM_003723358.1| 4079
gi|356517317|ref|XM_003527287.1| 3251
gi|356543101|ref|XM_003539954.1| 2936
\end{verbatim}
The advantage of having the \verb|in_place| flag here is that we're preserving
the native ordering, so we may use it again later. You should note that this is
not the default behavior of \verb|QueryResult.sort|, however, which is why we
needed to set the \verb|in_place| flag to \verb|True| explicitly.
At this point, you've known enough about \verb|QueryResult| objects to make it
work for you. But before we go on to the next object in the \verb|Bio.SearchIO|
model, let's take a look at two more sets of methods that could make it even
easier to work with \verb|QueryResult| objects: the \verb|filter| and \verb|map|
methods.
If you're familiar with Python's list comprehensions, generator expressions
or the built in \verb|filter| and \verb|map| functions,
you'll know how useful they are for working with list-like objects (if you're
not, check them out!). You can use these built in methods to manipulate
\verb|QueryResult| objects, but you'll end up with regular Python lists and lose
the ability to do more interesting manipulations.
That's why, \verb|QueryResult| objects provide its own flavor of
\verb|filter| and \verb|map| methods. Analogous to \verb|filter|, there are
\verb|hit_filter| and \verb|hsp_filter| methods. As their name implies, these
methods filter its \verb|QueryResult| object either on its \verb|Hit| objects
or \verb|HSP| objects. Similarly, analogous to \verb|map|, \verb|QueryResult|
objects also provide the \verb|hit_map| and \verb|hsp_map| methods. These
methods apply a given function to all hits or HSPs in a \verb|QueryResult|
object, respectively.
Let's see these methods in action, beginning with \verb|hit_filter|. This method
accepts a callback function that checks whether a given \verb|Hit| object passes
the condition you set or not. In other words, the function must accept as its
argument a single \verb|Hit| object and returns \verb|True| or \verb|False|.
Here is an example of using \verb|hit_filter| to filter out \verb|Hit| objects
that only have one HSP:
%cont-doctest
\begin{verbatim}
>>> filter_func = lambda hit: len(hit.hsps) > 1 # the callback function
>>> len(blast_qresult) # no. of hits before filtering
100
>>> filtered_qresult = blast_qresult.hit_filter(filter_func)
>>> len(filtered_qresult) # no. of hits after filtering
37
>>> for hit in filtered_qresult[:5]: # quick check for the hit lengths
... print hit.id, len(hit.hsps)
gi|301171322|ref|NR_035857.1| 2
gi|262205330|ref|NR_030198.1| 2
gi|301171447|ref|NR_035871.1| 2
gi|262205298|ref|NR_030190.1| 2
gi|270132717|ref|NR_032716.1| 2
\end{verbatim}
\verb|hsp_filter| works the same as \verb|hit_filter|, only instead of looking
at the \verb|Hit| objects, it performs filtering on the \verb|HSP| objects in
each hits.
As for the \verb|map| methods, they too accept a callback function as their
arguments. However, instead of returning \verb|True| or \verb|False|, the
callback function must return the modified \verb|Hit| or \verb|HSP| object
(depending on whether you're using \verb|hit_map| or \verb|hsp_map|).
Let's see an example where we're using \verb|hit_map| to rename the hit IDs:
%cont-doctest
\begin{verbatim}
>>> def map_func(hit):
... hit.id = hit.id.split('|')[3] # renames 'gi|301171322|ref|NR_035857.1|' to 'NR_035857.1'
... return hit
...
>>> mapped_qresult = blast_qresult.hit_map(map_func)
>>> for hit in mapped_qresult[:5]:
... print hit.id
NR_030195.1
NR_035856.1
NR_032573.1
NR_035857.1
NR_035851.1
\end{verbatim}
Again, \verb|hsp_map| works the same as \verb|hit_map|, but on \verb|HSP|
objects instead of \verb|Hit| objects.
\subsection{Hit}
\label{sec:searchio-hit}
\verb|Hit| objects represent all query results from a single database entry.
They are the second-level container in the \verb|Bio.SearchIO| object hierarchy.
You've seen that they are contained by \verb|QueryResult| objects, but they
themselves contain \verb|HSP| objects.
Let's see what they look like, beginning with our BLAST search:
%doctest ../Doc/examples
\begin{verbatim}
>>> from Bio import SearchIO
>>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
>>> blast_hit = blast_qresult[3] # fourth hit from the query result
\end{verbatim}
%HACK: because Py2.5 in windows output floating points slightly different
\begin{verbatim}
>>> print blast_hit
Query: 42291
mystery_seq
Hit: gi|301171322|ref|NR_035857.1| (86)
Pan troglodytes microRNA mir-520c (MIR520C), microRNA
HSPs: ---- -------- --------- ------ --------------- ---------------------
# E-value Bit score Span Query range Hit range
---- -------- --------- ------ --------------- ---------------------
0 8.9e-20 100.47 60 [1:61] [13:73]
1 3.3e-06 55.39 60 [0:60] [13:73]
\end{verbatim}
You see that we've got the essentials covered here:
\begin{itemize}
\item The query ID and description is present. A hit is always tied to a query,
so we want to keep track of the originating query as well. These values can
be accessed from a hit using the \verb|query_id| and
\verb|query_description| attributes.
\item We also have the unique hit ID, description, and full sequence lengths.
They can be accessed using \verb|id|, \verb|description|, and
\verb|seq_len|, respectively.
\item Finally, there's a table containing quick information about the HSPs this
hit contains. In each row, we've got the important HSP details listed: the
HSP index, its e-value, its bit score, its span (the alignment length
including gaps), its query coordinates, and its hit coordinates.
\end{itemize}
Now let's contrast this with the BLAT search. Remember that in the BLAT search we
had one hit with 17 HSPs.
%cont-doctest
\begin{verbatim}
>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
>>> blat_hit = blat_qresult[0] # the only hit
>>> print blat_hit
Query: mystery_seq
<unknown description>
Hit: chr19 (59128983)
<unknown description>
HSPs: ---- -------- --------- ------ --------------- ---------------------
# E-value Bit score Span Query range Hit range
---- -------- --------- ------ --------------- ---------------------
0 ? ? ? [0:61] [54204480:54204541]
1 ? ? ? [0:61] [54233104:54264463]
2 ? ? ? [0:61] [54254477:54260071]
3 ? ? ? [1:61] [54210720:54210780]
4 ? ? ? [0:60] [54198476:54198536]
5 ? ? ? [0:61] [54265610:54265671]
6 ? ? ? [0:61] [54238143:54240175]
7 ? ? ? [0:60] [54189735:54189795]
8 ? ? ? [0:61] [54185425:54185486]
9 ? ? ? [0:60] [54197657:54197717]
10 ? ? ? [0:61] [54255662:54255723]
11 ? ? ? [0:61] [54201651:54201712]
12 ? ? ? [8:60] [54206009:54206061]
13 ? ? ? [10:61] [54178987:54179038]
14 ? ? ? [8:61] [54212018:54212071]
15 ? ? ? [8:51] [54234278:54234321]
16 ? ? ? [8:61] [54238143:54238196]
\end{verbatim}
Here, we've got a similar level of detail as with the BLAST hit we saw earlier.
There are some differences worth explaining, though:
\begin{itemize}
\item The e-value and bit score column values. As BLAT HSPs do not have e-values
and bit scores, the display defaults to `?'.
\item What about the span column? The span values is meant to display the
complete alignment length, which consists of all residues and any gaps that
may be present. The PSL format do not have this information readily available
and \verb|Bio.SearchIO| does not attempt to try guess what it is, so we get a
`?' similar to the e-value and bit score columns.
\end{itemize}
In terms of Python objects, \verb|Hit| behaves almost the same as Python lists,
but contain \verb|HSP| objects exclusively. If you're familiar with lists, you
should encounter no difficulties working with the \verb|Hit| object.
Just like Python lists, \verb|Hit| objects are iterable, and each iteration
returns one \verb|HSP| object it contains:
%cont-doctest
\begin{verbatim}
>>> for hsp in blast_hit:
... hsp
HSP(hit_id='gi|301171322|ref|NR_035857.1|', query_id='42291', 1 fragments)
HSP(hit_id='gi|301171322|ref|NR_035857.1|', query_id='42291', 1 fragments)
\end{verbatim}
You can invoke \verb|len| on a \verb|Hit| to see how many \verb|HSP| objects it
has:
%cont-doctest
\begin{verbatim}
>>> len(blast_hit)
2
>>> len(blat_hit)
17
\end{verbatim}
You can use the slice notation on \verb|Hit| objects, whether to retrieve single
\verb|HSP| or multiple \verb|HSP| objects. Like \verb|QueryResult|, if you slice
for multiple \verb|HSP|, a new \verb|Hit| object will be returned containing
only the sliced \verb|HSP| objects:
%cont-doctest
\begin{verbatim}
>>> blat_hit[0] # retrieve single items
HSP(hit_id='chr19', query_id='mystery_seq', 1 fragments)
>>> sliced_hit = blat_hit[4:9] # retrieve multiple items
>>> len(sliced_hit)
5
>>> print sliced_hit
Query: mystery_seq
<unknown description>
Hit: chr19 (59128983)
<unknown description>
HSPs: ---- -------- --------- ------ --------------- ---------------------
# E-value Bit score Span Query range Hit range
---- -------- --------- ------ --------------- ---------------------
0 ? ? ? [0:60] [54198476:54198536]
1 ? ? ? [0:61] [54265610:54265671]
2 ? ? ? [0:61] [54238143:54240175]
3 ? ? ? [0:60] [54189735:54189795]
4 ? ? ? [0:61] [54185425:54185486]
\end{verbatim}
You can also sort the \verb|HSP| inside a \verb|Hit|, using the exact same
arguments like the sort method you saw in the \verb|QueryResult| object.
Finally, there are also the \verb|filter| and \verb|map| methods you can use
on \verb|Hit| objects. Unlike in the \verb|QueryResult| object, \verb|Hit|
objects only have one variant of \verb|filter| (\verb|Hit.filter|) and one
variant of \verb|map| (\verb|Hit.map|). Both of \verb|Hit.filter| and
\verb|Hit.map| work on the \verb|HSP| objects a \verb|Hit| has.
\subsection{HSP}
\label{sec:searchio-hsp}
\verb|HSP| (high-scoring pair) represents region(s) in the hit sequence that
contains significant alignment(s) to the query sequence. It contains the actual
match between your query sequence and a database entry. As this match is
determined by the sequence search tool's algorithms, the \verb|HSP| object
contains the bulk of the statistics computed by the search tool. This also makes
the distinction between \verb|HSP| objects from different search tools more
apparent compared to the differences you've seen in \verb|QueryResult| or
\verb|Hit| objects.
Let's see some examples from our BLAST and BLAT searches. We'll look at the
BLAST HSP first:
%doctest ../Doc/examples
\begin{verbatim}
>>> from Bio import SearchIO
>>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
>>> blast_hsp = blast_qresult[0][0] # first hit, first hsp
\end{verbatim}
%HACK: because Py2.5 in windows output floating points slightly different
\begin{verbatim}
>>> print blast_hsp
Query: 42291 mystery_seq
Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520...
Query range: [0:61] (1)
Hit range: [0:61] (1)
Quick stats: evalue 4.9e-23; bitscore 111.29
Fragments: 1 (61 columns)
Query - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Hit - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
\end{verbatim}
Just like \verb|QueryResult| and \verb|Hit|, invoking \verb|print| on an
\verb|HSP| shows its general details:
\begin{itemize}
\item There are the query and hit IDs and descriptions. We need these to
identify our \verb|HSP|.
\item We've also got the matching range of the query and hit sequences. The
slice notation we're using here is an indication that the range is displayed
using Python's indexing style (zero-based, half open). The number inside the
parenthesis denotes the strand. In this case, both sequences have the plus
strand.
\item Some quick statistics are available: the e-value and bitscore.
\item There is information about the HSP fragments. Ignore this for now; it will
be explained later on.
\item And finally, we have the query and hit sequence alignment itself.
\end{itemize}
These details can be accessed on their own using the dot notation, just like in
\verb|QueryResult| and \verb|Hit|:
%cont-doctest
\begin{verbatim}
>>> blast_hsp.query_range
(0, 61)
\end{verbatim}
%hack! since float display may be different across versions
\begin{verbatim}
>>> blast_hsp.evalue
4.91307e-23
\end{verbatim}
They're not the only attributes available, though. \verb|HSP| objects come with
a default set of properties that makes it easy to probe their various
details. Here are some examples:
%cont-doctest
\begin{verbatim}
>>> blast_hsp.hit_start # start coordinate of the hit sequence
0
>>> blast_hsp.query_span # how many residues in the query sequence
61
>>> blast_hsp.aln_span # how long the alignment is
61
\end{verbatim}
Check out the \verb|HSP|
\href{http://biopython.org/DIST/docs/api/Bio.SearchIO._model.hsp-module.html}{documentation}
for a full list of these predefined properties.
Furthermore, each sequence search tool usually computes its own statistics /
details for its \verb|HSP| objects. For example, an XML BLAST search also
outputs the number of gaps and identical residues. These attributes can be
accessed like so:
%cont-doctest
\begin{verbatim}
>>> blast_hsp.gap_num # number of gaps
0
>>> blast_hsp.ident_num # number of identical residues
61
\end{verbatim}
These details are format-specific; they may not be present in other formats.
To see which details are available for a given sequence search tool, you
should check the format's documentation in \verb|Bio.SearchIO|. Alternatively,
you may also use \verb|.__dict__.keys()| for a quick list of what's available:
\begin{verbatim}
>>> blast_hsp.__dict__.keys()
['bitscore', 'evalue', 'ident_num', 'gap_num', 'bitscore_raw', 'pos_num', '_items']
\end{verbatim}
Finally, you may have noticed that the \verb|query| and \verb|hit| attributes
of our HSP are not just regular strings:
%cont-doctest
\begin{verbatim}
>>> blast_hsp.query
SeqRecord(seq=Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG', DNAAlphabet()), id='42291', name='aligned query sequence', description='mystery_seq', dbxrefs=[])
>>> blast_hsp.hit
SeqRecord(seq=Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG', DNAAlphabet()), id='gi|262205317|ref|NR_030195.1|', name='aligned hit sequence', description='Homo sapiens microRNA 520b (MIR520B), microRNA', dbxrefs=[])
\end{verbatim}
They are \verb|SeqRecord| objects you saw earlier in
Section~\ref{chapter:SeqRecord}! This means that you can do all sorts of
interesting things you can do with \verb|SeqRecord| objects on \verb|HSP.query|
and/or \verb|HSP.hit|.
It should not surprise you now that the \verb|HSP| object has an
\verb|alignment| property which is a \verb|MultipleSeqAlignment| object:
%cont-doctest
\begin{verbatim}
>>> print blast_hsp.aln
DNAAlphabet() alignment with 2 rows and 61 columns
CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG 42291
CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG gi|262205317|ref|NR_030195.1|
\end{verbatim}
Having probed the BLAST HSP, let's now take a look at HSPs from our BLAT
results for a different kind of HSP. As usual, we'll begin by invoking
\verb|print| on it:
%cont-doctest
\begin{verbatim}
>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
>>> blat_hsp = blat_qresult[0][0] # first hit, first hsp
>>> print blat_hsp
Query: mystery_seq <unknown description>
Hit: chr19 <unknown description>
Query range: [0:61] (1)
Hit range: [54204480:54204541] (1)
Quick stats: evalue ?; bitscore ?
Fragments: 1 (? columns)
\end{verbatim}
Some of the outputs you may have already guessed. We have the query and hit IDs
and descriptions and the sequence coordinates. Values for evalue and bitscore is
`?' as BLAT HSPs do not have these attributes. But The biggest difference here
is that you don't see any sequence alignments displayed. If you look closer, PSL
formats themselves do not have any hit or query sequences, so
\verb|Bio.SearchIO| won't create any sequence or alignment objects. What happens
if you try to access \verb|HSP.query|, \verb|HSP.hit|, or \verb|HSP.aln|?
You'll get the default values for these attributes, which is \verb|None|:
%cont-doctest
\begin{verbatim}
>>> blat_hsp.hit is None
True
>>> blat_hsp.query is None
True
>>> blat_hsp.aln is None
True
\end{verbatim}
This does not affect other attributes, though. For example, you can still
access the length of the query or hit alignment. Despite not displaying any
attributes, the PSL format still have this information so \verb|Bio.SearchIO|
can extract them:
%cont-doctest
\begin{verbatim}
>>> blat_hsp.query_span # length of query match
61
>>> blat_hsp.hit_span # length of hit match
61
\end{verbatim}
Other format-specific attributes are still present as well:
%cont-doctest
\begin{verbatim}
>>> blat_hsp.score # PSL score
61
>>> blat_hsp.mismatch_num # the mismatch column
0
\end{verbatim}
So far so good? Things get more interesting when you look at another `variant'
of HSP present in our BLAT results. You might recall that in BLAT searches,
sometimes we get our results separated into `blocks'. These blocks are
essentially alignment fragments that may have some intervening sequence between
them.
Let's take a look at a BLAT HSP that contains multiple blocks to see how
\verb|Bio.SearchIO| deals with this:
%cont-doctest
\begin{verbatim}
>>> blat_hsp2 = blat_qresult[0][1] # first hit, second hsp
>>> print blat_hsp2
Query: mystery_seq <unknown description>
Hit: chr19 <unknown description>
Query range: [0:61] (1)
Hit range: [54233104:54264463] (1)
Quick stats: evalue ?; bitscore ?
Fragments: --- -------------- ---------------------- ----------------------
# Span Query range Hit range
--- -------------- ---------------------- ----------------------
0 ? [0:18] [54233104:54233122]
1 ? [18:61] [54264420:54264463]
\end{verbatim}
What's happening here? We still some essential details covered: the IDs and
descriptions, the coordinates, and the quick statistics are similar to what
you've seen before. But the fragments detail is all different. Instead of
showing `Fragments: 1', we now have a table with two data rows.
This is how \verb|Bio.SearchIO| deals with HSPs having multiple fragments. As
mentioned before, an HSP alignment may be separated by intervening sequences
into fragments. The intervening sequences are not part of the query-hit match,
so they should not be considered part of query nor hit sequence. However, they
do affect how we deal with sequence coordinates, so we can't ignore them.
Take a look at the hit coordinate of the HSP above. In the \verb|Hit range:| field,
we see that the coordinate is \verb|[54233104:54264463]|. But looking at the
table rows, we see that not the entire region spanned by this coordinate matches
our query. Specifically, the intervening region spans from \verb|54233122| to
\verb|54264420|.
Why then, is the query coordinates seem to be contiguous, you ask? This is
perfectly fine. In this case it means that the query match is contiguous (no
intervening regions), while the hit match is not.
All these attributes are accessible from the HSP directly, by the way:
%cont-doctest
\begin{verbatim}
>>> blat_hsp2.hit_range # hit start and end coordinates of the entire HSP
(54233104, 54264463)
>>> blat_hsp2.hit_range_all # hit start and end coordinates of each fragment
[(54233104, 54233122), (54264420, 54264463)]
>>> blat_hsp2.hit_span # hit span of the entire HSP
31359
>>> blat_hsp2.hit_span_all # hit span of each fragment
[18, 43]
>>> blat_hsp2.hit_inter_ranges # start and end coordinates of intervening regions in the hit sequence
[(54233122, 54264420)]
>>> blat_hsp2.hit_inter_spans # span of intervening regions in the hit sequence
[31298]
\end{verbatim}
Most of these attributes are not readily available from the PSL file we have,
but \verb|Bio.SearchIO| calculates them for you on the fly when you parse the
PSL file. All it needs are the start and end coordinates of each fragment.
What about the \verb|query|, \verb|hit|, and \verb|aln| attributes? If the
HSP has multiple fragments, you won't be able to use these attributes as they
only fetch single \verb|SeqRecord| or \verb|MultipleSeqAlignment| objects.
However, you can use their \verb|*_all| counterparts: \verb|query_all|,
\verb|hit_all|, and \verb|aln_all|. These properties will return a list containing
\verb|SeqRecord| or \verb|MultipleSeqAlignment| objects from each of the HSP
fragment. There are other attributes that behave similarly, i.e. they only work
for HSPs with one fragment. Check out the \verb|HSP| \href{http://biopython.org/DIST/docs/api/Bio.SearchIO._model.hsp-module.html}{documentation}
for a full list.
Finally, to check whether you have multiple fragments or not, you can use the
\verb|is_fragmented| property like so:
%cont-doctest
\begin{verbatim}
>>> blat_hsp2.is_fragmented # BLAT HSP with 2 fragments
True
>>> blat_hsp.is_fragmented # BLAT HSP from earlier, with one fragment
False
\end{verbatim}
Before we move on, you should also know that we can use the slice notation on
\verb|HSP| objects, just like \verb|QueryResult| or \verb|Hit| objects. When
you use this notation, you'll get an \verb|HSPFragment| object in return, the
last component of the object model.
\subsection{HSPFragment}
\label{sec:searchio-hspfragment}
\verb|HSPFragment| represents a single, contiguous match between the query and
hit sequences. You could consider it the core of the object model and search
result, since it is the presence of these fragments that determine whether your
search have results or not.
In most cases, you don't have to deal with \verb|HSPFragment| objects directly
since not that many sequence search tools fragment their HSPs. When you do have
to deal with them, what you should remember is that \verb|HSPFragment| objects
were written with to be as compact as possible. In most cases, they only contain
attributes directly related to sequences: strands, reading frames, alphabets,
coordinates, the sequences themselves, and their IDs and descriptions.
These attributes are readily shown when you invoke \verb|print| on an
\verb|HSPFragment|. Here's an example, taken from our BLAST search:
%doctest ../Doc/examples
\begin{verbatim}
>>> from Bio import SearchIO
>>> blast_qresult = SearchIO.read('my_blast.xml', 'blast-xml')
>>> blast_frag = blast_qresult[0][0][0] # first hit, first hsp, first fragment
>>> print blast_frag
Query: 42291 mystery_seq
Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520...
Query range: [0:61] (1)
Hit range: [0:61] (1)
Fragments: 1 (61 columns)
Query - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Hit - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
\end{verbatim}
At this level, the BLAT fragment looks quite similar to the BLAST fragment, save
for the query and hit sequences which are not present:
%cont-doctest
\begin{verbatim}
>>> blat_qresult = SearchIO.read('my_blat.psl', 'blat-psl')
>>> blat_frag = blat_qresult[0][0][0] # first hit, first hsp, first fragment
>>> print blat_frag
Query: mystery_seq <unknown description>
Hit: chr19 <unknown description>
Query range: [0:61] (1)
Hit range: [54204480:54204541] (1)
Fragments: 1 (? columns)
\end{verbatim}
In all cases, these attributes are accessible using our favorite dot notation.
Some examples:
%cont-doctest
\begin{verbatim}
>>> blast_frag.query_start # query start coordinate
0
>>> blast_frag.hit_strand # hit sequence strand
1
>>> blast_frag.hit # hit sequence, as a SeqRecord object
SeqRecord(seq=Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG', DNAAlphabet()), id='gi|262205317|ref|NR_030195.1|', name='aligned hit sequence', description='Homo sapiens microRNA 520b (MIR520B), microRNA', dbxrefs=[])
\end{verbatim}
\section{A note about standards and conventions}
\label{sec:searchio-standards}
Before we move on to the main functions, there is something you ought to know
about the standards \verb|Bio.SearchIO| uses. If you've worked with multiple
sequence search tools, you might have had to deal with the many different ways
each program deals with things like sequence coordinates. It might not have been
a pleasant experience as these search tools usually have their own standards.
For example, one tools might use one-based coordinates, while the other uses
zero-based coordinates. Or, one program might reverse the start and end
coordinates if the strand is minus, while others don't. In short, these often
creates unnecessary mess must be dealt with.
We realize this problem ourselves and we intend to address it in
\verb|Bio.SearchIO|. After all, one of the goals of \verb|Bio.SearchIO| is to
create a common, easy to use interface to deal with various search output files.
This means creating standards that extend beyond the object model you just saw.
Now, you might complain, "Not another standard!". Well, eventually we have to
choose one convention or the other, so this is necessary. Plus, we're not
creating something entirely new here; just adopting a standard we think is best
for a Python programmer (it is Biopython, after all).
There are three implicit standards that you can expect when working with
\verb|Bio.SearchIO|:
\begin{itemize}
\item The first one pertains to sequence coordinates. In \verb|Bio.SearchIO|,
all sequence coordinates follows Python's coordinate style: zero-based and
half open. For example, if in a BLAST XML output file the start and end
coordinates of an HSP are 10 and 28, they would become 9 and 28 in
\verb|Bio.SearchIO|. The start coordinate becomes 9 because Python indices
start from zero, while the end coordinate remains 28 as Python slices omit
the last item in an interval.
\item The second is on sequence coordinate orders. In \verb|Bio.SearchIO|, start
coordinates are always less than or equal to end coordinates. This isn't
always the case with all sequence search tools, as some of them have larger
start coordinates when the sequence strand is minus.
\item The last one is on strand and reading frame values. For strands, there are
only four valid choices: \verb|1| (plus strand), \verb|-1| (minus strand),
\verb|0| (protein sequences), and \verb|None| (no strand). For reading
frames, the valid choices are integers from \verb|-3| to \verb|3| and
\verb|None|.
\end{itemize}
Note that these standards only exist in \verb|Bio.SearchIO| objects. If you
write \verb|Bio.SearchIO| objects into an output format, \verb|Bio.SearchIO|
will use the format's standard for the output. It does not force its standard
over to your output file.
\section{Reading search output files}
\label{sec:searchio-input}
There are two functions you can use for reading search output files into
\verb|Bio.SearchIO| objects: \verb|read| and \verb|parse|. They're essentially
similar to \verb|read| and \verb|parse| functions in other submodules like
\verb|Bio.SeqIO| or \verb|Bio.AlignIO|. In both cases, you need to supply the
search output file name and the file format name, both as Python strings. You
can check the documentation for a list of format names \verb|Bio.SearchIO|
recognizes.
\verb|Bio.SearchIO.read| is used for reading search output files with only one
query and returns a \verb|QueryResult| object. You've seen \verb|read| used in
our previous examples. What you haven't seen is that \verb|read| may also accept
additional keyword arguments, depending on the file format.
Here are some examples. In the first one, we use \verb|read| just like
previously to read a BLAST tabular output file. In the second one, we use a
keyword argument to modify so it parses the BLAST tabular variant with comments
in it:
%doctest ../Tests/Blast
\begin{verbatim}
>>> from Bio import SearchIO
>>> qresult = SearchIO.read('tab_2226_tblastn_003.txt', 'blast-tab')
>>> qresult
QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
>>> qresult2 = SearchIO.read('tab_2226_tblastn_007.txt', 'blast-tab', comments=True)
>>> qresult2
QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
\end{verbatim}
These keyword arguments differs among file formats. Check the format
documentation to see if it has keyword arguments that modifies its parser's
behavior.
As for the \verb|Bio.SearchIO.parse|, it is used for reading search output
files with any number of queries. The function returns a generator object that
yields a \verb|QueryResult| object in each iteration. Like
\verb|Bio.SearchIO.read|, it also accepts format-specific keyword arguments:
%doctest ../Tests/Blast
\begin{verbatim}
>>> from Bio import SearchIO
>>> qresults = SearchIO.parse('tab_2226_tblastn_001.txt', 'blast-tab')
>>> for qresult in qresults:
... print qresult.id
gi|16080617|ref|NP_391444.1|
gi|11464971:4-101
>>> qresults2 = SearchIO.parse('tab_2226_tblastn_005.txt', 'blast-tab', comments=True)
>>> for qresult in qresults2:
... print qresult.id
random_s00
gi|16080617|ref|NP_391444.1|
gi|11464971:4-101
\end{verbatim}
\section{Dealing with large search output files with indexing}
\label{sec:searchio-index}
Sometimes, you're handed a search output file containing hundreds or thousands
of queries that you need to parse. You can of course use
\verb|Bio.SearchIO.parse| for this file, but that would be grossly inefficient
if you need to access only a few of the queries. This is because \verb|parse|
will parse all queries it sees before it fetches your query of interest.
In this case, the ideal choice would be to index the file using
\verb|Bio.SearchIO.index| or \verb|Bio.SearchIO.index_db|. If the names sound
familiar, it's because you've seen them before in Section~\ref{sec:SeqIO-index}.
These functions also behave similarly to their \verb|Bio.SeqIO| counterparts,
with the addition of format-specific keyword arguments.
Here are some examples. You can use \verb|index| with just the filename and
format name:
%doctest ../Tests/Blast
\begin{verbatim}
>>> from Bio import SearchIO
>>> idx = SearchIO.index('tab_2226_tblastn_001.txt', 'blast-tab')
>>> sorted(idx.keys())
['gi|11464971:4-101', 'gi|16080617|ref|NP_391444.1|']
>>> idx['gi|16080617|ref|NP_391444.1|']
QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
\end{verbatim}
Or also with the format-specific keyword argument:
%cont-doctest
\begin{verbatim}
>>> idx = SearchIO.index('tab_2226_tblastn_005.txt', 'blast-tab', comments=True)
>>> sorted(idx.keys())
['gi|11464971:4-101', 'gi|16080617|ref|NP_391444.1|', 'random_s00']
>>> idx['gi|16080617|ref|NP_391444.1|']
QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
\end{verbatim}
Or with the \verb|key_function| argument, as in \verb|Bio.SeqIO|:
%cont-doctest
\begin{verbatim}
>>> key_function = lambda id: id.upper() # capitalizes the keys
>>> idx = SearchIO.index('tab_2226_tblastn_001.txt', 'blast-tab', key_function=key_function)
>>> sorted(idx.keys())
['GI|11464971:4-101', 'GI|16080617|REF|NP_391444.1|']
>>> idx['GI|16080617|REF|NP_391444.1|']
QueryResult(id='gi|16080617|ref|NP_391444.1|', 3 hits)
\end{verbatim}
\verb|Bio.SearchIO.index_db| works like as \verb|index|, only it writes the
query offsets into an SQLite database file.
\section{Writing and converting search output files}
\label{sec:searchio-write}
It is occasionally useful to be able to manipulate search results from an output
file and write it again to a new file. \verb|Bio.SearchIO| provides a
\verb|write| function that lets you do exactly this. It takes as its arguments
an iterable returning \verb|QueryResult| objects, the output filename to write
to, the format name to write to, and optionally some format-specific keyword
arguments. It returns a four-item tuple, which denotes the number or
\verb|QueryResult|, \verb|Hit|, \verb|HSP|, and \verb|HSPFragment| objects that
were written.
\begin{verbatim}
>>> from Bio import SearchIO
>>> qresults = SearchIO.parse('mirna.xml', 'blast-xml') # read XML file
>>> SearchIO.write(qresults, 'results.tab', 'blast-tab') # write to tabular file
(3, 239, 277, 277)
\end{verbatim}
You should note different file formats require different attributes of the
\verb|QueryResult|, \verb|Hit|, \verb|HSP| and \verb|HSPFragment| objects. If
these attributes are not present, writing won't work. In other words, you can't
always write to the output format that you want. For example, if you read a
BLAST XML file, you wouldn't be able to write the results to a PSL file as PSL
files require attributes not calculated by BLAST (e.g. the number of repeat
matches). You can always set these attributes manually, if you really want to
write to PSL, though.
Like \verb|read|, \verb|parse|, \verb|index|, and \verb|index_db|, \verb|write|
also accepts format-specific keyword arguments. Check out the documentation for
a complete list of formats \verb|Bio.SearchIO| can write to and their arguments.
Finally, \verb|Bio.SearchIO| also provides a \verb|convert| function, which is
simply a shortcut for \verb|Bio.SearchIO.parse| and \verb|Bio.SearchIO.write|.
Using the convert function, our example above would be:
\begin{verbatim}
>>> from Bio import SearchIO
>>> SearchIO.convert('mirna.xml', 'blast-xml', 'results.tab', 'blast-tab')
(3, 239, 277, 277)
\end{verbatim}
As \verb|convert| uses \verb|write|, it is only limited to format conversions
that have all the required attributes. Here, the BLAST XML file provides all the
default values a BLAST tabular file requires, so it works just fine. However,
other format conversions are less likely to work since you need to manually
assign the required attributes first.
\chapter{Accessing NCBI's Entrez databases}
\label{chapter:entrez}
Entrez (\url{http://www.ncbi.nlm.nih.gov/Entrez}) is a data retrieval system that provides users access to NCBI's databases such as PubMed, GenBank, GEO, and many others. You can access Entrez from a web browser to manually enter queries, or you can use Biopython's \verb+Bio.Entrez+ module for programmatic access to Entrez. The latter allows you for example to search PubMed or download GenBank records from within a Python script.
The \verb+Bio.Entrez+ module makes use of the Entrez Programming Utilities (also known as EUtils), consisting of eight tools that are described in detail on NCBI's page at \url{http://www.ncbi.nlm.nih.gov/entrez/utils/}.
Each of these tools corresponds to one Python function in the \verb+Bio.Entrez+ module, as described in the sections below. This module makes sure that the correct URL is used for the queries, and that not more than one request is made every three seconds, as required by NCBI.
The output returned by the Entrez Programming Utilities is typically in XML format. To parse such output, you have several options:
\begin{enumerate}
\item Use \verb+Bio.Entrez+'s parser to parse the XML output into a Python object;
\item Use the DOM (Document Object Model) parser in Python's standard library;
\item Use the SAX (Simple API for XML) parser in Python's standard library;
\item Read the XML output as raw text, and parse it by string searching and manipulation.
\end{enumerate}
For the DOM and SAX parsers, see the Python documentation. The parser in \verb+Bio.Entrez+ is discussed below.
NCBI uses DTD (Document Type Definition) files to describe the structure of the information contained in XML files. Most of the DTD files used by NCBI are included in the Biopython distribution. The \verb+Bio.Entrez+ parser makes use of the DTD files when parsing an XML file returned by NCBI Entrez.
Occasionally, you may find that the DTD file associated with a specific XML file is missing in the Biopython distribution. In particular, this may happen when NCBI updates its DTD files. If this happens, \verb+Entrez.read+ will show a warning message with the name and URL of the missing DTD file. The parser will proceed to access the missing DTD file through the internet, allowing the parsing of the XML file to continue. However, the parser is much faster if the DTD file is available locally. For this purpose, please download the DTD file from the URL in the warning message and place it in the directory \verb+...site-packages/Bio/Entrez/DTDs+, containing the other DTD files. If you don't have write access to this directory, you can also place the DTD file in \verb+~/.biopython/Bio/Entrez/DTDs+, where \verb+~+ represents your home directory. Since this directory is read before the directory \verb+...site-packages/Bio/Entrez/DTDs+, you can also put newer versions of DTD files there if the ones in \verb+...site-packages/Bio/Entrez/DTDs+ become outdated. Alternatively, if you installed Biopython from source, you can add the DTD file to the source code's \verb+Bio/Entrez/DTDs+ directory, and reinstall Biopython. This will install the new DTD file in the correct location together with the other DTD files.
The Entrez Programming Utilities can also generate output in other formats, such as the Fasta or GenBank file formats for sequence databases, or the MedLine format for the literature database, discussed in Section~\ref{sec:entrez-specialized-parsers}.
\section{Entrez Guidelines}
\label{sec:entrez-guidelines}
Before using Biopython to access the NCBI's online resources (via \verb|Bio.Entrez| or some of the other modules), please read the
\href{http://www.ncbi.nlm.nih.gov/books/NBK25497/#chapter2.Usage_Guidelines_and_Requiremen}{NCBI's Entrez User Requirements}.
If the NCBI finds you are abusing their systems, they can and will ban your access!
To paraphrase:
\begin{itemize}
\item For any series of more than 100 requests, do this at weekends or outside USA peak times. This is up to you to obey.
\item Use the \url{http://eutils.ncbi.nlm.nih.gov} address, not the standard NCBI Web address. Biopython uses this web address.
\item Make no more than three requests every seconds (relaxed from at most one request every three seconds in early 2009). This is automatically enforced by Biopython.
\item Use the optional email parameter so the NCBI can contact you if there is a problem. You can either explicitly set this as a parameter with each call to Entrez (e.g. include {\tt email="[email protected]"} in the argument list), or you can set a global email address:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]"
\end{verbatim}
{\tt Bio.Entrez} will then use this email address with each call to Entrez. The {\tt example.com} address is a reserved domain name specifically for documentation (RFC 2606). Please DO NOT use a random email -- it's better not to give an email at all. The email parameter will be mandatory from June 1, 2010. In case of excessive usage, NCBI will attempt to contact a user at the e-mail address provided prior to blocking access to the E-utilities.
\item If you are using Biopython within some larger software suite, use the tool parameter to specify this. You can either explicitly set the tool name as a parameter with each call to Entrez (e.g. include {\tt tool="MyLocalScript"} in the argument list), or you can set a global tool name:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.tool = "MyLocalScript"
\end{verbatim}
The tool parameter will default to Biopython.
\item For large queries, the NCBI also recommend using their session history feature (the WebEnv session cookie string, see Section~\ref{sec:entrez-webenv}). This is only slightly more complicated.
\end{itemize}
In conclusion, be sensible with your usage levels. If you plan to download lots of data, consider other options. For example, if you want easy access to all the human genes, consider fetching each chromosome by FTP as a GenBank file, and importing these into your own BioSQL database (see Section~\ref{sec:BioSQL}).
\section{EInfo: Obtaining information about the Entrez databases}
\label{sec:entrez-einfo}
EInfo provides field index term counts, last update, and available links for each of NCBI's databases. In addition, you can use EInfo to obtain a list of all database names accessible through the Entrez utilities:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.einfo()
>>> result = handle.read()
\end{verbatim}
The variable \verb+result+ now contains a list of databases in XML format:
\begin{verbatim}
>>> print result
<?xml version="1.0"?>
<!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD eInfoResult, 11 May 2002//EN"
"http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eInfo_020511.dtd">
<eInfoResult>
<DbList>
<DbName>pubmed</DbName>
<DbName>protein</DbName>
<DbName>nucleotide</DbName>
<DbName>nuccore</DbName>
<DbName>nucgss</DbName>
<DbName>nucest</DbName>
<DbName>structure</DbName>
<DbName>genome</DbName>
<DbName>books</DbName>
<DbName>cancerchromosomes</DbName>
<DbName>cdd</DbName>
<DbName>gap</DbName>
<DbName>domains</DbName>
<DbName>gene</DbName>
<DbName>genomeprj</DbName>
<DbName>gensat</DbName>
<DbName>geo</DbName>
<DbName>gds</DbName>
<DbName>homologene</DbName>
<DbName>journals</DbName>
<DbName>mesh</DbName>
<DbName>ncbisearch</DbName>
<DbName>nlmcatalog</DbName>
<DbName>omia</DbName>
<DbName>omim</DbName>
<DbName>pmc</DbName>
<DbName>popset</DbName>
<DbName>probe</DbName>
<DbName>proteinclusters</DbName>
<DbName>pcassay</DbName>
<DbName>pccompound</DbName>
<DbName>pcsubstance</DbName>
<DbName>snp</DbName>
<DbName>taxonomy</DbName>
<DbName>toolkit</DbName>
<DbName>unigene</DbName>
<DbName>unists</DbName>
</DbList>
</eInfoResult>
\end{verbatim}
Since this is a fairly simple XML file, we could extract the information it contains simply by string searching. Using \verb+Bio.Entrez+'s parser instead, we can directly parse this XML file into a Python object:
\begin{verbatim}
>>> from Bio import Entrez
>>> handle = Entrez.einfo()
>>> record = Entrez.read(handle)
\end{verbatim}
Now \verb+record+ is a dictionary with exactly one key:
\begin{verbatim}
>>> record.keys()
[u'DbList']
\end{verbatim}
The values stored in this key is the list of database names shown in the XML above:
\begin{verbatim}
>>> record["DbList"]
['pubmed', 'protein', 'nucleotide', 'nuccore', 'nucgss', 'nucest',
'structure', 'genome', 'books', 'cancerchromosomes', 'cdd', 'gap',
'domains', 'gene', 'genomeprj', 'gensat', 'geo', 'gds', 'homologene',
'journals', 'mesh', 'ncbisearch', 'nlmcatalog', 'omia', 'omim', 'pmc',
'popset', 'probe', 'proteinclusters', 'pcassay', 'pccompound',
'pcsubstance', 'snp', 'taxonomy', 'toolkit', 'unigene', 'unists']
\end{verbatim}
For each of these databases, we can use EInfo again to obtain more information:
\begin{verbatim}
>>> handle = Entrez.einfo(db="pubmed")
>>> record = Entrez.read(handle)
>>> record["DbInfo"]["Description"]
'PubMed bibliographic record'
>>> record["DbInfo"]["Count"]
'17989604'
>>> record["DbInfo"]["LastUpdate"]
'2008/05/24 06:45'
\end{verbatim}
Try \verb+record["DbInfo"].keys()+ for other information stored in this record.
One of the most useful is a list of possible search fields for use with ESearch:
\begin{verbatim}
>>> for field in record["DbInfo"]["FieldList"]:
... print "%(Name)s, %(FullName)s, %(Description)s" % field
ALL, All Fields, All terms from all searchable fields
UID, UID, Unique number assigned to publication
FILT, Filter, Limits the records
TITL, Title, Words in title of publication
WORD, Text Word, Free text associated with publication
MESH, MeSH Terms, Medical Subject Headings assigned to publication
MAJR, MeSH Major Topic, MeSH terms of major importance to publication
AUTH, Author, Author(s) of publication
JOUR, Journal, Journal abbreviation of publication
AFFL, Affiliation, Author's institutional affiliation and address
...
\end{verbatim}
That's a long list, but indirectly this tells you that for the PubMed
database, you can do things like \texttt{Jones[AUTH]} to search the
author field, or \texttt{Sanger[AFFL]} to restrict to authors at the
Sanger Centre. This can be very handy - especially if you are not so
familiar with a particular database.
\section{ESearch: Searching the Entrez databases}
\label{sec:entrez-esearch}
To search any of these databases, we use \verb+Bio.Entrez.esearch()+. For example, let's search in PubMed for publications related to Biopython:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.esearch(db="pubmed", term="biopython")
>>> record = Entrez.read(handle)
>>> record["IdList"]
['19304878', '18606172', '16403221', '16377612', '14871861', '14630660', '12230038']
\end{verbatim}
In this output, you see seven PubMed IDs (including 19304878 which is the PMID for the Biopython application note), which can be retrieved by EFetch (see section \ref{sec:efetch}).
You can also use ESearch to search GenBank. Here we'll do a quick
search for the \emph{matK} gene in \emph{Cypripedioideae} orchids
(see Section~\ref{sec:entrez-einfo} about EInfo for one way to
find out which fields you can search in each Entrez database):
\begin{verbatim}
>>> handle = Entrez.esearch(db="nucleotide",term="Cypripedioideae[Orgn] AND matK[Gene]")
>>> record = Entrez.read(handle)
>>> record["Count"]
'25'
>>> record["IdList"]
['126789333', '37222967', '37222966', '37222965', ..., '61585492']
\end{verbatim}
\noindent Each of the IDs (126789333, 37222967, 37222966, \ldots) is a GenBank identifier.
See section~\ref{sec:efetch} for information on how to actually download these GenBank records.
Note that instead of a species name like \texttt{Cypripedioideae[Orgn]}, you can restrict the search using an NCBI taxon identifier, here this would be \texttt{txid158330[Orgn]}. This isn't currently documented on the ESearch help page - the NCBI explained this in reply to an email query. You can often deduce the search term formatting by playing with the Entrez web interface. For example, including \texttt{complete[prop]} in a genome search restricts to just completed genomes.
As a final example, let's get a list of computational journal titles:
\begin{verbatim}
>>> handle = Entrez.esearch(db="journals", term="computational")
>>> record = Entrez.read(handle)
>>> record["Count"]
'16'
>>> record["IdList"]
['30367', '33843', '33823', '32989', '33190', '33009', '31986',
'34502', '8799', '22857', '32675', '20258', '33859', '32534',
'32357', '32249']
\end{verbatim}
Again, we could use EFetch to obtain more information for each of these journal IDs.
ESearch has many useful options --- see the \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/esearch\_help.html}{ESearch help page} for more information.
\section{EPost: Uploading a list of identifiers}
EPost uploads a list of UIs for use in subsequent search strategies; see the
\href{http://www.ncbi.nlm.nih.gov/entrez/query/static/epost\_help.html}{EPost help page} for more information. It is available from Biopython through
the \verb+Bio.Entrez.epost()+ function.
To give an example of when this is useful, suppose you have a long list of IDs
you want to download using EFetch (maybe sequences, maybe citations --
anything). When you make a request with EFetch your list of IDs, the database
etc, are all turned into a long URL sent to the server. If your list of IDs is
long, this URL gets long, and long URLs can break (e.g. some proxies don't
cope well).
Instead, you can break this up into two steps, first uploading the list of IDs
using EPost (this uses an ``HTML post'' internally, rather than an ``HTML get'',
getting round the long URL problem). With the history support, you can then
refer to this long list of IDs, and download the associated data with EFetch.
Let's look at a simple example to see how EPost works -- uploading some PubMed identifiers:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> id_list = ["19304878", "18606172", "16403221", "16377612", "14871861", "14630660"]
>>> print Entrez.epost("pubmed", id=",".join(id_list)).read()
<?xml version="1.0"?>
<!DOCTYPE ePostResult PUBLIC "-//NLM//DTD ePostResult, 11 May 2002//EN"
"http://www.ncbi.nlm.nih.gov/entrez/query/DTD/ePost_020511.dtd">
<ePostResult>
<QueryKey>1</QueryKey>
<WebEnv>NCID_01_206841095_130.14.22.101_9001_1242061629</WebEnv>
</ePostResult>
\end{verbatim}
\noindent The returned XML includes two important strings, \verb|QueryKey| and \verb|WebEnv| which together define your history session.
You would extract these values for use with another Entrez call such as EFetch:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> id_list = ["19304878", "18606172", "16403221", "16377612", "14871861", "14630660"]
>>> search_results = Entrez.read(Entrez.epost("pubmed", id=",".join(id_list)))
>>> webenv = search_results["WebEnv"]
>>> query_key = search_results["QueryKey"]
\end{verbatim}
\noindent Section~\ref{sec:entrez-webenv} shows how to use the history feature.
\section{ESummary: Retrieving summaries from primary IDs}
ESummary retrieves document summaries from a list of primary IDs (see the \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/esummary\_help.html}{ESummary help page} for more information). In Biopython, ESummary is available as \verb+Bio.Entrez.esummary()+. Using the search result above, we can for example find out more about the journal with ID 30367:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.esummary(db="journals", id="30367")
>>> record = Entrez.read(handle)
>>> record[0]["Id"]
'30367'
>>> record[0]["Title"]
'Computational biology and chemistry'
>>> record[0]["Publisher"]
'Pergamon,'
\end{verbatim}
\section{EFetch: Downloading full records from Entrez}
\label{sec:efetch}
EFetch is what you use when you want to retrieve a full record from Entrez.
This covers several possible databases, as described on the main \href{http://eutils.ncbi.nlm.nih.gov/entrez/query/static/efetch_help.html}{EFetch Help page}.
For most of their databases, the NCBI support several different file formats. Requesting a specific file format from Entrez using \verb|Bio.Entrez.efetch()| requires specifying the \verb|rettype| and/or \verb|retmode| optional arguments. The different combinations are described for each database type on the pages linked to on \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/efetch_help.html}{NCBI efetch webpage} (e.g. \href{http://eutils.ncbi.nlm.nih.gov/corehtml/query/static/efetchlit_help.html}{literature}, \href{http://eutils.ncbi.nlm.nih.gov/corehtml/query/static/efetchseq_help.html}{sequences} and \href{http://eutils.ncbi.nlm.nih.gov/corehtml/query/static/efetchtax_help.html}{taxonomy}).
One common usage is downloading sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with \verb|Bio.SeqIO|, see Sections~\ref{sec:SeqIO_GenBank_Online} and~\ref{sec:efetch}). From the \emph{Cypripedioideae} example above, we can download GenBank record 186972394 using \verb+Bio.Entrez.efetch+:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.efetch(db="nucleotide", id="186972394", rettype="gb", retmode="text")
>>> print handle.read()
LOCUS EU490707 1302 bp DNA linear PLN 05-MAY-2008
DEFINITION Selenipedium aequinoctiale maturase K (matK) gene, partial cds;
chloroplast.
ACCESSION EU490707
VERSION EU490707.1 GI:186972394
KEYWORDS .
SOURCE chloroplast Selenipedium aequinoctiale
ORGANISM Selenipedium aequinoctiale
Eukaryota; Viridiplantae; Streptophyta; Embryophyta; Tracheophyta;
Spermatophyta; Magnoliophyta; Liliopsida; Asparagales; Orchidaceae;
Cypripedioideae; Selenipedium.
REFERENCE 1 (bases 1 to 1302)
AUTHORS Neubig,K.M., Whitten,W.M., Carlsward,B.S., Blanco,M.A.,
Endara,C.L., Williams,N.H. and Moore,M.J.
TITLE Phylogenetic utility of ycf1 in orchids
JOURNAL Unpublished
REFERENCE 2 (bases 1 to 1302)
AUTHORS Neubig,K.M., Whitten,W.M., Carlsward,B.S., Blanco,M.A.,
Endara,C.L., Williams,N.H. and Moore,M.J.
TITLE Direct Submission
JOURNAL Submitted (14-FEB-2008) Department of Botany, University of
Florida, 220 Bartram Hall, Gainesville, FL 32611-8526, USA
FEATURES Location/Qualifiers
source 1..1302
/organism="Selenipedium aequinoctiale"
/organelle="plastid:chloroplast"
/mol_type="genomic DNA"
/specimen_voucher="FLAS:Blanco 2475"
/db_xref="taxon:256374"
gene <1..>1302
/gene="matK"
CDS <1..>1302
/gene="matK"
/codon_start=1
/transl_table=11
/product="maturase K"
/protein_id="ACC99456.1"
/db_xref="GI:186972395"
/translation="IFYEPVEIFGYDNKSSLVLVKRLITRMYQQNFLISSVNDSNQKG
FWGHKHFFSSHFSSQMVSEGFGVILEIPFSSQLVSSLEEKKIPKYQNLRSIHSIFPFL
EDKFLHLNYVSDLLIPHPIHLEILVQILQCRIKDVPSLHLLRLLFHEYHNLNSLITSK
KFIYAFSKRKKRFLWLLYNSYVYECEYLFQFLRKQSSYLRSTSSGVFLERTHLYVKIE
HLLVVCCNSFQRILCFLKDPFMHYVRYQGKAILASKGTLILMKKWKFHLVNFWQSYFH
FWSQPYRIHIKQLSNYSFSFLGYFSSVLENHLVVRNQMLENSFIINLLTKKFDTIAPV
ISLIGSLSKAQFCTVLGHPISKPIWTDFSDSDILDRFCRICRNLCRYHSGSSKKQVLY
RIKYILRLSCARTLARKHKSTVRTFMRRLGSGLLEEFFMEEE"
ORIGIN
1 attttttacg aacctgtgga aatttttggt tatgacaata aatctagttt agtacttgtg
61 aaacgtttaa ttactcgaat gtatcaacag aattttttga tttcttcggt taatgattct
121 aaccaaaaag gattttgggg gcacaagcat tttttttctt ctcatttttc ttctcaaatg
181 gtatcagaag gttttggagt cattctggaa attccattct cgtcgcaatt agtatcttct
241 cttgaagaaa aaaaaatacc aaaatatcag aatttacgat ctattcattc aatatttccc
301 tttttagaag acaaattttt acatttgaat tatgtgtcag atctactaat accccatccc
361 atccatctgg aaatcttggt tcaaatcctt caatgccgga tcaaggatgt tccttctttg
421 catttattgc gattgctttt ccacgaatat cataatttga atagtctcat tacttcaaag
481 aaattcattt acgccttttc aaaaagaaag aaaagattcc tttggttact atataattct
541 tatgtatatg aatgcgaata tctattccag tttcttcgta aacagtcttc ttatttacga
601 tcaacatctt ctggagtctt tcttgagcga acacatttat atgtaaaaat agaacatctt
661 ctagtagtgt gttgtaattc ttttcagagg atcctatgct ttctcaagga tcctttcatg
721 cattatgttc gatatcaagg aaaagcaatt ctggcttcaa agggaactct tattctgatg
781 aagaaatgga aatttcatct tgtgaatttt tggcaatctt attttcactt ttggtctcaa
841 ccgtatagga ttcatataaa gcaattatcc aactattcct tctcttttct ggggtatttt
901 tcaagtgtac tagaaaatca tttggtagta agaaatcaaa tgctagagaa ttcatttata
961 ataaatcttc tgactaagaa attcgatacc atagccccag ttatttctct tattggatca
1021 ttgtcgaaag ctcaattttg tactgtattg ggtcatccta ttagtaaacc gatctggacc
1081 gatttctcgg attctgatat tcttgatcga ttttgccgga tatgtagaaa tctttgtcgt
1141 tatcacagcg gatcctcaaa aaaacaggtt ttgtatcgta taaaatatat acttcgactt
1201 tcgtgtgcta gaactttggc acggaaacat aaaagtacag tacgcacttt tatgcgaaga
1261 ttaggttcgg gattattaga agaattcttt atggaagaag aa
//
\end{verbatim}
The arguments \verb+rettype="gb"+ and \verb+retmode="text"+ let us download this record in the GenBank format.
Note that until Easter 2009, the Entrez EFetch API let you use ``genbank'' as the
return type, however the NCBI now insist on using the official return types of
``gb'' or ``gbwithparts'' (or ``gp'' for proteins) as described on online.
Also not that until Feb 2012, the Entrez EFetch API would default to returning
plain text files, but now defaults to XML.
Alternatively, you could for example use \verb+rettype="fasta"+ to get the Fasta-format; see the \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/efetchseq\_help.html}{EFetch Sequences Help page} for other options. Remember -- the available formats depend on which database you are downloading from - see the main \href{http://eutils.ncbi.nlm.nih.gov/entrez/query/static/efetch\_help.html}{EFetch Help page}.
If you fetch the record in one of the formats accepted by \verb+Bio.SeqIO+ (see Chapter~\ref{chapter:Bio.SeqIO}), you could directly parse it into a \verb+SeqRecord+:
\begin{verbatim}
>>> from Bio import Entrez, SeqIO
>>> handle = Entrez.efetch(db="nucleotide", id="186972394",rettype="gb", retmode="text")
>>> record = SeqIO.read(handle, "genbank")
>>> handle.close()
>>> print record
ID: EU490707.1
Name: EU490707
Description: Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast.
Number of features: 3
...
Seq('ATTTTTTACGAACCTGTGGAAATTTTTGGTTATGACAATAAATCTAGTTTAGTA...GAA', IUPACAmbiguousDNA())
\end{verbatim}
Note that a more typical use would be to save the sequence data to a local file, and \emph{then} parse it with \verb|Bio.SeqIO|. This can save you having to re-download the same file repeatedly while working on your script, and places less load on the NCBI's servers. For example:
\begin{verbatim}
import os
from Bio import SeqIO
from Bio import Entrez
Entrez.email = "[email protected]" # Always tell NCBI who you are
filename = "gi_186972394.gbk"
if not os.path.isfile(filename):
# Downloading...
net_handle = Entrez.efetch(db="nucleotide",id="186972394",rettype="gb", retmode="text")
out_handle = open(filename, "w")
out_handle.write(net_handle.read())
out_handle.close()
net_handle.close()
print "Saved"
print "Parsing..."
record = SeqIO.read(filename, "genbank")
print record
\end{verbatim}
To get the output in XML format, which you can parse using the \verb+Bio.Entrez.read()+ function, use \verb+retmode="xml"+:
\begin{verbatim}
>>> from Bio import Entrez
>>> handle = Entrez.efetch(db="nucleotide", id="186972394", retmode="xml")
>>> record = Entrez.read(handle)
>>> handle.close()
>>> record[0]["GBSeq_definition"]
'Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast'
>>> record[0]["GBSeq_source"]
'chloroplast Selenipedium aequinoctiale'
\end{verbatim}
So, that dealt with sequences. For examples of parsing file formats specific to the other databases (e.g. the \verb+MEDLINE+ format used in PubMed), see Section~\ref{sec:entrez-specialized-parsers}.
If you want to perform a search with \verb|Bio.Entrez.esearch()|, and then download the records with \verb|Bio.Entrez.efetch()|, you should use the WebEnv history feature -- see Section~\ref{sec:entrez-webenv}.
\section{ELink: Searching for related items in NCBI Entrez}
\label{sec:elink}
ELink, available from Biopython as \verb+Bio.Entrez.elink()+, can be used to find related items in the NCBI Entrez databases. For example, you can us this to find nucleotide entries for an entry in the gene database,
and other cool stuff.
Let's use ELink to find articles related to the Biopython application note published in \textit{Bioinformatics} in 2009. The PubMed ID of this article is 19304878:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]"
>>> pmid = "19304878"
>>> record = Entrez.read(Entrez.elink(dbfrom="pubmed", id=pmid))
\end{verbatim}
The \verb+record+ variable consists of a Python list, one for each database in which we searched. Since we specified only one PubMed ID to search for, \verb+record+ contains only one item. This item is a dictionary containing information about our search term, as well as all the related items that were found:
\begin{verbatim}
>>> record[0]["DbFrom"]
'pubmed'
>>> record[0]["IdList"]
['19304878']
\end{verbatim}
The \verb+"LinkSetDb"+ key contains the search results, stored as a list consisting of one item for each target database. In our search results, we only find hits in the PubMed database (although sub-divided into categories):
\begin{verbatim}
>>> len(record[0]["LinkSetDb"])
5
>>> for linksetdb in record[0]["LinkSetDb"]:
... print linksetdb["DbTo"], linksetdb["LinkName"], len(linksetdb["Link"])
...
pubmed pubmed_pubmed 110
pubmed pubmed_pubmed_combined 6
pubmed pubmed_pubmed_five 6
pubmed pubmed_pubmed_reviews 5
pubmed pubmed_pubmed_reviews_five 5
\end{verbatim}
The actual search results are stored as under the \verb+"Link"+ key. In total, 110 items were found under
standard search.
Let's now at the first search result:
\begin{verbatim}
>>> record[0]["LinkSetDb"][0]["Link"][0]
{u'Id': '19304878'}
\end{verbatim}
\noindent This is the article we searched for, which doesn't help us much, so let's look at the second search result:
\begin{verbatim}
>>> record[0]["LinkSetDb"][0]["Link"][1]
{u'Id': '14630660'}
\end{verbatim}
\noindent This paper, with PubMed ID 14630660, is about the Biopython PDB parser.
We can use a loop to print out all PubMed IDs:
\begin{verbatim}
>>> for link in record[0]["LinkSetDb"][0]["Link"] : print link["Id"]
19304878
14630660
18689808
17121776
16377612
12368254
......
\end{verbatim}
Now that was nice, but personally I am often more interested to find out if a paper has been cited.
Well, ELink can do that too -- at least for journals in Pubmed Central (see Section~\ref{sec:elink-citations}).
For help on ELink, see the \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/elink\_help.html}{ELink help page}.
There is an entire sub-page just for the \href{http://eutils.ncbi.nlm.nih.gov/corehtml/query/static/entrezlinks.html}{link names}, describing how different databases can be cross referenced.
\section{EGQuery: Global Query - counts for search terms}
EGQuery provides counts for a search term in each of the Entrez databases (i.e. a global query). This is particularly useful to find out how many items your search terms would find in each database without actually performing lots of separate searches with ESearch (see the example in \ref{subsec:entrez_example_genbank} below).
In this example, we use \verb+Bio.Entrez.egquery()+ to obtain the counts for ``Biopython'':
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.egquery(term="biopython")
>>> record = Entrez.read(handle)
>>> for row in record["eGQueryResult"]: print row["DbName"], row["Count"]
...
pubmed 6
pmc 62
journals 0
...
\end{verbatim}
See the \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/egquery\_help.html}{EGQuery help page} for more information.
\section{ESpell: Obtaining spelling suggestions}
ESpell retrieves spelling suggestions. In this example, we use \verb+Bio.Entrez.espell()+ to obtain the correct spelling of Biopython:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.espell(term="biopythooon")
>>> record = Entrez.read(handle)
>>> record["Query"]
'biopythooon'
>>> record["CorrectedQuery"]
'biopython'
\end{verbatim}
See the \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/espell\_help.html}{ESpell help page} for more information.
The main use of this is for GUI tools to provide automatic suggestions for search terms.
\section{Parsing huge Entrez XML files}
The \verb+Entrez.read+ function reads the entire XML file returned by Entrez into a single Python object, which is kept in memory. To parse Entrez XML files too large to fit in memory, you can use the function \verb+Entrez.parse+. This is a generator function that reads records in the XML file one by one. This function is only useful if the XML file reflects a Python list object (in other words, if \verb+Entrez.read+ on a computer with infinite memory resources would return a Python list).
For example, you can download the entire Entrez Gene database for a given organism as a file from NCBI's ftp site. These files can be very large. As an example, on September 4, 2009, the file \verb+Homo_sapiens.ags.gz+, containing the Entrez Gene database for human, had a size of 116576 kB. This file, which is in the \verb+ASN+ format, can be converted into an XML file using NCBI's \verb+gene2xml+ program (see NCBI's ftp site for more information):
\begin{verbatim}
gene2xml -b T -i Homo_sapiens.ags -o Homo_sapiens.xml
\end{verbatim}
The resulting XML file has a size of 6.1 GB. Attempting \verb+Entrez.read+ on this file will result in a \verb+MemoryError+ on many computers.
The XML file \verb+Homo_sapiens.xml+ consists of a list of Entrez gene records, each corresponding to one Entrez gene in human. \verb+Entrez.parse+ retrieves these gene records one by one. You can then print out or store the relevant information in each record by iterating over the records. For example, this script iterates over the Entrez gene records and prints out the gene numbers and names for all current genes:
\begin{verbatim}
>>> from Bio import Entrez
>>> handle = open("Homo_sapiens.xml")
>>> records = Entrez.parse(handle)
>>> for record in records:
... status = record['Entrezgene_track-info']['Gene-track']['Gene-track_status']
... if status.attributes['value']=='discontinued':
... continue
... geneid = record['Entrezgene_track-info']['Gene-track']['Gene-track_geneid']
... genename = record['Entrezgene_gene']['Gene-ref']['Gene-ref_locus']
... print geneid, genename
\end{verbatim}
This will print:
\begin{verbatim}
1 A1BG
2 A2M
3 A2MP
8 AA
9 NAT1
10 NAT2
11 AACP
12 SERPINA3
13 AADAC
14 AAMP
15 AANAT
16 AARS
17 AAVS1
...
\end{verbatim}
\section{Handling errors}
Three things can go wrong when parsing an XML file:
\begin{itemize}
\item The file may not be an XML file to begin with;
\item The file may end prematurely or otherwise be corrupted;
\item The file may be correct XML, but contain items that are not represented in the associated DTD.
\end{itemize}
The first case occurs if, for example, you try to parse a Fasta file as if it were an XML file:
\begin{verbatim}
>>> from Bio import Entrez
>>> handle = open("NC_005816.fna") # a Fasta file
>>> record = Entrez.read(handle)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/__init__.py", line 257, in read
record = handler.read(handle)
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 164, in read
raise NotXMLError(e)
Bio.Entrez.Parser.NotXMLError: Failed to parse the XML data (syntax error: line 1, column 0). Please make sure that the input data are in XML format.
\end{verbatim}
Here, the parser didn't find the \verb|<?xml ...| tag with which an XML file is supposed to start, and therefore decides (correctly) that the file is not an XML file.
When your file is in the XML format but is corrupted (for example, by ending prematurely), the parser will raise a CorruptedXMLError.
Here is an example of an XML file that ends prematurely:
\begin{verbatim}
<?xml version="1.0"?>
<!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD eInfoResult, 11 May 2002//EN" "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eInfo_020511.dtd">
<eInfoResult>
<DbList>
<DbName>pubmed</DbName>
<DbName>protein</DbName>
<DbName>nucleotide</DbName>
<DbName>nuccore</DbName>
<DbName>nucgss</DbName>
<DbName>nucest</DbName>
<DbName>structure</DbName>
<DbName>genome</DbName>
<DbName>books</DbName>
<DbName>cancerchromosomes</DbName>
<DbName>cdd</DbName>
\end{verbatim}
which will generate the following traceback:
\begin{verbatim}
>>> Entrez.read(handle)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/__init__.py", line 257, in read
record = handler.read(handle)
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 160, in read
raise CorruptedXMLError(e)
Bio.Entrez.Parser.CorruptedXMLError: Failed to parse the XML data (no element found: line 16, column 0). Please make sure that the input data are not corrupted.
>>>
\end{verbatim}
Note that the error message tells you at what point in the XML file the error was detected.
The third type of error occurs if the XML file contains tags that do not have a description in the corresponding DTD file. This is an example of such an XML file:
\begin{verbatim}
<?xml version="1.0"?>
<!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD eInfoResult, 11 May 2002//EN" "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eInfo_020511.dtd">
<eInfoResult>
<DbInfo>
<DbName>pubmed</DbName>
<MenuName>PubMed</MenuName>
<Description>PubMed bibliographic record</Description>
<Count>20161961</Count>
<LastUpdate>2010/09/10 04:52</LastUpdate>
<FieldList>
<Field>
...
</Field>
</FieldList>
<DocsumList>
<Docsum>
<DsName>PubDate</DsName>
<DsType>4</DsType>
<DsTypeName>string</DsTypeName>
</Docsum>
<Docsum>
<DsName>EPubDate</DsName>
...
</DbInfo>
</eInfoResult>
\end{verbatim}
In this file, for some reason the tag \verb|<DocsumList>| (and several others) are not listed in the DTD file \verb|eInfo_020511.dtd|, which is specified on the second line as the DTD for this XML file. By default, the parser will stop and raise a ValidationError if it cannot find some tag in the DTD:
\begin{verbatim}
>>> from Bio import Entrez
>>> handle = open("einfo3.xml")
>>> record = Entrez.read(handle)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/__init__.py", line 257, in read
record = handler.read(handle)
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 154, in read
self.parser.ParseFile(handle)
File "/usr/local/lib/python2.7/site-packages/Bio/Entrez/Parser.py", line 246, in startElementHandler
raise ValidationError(name)
Bio.Entrez.Parser.ValidationError: Failed to find tag 'DocsumList' in the DTD. To skip all tags that are not represented in the DTD, please call Bio.Entrez.read or Bio.Entrez.parse with validate=False.
\end{verbatim}
Optionally, you can instruct the parser to skip such tags instead of raising a ValidationError. This is done by calling \verb|Entrez.read| or \verb|Entrez.parse| with the argument \verb|validate| equal to False:
\begin{verbatim}
>>> from Bio import Entrez
>>> handle = open("einfo3.xml")
>>> record = Entrez.read(handle,validate=False)
>>>
\end{verbatim}
Of course, the information contained in the XML tags that are not in the DTD are not present in the record returned by \verb|Entrez.read|.
\section{Specialized parsers}
\label{sec:entrez-specialized-parsers}
The \verb|Bio.Entrez.read()| function can parse most (if not all) XML output returned by Entrez. Entrez typically allows you to retrieve records in other formats, which may have some advantages compared to the XML format in terms of readability (or download size).
To request a specific file format from Entrez using \verb|Bio.Entrez.efetch()| requires specifying the \verb|rettype| and/or \verb|retmode| optional arguments. The different combinations are described for each database type on the \href{http://www.ncbi.nlm.nih.gov/entrez/query/static/efetch_help.html}{NCBI efetch webpage}.
One obvious case is you may prefer to download sequences in the FASTA or GenBank/GenPept plain text formats (which can then be parsed with \verb|Bio.SeqIO|, see Sections~\ref{sec:SeqIO_GenBank_Online} and~\ref{sec:efetch}). For the literature databases, Biopython contains a parser for the \verb+MEDLINE+ format used in PubMed.
\subsection{Parsing Medline records}
\label{subsec:entrez-and-medline}
You can find the Medline parser in \verb+Bio.Medline+. Suppose we want to parse the file \verb+pubmed_result1.txt+, containing one Medline record. You can find this file in Biopython's \verb+Tests\Medline+ directory. The file looks like this:
\begin{verbatim}
PMID- 12230038
OWN - NLM
STAT- MEDLINE
DA - 20020916
DCOM- 20030606
LR - 20041117
PUBM- Print
IS - 1467-5463 (Print)
VI - 3
IP - 3
DP - 2002 Sep
TI - The Bio* toolkits--a brief overview.
PG - 296-302
AB - Bioinformatics research is often difficult to do with commercial software. The
Open Source BioPerl, BioPython and Biojava projects provide toolkits with
...
\end{verbatim}
We first open the file and then parse it:
%doctest ../Tests/Medline
\begin{verbatim}
>>> from Bio import Medline
>>> input = open("pubmed_result1.txt")
>>> record = Medline.read(input)
\end{verbatim}
The \verb+record+ now contains the Medline record as a Python dictionary:
%cont-doctest
\begin{verbatim}
>>> record["PMID"]
'12230038'
\end{verbatim}
%TODO - doctest wrapping?
\begin{verbatim}
>>> record["AB"]
'Bioinformatics research is often difficult to do with commercial software.
The Open Source BioPerl, BioPython and Biojava projects provide toolkits with
multiple functionality that make it easier to create customised pipelines or
analysis. This review briefly compares the quirks of the underlying languages
and the functionality, documentation, utility and relative advantages of the
Bio counterparts, particularly from the point of view of the beginning
biologist programmer.'
\end{verbatim}
The key names used in a Medline record can be rather obscure; use
\begin{verbatim}
>>> help(record)
\end{verbatim}
for a brief summary.
To parse a file containing multiple Medline records, you can use the \verb+parse+ function instead:
%doctest ../Tests/Medline
\begin{verbatim}
>>> from Bio import Medline
>>> input = open("pubmed_result2.txt")
>>> records = Medline.parse(input)
>>> for record in records:
... print record["TI"]
A high level interface to SCOP and ASTRAL implemented in python.
GenomeDiagram: a python package for the visualization of large-scale genomic data.
Open source clustering software.
PDB file parser and structure class implemented in Python.
\end{verbatim}
Instead of parsing Medline records stored in files, you can also parse Medline records downloaded by \verb+Bio.Entrez.efetch+. For example, let's look at all Medline records in PubMed related to Biopython:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.esearch(db="pubmed",term="biopython")
>>> record = Entrez.read(handle)
>>> record["IdList"]
['19304878', '18606172', '16403221', '16377612', '14871861', '14630660', '12230038']
\end{verbatim}
We now use \verb+Bio.Entrez.efetch+ to download these Medline records:
\begin{verbatim}
>>> idlist = record["IdList"]
>>> handle = Entrez.efetch(db="pubmed",id=idlist,rettype="medline",retmode="text")
\end{verbatim}
Here, we specify \verb+rettype="medline", retmode="text"+ to obtain the Medline records in plain-text Medline format. Now we use \verb+Bio.Medline+ to parse these records:
\begin{verbatim}
>>> from Bio import Medline
>>> records = Medline.parse(handle)
>>> for record in records:
... print record["AU"]
['Cock PJ', 'Antao T', 'Chang JT', 'Chapman BA', 'Cox CJ', 'Dalke A', ..., 'de Hoon MJ']
['Munteanu CR', 'Gonzalez-Diaz H', 'Magalhaes AL']
['Casbon JA', 'Crooks GE', 'Saqi MA']
['Pritchard L', 'White JA', 'Birch PR', 'Toth IK']
['de Hoon MJ', 'Imoto S', 'Nolan J', 'Miyano S']
['Hamelryck T', 'Manderick B']
['Mangalam H']
\end{verbatim}
For comparison, here we show an example using the XML format:
\begin{verbatim}
>>> idlist = record["IdList"]
>>> handle = Entrez.efetch(db="pubmed",id=idlist,rettype="medline",retmode="xml")
>>> records = Entrez.read(handle)
>>> for record in records:
... print record["MedlineCitation"]["Article"]["ArticleTitle"]
Biopython: freely available Python tools for computational molecular biology and
bioinformatics.
Enzymes/non-enzymes classification model complexity based on composition, sequence,
3D and topological indices.
A high level interface to SCOP and ASTRAL implemented in python.
GenomeDiagram: a python package for the visualization of large-scale genomic data.
Open source clustering software.
PDB file parser and structure class implemented in Python.
The Bio* toolkits--a brief overview.
\end{verbatim}
Note that in both of these examples, for simplicity we have naively combined ESearch and EFetch.
In this situation, the NCBI would expect you to use their history feature,
as illustrated in Section~\ref{sec:entrez-webenv}.
\subsection{Parsing GEO records}
GEO (\href{http://www.ncbi.nlm.nih.gov/geo/}{Gene Expression Omnibus})
is a data repository of high-throughput gene expression and hybridization
array data. The \verb|Bio.Geo| module can be used to parse GEO-formatted
data.
The following code fragment shows how to parse the example GEO file
\verb|GSE16.txt| into a record and print the record:
\begin{verbatim}
>>> from Bio import Geo
>>> handle = open("GSE16.txt")
>>> records = Geo.parse(handle)
>>> for record in records:
... print record
\end{verbatim}
You can search the ``gds'' database (GEO datasets) with ESearch:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.esearch(db="gds",term="GSE16")
>>> record = Entrez.read(handle)
>>> record["Count"]
2
>>> record["IdList"]
['200000016', '100000028']
\end{verbatim}
From the Entrez website, UID ``200000016'' is GDS16 while the other hit
``100000028'' is for the associated platform, GPL28. Unfortunately, at the
time of writing the NCBI don't seem to support downloading GEO files using
Entrez (not as XML, nor in the \textit{Simple Omnibus Format in Text} (SOFT)
format).
However, it is actually pretty straight forward to download the GEO files by FTP
from \url{ftp://ftp.ncbi.nih.gov/pub/geo/} instead. In this case you might want
\url{ftp://ftp.ncbi.nih.gov/pub/geo/DATA/SOFT/by_series/GSE16/GSE16_family.soft.gz}
(a compressed file, see the Python module gzip).
\subsection{Parsing UniGene records}
UniGene is an NCBI database of the transcriptome, with each UniGene record showing the set of transcripts that are associated with a particular gene in a specific organism. A typical UniGene record looks like this:
\begin{verbatim}
ID Hs.2
TITLE N-acetyltransferase 2 (arylamine N-acetyltransferase)
GENE NAT2
CYTOBAND 8p22
GENE_ID 10
LOCUSLINK 10
HOMOL YES
EXPRESS bone| connective tissue| intestine| liver| liver tumor| normal| soft tissue/muscle tissue tumor| adult
RESTR_EXPR adult
CHROMOSOME 8
STS ACC=PMC310725P3 UNISTS=272646
STS ACC=WIAF-2120 UNISTS=44576
STS ACC=G59899 UNISTS=137181
...
STS ACC=GDB:187676 UNISTS=155563
PROTSIM ORG=10090; PROTGI=6754794; PROTID=NP_035004.1; PCT=76.55; ALN=288
PROTSIM ORG=9796; PROTGI=149742490; PROTID=XP_001487907.1; PCT=79.66; ALN=288
PROTSIM ORG=9986; PROTGI=126722851; PROTID=NP_001075655.1; PCT=76.90; ALN=288
...
PROTSIM ORG=9598; PROTGI=114619004; PROTID=XP_519631.2; PCT=98.28; ALN=288
SCOUNT 38
SEQUENCE ACC=BC067218.1; NID=g45501306; PID=g45501307; SEQTYPE=mRNA
SEQUENCE ACC=NM_000015.2; NID=g116295259; PID=g116295260; SEQTYPE=mRNA
SEQUENCE ACC=D90042.1; NID=g219415; PID=g219416; SEQTYPE=mRNA
SEQUENCE ACC=D90040.1; NID=g219411; PID=g219412; SEQTYPE=mRNA
SEQUENCE ACC=BC015878.1; NID=g16198419; PID=g16198420; SEQTYPE=mRNA
SEQUENCE ACC=CR407631.1; NID=g47115198; PID=g47115199; SEQTYPE=mRNA
SEQUENCE ACC=BG569293.1; NID=g13576946; CLONE=IMAGE:4722596; END=5'; LID=6989; SEQTYPE=EST; TRACE=44157214
...
SEQUENCE ACC=AU099534.1; NID=g13550663; CLONE=HSI08034; END=5'; LID=8800; SEQTYPE=EST
//
\end{verbatim}
This particular record shows the set of transcripts (shown in the \verb+SEQUENCE+ lines) that originate from the human gene NAT2, encoding en N-acetyltransferase. The \verb+PROTSIM+ lines show proteins with significant similarity to NAT2, whereas the \verb+STS+ lines show the corresponding sequence-tagged sites in the genome.
To parse UniGene files, use the \verb+Bio.UniGene+ module:
\begin{verbatim}
>>> from Bio import UniGene
>>> input = open("myunigenefile.data")
>>> record = UniGene.read(input)
\end{verbatim}
The \verb+record+ returned by \verb+UniGene.read+ is a Python object with attributes corresponding to the fields in the UniGene record. For example,
\begin{verbatim}
>>> record.ID
"Hs.2"
>>> record.title
"N-acetyltransferase 2 (arylamine N-acetyltransferase)"
\end{verbatim}
The \verb+EXPRESS+ and \verb+RESTR_EXPR+ lines are stored as Python lists of strings:
\begin{verbatim}
['bone', 'connective tissue', 'intestine', 'liver', 'liver tumor', 'normal', 'soft tissue/muscle tissue tumor', 'adult']
\end{verbatim}
Specialized objects are returned for the \verb+STS+, \verb+PROTSIM+, and \verb+SEQUENCE+ lines, storing the keys shown in each line as attributes:
\begin{verbatim}
>>> record.sts[0].acc
'PMC310725P3'
>>> record.sts[0].unists
'272646'
\end{verbatim}
and similarly for the \verb+PROTSIM+ and \verb+SEQUENCE+ lines.
To parse a file containing more than one UniGene record, use the \verb+parse+ function in \verb+Bio.UniGene+:
\begin{verbatim}
>>> from Bio import UniGene
>>> input = open("unigenerecords.data")
>>> records = UniGene.parse(input)
>>> for record in records:
... print record.ID
\end{verbatim}
\section{Using a proxy}
Normally you won't have to worry about using a proxy, but if this is an issue
on your network here is how to deal with it. Internally, \verb|Bio.Entrez|
uses the standard Python library \verb|urllib| for accessing the NCBI servers.
This will check an environment variable called \verb|http_proxy| to configure
any simple proxy automatically. Unfortunately this module does not support
the use of proxies which require authentication.
You may choose to set the \verb|http_proxy| environment variable once (how you
do this will depend on your operating system). Alternatively you can set this
within Python at the start of your script, for example:
\begin{verbatim}
import os
os.environ["http_proxy"] = "http://proxyhost.example.com:8080"
\end{verbatim}
\noindent See the \href{http://www.python.org/doc/lib/module-urllib.html}
{urllib documentation} for more details.
\section{Examples}
\label{sec:entrez_examples}
\subsection{PubMed and Medline}
\label{subsec:pub_med}
If you are in the medical field or interested in human issues (and many times even if you are not!), PubMed (\url{http://www.ncbi.nlm.nih.gov/PubMed/}) is an excellent source of all kinds of goodies. So like other things, we'd like to be able to grab information from it and use it in Python scripts.
In this example, we will query PubMed for all articles having to do with orchids (see section~\ref{sec:orchids} for our motivation). We first check how many of such articles there are:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.egquery(term="orchid")
>>> record = Entrez.read(handle)
>>> for row in record["eGQueryResult"]:
... if row["DbName"]=="pubmed":
... print row["Count"]
463
\end{verbatim}
Now we use the \verb+Bio.Entrez.efetch+ function to download the PubMed IDs of these 463 articles:
\begin{verbatim}
>>> handle = Entrez.esearch(db="pubmed", term="orchid", retmax=463)
>>> record = Entrez.read(handle)
>>> idlist = record["IdList"]
>>> print idlist
\end{verbatim}
This returns a Python list containing all of the PubMed IDs of articles related to orchids:
\begin{verbatim}
['18680603', '18665331', '18661158', '18627489', '18627452', '18612381',
'18594007', '18591784', '18589523', '18579475', '18575811', '18575690',
...
\end{verbatim}
Now that we've got them, we obviously want to get the corresponding Medline records and extract the information from them. Here, we'll download the Medline records in the Medline flat-file format, and use the \verb+Bio.Medline+ module to parse them:
\begin{verbatim}
>>> from Bio import Medline
>>> handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline",
retmode="text")
>>> records = Medline.parse(handle)
\end{verbatim}
NOTE - We've just done a separate search and fetch here, the NCBI much prefer you to take advantage of their history support in this situation. See Section~\ref{sec:entrez-webenv}.
Keep in mind that \verb+records+ is an iterator, so you can iterate through the records only once. If you want to save the records, you can convert them to a list:
\begin{verbatim}
>>> records = list(records)
\end{verbatim}
Let's now iterate over the records to print out some information about each record:
\begin{verbatim}
>>> for record in records:
... print "title:", record.get("TI", "?")
... print "authors:", record.get("AU", "?")
... print "source:", record.get("SO", "?")
... print
\end{verbatim}
The output for this looks like:
\begin{verbatim}
title: Sex pheromone mimicry in the early spider orchid (ophrys sphegodes):
patterns of hydrocarbons as the key mechanism for pollination by sexual
deception [In Process Citation]
authors: ['Schiestl FP', 'Ayasse M', 'Paulus HF', 'Lofstedt C', 'Hansson BS',
'Ibarra F', 'Francke W']
source: J Comp Physiol [A] 2000 Jun;186(6):567-74
\end{verbatim}
Especially interesting to note is the list of authors, which is returned as a standard Python list. This makes it easy to manipulate and search using standard Python tools. For instance, we could loop through a whole bunch of entries searching for a particular author with code like the following:
\begin{verbatim}
>>> search_author = "Waits T"
>>> for record in records:
... if not "AU" in record:
... continue
... if search_author in record["AU"]:
... print "Author %s found: %s" % (search_author, record["SO"])
\end{verbatim}
Hopefully this section gave you an idea of the power and flexibility of the Entrez and Medline interfaces and how they can be used together.
\subsection{Searching, downloading, and parsing Entrez Nucleotide records}
\label{subsec:entrez_example_genbank}
Here we'll show a simple example of performing a remote Entrez query. In section~\ref{sec:orchids} of the parsing examples, we talked about using NCBI's Entrez website to search the NCBI nucleotide databases for info on Cypripedioideae, our friends the lady slipper orchids. Now, we'll look at how to automate that process using a Python script. In this example, we'll just show how to connect, get the results, and parse them, with the Entrez module doing all of the work.
First, we use EGQuery to find out the number of results we will get before actually downloading them. EGQuery will tell us how many search results were found in each of the databases, but for this example we are only interested in nucleotides:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.egquery(term="Cypripedioideae")
>>> record = Entrez.read(handle)
>>> for row in record["eGQueryResult"]:
... if row["DbName"]=="nuccore":
... print row["Count"]
814
\end{verbatim}
So, we expect to find 814 Entrez Nucleotide records (this is the number I obtained in 2008; it is likely to increase in the future). If you find some ridiculously high number of hits, you may want to reconsider if you really want to download all of them, which is our next step:
\begin{verbatim}
>>> from Bio import Entrez
>>> handle = Entrez.esearch(db="nucleotide", term="Cypripedioideae", retmax=814)
>>> record = Entrez.read(handle)
\end{verbatim}
Here, \verb+record+ is a Python dictionary containing the search results and some auxiliary information. Just for information, let's look at what is stored in this dictionary:
\begin{verbatim}
>>> print record.keys()
[u'Count', u'RetMax', u'IdList', u'TranslationSet', u'RetStart', u'QueryTranslation']
\end{verbatim}
First, let's check how many results were found:
\begin{verbatim}
>>> print record["Count"]
'814'
\end{verbatim}
which is the number we expected. The 814 results are stored in \verb+record['IdList']+:
\begin{verbatim}
>>> print len(record["IdList"])
814
\end{verbatim}
Let's look at the first five results:
\begin{verbatim}
>>> print record["IdList"][:5]
['187237168', '187372713', '187372690', '187372688', '187372686']
\end{verbatim}
\label{sec:entrez-batched-efetch}
We can download these records using \verb+efetch+.
While you could download these records one by one, to reduce the load on NCBI's servers, it is better to fetch a bunch of records at the same time, shown below.
However, in this situation you should ideally be using the history feature described later in Section~\ref{sec:entrez-webenv}.
\begin{verbatim}
>>> idlist = ",".join(record["IdList"][:5])
>>> print idlist
187237168,187372713,187372690,187372688,187372686
>>> handle = Entrez.efetch(db="nucleotide", id=idlist, retmode="xml")
>>> records = Entrez.read(handle)
>>> print len(records)
5
\end{verbatim}
Each of these records corresponds to one GenBank record.
\begin{verbatim}
>>> print records[0].keys()
[u'GBSeq_moltype', u'GBSeq_source', u'GBSeq_sequence',
u'GBSeq_primary-accession', u'GBSeq_definition', u'GBSeq_accession-version',
u'GBSeq_topology', u'GBSeq_length', u'GBSeq_feature-table',
u'GBSeq_create-date', u'GBSeq_other-seqids', u'GBSeq_division',
u'GBSeq_taxonomy', u'GBSeq_references', u'GBSeq_update-date',
u'GBSeq_organism', u'GBSeq_locus', u'GBSeq_strandedness']
>>> print records[0]["GBSeq_primary-accession"]
DQ110336
>>> print records[0]["GBSeq_other-seqids"]
['gb|DQ110336.1|', 'gi|187237168']
>>> print records[0]["GBSeq_definition"]
Cypripedium calceolus voucher Davis 03-03 A maturase (matR) gene, partial cds;
mitochondrial
>>> print records[0]["GBSeq_organism"]
Cypripedium calceolus
\end{verbatim}
You could use this to quickly set up searches -- but for heavy usage, see Section~\ref{sec:entrez-webenv}.
\subsection{Searching, downloading, and parsing GenBank records}
\label{sec:entrez-search-fetch-genbank}
The GenBank record format is a very popular method of holding information about sequences, sequence features, and other associated sequence information. The format is a good way to get information from the NCBI databases at \url{http://www.ncbi.nlm.nih.gov/}.
In this example we'll show how to query the NCBI databases,to retrieve the records from the query, and then parse them using \verb+Bio.SeqIO+ - something touched on in Section~\ref{sec:SeqIO_GenBank_Online}.
For simplicity, this example \emph{does not} take advantage of the WebEnv history feature -- see Section~\ref{sec:entrez-webenv} for this.
First, we want to make a query and find out the ids of the records to retrieve. Here we'll do a quick search for one of our favorite organisms, \emph{Opuntia} (prickly-pear cacti). We can do quick search and get back the GIs (GenBank identifiers) for all of the corresponding records. First we check how many records there are:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.egquery(term="Opuntia AND rpl16")
>>> record = Entrez.read(handle)
>>> for row in record["eGQueryResult"]:
... if row["DbName"]=="nuccore":
... print row["Count"]
...
9
\end{verbatim}
Now we download the list of GenBank identifiers:
\begin{verbatim}
>>> handle = Entrez.esearch(db="nuccore", term="Opuntia AND rpl16")
>>> record = Entrez.read(handle)
>>> gi_list = record["IdList"]
>>> gi_list
['57240072', '57240071', '6273287', '6273291', '6273290', '6273289', '6273286',
'6273285', '6273284']
\end{verbatim}
Now we use these GIs to download the GenBank records - note that with older versions of Biopython you had to supply a comma separated list of GI numbers to Entrez, as of Biopython 1.59 you can pass a list and this is converted for you:
\begin{verbatim}
>>> gi_str = ",".join(gi_list)
>>> handle = Entrez.efetch(db="nuccore", id=gi_str, rettype="gb", retmode="text")
\end{verbatim}
If you want to look at the raw GenBank files, you can read from this handle and print out the result:
\begin{verbatim}
>>> text = handle.read()
>>> print text
LOCUS AY851612 892 bp DNA linear PLN 10-APR-2007
DEFINITION Opuntia subulata rpl16 gene, intron; chloroplast.
ACCESSION AY851612
VERSION AY851612.1 GI:57240072
KEYWORDS .
SOURCE chloroplast Austrocylindropuntia subulata
ORGANISM Austrocylindropuntia subulata
Eukaryota; Viridiplantae; Streptophyta; Embryophyta; Tracheophyta;
Spermatophyta; Magnoliophyta; eudicotyledons; core eudicotyledons;
Caryophyllales; Cactaceae; Opuntioideae; Austrocylindropuntia.
REFERENCE 1 (bases 1 to 892)
AUTHORS Butterworth,C.A. and Wallace,R.S.
...
\end{verbatim}
In this case, we are just getting the raw records. To get the records in a more Python-friendly form, we can use \verb+Bio.SeqIO+ to parse the GenBank data into \verb|SeqRecord| objects, including \verb|SeqFeature| objects (see Chapter~\ref{chapter:Bio.SeqIO}):
\begin{verbatim}
>>> from Bio import SeqIO
>>> handle = Entrez.efetch(db="nuccore", id=gi_str, rettype="gb", retmode="text")
>>> records = SeqIO.parse(handle, "gb")
\end{verbatim}
\noindent We can now step through the records and look at the information we are interested in:
\begin{verbatim}
>>> for record in records:
>>> ... print "%s, length %i, with %i features" \
>>> ... % (record.name, len(record), len(record.features))
AY851612, length 892, with 3 features
AY851611, length 881, with 3 features
AF191661, length 895, with 3 features
AF191665, length 902, with 3 features
AF191664, length 899, with 3 features
AF191663, length 899, with 3 features
AF191660, length 893, with 3 features
AF191659, length 894, with 3 features
AF191658, length 896, with 3 features
\end{verbatim}
Using these automated query retrieval functionality is a big plus over doing things by hand. Although the module should obey the NCBI's max three queries per second rule, the NCBI have other recommendations like avoiding peak hours. See Section~\ref{sec:entrez-guidelines}.
In particular, please note that for simplicity, this example does not use the WebEnv history feature. You should use this for any non-trivial search and download work, see Section~\ref{sec:entrez-webenv}.
Finally, if plan to repeat your analysis, rather than downloading the files from the NCBI and parsing them immediately (as shown in this example), you should just download the records \emph{once} and save them to your hard disk, and then parse the local file.
\subsection{Finding the lineage of an organism}
Staying with a plant example, let's now find the lineage of the Cypripedioideae orchid family. First, we search the Taxonomy database for Cypripedioideae, which yields exactly one NCBI taxonomy identifier:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]" # Always tell NCBI who you are
>>> handle = Entrez.esearch(db="Taxonomy", term="Cypripedioideae")
>>> record = Entrez.read(handle)
>>> record["IdList"]
['158330']
>>> record["IdList"][0]
'158330'
\end{verbatim}
Now, we use \verb+efetch+ to download this entry in the Taxonomy database, and then parse it:
\begin{verbatim}
>>> handle = Entrez.efetch(db="Taxonomy", id="158330", retmode="xml")
>>> records = Entrez.read(handle)
\end{verbatim}
Again, this record stores lots of information:
\begin{verbatim}
>>> records[0].keys()
[u'Lineage', u'Division', u'ParentTaxId', u'PubDate', u'LineageEx',
u'CreateDate', u'TaxId', u'Rank', u'GeneticCode', u'ScientificName',
u'MitoGeneticCode', u'UpdateDate']
\end{verbatim}
We can get the lineage directly from this record:
\begin{verbatim}
>>> records[0]["Lineage"]
'cellular organisms; Eukaryota; Viridiplantae; Streptophyta; Streptophytina;
Embryophyta; Tracheophyta; Euphyllophyta; Spermatophyta; Magnoliophyta;
Liliopsida; Asparagales; Orchidaceae'
\end{verbatim}
The record data contains much more than just the information shown here - for example look under \texttt{"LineageEx"} instead of \texttt{"Lineage"} and you'll get the NCBI taxon identifiers of the lineage entries too.
\section{Using the history and WebEnv}
\label{sec:entrez-webenv}
Often you will want to make a series of linked queries. Most typically,
running a search, perhaps refining the search, and then retrieving detailed
search results. You \emph{can} do this by making a series of separate calls
to Entrez. However, the NCBI prefer you to take advantage of their history
support - for example combining ESearch and EFetch.
Another typical use of the history support would be to combine EPost and
EFetch. You use EPost to upload a list of identifiers, which starts a new
history session. You then download the records with EFetch by referring
to the session (instead of the identifiers).
\subsection{Searching for and downloading sequences using the history}
Suppose we want to search and download all the \textit{Opuntia} rpl16
nucleotide sequences, and store them in a FASTA file. As shown in
Section~\ref{sec:entrez-search-fetch-genbank}, we can naively combine
\verb|Bio.Entrez.esearch()| to get a list of GI numbers, and then call
\verb|Bio.Entrez.efetch()| to download them all.
However, the approved approach is to run the search with the history
feature. Then, we can fetch the results by reference to the search
results - which the NCBI can anticipate and cache.
To do this, call \verb|Bio.Entrez.esearch()| as normal, but with the
additional argument of \verb|usehistory="y"|,
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]"
>>> search_handle = Entrez.esearch(db="nucleotide",term="Opuntia[orgn] and rpl16",
usehistory="y")
>>> search_results = Entrez.read(search_handle)
>>> search_handle.close()
\end{verbatim}
\noindent When you get the XML output back, it will still include the usual search results:
\begin{verbatim}
>>> gi_list = search_results["IdList"]
>>> count = int(search_results["Count"])
>>> assert count == len(gi_list)
\end{verbatim}
\noindent However, you also get given two additional pieces of information, the {\tt WebEnv} session cookie, and the {\tt QueryKey}:
\begin{verbatim}
>>> webenv = search_results["WebEnv"]
>>> query_key = search_results["QueryKey"]
\end{verbatim}
Having stored these values in variables {\tt session\_cookie} and {\tt query\_key} we can use them as parameters to \verb|Bio.Entrez.efetch()| instead of giving the GI numbers as identifiers.
While for small searches you might be OK downloading everything at once, it is better to download in batches. You use the {\tt retstart} and {\tt retmax} parameters to specify which range of search results you want returned (starting entry using zero-based counting, and maximum number of results to return). For example,
\begin{verbatim}
batch_size = 3
out_handle = open("orchid_rpl16.fasta", "w")
for start in range(0,count,batch_size):
end = min(count, start+batch_size)
print "Going to download record %i to %i" % (start+1, end)
fetch_handle = Entrez.efetch(db="nucleotide", rettype="fasta", retmode="text",
retstart=start, retmax=batch_size,
webenv=webenv, query_key=query_key)
data = fetch_handle.read()
fetch_handle.close()
out_handle.write(data)
out_handle.close()
\end{verbatim}
\noindent For illustrative purposes, this example downloaded the FASTA records in batches of three. Unless you are downloading genomes or chromosomes, you would normally pick a larger batch size.
\subsection{Searching for and downloading abstracts using the history}
Here is another history example, searching for papers published in the last year about the \textit{Opuntia}, and then downloading them into a file in MedLine format:
\begin{verbatim}
from Bio import Entrez
Entrez.email = "[email protected]"
search_results = Entrez.read(Entrez.esearch(db="pubmed",
term="Opuntia[ORGN]",
reldate=365, datetype="pdat",
usehistory="y"))
count = int(search_results["Count"])
print "Found %i results" % count
batch_size = 10
out_handle = open("recent_orchid_papers.txt", "w")
for start in range(0,count,batch_size):
end = min(count, start+batch_size)
print "Going to download record %i to %i" % (start+1, end)
fetch_handle = Entrez.efetch(db="pubmed",
rettype="medline", retmode="text",
retstart=start, retmax=batch_size,
webenv=search_results["WebEnv"],
query_key=search_results["QueryKey"])
data = fetch_handle.read()
fetch_handle.close()
out_handle.write(data)
out_handle.close()
\end{verbatim}
\noindent At the time of writing, this gave 28 matches - but because this is a date dependent search, this will of course vary. As described in Section~\ref{subsec:entrez-and-medline} above, you can then use \verb|Bio.Medline| to parse the saved records.
\subsection{Searching for citations}
\label{sec:elink-citations}
Back in Section~\ref{sec:elink} we mentioned ELink can be used to search for citations of a given paper.
Unfortunately this only covers journals indexed for PubMed Central
(doing it for all the journals in PubMed would mean a lot more work for the NIH).
Let's try this for the Biopython PDB parser paper, PubMed ID 14630660:
\begin{verbatim}
>>> from Bio import Entrez
>>> Entrez.email = "[email protected]"
>>> pmid = "14630660"
>>> results = Entrez.read(Entrez.elink(dbfrom="pubmed", db="pmc",
... LinkName="pubmed_pmc_refs", from_uid=pmid))
>>> pmc_ids = [link["Id"] for link in results[0]["LinkSetDb"][0]["Link"]]
>>> pmc_ids
['2744707', '2705363', '2682512', ..., '1190160']
\end{verbatim}
Great - eleven articles. But why hasn't the Biopython application note been
found (PubMed ID 19304878)? Well, as you might have guessed from the variable
names, there are not actually PubMed IDs, but PubMed Central IDs. Our
application note is the third citing paper in that list, PMCID 2682512.
So, what if (like me) you'd rather get back a list of PubMed IDs? Well we
can call ELink again to translate them. This becomes a two step process,
so by now you should expect to use the history feature to accomplish it
(Section~\ref{sec:entrez-webenv}).
But first, taking the more straightforward approach of making a second
(separate) call to ELink:
\begin{verbatim}
>>> results2 = Entrez.read(Entrez.elink(dbfrom="pmc", db="pubmed", LinkName="pmc_pubmed",
... from_uid=",".join(pmc_ids)))
>>> pubmed_ids = [link["Id"] for link in results2[0]["LinkSetDb"][0]["Link"]]
>>> pubmed_ids
['19698094', '19450287', '19304878', ..., '15985178']
\end{verbatim}
\noindent This time you can immediately spot the Biopython application note
as the third hit (PubMed ID 19304878).
Now, let's do that all again but with the history \ldots
\textit{TODO}.
And finally, don't forget to include your \emph{own} email address in the Entrez calls.
\chapter{Swiss-Prot and ExPASy}
\label{chapter:swiss_prot}
\section{Parsing Swiss-Prot files}
Swiss-Prot (\url{http://www.expasy.org/sprot}) is a hand-curated database of protein sequences. Biopython can parse the ``plain text'' Swiss-Prot file format, which is still used for the UniProt Knowledgebase which combined Swiss-Prot, TrEMBL and PIR-PSD. We do not (yet) support the UniProtKB XML file format.
\subsection{Parsing Swiss-Prot records}
In Section~\ref{sec:SeqIO_ExPASy_and_SwissProt}, we described how to extract the sequence of a Swiss-Prot record as a \verb|SeqRecord| object. Alternatively, you can store the Swiss-Prot record in a \verb|Bio.SwissProt.Record| object, which in fact stores the complete information contained in the Swiss-Prot record. In this Section, we describe how to extract \verb|Bio.SwissProt.Record| objects from a Swiss-Prot file.
To parse a Swiss-Prot record, we first get a handle to a Swiss-Prot record. There are several ways to do so, depending on where and how the Swiss-Prot record is stored:
\begin{itemize}
\item Open a Swiss-Prot file locally: \newline
\verb|>>> handle = open("myswissprotfile.dat")|
\item Open a gzipped Swiss-Prot file:
\begin{verbatim}
>>> import gzip
>>> handle = gzip.open("myswissprotfile.dat.gz")
\end{verbatim}
\item Open a Swiss-Prot file over the internet:
\begin{verbatim}
>>> import urllib
>>> handle = urllib.urlopen("http://www.somelocation.org/data/someswissprotfile.dat")
\end{verbatim}
\item Open a Swiss-Prot file over the internet from the ExPASy database
(see section \ref{subsec:expasy_swissprot}):
\begin{verbatim}
>>> from Bio import ExPASy
>>> handle = ExPASy.get_sprot_raw(myaccessionnumber)
\end{verbatim}
\end{itemize}
The key point is that for the parser, it doesn't matter how the handle was created, as long as it points to data in the Swiss-Prot format.
We can use \verb+Bio.SeqIO+ as described in Section~\ref{sec:SeqIO_ExPASy_and_SwissProt} to get file format agnostic \verb|SeqRecord| objects. Alternatively, we can use \verb+Bio.SwissProt+ get \verb|Bio.SwissProt.Record| objects, which are a much closer match to the underlying file format.
To read one Swiss-Prot record from the handle, we use the function \verb|read()|:
\begin{verbatim}
>>> from Bio import SwissProt
>>> record = SwissProt.read(handle)
\end{verbatim}
This function should be used if the handle points to exactly one Swiss-Prot record. It raises a \verb|ValueError| if no Swiss-Prot record was found, and also if more than one record was found.
We can now print out some information about this record:
\begin{verbatim}
>>> print record.description
'RecName: Full=Chalcone synthase 3; EC=2.3.1.74; AltName: Full=Naringenin-chalcone synthase 3;'
>>> for ref in record.references:
... print "authors:", ref.authors
... print "title:", ref.title
...
authors: Liew C.F., Lim S.H., Loh C.S., Goh C.J.;
title: "Molecular cloning and sequence analysis of chalcone synthase cDNAs of
Bromheadia finlaysoniana.";
>>> print record.organism_classification
['Eukaryota', 'Viridiplantae', 'Streptophyta', 'Embryophyta', ..., 'Bromheadia']
\end{verbatim}
To parse a file that contains more than one Swiss-Prot record, we use the \verb|parse| function instead. This function allows us to iterate over the records in the file.
For example, let's parse the full Swiss-Prot database and collect all the descriptions.
You can download this from the \href{ftp://ftp.expasy.org/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.dat.gz}{ExPAYs FTP site} as a single gzipped-file \verb|uniprot_sprot.dat.gz| (about 300MB). This is a compressed file containing a single file, \verb|uniprot_sprot.dat| (over 1.5GB).
As described at the start of this section, you can use the Python library \verb|gzip| to open and uncompress a \texttt{.gz} file, like this:
\begin{verbatim}
>>> import gzip
>>> handle = gzip.open("uniprot_sprot.dat.gz")
\end{verbatim}
However, uncompressing a large file takes time, and each time you open the file for reading in this way, it has to be decompressed on the fly. So, if you can spare the disk space you'll save time in the long run if you first decompress the file to disk, to get the \verb|uniprot_sprot.dat| file inside. Then you can open the file for reading as usual:
\begin{verbatim}
>>> handle = open("uniprot_sprot.dat")
\end{verbatim}
As of June 2009, the full Swiss-Prot database downloaded from ExPASy contained 468851 Swiss-Prot records. One concise way to build up a list of the record descriptions is with a list comprehension:
\begin{verbatim}
>>> from Bio import SwissProt
>>> handle = open("uniprot_sprot.dat")
>>> descriptions = [record.description for record in SwissProt.parse(handle)]
>>> len(descriptions)
468851
>>> descriptions[:5]
['RecName: Full=Protein MGF 100-1R;',
'RecName: Full=Protein MGF 100-1R;',
'RecName: Full=Protein MGF 100-1R;',
'RecName: Full=Protein MGF 100-1R;',
'RecName: Full=Protein MGF 100-2L;']
\end{verbatim}
Or, using a for loop over the record iterator:
\begin{verbatim}
>>> from Bio import SwissProt
>>> descriptions = []
>>> handle = open("uniprot_sprot.dat")
>>> for record in SwissProt.parse(handle):
... descriptions.append(record.description)
...
>>> len(descriptions)
468851
\end{verbatim}
Because this is such a large input file, either way takes about eleven minutes on my new desktop computer (using the uncompressed \verb|uniprot_sprot.dat| file as input).
It is equally easy to extract any kind of information you'd like from Swiss-Prot records. To see the members of a Swiss-Prot record, use
\begin{verbatim}
>>> dir(record)
['__doc__', '__init__', '__module__', 'accessions', 'annotation_update',
'comments', 'created', 'cross_references', 'data_class', 'description',
'entry_name', 'features', 'gene_name', 'host_organism', 'keywords',
'molecule_type', 'organelle', 'organism', 'organism_classification',
'references', 'seqinfo', 'sequence', 'sequence_length',
'sequence_update', 'taxonomy_id']
\end{verbatim}
\subsection{Parsing the Swiss-Prot keyword and category list}
Swiss-Prot also distributes a file \verb+keywlist.txt+, which lists the keywords and categories used in Swiss-Prot. The file contains entries in the following form:
\begin{verbatim}
ID 2Fe-2S.
AC KW-0001
DE Protein which contains at least one 2Fe-2S iron-sulfur cluster: 2 iron
DE atoms complexed to 2 inorganic sulfides and 4 sulfur atoms of
DE cysteines from the protein.
SY Fe2S2; [2Fe-2S] cluster; [Fe2S2] cluster; Fe2/S2 (inorganic) cluster;
SY Di-mu-sulfido-diiron; 2 iron, 2 sulfur cluster binding.
GO GO:0051537; 2 iron, 2 sulfur cluster binding
HI Ligand: Iron; Iron-sulfur; 2Fe-2S.
HI Ligand: Metal-binding; 2Fe-2S.
CA Ligand.
//
ID 3D-structure.
AC KW-0002
DE Protein, or part of a protein, whose three-dimensional structure has
DE been resolved experimentally (for example by X-ray crystallography or
DE NMR spectroscopy) and whose coordinates are available in the PDB
DE database. Can also be used for theoretical models.
HI Technical term: 3D-structure.
CA Technical term.
//
ID 3Fe-4S.
...
\end{verbatim}
The entries in this file can be parsed by the \verb+parse+ function in the \verb+Bio.SwissProt.KeyWList+ module. Each entry is then stored as a \verb+Bio.SwissProt.KeyWList.Record+, which is a Python dictionary.
\begin{verbatim}
>>> from Bio.SwissProt import KeyWList
>>> handle = open("keywlist.txt")
>>> records = KeyWList.parse(handle)
>>> for record in records:
... print record['ID']
... print record['DE']
\end{verbatim}
This prints
\begin{verbatim}
2Fe-2S.
Protein which contains at least one 2Fe-2S iron-sulfur cluster: 2 iron atoms
complexed to 2 inorganic sulfides and 4 sulfur atoms of cysteines from the
protein.
...
\end{verbatim}
\section{Parsing Prosite records}
Prosite is a database containing protein domains, protein families, functional sites, as well as the patterns and profiles to recognize them. Prosite was developed in parallel with Swiss-Prot. In Biopython, a Prosite record is represented by the \verb|Bio.ExPASy.Prosite.Record| class, whose members correspond to the different fields in a Prosite record.
In general, a Prosite file can contain more than one Prosite records. For example, the full set of Prosite records, which can be downloaded as a single file (\verb|prosite.dat|) from the \href{ftp://ftp.expasy.org/databases/prosite/prosite.dat}{ExPASy FTP site}, contains 2073 records (version 20.24 released on 4 December 2007). To parse such a file, we again make use of an iterator:
\begin{verbatim}
>>> from Bio.ExPASy import Prosite
>>> handle = open("myprositefile.dat")
>>> records = Prosite.parse(handle)
\end{verbatim}
We can now take the records one at a time and print out some information. For example, using the file containing the complete Prosite database, we'd find
\begin{verbatim}
>>> from Bio.ExPASy import Prosite
>>> handle = open("prosite.dat")
>>> records = Prosite.parse(handle)
>>> record = records.next()
>>> record.accession
'PS00001'
>>> record.name
'ASN_GLYCOSYLATION'
>>> record.pdoc
'PDOC00001'
>>> record = records.next()
>>> record.accession
'PS00004'
>>> record.name
'CAMP_PHOSPHO_SITE'
>>> record.pdoc
'PDOC00004'
>>> record = records.next()
>>> record.accession
'PS00005'
>>> record.name
'PKC_PHOSPHO_SITE'
>>> record.pdoc
'PDOC00005'
\end{verbatim}
and so on. If you're interested in how many Prosite records there are, you could use
\begin{verbatim}
>>> from Bio.ExPASy import Prosite
>>> handle = open("prosite.dat")
>>> records = Prosite.parse(handle)
>>> n = 0
>>> for record in records: n+=1
...
>>> print n
2073
\end{verbatim}
To read exactly one Prosite from the handle, you can use the \verb|read| function:
\begin{verbatim}
>>> from Bio.ExPASy import Prosite
>>> handle = open("mysingleprositerecord.dat")
>>> record = Prosite.read(handle)
\end{verbatim}
This function raises a ValueError if no Prosite record is found, and also if more than one Prosite record is found.
\section{Parsing Prosite documentation records}
In the Prosite example above, the \verb|record.pdoc| accession numbers \verb|'PDOC00001'|, \verb|'PDOC00004'|, \verb|'PDOC00005'| and so on refer to Prosite documentation. The Prosite documentation records are available from ExPASy as individual files, and as one file (\verb|prosite.doc|) containing all Prosite documentation records.
We use the parser in \verb|Bio.ExPASy.Prodoc| to parse Prosite documentation records. For example, to create a list of all accession numbers of Prosite documentation record, you can use
\begin{verbatim}
>>> from Bio.ExPASy import Prodoc
>>> handle = open("prosite.doc")
>>> records = Prodoc.parse(handle)
>>> accessions = [record.accession for record in records]
\end{verbatim}
Again a \verb|read()| function is provided to read exactly one Prosite documentation record from the handle.
\section{Parsing Enzyme records}
ExPASy's Enzyme database is a repository of information on enzyme nomenclature. A typical Enzyme record looks as follows:
\begin{verbatim}
ID 3.1.1.34
DE Lipoprotein lipase.
AN Clearing factor lipase.
AN Diacylglycerol lipase.
AN Diglyceride lipase.
CA Triacylglycerol + H(2)O = diacylglycerol + a carboxylate.
CC -!- Hydrolyzes triacylglycerols in chylomicrons and very low-density
CC lipoproteins (VLDL).
CC -!- Also hydrolyzes diacylglycerol.
PR PROSITE; PDOC00110;
DR P11151, LIPL_BOVIN ; P11153, LIPL_CAVPO ; P11602, LIPL_CHICK ;
DR P55031, LIPL_FELCA ; P06858, LIPL_HUMAN ; P11152, LIPL_MOUSE ;
DR O46647, LIPL_MUSVI ; P49060, LIPL_PAPAN ; P49923, LIPL_PIG ;
DR Q06000, LIPL_RAT ; Q29524, LIPL_SHEEP ;
//
\end{verbatim}
In this example, the first line shows the EC (Enzyme Commission) number of lipoprotein lipase (second line). Alternative names of lipoprotein lipase are "clearing factor lipase", "diacylglycerol lipase", and "diglyceride lipase" (lines 3 through 5). The line starting with "CA" shows the catalytic activity of this enzyme. Comment lines start with "CC". The "PR" line shows references to the Prosite Documentation records, and the "DR" lines show references to Swiss-Prot records. Not of these entries are necessarily present in an Enzyme record.
In Biopython, an Enzyme record is represented by the \verb|Bio.ExPASy.Enzyme.Record| class. This record derives from a Python dictionary and has keys corresponding to the two-letter codes used in Enzyme files. To read an Enzyme file containing one Enzyme record, use the \verb+read+ function in \verb|Bio.ExPASy.Enzyme|:
%doctest ../Tests/Enzymes
\begin{verbatim}
>>> from Bio.ExPASy import Enzyme
>>> handle = open("lipoprotein.txt")
>>> record = Enzyme.read(handle)
>>> record["ID"]
'3.1.1.34'
>>> record["DE"]
'Lipoprotein lipase.'
>>> record["AN"]
['Clearing factor lipase.', 'Diacylglycerol lipase.', 'Diglyceride lipase.']
>>> record["CA"]
'Triacylglycerol + H(2)O = diacylglycerol + a carboxylate.'
>>> record["PR"]
['PDOC00110']
\end{verbatim}
%TODO - line wrapping?
\begin{verbatim}
>>> record["CC"]
['Hydrolyzes triacylglycerols in chylomicrons and very low-density lipoproteins
(VLDL).', 'Also hydrolyzes diacylglycerol.']
>>> record["DR"]
[['P11151', 'LIPL_BOVIN'], ['P11153', 'LIPL_CAVPO'], ['P11602', 'LIPL_CHICK'],
['P55031', 'LIPL_FELCA'], ['P06858', 'LIPL_HUMAN'], ['P11152', 'LIPL_MOUSE'],
['O46647', 'LIPL_MUSVI'], ['P49060', 'LIPL_PAPAN'], ['P49923', 'LIPL_PIG'],
['Q06000', 'LIPL_RAT'], ['Q29524', 'LIPL_SHEEP']]
\end{verbatim}
The \verb+read+ function raises a ValueError if no Enzyme record is found, and also if more than one Enzyme record is found.
The full set of Enzyme records can be downloaded as a single file (\verb|enzyme.dat|) from the \href{ftp://ftp.expasy.org/databases/enzyme/enzyme.dat}{ExPASy FTP site}, containing 4877 records (release of 3 March 2009). To parse such a file containing multiple Enzyme records, use the \verb+parse+ function in \verb+Bio.ExPASy.Enzyme+ to obtain an iterator:
\begin{verbatim}
>>> from Bio.ExPASy import Enzyme
>>> handle = open("enzyme.dat")
>>> records = Enzyme.parse(handle)
\end{verbatim}
We can now iterate over the records one at a time. For example, we can make a list of all EC numbers for which an Enzyme record is available:
\begin{verbatim}
>>> ecnumbers = [record["ID"] for record in records]
\end{verbatim}
\section{Accessing the ExPASy server}
Swiss-Prot, Prosite, and Prosite documentation records can be downloaded from the ExPASy web server at \url{http://www.expasy.org}. Six kinds of queries are available from ExPASy:
\begin{description}
\item[get\_prodoc\_entry]To download a Prosite documentation record in HTML format
\item[get\_prosite\_entry]To download a Prosite record in HTML format
\item[get\_prosite\_raw]To download a Prosite or Prosite documentation record in raw format
\item[get\_sprot\_raw]To download a Swiss-Prot record in raw format
\item[sprot\_search\_ful]To search for a Swiss-Prot record
\item[sprot\_search\_de]To search for a Swiss-Prot record
\end{description}
To access this web server from a Python script, we use the \verb|Bio.ExPASy| module.
\subsection{Retrieving a Swiss-Prot record}
\label{subsec:expasy_swissprot}
Let's say we are looking at chalcone synthases for Orchids (see section~\ref{sec:orchids} for some justification for looking for interesting things about orchids). Chalcone synthase is involved in flavanoid biosynthesis in plants, and flavanoids make lots of cool things like pigment colors and UV protectants.
If you do a search on Swiss-Prot, you can find three orchid proteins for Chalcone Synthase, id numbers O23729, O23730, O23731. Now, let's write a script which grabs these, and parses out some interesting information.
First, we grab the records, using the \verb|get_sprot_raw()| function of \verb|Bio.ExPASy|. This function is very nice since you can feed it an id and get back a handle to a raw text record (no html to mess with!). We can the use \verb|Bio.SwissProt.read| to pull out the Swiss-Prot record, or \verb|Bio.SeqIO.read| to get a SeqRecord. The following code accomplishes what I just wrote:
\begin{verbatim}
>>> from Bio import ExPASy
>>> from Bio import SwissProt
>>> accessions = ["O23729", "O23730", "O23731"]
>>> records = []
>>> for accession in accessions:
... handle = ExPASy.get_sprot_raw(accession)
... record = SwissProt.read(handle)
... records.append(record)
\end{verbatim}
If the accession number you provided to \verb|ExPASy.get_sprot_raw| does not exist, then \verb|SwissProt.read(handle)| will raise a \verb|ValueError|. You can catch \verb|ValueException| exceptions to detect invalid accession numbers:
\begin{verbatim}
>>> for accession in accessions:
... handle = ExPASy.get_sprot_raw(accession)
... try:
... record = SwissProt.read(handle)
... except ValueException:
... print "WARNING: Accession %s not found" % accession
... records.append(record)
\end{verbatim}
\subsection{Searching Swiss-Prot}
Now, you may remark that I knew the records' accession numbers
beforehand. Indeed, \verb|get_sprot_raw()| needs either the entry name
or an accession number. When you don't have them handy, you can use
one of the \verb|sprot_search_de()| or \verb|sprot_search_ful()|
functions.
\verb|sprot_search_de()| searches in the ID, DE, GN, OS and OG lines;
\verb|sprot_search_ful()| searches in (nearly) all the fields. They
are detailed on
\url{http://www.expasy.org/cgi-bin/sprot-search-de} and
\url{http://www.expasy.org/cgi-bin/sprot-search-ful}
respectively. Note that they don't search in TrEMBL by default
(argument \verb|trembl|). Note also that they return html pages;
however, accession numbers are quite easily extractable:
\begin{verbatim}
>>> from Bio import ExPASy
>>> import re
>>> handle = ExPASy.sprot_search_de("Orchid Chalcone Synthase")
>>> # or:
>>> # handle = ExPASy.sprot_search_ful("Orchid and {Chalcone Synthase}")
>>> html_results = handle.read()
>>> if "Number of sequences found" in html_results:
... ids = re.findall(r'HREF="/uniprot/(\w+)"', html_results)
... else:
... ids = re.findall(r'href="/cgi-bin/niceprot\.pl\?(\w+)"', html_results)
\end{verbatim}
\subsection{Retrieving Prosite and Prosite documentation records}
Prosite and Prosite documentation records can be retrieved either in HTML format, or in raw format. To parse Prosite and Prosite documentation records with Biopython, you should retrieve the records in raw format. For other purposes, however, you may be interested in these records in HTML format.
To retrieve a Prosite or Prosite documentation record in raw format, use \verb|get_prosite_raw()|. For example, to download a Prosite record and print it out in raw text format, use
\begin{verbatim}
>>> from Bio import ExPASy
>>> handle = ExPASy.get_prosite_raw('PS00001')
>>> text = handle.read()
>>> print text
\end{verbatim}
To retrieve a Prosite record and parse it into a \verb|Bio.Prosite.Record| object, use
\begin{verbatim}
>>> from Bio import ExPASy
>>> from Bio import Prosite
>>> handle = ExPASy.get_prosite_raw('PS00001')
>>> record = Prosite.read(handle)
\end{verbatim}
The same function can be used to retrieve a Prosite documentation record and parse it into a \verb|Bio.ExPASy.Prodoc.Record| object:
\begin{verbatim}
>>> from Bio import ExPASy
>>> from Bio.ExPASy import Prodoc
>>> handle = ExPASy.get_prosite_raw('PDOC00001')
>>> record = Prodoc.read(handle)
\end{verbatim}
For non-existing accession numbers, \verb|ExPASy.get_prosite_raw| returns a handle to an emptry string. When faced with an empty string, \verb|Prosite.read| and \verb|Prodoc.read| will raise a ValueError. You can catch these exceptions to detect invalid accession numbers.
The functions \verb|get_prosite_entry()| and \verb|get_prodoc_entry()| are used to download Prosite and Prosite documentation records in HTML format. To create a web page showing one Prosite record, you can use
\begin{verbatim}
>>> from Bio import ExPASy
>>> handle = ExPASy.get_prosite_entry('PS00001')
>>> html = handle.read()
>>> output = open("myprositerecord.html", "w")
>>> output.write(html)
>>> output.close()
\end{verbatim}
and similarly for a Prosite documentation record:
\begin{verbatim}
>>> from Bio import ExPASy
>>> handle = ExPASy.get_prodoc_entry('PDOC00001')
>>> html = handle.read()
>>> output = open("myprodocrecord.html", "w")
>>> output.write(html)
>>> output.close()
\end{verbatim}
For these functions, an invalid accession number returns an error message in HTML format.
\section{Scanning the Prosite database}
\href{http://www.expasy.org/tools/scanprosite/}{ScanProsite} allows you to scan protein sequences online against the Prosite database by providing a UniProt or PDB sequence identifier or the sequence itself. For more information about ScanProsite, please see the \href{http://www.expasy.org/tools/scanprosite/scanprosite-doc.html}{ScanProsite documentation} as well as the \href{http://www.expasy.org/tools/scanprosite/ScanPrositeREST.html}{documentation for programmatic access of ScanProsite}.
You can use Biopython's \verb+Bio.ExPASy.ScanProsite+ module to scan the Prosite database from Python. This module both helps you to access ScanProsite programmatically, and to parse the results returned by ScanProsite. To scan for Prosite patterns in the following protein sequence:
\begin{verbatim}
MEHKEVVLLLLLFLKSGQGEPLDDYVNTQGASLFSVTKKQLGAGSIEECAAKCEEDEEFT
CRAFQYHSKEQQCVIMAENRKSSIIIRMRDVVLFEKKVYLSECKTGNGKNYRGTMSKTKN
\end{verbatim}
you can use the following code:
\begin{verbatim}
>>> sequence = "MEHKEVVLLLLLFLKSGQGEPLDDYVNTQGASLFSVTKKQLGAGSIEECAAKCEEDEEFT
CRAFQYHSKEQQCVIMAENRKSSIIIRMRDVVLFEKKVYLSECKTGNGKNYRGTMSKTKN"
>>> from Bio.ExPASy import ScanProsite
>>> handle = ScanProsite.scan(seq=sequence)
\end{verbatim}
By executing \verb+handle.read()+, you can obtain the search results in raw XML format. Instead, let's use \verb+Bio.ExPASy.ScanProsite.read+ to parse the raw XML into a Python object:
\begin{verbatim}
>>> result = ScanProsite.read(handle)
>>> type(result)
<class 'Bio.ExPASy.ScanProsite.Record'>
\end{verbatim}
A \verb+Bio.ExPASy.ScanProsite.Record+ object is derived from a list, with each element in the list storing one ScanProsite hit. This object also stores the number of hits, as well as the number of search sequences, as returned by ScanProsite. This ScanProsite search resulted in six hits:
\begin{verbatim}
>>> result.n_seq
1
>>> result.n_match
6
>>> len(result)
6
>>> result[0]
{'signature_ac': u'PS50948', 'level': u'0', 'stop': 98, 'sequence_ac': u'USERSEQ1', 'start': 16, 'score': u'8.873'}
>>> result[1]
{'start': 37, 'stop': 39, 'sequence_ac': u'USERSEQ1', 'signature_ac': u'PS00005'}
>>> result[2]
{'start': 45, 'stop': 48, 'sequence_ac': u'USERSEQ1', 'signature_ac': u'PS00006'}
>>> result[3]
{'start': 60, 'stop': 62, 'sequence_ac': u'USERSEQ1', 'signature_ac': u'PS00005'}
>>> result[4]
{'start': 80, 'stop': 83, 'sequence_ac': u'USERSEQ1', 'signature_ac': u'PS00004'}
>>> result[5]
{'start': 106, 'stop': 111, 'sequence_ac': u'USERSEQ1', 'signature_ac': u'PS00008'}
\end{verbatim}
Other ScanProsite parameters can be passed as keyword arguments; see the \href{http://www.expasy.org/tools/scanprosite/ScanPrositeREST.html}{documentation for programmatic access of ScanProsite} for more information. As an example, passing \verb+lowscore=1+ to include matches with low level scores lets use find one additional hit:
\begin{verbatim}
>>> handle = ScanProsite.scan(seq=sequence, lowscore=1)
>>> result = ScanProsite.read(handle)
>>> result.n_match
7
\end{verbatim}
\chapter{Going 3D: The PDB module}
Bio.PDB is a Biopython module that focuses on working with crystal structures of biological macromolecules. Among other things, Bio.PDB includes a PDBParser class that produces a Structure object, which can be used to access the atomic data in the file in a convenient manner. There is limited support for parsing the information contained in the PDB header.
%Note the \verb|Bio.PDB| module requires Numerical Python (numpy) to be installed.
\section{Reading and writing crystal structure files}
\subsection{Reading a PDB file}
First we create a \texttt{PDBParser} object:
\begin{verbatim}
>>> from Bio.PDB.PDBParser import PDBParser
>>> p = PDBParser(PERMISSIVE=1)
\end{verbatim}
The {\tt PERMISSIVE} flag indicates that a number of common problems (see \ref{problem structures}) associated with PDB files will be ignored (but note that some atoms and/or residues will be missing). If the flag is not present a {\tt PDBConstructionException} will be generated if any problems are detected during the parse operation.
The Structure object is then produced by letting the \texttt{PDBParser} object parse a PDB file (the PDB file in this case is called 'pdb1fat.ent', '1fat' is a user defined name for the structure):
\begin{verbatim}
>>> structure_id = "1fat"
>>> filename = "pdb1fat.ent"
>>> s = p.get_structure(structure_id, filename)
\end{verbatim}
You can extract the header and trailer (simple lists of strings) of the PDB
file from the PDBParser object with the {\tt get\_header} and {\tt get\_trailer}
methods. Note however that many PDB files contain headers with
incomplete or erroneous information. Many of the errors have been
fixed in the equivalent mmCIF files. \emph{Hence, if you are interested
in the header information, it is a good idea to extract information
from mmCIF files using the} \texttt{\emph{MMCIF2Dict}} \emph{tool
described below, instead of parsing the PDB header. }
Now that is clarified, let's return to parsing the PDB header. The
structure object has an attribute called \texttt{header} which is
a Python dictionary that maps header records to their values.
Example:
\begin{verbatim}
>>> resolution = structure.header['resolution']
>>> keywords = structure.header['keywords']
\end{verbatim}
The available keys are \verb+name+, \verb+head+, \verb+deposition_date+, \verb+release_date+, \verb+structure_method+, \verb+resolution+, \verb+structure_reference+ (which maps to a list of references), \verb+journal_reference+, \verb+author+, and \verb+compound+ (which maps to a dictionary with various information about the crystallized compound).
The dictionary can also be created without creating a \texttt{Structure}
object, ie. directly from the PDB file:
\begin{verbatim}
>>> file = open(filename,'r')
>>> header_dict = parse_pdb_header(file)
>>> file.close()
\end{verbatim}
\subsection{Reading an mmCIF file}
Similarly to the case the case of PDB files, first create an \texttt{MMCIFParser} object:
\begin{verbatim}
>>> from Bio.PDB.MMCIFParser import MMCIFParser
>>> parser = MMCIFParser()
\end{verbatim}
Then use this parser to create a structure object from the mmCIF file:
\begin{verbatim}
>>> structure = parser.get_structure('1fat', '1fat.cif')
\end{verbatim}
To have some more low level access to an mmCIF file, you can use the \verb+MMCIF2Dict+ class to create a Python dictionary that maps all mmCIF
tags in an mmCIF file to their values. If there are multiple values
(like in the case of tag \verb+_atom_site.Cartn_y+, which holds
the $y$ coordinates of all atoms), the tag is mapped to a list of values.
The dictionary is created from the mmCIF file as follows:
\begin{verbatim}
>>> from Bio.PDB.MMCIF2Dict import MMCIF2Dict
>>> mmcif_dict = MMCIF2Dict('1FAT.cif')
\end{verbatim}
Example: get the solvent content from an mmCIF file:
\begin{verbatim}
>>> sc = mmcif_dict['_exptl_crystal.density_percent_sol']
\end{verbatim}
Example: get the list of the $y$ coordinates of all atoms
\begin{verbatim}
>>> y_list = mmcif_dict['_atom_site.Cartn_y']
\end{verbatim}
\subsection{Reading files in the PDB XML format}
That's not yet supported, but we are definitely planning to support that
in the future (it's not a lot of work). Contact the Biopython developers
(\mailto{[email protected]}) if you need this).
\subsection{Writing PDB files}
Use the PDBIO class for this. It's easy to write out specific parts
of a structure too, of course.
Example: saving a structure
\begin{verbatim}
>>> io = PDBIO()
>>> io.set_structure(s)
>>> io.save('out.pdb')
\end{verbatim}
If you want to write out a part of the structure, make use of the
\texttt{Select} class (also in \texttt{PDBIO}). Select has four methods:
\begin{itemize}
\item \verb+accept_model(model)+
\item \verb+accept_chain(chain)+
\item \verb+accept_residue(residue)+
\item \verb+accept_atom(atom)+
\end{itemize}
By default, every method returns 1 (which means the model/\-chain/\-residue/\-atom
is included in the output). By subclassing \texttt{Select} and returning
0 when appropriate you can exclude models, chains, etc. from the output.
Cumbersome maybe, but very powerful. The following code only writes
out glycine residues:
\begin{verbatim}
>>> class GlySelect(Select):
... def accept_residue(self, residue):
... if residue.get_name()=='GLY':
... return True
... else:
... return False
...
>>> io = PDBIO()
>>> io.set_structure(s)
>>> io.save('gly_only.pdb', GlySelect())
\end{verbatim}
If this is all too complicated for you, the \texttt{Dice} module contains
a handy \texttt{extract} function that writes out all residues in
a chain between a start and end residue.
\section{Structure representation}
The overall layout of a \texttt{Structure} object follows the so-called SMCRA
(Structure/Model/Chain/Residue/Atom) architecture:
\begin{itemize}
\item A structure consists of models
\item A model consists of chains
\item A chain consists of residues
\item A residue consists of atoms
\end{itemize}
This is the way many structural biologists/bioinformaticians think
about structure, and provides a simple but efficient way to deal with
structure. Additional stuff is essentially added when needed. A UML
diagram of the \texttt{Structure} object (forget about the \texttt{Disordered}
classes for now) is shown in Fig. \ref{fig:smcra}. Such a data structure is not
necessarily best suited for the representation of the macromolecular content of
a structure, but it is absolutely necessary for a good interpretation of the
data present in a file that describes the structure (typically a PDB or MMCIF
file). If this hierarchy cannot represent the contents of a structure file, it
is fairly certain that the file contains an error or at least does not describe
the structure unambiguously. If a SMCRA data structure cannot be generated,
there is reason to suspect a problem. Parsing a PDB file can thus be used to
detect likely problems. We will give several examples of this in section
\ref{problem structures}.
\begin{figure}[htbp]
\begin{htmlonly}
\imgsrc[width=650, height=750]{images/smcra.png}
\end{htmlonly}
\begin{latexonly}
\centering
\includegraphics[width=0.8\textwidth]{images/smcra.png}
\end{latexonly}
\caption{UML diagram of SMCRA architecture of the \texttt{Structure} class used to represent a macromolecular structure.
Full lines with diamonds denote aggregation, full lines with
arrows denote referencing, full lines with triangles denote inheritance
and dashed lines with triangles denote interface realization.}
\label{fig:smcra}
\end{figure}
Structure, Model, Chain and Residue are all subclasses of the Entity base class.
The Atom class only (partly) implements the Entity interface (because an Atom
does not have children).
For each Entity subclass, you can extract a child by using a unique id for that
child as a key (e.g. you can extract an Atom object from a Residue object by
using an atom name string as a key, you can extract a Chain object from a Model
object by using its chain identifier as a key).
Disordered atoms and residues are represented by DisorderedAtom and DisorderedResidue
classes, which are both subclasses of the DisorderedEntityWrapper base class.
They hide the complexity associated with disorder and behave exactly as Atom
and Residue objects.
In general, a child Entity object (i.e. Atom, Residue, Chain, Model) can be
extracted from its parent (i.e. Residue, Chain, Model, Structure, respectively)
by using an id as a key.
\begin{verbatim}
>>> child_entity = parent_entity[child_id]
\end{verbatim}
You can also get a list of all child Entities of a parent Entity object. Note
that this list is sorted in a specific way (e.g. according to chain identifier
for Chain objects in a Model object).
\begin{verbatim}
>>> child_list = parent_entity.get_list()
\end{verbatim}
You can also get the parent from a child:
\begin{verbatim}
>>> parent_entity = child_entity.get_parent()
\end{verbatim}
At all levels of the SMCRA hierarchy, you can also extract a \emph{full id}.
The full id is a tuple containing all id's starting from the top object (Structure)
down to the current object. A full id for a Residue object e.g. is something
like:
\begin{verbatim}
>>> full_id = residue.get_full_id()
>>> print full_id
("1abc", 0, "A", ("", 10, "A"))
\end{verbatim}
This corresponds to:
\begin{itemize}
\item The Structure with id \char`\"{}1abc\char`\"{}
\item The Model with id 0
\item The Chain with id \char`\"{}A\char`\"{}
\item The Residue with id (\char`\"{} \char`\"{}, 10, \char`\"{}A\char`\"{}).
\end{itemize}
The Residue id indicates that the residue is not a hetero-residue (nor a water)
because it has a blank hetero field, that its sequence identifier is 10 and
that its insertion code is \char`\"{}A\char`\"{}.
To get the entity's id, use the \verb+get_id+ method:
\begin{verbatim}
>>> entity.get_id()
\end{verbatim}
You can check if the entity has a child with a given id by using the \verb+has_id+ method:
\begin{verbatim}
>>> entity.has_id(entity_id)
\end{verbatim}
The length of an entity is equal to its number of children:
\begin{verbatim}
>>> nr_children = len(entity)
\end{verbatim}
It is possible to delete, rename, add, etc. child entities from a parent entity,
but this does not include any sanity checks (e.g. it is possible to add two
residues with the same id to one chain). This really should be done via a nice
Decorator class that includes integrity checking, but you can take a look at
the code (Entity.py) if you want to use the raw interface.
\subsection{Structure}
The Structure object is at the top of the hierarchy. Its id is a user given
string. The Structure contains a number of Model children. Most crystal structures
(but not all) contain a single model, while NMR structures typically consist
of several models. Disorder in crystal structures of large parts of molecules
can also result in several models.
\subsection{Model}
The id of the Model object is an integer, which is derived from the position
of the model in the parsed file (they are automatically numbered starting from
0).
Crystal structures generally have only one model (with id 0), while NMR files usually have several models. Whereas many PDB parsers assume that there is only one model, the \verb+Structure+ class in \verb+Bio.PDB+ is designed such that it can easily handle PDB files with more than one model.
As an example, to get the first model from a Structure object, use
\begin{verbatim}
>>> first_model = structure[0]
\end{verbatim}
The Model object stores a list of Chain children.
\subsection{Chain}
The id of a Chain object is derived from the chain identifier in the PDB/mmCIF
file, and is a single character (typically a letter). Each Chain in a Model object has a unique id. As an example, to get the Chain object with identifier ``A'' from a Model object, use
\begin{verbatim}
>>> chain_A = model["A"]
\end{verbatim}
The Chain object stores a list of Residue children.
\subsection{Residue}
A residue id is a tuple with three elements:
\begin{itemize}
\item The \textbf{hetero-field} (hetfield): this is
\begin{itemize}
\item \verb+'W'+ in the case of a water molecule;
\item \verb+'H_'+ followed by the residue name for other hetero residues (e.g. \verb+'H_GLC'+ in the case of a glucose molecule);
\item blank for standard amino and nucleic acids.
\end{itemize}
This scheme is adopted for reasons described in section \ref{hetero problems}.
\item The \textbf{sequence identifier} (resseq), an integer describing the position of the residue in the chain (e.g., 100);
\item The \textbf{insertion code} (icode); a string, e.g. 'A'. The insertion code is sometimes used to preserve a certain desirable residue numbering scheme. A Ser 80 insertion mutant (inserted e.g. between a Thr 80 and an Asn 81
residue) could e.g. have sequence identifiers and insertion codes
as follows: Thr 80 A, Ser 80 B, Asn 81. In this way the residue numbering
scheme stays in tune with that of the wild type structure.
\end{itemize}
The id of the above glucose residue would thus be \texttt{('H\_GLC',
100, 'A')}. If the hetero-flag and insertion code are blank, the sequence
identifier alone can be used:
\begin{verbatim}
# Full id
>>> residue=chain[(' ', 100, ' ')]
# Shortcut id
>>> residue=chain[100]
\end{verbatim}
The reason for the hetero-flag is that many, many PDB files use the
same sequence identifier for an amino acid and a hetero-residue or
a water, which would create obvious problems if the hetero-flag was
not used.
Unsurprisingly, a Residue object stores a set of Atom children. It also contains a string that specifies the residue name (e.g. ``ASN'')
and the segment identifier of the residue (well known to X-PLOR users, but not
used in the construction of the SMCRA data structure).
Let's look at some examples. Asn 10 with a blank insertion code would have residue
id {\tt (' ', 10, ' ')}. Water 10 would have residue id {\tt ('W', 10, ' ')}.
A glucose molecule (a hetero residue with residue name GLC) with sequence identifier
10 would have residue id {\tt ('H\_GLC', 10, ' ')}. In this way, the three
residues (with the same insertion code and sequence identifier) can be part
of the same chain because their residue id's are distinct.
In most cases, the hetflag and insertion code fields will be blank, e.g. {\tt (' ', 10, ' ')}.
In these cases, the sequence identifier can be used as a shortcut for the full
id:
\begin{verbatim}
# use full id
>>> res10 = chain[(' ', 10, ' ')]
# use shortcut
>>> res10 = chain[10]
\end{verbatim}
Each Residue object in a Chain object should have a unique id. However, disordered
residues are dealt with in a special way, as described in section \ref{point mutations}.
A Residue object has a number of additional methods:
\begin{verbatim}
>>> residue.get_resname() # returns the residue name, e.g. "ASN"
>>> residue.is_disordered() # returns 1 if the residue has disordered atoms
>>> residue.get_segid() # returns the SEGID, e.g. "CHN1"
>>> residue.has_id(name) # test if a residue has a certain atom
\end{verbatim}
You can use \texttt{is\_aa(residue)} to test if a Residue object is an amino acid.
\subsection{Atom}
The Atom object stores the data associated with an atom, and has no children.
The id of an atom is its atom name (e.g. ``OG'' for the side chain oxygen
of a Ser residue). An Atom id needs to be unique in a Residue. Again, an exception is made for disordered atoms, as described in section \ref{disordered atoms}.
The atom id is simply the atom name (eg. \texttt{'CA'}). In practice,
the atom name is created by stripping all spaces from the atom name
in the PDB file.
However, in PDB files, a space can be part of an atom name. Often,
calcium atoms are called \texttt{'CA..'} in order to distinguish them
from C$\alpha$ atoms (which are called \texttt{'.CA.'}). In cases
were stripping the spaces would create problems (ie. two atoms called
\texttt{'CA'} in the same residue) the spaces are kept.
In a PDB file, an atom name consists of 4 chars, typically with leading and
trailing spaces. Often these spaces can be removed for ease of use (e.g. an
amino acid C\( \alpha \) atom is labeled ``.CA.'' in a PDB file, where
the dots represent spaces). To generate an atom name (and thus an atom id) the
spaces are removed, unless this would result in a name collision in a Residue
(i.e. two Atom objects with the same atom name and id). In the latter case,
the atom name including spaces is tried. This situation can e.g. happen when
one residue contains atoms with names ``.CA.'' and ``CA..'', although
this is not very likely.
The atomic data stored includes the atom name, the atomic coordinates (including
standard deviation if present), the B factor (including anisotropic B factors
and standard deviation if present), the altloc specifier and the full atom name
including spaces. Less used items like the atom element number or the atomic
charge sometimes specified in a PDB file are not stored.
To manipulate the atomic coordinates, use the \texttt{transform} method of
the \texttt{Atom} object. Use the \texttt{set\_coord} method to specify the
atomic coordinates directly.
An Atom object has the following additional methods:
\begin{verbatim}
>>> a.get_name() # atom name (spaces stripped, e.g. "CA")
>>> a.get_id() # id (equals atom name)
>>> a.get_coord() # atomic coordinates
>>> a.get_vector() # atomic coordinates as Vector object
>>> a.get_bfactor() # isotropic B factor
>>> a.get_occupancy() # occupancy
>>> a.get_altloc() # alternative location specifier
>>> a.get_sigatm() # standard deviation of atomic parameters
>>> a.get_siguij() # standard deviation of anisotropic B factor
>>> a.get_anisou() # anisotropic B factor
>>> a.get_fullname() # atom name (with spaces, e.g. ".CA.")
\end{verbatim}
To represent the atom coordinates, siguij, anisotropic B factor and sigatm Numpy
arrays are used.
The \texttt{get\_vector} method returns a \texttt{Vector} object representation of the coordinates of the \texttt{Atom} object, allowing you to do vector operations on atomic coordinates. \texttt{Vector} implements the full set of 3D vector operations, matrix multiplication (left and right) and some advanced rotation-related operations as well.
As an example of the capabilities of Bio.PDB's \texttt{Vector} module,
suppose that you would like to find the position of a Gly residue's C$\beta$
atom, if it had one. Rotating the N atom of
the Gly residue along the C$\alpha$-C bond over -120 degrees roughly
puts it in the position of a virtual C$\beta$ atom. Here's how to
do it, making use of the \texttt{rotaxis} method (which can be used
to construct a rotation around a certain axis) of the \texttt{Vector}
module:
\begin{verbatim}
# get atom coordinates as vectors
>>> n = residue['N'].get_vector()
>>> c = residue['C'].get_vector()
>>> ca = residue['CA'].get_vector()
# center at origin
>>> n = n - ca
>>> c = c - ca
# find rotation matrix that rotates n
# -120 degrees along the ca-c vector
>>> rot = rotaxis(-pi * 120.0/180.0, c)
# apply rotation to ca-n vector
>>> cb_at_origin = n.left_multiply(rot)
# put on top of ca atom
>>> cb = cb_at_origin+ca
\end{verbatim}
This example shows that it's possible to do some quite nontrivial
vector operations on atomic data, which can be quite useful. In addition
to all the usual vector operations (cross (use \texttt{{*}{*}}), and
dot (use \texttt{{*}}) product, angle, norm, etc.) and the above mentioned
\texttt{rotaxis} function, the \texttt{Vector} module also has methods
to rotate (\texttt{rotmat}) or reflect (\texttt{refmat}) one vector
on top of another.
\subsection{Extracting a specific \texttt{Atom/\-Residue/\-Chain/\-Model}
from a Structure}
These are some examples:
\begin{verbatim}
>>> model = structure[0]
>>> chain = model['A']
>>> residue = chain[100]
>>> atom = residue['CA']
\end{verbatim}
Note that you can use a shortcut:
\begin{verbatim}
>>> atom = structure[0]['A'][100]['CA']
\end{verbatim}
\section{Disorder}
Bio.PDB can handle both disordered atoms and point mutations (i.e. a
Gly and an Ala residue in the same position).
\subsection{General approach\label{disorder problems}}
Disorder should be dealt with from two points of view: the atom and the residue
points of view. In general, we have tried to encapsulate all the complexity that
arises from disorder. If you just want to loop over all C$\alpha$ atoms,
you do not care that some residues have a disordered side chain. On the other
hand it should also be possible to represent disorder completely in the data
structure. Therefore, disordered atoms or residues are stored in special objects
that behave as if there is no disorder. This is done by only representing a
subset of the disordered atoms or residues. Which subset is picked (e.g. which
of the two disordered OG side chain atom positions of a Ser residue is used)
can be specified by the user.
\subsection{Disordered atoms\label{disordered atoms}}
Disordered atoms are represented by ordinary \texttt{Atom} objects, but
all \texttt{Atom} objects that represent the same physical atom are stored
in a \texttt{Disordered\-Atom} object (see Fig. \ref{fig:smcra}).
Each \texttt{Atom} object in a \texttt{Disordered\-Atom} object can
be uniquely indexed using its altloc specifier. The \texttt{Disordered\-Atom}
object forwards all uncaught method calls to the selected Atom object,
by default the one that represents the atom with the highest
occupancy. The user can of course change the selected \texttt{Atom}
object, making use of its altloc specifier. In this way atom disorder
is represented correctly without much additional complexity. In other
words, if you are not interested in atom disorder, you will not be
bothered by it.
Each disordered atom has a characteristic altloc identifier. You can
specify that a \texttt{Disordered\-Atom} object should behave like
the \texttt{Atom} object associated with a specific altloc identifier:
\begin{verbatim}
>>> atom.disordered_select('A') # select altloc A atom
>>> print atom.get_altloc()
"A"
>>> atom.disordered_select('B') # select altloc B atom
>>> print atom.get_altloc()
"B"
\end{verbatim}
\subsection{Disordered residues}
\subsubsection*{Common case}
The most common case is a residue that contains one or more disordered atoms.
This is evidently solved by using DisorderedAtom objects to represent the disordered
atoms, and storing the DisorderedAtom object in a Residue object just like ordinary
Atom objects. The DisorderedAtom will behave exactly like an ordinary atom (in
fact the atom with the highest occupancy) by forwarding all uncaught method
calls to one of the Atom objects (the selected Atom object) it contains.
\subsubsection*{Point mutations\label{point mutations}}
A special case arises when disorder is due to a point mutation, i.e. when two
or more point mutants of a polypeptide are present in the crystal. An example
of this can be found in PDB structure 1EN2.
Since these residues belong to a different residue type (e.g. let's
say Ser 60 and Cys 60) they should not be stored in a single \texttt{Residue}
object as in the common case. In this case, each residue is represented
by one \texttt{Residue} object, and both \texttt{Residue} objects
are stored in a single \texttt{Disordered\-Residue} object (see Fig.
\ref{fig:smcra}).
The \texttt{Dis\-ordered\-Residue} object forwards all un\-caught methods to
the selected \texttt{Residue} object (by default the last \texttt{Residue}
object added), and thus behaves like an ordinary residue. Each
\texttt{Residue} object in a \texttt{Disordered\-Residue} object can be
uniquely identified by its residue name. In the above example, residue Ser 60
would have id ``SER'' in the \texttt{Disordered\-Residue} object, while
residue Cys 60 would have id ``CYS''. The user can select the active
\texttt{Residue} object in a \texttt{Disordered\-Residue} object via this id.
Example: suppose that a chain has a point mutation at position 10,
consisting of a Ser and a Cys residue. Make sure that residue 10 of
this chain behaves as the Cys residue.
\begin{verbatim}
>>> residue = chain[10]
>>> residue.disordered_select('CYS')
\end{verbatim}
In addition, you can get a list of all \texttt{Atom} objects (ie.
all \texttt{DisorderedAtom} objects are 'unpacked' to their individual
\texttt{Atom} objects) using the \texttt{get\_unpacked\_list} method
of a \texttt{(Disordered)\-Residue} object.
\section{Hetero residues}
\subsection{Associated problems\label{hetero problems}}
A common problem with hetero residues is that several hetero and non-hetero
residues present in the same chain share the same sequence identifier (and insertion
code). Therefore, to generate a unique id for each hetero residue, waters and
other hetero residues are treated in a different way.
Remember that Residue object have the tuple (hetfield, resseq, icode) as id.
The hetfield is blank (`` '') for amino and nucleic acids, and a string
for waters and other hetero residues. The content of the hetfield is explained
below.
\subsection{Water residues}
The hetfield string of a water residue consists of the letter ``W''. So
a typical residue id for a water is (``W'', 1, `` '').
\subsection{Other hetero residues}
The hetfield string for other hetero residues starts with ``H\_'' followed
by the residue name. A glucose molecule e.g. with residue name ``GLC''
would have hetfield ``H\_GLC''. Its residue id could e.g. be (``H\_GLC'',
1, `` '').
\section{Navigating through a Structure object}
\subsubsection*{Parse a PDB file, and extract some Model, Chain, Residue and Atom objects}
\begin{verbatim}
>>> from Bio.PDB.PDBParser import PDBParser
>>> parser = PDBParser()
>>> structure = parser.get_structure("test", "1fat.pdb")
>>> model = structure[0]
>>> chain = model["A"]
>>> residue = chain[1]
>>> atom = residue["CA"]
\end{verbatim}
\subsubsection*{Iterating through all atoms of a structure}
\begin{verbatim}
>>> p = PDBParser()
>>> structure = p.get_structure('X', 'pdb1fat.ent')
>>> for model in structure:
... for chain in model:
... for residue in chain:
... for atom in residue:
... print atom
...
\end{verbatim}
There is a shortcut if you want to iterate over all atoms in a structure:
\begin{verbatim}
>>> atoms = structure.get_atoms()
>>> for atom in atoms:
... print atom
...
\end{verbatim}
Similarly, to iterate over all atoms in a chain, use
\begin{verbatim}
>>> atoms = chain.get_atoms()
>>> for atom in atoms:
... print atom
...
\end{verbatim}
\subsubsection*{Iterating over all residues of a model}
or if you want to iterate over all residues in a model:
\begin{verbatim}
>>> residues = model.get_residues()
>>> for residue in residues:
... print residue
...
\end{verbatim}
You can also use the \verb+Selection.unfold_entities+ function to get all residues from a structure:
\begin{verbatim}
>>> res_list = Selection.unfold_entities(structure, 'R')
\end{verbatim}
or to get all atoms from a chain:
\begin{verbatim}
>>> atom_list = Selection.unfold_entities(chain, 'A')
\end{verbatim}
Obviously, \verb+A=atom, R=residue, C=chain, M=model, S=structure+.
You can use this to go up in the hierarchy, e.g. to get a list of
(unique) \verb+Residue+ or \verb+Chain+ parents from a list of
\verb+Atoms+:
\begin{verbatim}
>>> residue_list = Selection.unfold_entities(atom_list, 'R')
>>> chain_list = Selection.unfold_entities(atom_list, 'C')
\end{verbatim}
For more info, see the API documentation.
\subsubsection*{Extract a hetero residue from a chain (e.g. a glucose (GLC) moiety with resseq 10)}
\begin{verbatim}
>>> residue_id = ("H_GLC", 10, " ")
>>> residue = chain[residue_id]
\end{verbatim}
\subsubsection*{Print all hetero residues in chain}
\begin{verbatim}
>>> for residue in chain.get_list():
... residue_id = residue.get_id()
... hetfield = residue_id[0]
... if hetfield[0]=="H":
... print residue_id
...
\end{verbatim}
\subsubsection*{Print out the coordinates of all CA atoms in a structure with B factor greater than 50}
\begin{verbatim}
>>> for model in structure.get_list():
... for chain in model.get_list():
... for residue in chain.get_list():
... if residue.has_id("CA"):
... ca = residue["CA"]
... if ca.get_bfactor() > 50.0:
... print ca.get_coord()
...
\end{verbatim}
\subsubsection*{Print out all the residues that contain disordered atoms}
\begin{verbatim}
>>> for model in structure.get_list():
... for chain in model.get_list():
... for residue in chain.get_list():
... if residue.is_disordered():
... resseq = residue.get_id()[1]
... resname = residue.get_resname()
... model_id = model.get_id()
... chain_id = chain.get_id()
... print model_id, chain_id, resname, resseq
...
\end{verbatim}
\subsubsection*{Loop over all disordered atoms, and select all atoms with altloc A (if present)}
This will make sure that the SMCRA data structure will behave as if only the
atoms with altloc A are present.
\begin{verbatim}
>>> for model in structure.get_list():
... for chain in model.get_list():
... for residue in chain.get_list():
... if residue.is_disordered():
... for atom in residue.get_list():
... if atom.is_disordered():
... if atom.disordered_has_id("A"):
... atom.disordered_select("A")
...
\end{verbatim}
\subsubsection*{Extracting polypeptides from a \texttt{Structure} object\label{subsubsec:extracting_polypeptides}}
To extract polypeptides from a structure, construct a list of \texttt{Polypeptide} objects from a \texttt{Structure} object using \texttt{PolypeptideBuilder} as follows:
\begin{verbatim}
>>> model_nr = 1
>>> polypeptide_list = build_peptides(structure, model_nr)
>>> for polypeptide in polypeptide_list:
... print polypeptide
...
\end{verbatim}
A Polypeptide object is simply a UserList of Residue objects, and is always created from a single Model (in this case model 1).
You can use the resulting \texttt{Polypeptide} object to get the sequence as a \texttt{Seq} object or to get a list of C$\alpha$ atoms as well. Polypeptides can be built using a C-N or a C$\alpha$-C$\alpha$ distance criterion.
Example:
\begin{verbatim}
# Using C-N
>>> ppb=PPBuilder()
>>> for pp in ppb.build_peptides(structure):
... print pp.get_sequence()
...
# Using CA-CA
>>> ppb=CaPPBuilder()
>>> for pp in ppb.build_peptides(structure):
... print pp.get_sequence()
...
\end{verbatim}
Note that in the above case only model 0 of the structure is considered
by \texttt{PolypeptideBuilder}. However, it is possible to use \texttt{PolypeptideBuilder}
to build \texttt{Polypeptide} objects from \texttt{Model} and \texttt{Chain}
objects as well.
\subsubsection*{Obtaining the sequence of a structure}
The first thing to do is to extract all polypeptides from the structure
(as above). The sequence of each polypeptide can then easily
be obtained from the \texttt{Polypeptide} objects. The sequence is
represented as a Biopython \texttt{Seq} object, and its alphabet is
defined by a \texttt{ProteinAlphabet} object.
Example:
\begin{verbatim}
>>> seq = polypeptide.get_sequence()
>>> print seq
Seq('SNVVE...', <class Bio.Alphabet.ProteinAlphabet>)
\end{verbatim}
\section{Analyzing structures}
\subsection{Measuring distances}
The minus operator for atoms has been overloaded to return the distance between two atoms.
\begin{verbatim}
# Get some atoms
>>> ca1 = residue1['CA']
>>> ca2 = residue2['CA']
# Simply subtract the atoms to get their distance
>>> distance = ca1-ca2
\end{verbatim}
\subsection{Measuring angles}
Use the vector representation of the atomic coordinates, and
the \texttt{calc\_angle} function from the \texttt{Vector} module:
\begin{verbatim}
>>> vector1 = atom1.get_vector()
>>> vector2 = atom2.get_vector()
>>> vector3 = atom3.get_vector()
>>> angle = calc_angle(vector1, vector2, vector3)
\end{verbatim}
\subsection{Measuring torsion angles}
Use the vector representation of the atomic coordinates, and
the \texttt{calc\_dihedral} function from the \texttt{Vector} module:
\begin{verbatim}
>>> vector1 = atom1.get_vector()
>>> vector2 = atom2.get_vector()
>>> vector3 = atom3.get_vector()
>>> vector4 = atom4.get_vector()
>>> angle = calc_dihedral(vector1, vector2, vector3, vector4)
\end{verbatim}
\subsection{Determining atom-atom contacts}
Use \texttt{NeighborSearch} to perform neighbor lookup.
The neighbor lookup is done using a KD tree module written in C (see \texttt{Bio.KDTree}), making it very fast.
It also includes a fast method to find all point pairs within a certain distance of each other.
\subsection{Superimposing two structures}
Use a \texttt{Superimposer} object to superimpose two coordinate sets.
This object calculates the rotation and translation matrix that rotates
two lists of atoms on top of each other in such a way that their RMSD
is minimized. Of course, the two lists need to contain the same number
of atoms. The \texttt{Superimposer} object can also apply the rotation/translation
to a list of atoms. The rotation and translation are stored as a tuple
in the \texttt{rotran} attribute of the \texttt{Superimposer} object
(note that the rotation is right multiplying!). The RMSD is stored
in the \texttt{rmsd} attribute.
The algorithm used by \texttt{Superimposer} comes from \cite[Golub \& Van Loan]{golub1989} and makes use of singular value decomposition (this is implemented in the general \texttt{Bio.SVDSuperimposer} module).
Example:
\begin{verbatim}
>>> sup = Superimposer()
# Specify the atom lists
# 'fixed' and 'moving' are lists of Atom objects
# The moving atoms will be put on the fixed atoms
>>> sup.set_atoms(fixed, moving)
# Print rotation/translation/rmsd
>>> print sup.rotran
>>> print sup.rms
# Apply rotation/translation to the moving atoms
>>> sup.apply(moving)
\end{verbatim}
To superimpose two structures based on their active sites, use the active site atoms to calculate the rotation/translation matrices (as above), and apply these to the whole molecule.
\subsection{Mapping the residues of two related structures onto each other}
First, create an alignment file in FASTA format, then use the \texttt{StructureAlignment}
class. This class can also be used for alignments with more than two
structures.
\subsection{Calculating the Half Sphere Exposure}
Half Sphere Exposure (HSE) is a new, 2D measure of solvent exposure
\cite{hamelryck2005}.
Basically, it counts the number of C$\alpha$ atoms around a residue
in the direction of its side chain, and in the opposite direction
(within a radius of $13 \AA$). Despite its simplicity, it outperforms
many other measures of solvent exposure.
HSE comes in two flavors: HSE$\alpha$ and HSE$\beta$. The former
only uses the C$\alpha$ atom positions, while the latter uses the
C$\alpha$ and C$\beta$ atom positions. The HSE measure is calculated
by the \texttt{HSExposure} class, which can also calculate the contact
number. The latter class has methods which return dictionaries that
map a \texttt{Residue} object to its corresponding HSE$\alpha$, HSE$\beta$
and contact number values.
Example:
\begin{verbatim}
>>> model = structure[0]
>>> hse = HSExposure()
# Calculate HSEalpha
>>> exp_ca = hse.calc_hs_exposure(model, option='CA3')
# Calculate HSEbeta
>>> exp_cb=hse.calc_hs_exposure(model, option='CB')
# Calculate classical coordination number
>>> exp_fs = hse.calc_fs_exposure(model)
# Print HSEalpha for a residue
>>> print exp_ca[some_residue]
\end{verbatim}
\subsection{Determining the secondary structure}
For this functionality, you need to install DSSP (and obtain a license
for it --- free for academic use, see \url{http://www.cmbi.kun.nl/gv/dssp/}).
Then use the \texttt{DSSP} class, which maps \texttt{Residue} objects
to their secondary structure (and accessible surface area). The DSSP
codes are listed in Table \ref{cap:DSSP-codes}. Note that DSSP (the
program, and thus by consequence the class) cannot handle multiple
models!
\begin{table}
\begin{tabular}{|c|c|}
\hline
Code&
Secondary structure \\
\hline
\hline
H&
$\alpha$-helix \\
\hline
B&
Isolated $\beta$-bridge residue \\
\hline
E&
Strand \\
\hline
G&
3-10 helix \\
\hline
I&
$\Pi$-helix \\
\hline
T&
Turn\\
\hline
S&
Bend \\
\hline
-&
Other\\
\hline
\end{tabular}
\caption{\label{cap:DSSP-codes}DSSP codes in Bio.PDB.}
\end{table}
The \texttt{DSSP} class can also be used to calculate the accessible surface area of a residue. But see also section \ref{subsec:residue_depth}.
\subsection{Calculating the residue depth\label{subsec:residue_depth}}
Residue depth is the average distance of a residue's atoms from the
solvent accessible surface. It's a fairly new and very powerful parameterization
of solvent accessibility. For this functionality, you need to install
Michel Sanner's MSMS program (\url{http://www.scripps.edu/pub/olson-web/people/sanner/html/msms_home.html}).
Then use the \texttt{ResidueDepth} class. This class behaves as a
dictionary which maps \texttt{Residue} objects to corresponding (residue
depth, C$\alpha$ depth) tuples. The C$\alpha$ depth is the distance
of a residue's C$\alpha$ atom to the solvent accessible surface.
Example:
\begin{verbatim}
>>> model = structure[0]
>>> rd = ResidueDepth(model, pdb_file)
>>> residue_depth, ca_depth=rd[some_residue]
\end{verbatim}
You can also get access to the molecular surface itself (via the \texttt{get\_surface}
function), in the form of a Numeric Python array with the surface points.
\section{Common problems in PDB files}
It is well known that many PDB files contain semantic errors (not the
structures themselves, but their representation in PDB files).
Bio.PDB tries to handle this in two ways. The PDBParser
object can behave in two ways: a restrictive way and a permissive
way, which is the default.
Example:
\begin{verbatim}
# Permissive parser
>>> parser = PDBParser(PERMISSIVE=1)
>>> parser = PDBParser() # The same (default)
# Strict parser
>>> strict_parser = PDBParser(PERMISSIVE=0)
\end{verbatim}
In the permissive state (DEFAULT), PDB files that obviously contain
errors are ``corrected'' (i.e. some residues or atoms are left out).
These errors include:
\begin{itemize}
\item Multiple residues with the same identifier
\item Multiple atoms with the same identifier (taking into account the altloc
identifier)
\end{itemize}
These errors indicate real problems in the PDB file (for details see
\cite[Hamelryck and Manderick, 2003]{hamelryck2003a}). In the restrictive state, PDB files with errors cause an exception to occur. This is useful to find errors in PDB files.
Some errors however are automatically corrected. Normally each disordered
atom should have a non-blank altloc identifier. However, there are
many structures that do not follow this convention, and have a blank
and a non-blank identifier for two disordered positions of the same
atom. This is automatically interpreted in the right way.
Sometimes a structure contains a list of residues belonging to chain
A, followed by residues belonging to chain B, and again followed by
residues belonging to chain A, i.e. the chains are 'broken'. This
is also correctly interpreted.
\subsection{Examples\label{problem structures}}
The PDBParser/Structure class was tested on about 800 structures (each belonging
to a unique SCOP superfamily). This takes about 20 minutes, or on average 1.5
seconds per structure. Parsing the structure of the large ribosomal subunit
(1FKK), which contains about 64000 atoms, takes 10 seconds on a 1000 MHz PC.
Three exceptions were generated in cases where an unambiguous data structure
could not be built. In all three cases, the likely cause is an error in the
PDB file that should be corrected. Generating an exception in these cases
is much better than running the chance of incorrectly describing
the structure in a data structure.
\subsubsection{Duplicate residues}
One structure contains two amino acid residues in one chain with the same sequence
identifier (resseq 3) and icode. Upon inspection it was found that this chain
contains the residues Thr A3, \ldots, Gly A202, Leu A3, Glu A204. Clearly,
Leu A3 should be Leu A203. A couple of similar situations exist for structure
1FFK (which e.g. contains Gly B64, Met B65, Glu B65, Thr B67, i.e. residue Glu
B65 should be Glu B66).
\subsubsection{Duplicate atoms}
Structure 1EJG contains a Ser/Pro point mutation in chain A at position 22.
In turn, Ser 22 contains some disordered atoms. As expected, all atoms belonging
to Ser 22 have a non-blank altloc specifier (B or C). All atoms of Pro 22 have
altloc A, except the N atom which has a blank altloc. This generates an exception,
because all atoms belonging to two residues at a point mutation should have
non-blank altloc. It turns out that this atom is probably shared by Ser and
Pro 22, as Ser 22 misses the N atom. Again, this points to a problem in the
file: the N atom should be present in both the Ser and the Pro residue, in both
cases associated with a suitable altloc identifier.
\subsection{Automatic correction}
Some errors are quite common and can be easily corrected without much risk of
making a wrong interpretation. These cases are listed below.
\subsubsection{A blank altloc for a disordered atom}
Normally each disordered atom should have a non-blank altloc identifier. However,
there are many structures that do not follow this convention, and have a blank
and a non-blank identifier for two disordered positions of the same atom. This
is automatically interpreted in the right way.
\subsubsection{Broken chains}
Sometimes a structure contains a list of residues belonging to chain A, followed
by residues belonging to chain B, and again followed by residues belonging to
chain A, i.e. the chains are ``broken''. This is correctly interpreted.
\subsection{Fatal errors}
Sometimes a PDB file cannot be unambiguously interpreted. Rather than guessing
and risking a mistake, an exception is generated, and the user is expected to
correct the PDB file. These cases are listed below.
\subsubsection{Duplicate residues}
All residues in a chain should have a unique id. This id is generated based
on:
\begin{itemize}
\item The sequence identifier (resseq).
\item The insertion code (icode).
\item The hetfield string (``W'' for waters and ``H\_'' followed by the
residue name for other hetero residues)
\item The residue names of the residues in the case of point mutations (to store the
Residue objects in a DisorderedResidue object).
\end{itemize}
If this does not lead to a unique id something is quite likely wrong, and an
exception is generated.
\subsubsection{Duplicate atoms}
All atoms in a residue should have a unique id. This id is generated based on:
\begin{itemize}
\item The atom name (without spaces, or with spaces if a problem arises).
\item The altloc specifier.
\end{itemize}
If this does not lead to a unique id something is quite likely wrong, and an
exception is generated.
\section{Accessing the Protein Data Bank}
\subsection{Downloading structures from the Protein Data Bank}
Structures can be downloaded from the PDB (Protein Data Bank)
by using the \texttt{retrieve\_pdb\_file} method on a \texttt{PDBList} object.
The argument for this method is the PDB identifier of the structure.
\begin{verbatim}
>>> pdbl = PDBList()
>>> pdbl.retrieve_pdb_file('1FAT')
\end{verbatim}
The \texttt{PDBList} class can also be used as a command-line tool:
\begin{verbatim}
python PDBList.py 1fat
\end{verbatim}
The downloaded file will be called \texttt{pdb1fat.ent} and stored
in the current working directory. Note that the \texttt{retrieve\_pdb\_file}
method also has an optional argument \texttt{pdir} that specifies
a specific directory in which to store the downloaded PDB files.
The \texttt{retrieve\_pdb\_file} method also has some options to specify
the compression format used for the download, and the program used
for local decompression (default \texttt{.Z} format and \texttt{gunzip}).
In addition, the PDB ftp site can be specified upon creation of the
\texttt{PDBList} object. By default, the server of the Worldwide Protein Data Bank (\url{ftp://ftp.wwpdb.org/pub/pdb/data/structures/divided/pdb/})
is used. See the API documentation for more details. Thanks again
to Kristian Rother for donating this module.
\subsection{Downloading the entire PDB}
The following commands will store all PDB files in the \texttt{/data/pdb}
directory:
\begin{verbatim}
python PDBList.py all /data/pdb
python PDBList.py all /data/pdb -d
\end{verbatim}
\noindent The API method for this is called \texttt{download\_entire\_pdb}.
Adding the \texttt{-d} option will store all files in the same directory.
Otherwise, they are sorted into PDB-style subdirectories according
to their PDB ID's. Depending on the traffic, a complete download will
take 2-4 days.
\subsection{Keeping a local copy of the PDB up to date}
This can also be done using the \texttt{PDBList} object. One simply
creates a \texttt{PDBList} object (specifying the directory where
the local copy of the PDB is present) and calls the \texttt{update\_pdb}
method:
\begin{verbatim}
>>> pl = PDBList(pdb='/data/pdb')
>>> pl.update_pdb()
\end{verbatim}
One can of course make a weekly \texttt{cronjob} out of this to keep
the local copy automatically up-to-date. The PDB ftp site can also
be specified (see API documentation).
\texttt{PDBList} has some additional methods that can be of use. The
\texttt{get\_all\_obsolete} method can be used to get a list of all
obsolete PDB entries. The \texttt{changed\_this\_week} method can
be used to obtain the entries that were added, modified or obsoleted
during the current week. For more info on the possibilities of \texttt{PDBList},
see the API documentation.
\section{General questions}
\subsection{How well tested is Bio.PDB?}
Pretty well, actually. Bio.PDB has been extensively tested on nearly
5500 structures from the PDB - all structures seemed to be parsed
correctly. More details can be found in the Bio.PDB Bioinformatics
article. Bio.PDB has been used/is being used in many research projects
as a reliable tool. In fact, I'm using Bio.PDB almost daily for research
purposes and continue working on improving it and adding new features.
\subsection{How fast is it?}
The \texttt{PDBParser} performance was tested on about 800 structures
(each belonging to a unique SCOP superfamily). This takes about 20
minutes, or on average 1.5 seconds per structure. Parsing the structure
of the large ribosomal subunit (1FKK), which contains about 64000
atoms, takes 10 seconds on a 1000 MHz PC. In short: it's more than
fast enough for many applications.
\subsection{Is there support for molecular graphics?}
Not directly, mostly since there are quite a few Python based/Python
aware solutions already, that can potentially be used with Bio.PDB.
My choice is Pymol, BTW (I've used this successfully with Bio.PDB,
and there will probably be specific PyMol modules in Bio.PDB soon/some
day). Python based/aware molecular graphics solutions include:
\begin{itemize}
\item PyMol: \url{http://pymol.sourceforge.net/}
\item Chimera: \url{http://www.cgl.ucsf.edu/chimera/}
\item PMV: \url{http://www.scripps.edu/~sanner/python/}
\item Coot: \url{http://www.ysbl.york.ac.uk/~emsley/coot/}
\item CCP4mg: \url{http://www.ysbl.york.ac.uk/~lizp/molgraphics.html}
\item mmLib: \url{http://pymmlib.sourceforge.net/}
\item VMD: \url{http://www.ks.uiuc.edu/Research/vmd/}
\item MMTK: \url{http://starship.python.net/crew/hinsen/MMTK/}
\end{itemize}
\subsection{Who's using Bio.PDB?}
Bio.PDB was used in the construction of DISEMBL, a web server that
predicts disordered regions in proteins (\url{http://dis.embl.de/}),
and COLUMBA, a website that provides annotated protein structures
(\url{http://www.columba-db.de/}). Bio.PDB has also been used to
perform a large scale search for active sites similarities between
protein structures in the PDB \cite[Hamelryck, 2003]{hamelryck2003b}, and to develop a new algorithm
that identifies linear secondary structure elements \cite[Majumdar \textit{et al.}, 2005]{majumdar2005}.
Judging from requests for features and information, Bio.PDB is also
used by several LPCs (Large Pharmaceutical Companies :-).
% Perhaps this section should be updated for other Biopython modules, and
% moved to the Biopython FAQ above.
\chapter{Bio.PopGen: Population genetics}
Bio.PopGen is a Biopython module supporting population genetics,
available in Biopython 1.44 onwards.
The medium term objective for the module is to support widely used data
formats, applications and databases. This module is currently under intense
development and support for new features should appear at a rather fast pace.
Unfortunately this might also entail some instability on the API, especially
if you are using a development version. APIs that are made available on
our official public releases should be much more stable.
\section{GenePop}
GenePop (\url{http://genepop.curtin.edu.au/}) is a popular population
genetics software package supporting Hardy-Weinberg tests, linkage
desiquilibrium, population diferentiation, basic statistics, $F_{st}$ and
migration estimates, among others. GenePop does not supply sequence
based statistics as it doesn't handle sequence data.
The GenePop file format is supported by a wide range of other population
genetic software applications, thus making it a relevant format in the
population genetics field.
Bio.PopGen provides a parser and generator of GenePop file format.
Utilities to manipulate the content of a record are also provided.
Here is an example on how to read a GenePop file (you can find
example GenePop data files in the Test/PopGen directory of Biopython):
\begin{verbatim}
from Bio.PopGen import GenePop
handle = open("example.gen")
rec = GenePop.read(handle)
handle.close()
\end{verbatim}
This will read a file called example.gen and parse it. If you
do print rec, the record will be output again, in GenePop format.
The most important information in rec will be the loci names and
population information (but there is more -- use help(GenePop.Record)
to check the API documentation). Loci names can be found on rec.loci\_list.
Population information can be found on rec.populations.
Populations is a list with one element per population. Each element is itself
a list of individuals, each individual is a pair composed by individual
name and a list of alleles (2 per marker), here is an example for
rec.populations:
\begin{verbatim}
[
[
('Ind1', [(1, 2), (3, 3), (200, 201)],
('Ind2', [(2, None), (3, 3), (None, None)],
],
[
('Other1', [(1, 1), (4, 3), (200, 200)],
]
]
\end{verbatim}
So we have two populations, the first with two individuals, the
second with only one. The first individual of the first
population is called Ind1, allelic information for each of
the 3 loci follows. Please note that for any locus, information
might be missing (see as an example, Ind2 above).
A few utility functions to manipulate GenePop records are made
available, here is an example:
\begin{verbatim}
from Bio.PopGen import GenePop
#Imagine that you have loaded rec, as per the code snippet above...
rec.remove_population(pos)
#Removes a population from a record, pos is the population position in
# rec.populations, remember that it starts on position 0.
# rec is altered.
rec.remove_locus_by_position(pos)
#Removes a locus by its position, pos is the locus position in
# rec.loci_list, remember that it starts on position 0.
# rec is altered.
rec.remove_locus_by_name(name)
#Removes a locus by its name, name is the locus name as in
# rec.loci_list. If the name doesn't exist the function fails
# silently.
# rec is altered.
rec_loci = rec.split_in_loci()
#Splits a record in loci, that is, for each loci, it creates a new
# record, with a single loci and all populations.
# The result is returned in a dictionary, being each key the locus name.
# The value is the GenePop record.
# rec is not altered.
rec_pops = rec.split_in_pops(pop_names)
#Splits a record in populations, that is, for each population, it creates
# a new record, with a single population and all loci.
# The result is returned in a dictionary, being each key
# the population name. As population names are not available in GenePop,
# they are passed in array (pop_names).
# The value of each dictionary entry is the GenePop record.
# rec is not altered.
\end{verbatim}
GenePop does not support population names, a limitation which can be
cumbersome at times. Functionality to enable population names is currently
being planned for Biopython. These extensions won't break compatibility in
any way with the standard format. In the medium term, we would also like to
support the GenePop web service.
\section{Coalescent simulation}
A coalescent simulation is a backward model of population genetics with relation to
time. A simulation of ancestry is done until the Most Recent Common Ancestor (MRCA) is found.
This ancestry relationship starting on the MRCA and ending on the current generation
sample is sometimes called a genealogy. Simple cases assume a population of constant
size in time, haploidy, no population structure, and simulate the alleles of a single
locus under no selection pressure.
Coalescent theory is used in many fields like selection detection, estimation of
demographic parameters of real populations or disease gene mapping.
The strategy followed in the Biopython implementation of the coalescent was not
to create a new, built-in, simulator from scratch but to use an existing one,
SIMCOAL2 (\url{http://cmpg.unibe.ch/software/simcoal2/}). SIMCOAL2 allows for,
among others, population structure, multiple demographic events, simulation
of multiple types of loci (SNPs, sequences, STRs/microsatellites and RFLPs)
with recombination, diploidy multiple chromosomes or ascertainment bias. Notably
SIMCOAL2 doesn't support any selection model. We recommend reading SIMCOAL2's
documentation, available in the link above.
The input for SIMCOAL2 is a file specifying the desired demography and genome,
the output is a set of files (typically around 1000) with the simulated genomes
of a sample of individuals per subpopulation. This set of files can be used
in many ways, like to compute confidence intervals where which certain
statistics (e.g., $F_{st}$ or Tajima D) are expected to lie. Real population
genetics datasets statistics can then be compared to those confidence intervals.
Biopython coalescent code allows to create demographic scenarios and genomes and
to run SIMCOAL2.
\subsection{Creating scenarios}
Creating a scenario involves both creating a demography and a chromosome structure.
In many cases (e.g. when doing Approximate Bayesian Computations -- ABC) it is
important to test many parameter variations (e.g. vary the effective population size,
$N_e$, between 10, 50, 500 and 1000 individuals). The code provided allows for
the simulation of scenarios with different demographic parameters very easily.
Below we see how we can create scenarios and then how simulate them.
\subsubsection{Demography}
A few predefined demographies are built-in, all have two shared parameters: sample size
(called sample\_size on the template, see below for its use) per deme and deme size, i.e.
subpopulation size (pop\_size). All demographies are available as templates where all
parameters can be varied, each template has a system name. The prefedined
demographies/templates are:
\begin{description}
\item[Single population, constant size] The standard parameters are enough to specify
it. Template name: simple.
\item[Single population, bottleneck] As seen on figure \ref{fig:bottle}. The parameters
are current population size (pop\_size on template ne3 on figure), time of expansion,
given as the generation in the past when it occurred (expand\_gen),
effective population size during bottleneck (ne2), time of contraction
(contract\_gen) and original size in the remote past (ne3). Template name: bottle.
\item[Island model] The typical island model. The total number of demes is specified
by total\_demes and the migration rate by mig. Template name island.
\item[Stepping stone model - 1 dimension] The stepping stone model in 1 dimension,
extremes disconnected. The total number of demes is total\_demes, migration rate
is mig. Template name is ssm\_1d.
\item[Stepping stone model - 2 dimensions] The stepping stone model in 2 dimensions,
extremes disconnected. The parameters are x for the horizontal dimension and y
for the vertical (being the total number of demes x times y), migration rate is mig.
Template name is ssm\_2d.
\end{description}
\begin{htmlonly}
\label{fig:bottle}
\imgsrc{images/bottle.png}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics{images/bottle.png}
\caption{A bottleneck}
\label{fig:bottle}
\end{figure}
\end{latexonly}
In our first example, we will generate a template for a single population, constant size
model with a sample size of 30 and a deme size of 500. The code for this is:
\begin{verbatim}
from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
generate_simcoal_from_template('simple',
[(1, [('SNP', [24, 0.0005, 0.0])])],
[('sample_size', [30]),
('pop_size', [100])])
\end{verbatim}
Executing this code snippet will generate a file on the current directory called
simple\_100\_300.par this file can be given as input to SIMCOAL2 to simulate the
demography (below we will see how Biopython can take care of calling SIMCOAL2).
This code consists of a single function call, let's discuss it parameter by parameter.
The first parameter is the template id (from the list above). We are using the id
'simple' which is the template for a single population of constant size along time.
The second parameter is the chromosome structure. Please ignore it for now, it will be
explained in the next section.
The third parameter is a list of all required parameters (recall that the simple model
only needs sample\_size and pop\_size) and possible values (in this case each
parameter only has a possible value).
Now, let's consider an example where we want to generate several island models, and we
are interested in varying the number of demes: 10, 50 and 100 with a migration
rate of 1\%. Sample size and deme
size will be the same as before. Here is the code:
\begin{verbatim}
from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
generate_simcoal_from_template('island',
[(1, [('SNP', [24, 0.0005, 0.0])])],
[('sample_size', [30]),
('pop_size', [100]),
('mig', [0.01]),
('total_demes', [10, 50, 100])])
\end{verbatim}
In this case, 3 files will be generated: island\_100\_0.01\_100\_30.par,
island\_10\_0.01\_100\_30.par and island\_50\_0.01\_100\_30.par. Notice the
rule to make file names: template name, followed by parameter values in
reverse order.
A few, arguably more esoteric template demographies exist (please check the
Bio/PopGen/SimCoal/data directory on Biopython source tree). Furthermore it is possible
for the user to create new templates. That functionality will be discussed in a future
version of this document.
\subsubsection{Chromosome structure}
We strongly recommend reading SIMCOAL2 documentation to understand the full potential
available in modeling chromosome structures. In this subsection we only discuss how
to implement chromosome structures using the Biopython interface, not the underlying
SIMCOAL2 capabilities.
We will start by implementing a single chromosome, with 24 SNPs with
a recombination rate immediately on the right of each locus of 0.0005 and a
minimum frequency of the minor allele of 0. This will be specified by the
following list (to be passed as second parameter to the function
generate\_simcoal\_from\_template):
\begin{verbatim}
[(1, [('SNP', [24, 0.0005, 0.0])])]
\end{verbatim}
This is actually the chromosome structure used in the above examples.
The chromosome structure is represented by a list of chromosomes,
each chromosome (i.e., each element in the list)
is composed by a tuple (a pair): the first element
is the number of times the chromosome is to be repeated (as there
might be interest in repeating the same chromosome many times).
The second element is a list of the actual components of the chromosome.
Each element is again a pair, the first member is the locus type and
the second element the parameters for that locus type. Confused?
Before showing more examples let's review the example above: We have
a list with one element (thus one chromosome), the chromosome is
a single instance (therefore not to be repeated), it is composed
of 24 SNPs, with a recombination rate of 0.0005 between each
consecutive SNP, the minimum frequency of the minor allele is
0.0 (i.e, it can be absent from a certain population).
Let's see a more complicated example:
\begin{verbatim}
[
(5, [
('SNP', [24, 0.0005, 0.0])
]
),
(2, [
('DNA', [10, 0.0, 0.00005, 0.33]),
('RFLP', [1, 0.0, 0.0001]),
('MICROSAT', [1, 0.0, 0.001, 0.0, 0.0])
]
)
]
\end{verbatim}
We start by having 5 chromosomes with the same structure as
above (i.e., 24 SNPs). We then have 2 chromosomes which
have a DNA sequence with 10 nucleotides, 0.0 recombination rate,
0.0005 mutation rate, and a transition rate of 0.33. Then we
have an RFLP with 0.0 recombination rate to the next locus and
a 0.0001 mutation rate. Finally we have a microsatellite (or STR),
with 0.0 recombination rate to the next locus (note, that as this
is a single microsatellite which has no loci following, this
recombination rate here is irrelevant), with a mutation rate
of 0.001, geometric parameter of 0.0 and a range constraint
of 0.0 (for information about this parameters please consult
the SIMCOAL2 documentation, you can use them to simulate
various mutation models, including the typical -- for microsatellites --
stepwise mutation model among others).
\subsection{Running SIMCOAL2}
We now discuss how to run SIMCOAL2 from inside Biopython. It is required
that the binary for SIMCOAL2 is called simcoal2 (or simcoal2.exe on Windows
based platforms), please note that the typical name when downloading the
program is in the format simcoal2\_x\_y. As such, when installing SIMCOAL2
you will need to rename of the downloaded executable so that Biopython can
find it.
It is possible to run SIMCOAL2 on files that were not generated using the method
above (e.g., writing a parameter file by hand), but we will show an
example by creating a model using the framework presented above.
\begin{verbatim}
from Bio.PopGen.SimCoal.Template import generate_simcoal_from_template
from Bio.PopGen.SimCoal.Controller import SimCoalController
generate_simcoal_from_template('simple',
[
(5, [
('SNP', [24, 0.0005, 0.0])
]
),
(2, [
('DNA', [10, 0.0, 0.00005, 0.33]),
('RFLP', [1, 0.0, 0.0001]),
('MICROSAT', [1, 0.0, 0.001, 0.0, 0.0])
]
)
],
[('sample_size', [30]),
('pop_size', [100])])
ctrl = SimCoalController('.')
ctrl.run_simcoal('simple_100_30.par', 50)
\end{verbatim}
The lines of interest are the last two (plus the new import).
Firstly a controller for the
application is created. The directory where the binary is located has
to be specified.
The simulator is then run on the last line: we know, from the rules explained
above, that the input file name is simple\_100\_30.par for the
simulation parameter file created. We then specify
that we want to run 50 independent simulations, by default Biopython
requests a simulation of diploid data, but a third parameter can
be added to simulate haploid data (adding as a parameter the
string '0'). SIMCOAL2 will now run (please
note that this can take quite a lot of time) and will create a directory
with the simulation results. The results can now be analysed (typically
studying the data with Arlequin3). In the future Biopython might support
reading the Arlequin3 format and thus allowing for the analysis of SIMCOAL2
data inside Biopython.
\section{Other applications}
Here we discuss interfaces and utilities to deal with population genetics'
applications which arguably have a smaller user base.
\subsection{FDist: Detecting selection and molecular adaptation}
FDist is a selection detection application suite based on computing
(i.e. simulating) a ``neutral'' confidence interval based on $F_{st}$ and
heterozygosity. Markers (which can be SNPs, microsatellites, AFLPs
among others) which lie outside the ``neutral'' interval are to be
considered as possible candidates for being under selection.
FDist is mainly used when the number of markers is considered enough
to estimate an average $F_{st}$, but not enough to either have outliers
calculated from the dataset directly or, with even more markers for
which the relative positions in the genome are known, to use
approaches based on, e.g., Extended Haplotype Heterozygosity (EHH).
The typical usage pattern for FDist is as follows:
\begin{enumerate}
\item Import a dataset from an external format into FDist format.
\item Compute average $F_{st}$. This is done by datacal inside FDist.
\item Simulate ``neutral'' markers based on the
average $F_{st}$ and expected number of total populations.
This is the core operation, done by fdist inside FDist.
\item Calculate the confidence interval, based on the desired
confidence boundaries (typically 95\% or 99\%). This is done by
cplot and is mainly used to plot the interval.
\item Assess each marker status against the simulation ``neutral''
confidence interval. Done
by pv. This is used to detect the outlier status of each marker
against the simulation.
\end{enumerate}
We will now discuss each step with illustrating example code
(for this example to work FDist binaries have to be on the
executable PATH).
The FDist data format is application specific and is not used at
all by other applications, as such you will probably have to convert
your data for use with FDist. Biopython can help you do this.
Here is an example converting from GenePop format to FDist format
(along with imports that will be needed on examples further below):
\begin{verbatim}
from Bio.PopGen import GenePop
from Bio.PopGen import FDist
from Bio.PopGen.FDist import Controller
from Bio.PopGen.FDist.Utils import convert_genepop_to_fdist
gp_rec = GenePop.read(open("example.gen"))
fd_rec = convert_genepop_to_fdist(gp_rec)
in_file = open("infile", "w")
in_file.write(str(fd_rec))
in_file.close()
\end{verbatim}
In this code we simply parse a GenePop file and convert it to a FDist
record.
Printing an FDist record will generate
a string that can be directly saved to a file and supplied to FDist. FDist
requires the input file to be called infile, therefore we save the record on
a file with that name.
The most important fields on a FDist record are: num\_pops, the number of
populations; num\_loci, the number of loci and loci\_data with the marker
data itself. Most probably the details of the record are of no interest
to the user, as the record only purpose is to be passed to FDist.
The next step is to calculate the average $F_{st}$ of the dataset (along
with the sample size):
\begin{verbatim}
ctrl = Controller.FDistController()
fst, samp_size = ctrl.run_datacal()
\end{verbatim}
On the first line we create an object to control the call of FDist
suite, this object will be used further on in order to call other
suite applications.
On the second line we call the datacal application which computes the
average $F_{st}$
and the sample size. It is worth noting that the $F_{st}$ computed by
datacal is a \emph{variation} of Weir and Cockerham's $\theta$.
We can now call the main fdist application in order to simulate neutral
markers.
\begin{verbatim}
sim_fst = ctrl.run_fdist(npops = 15, nsamples = fd_rec.num_pops, fst = fst,
sample_size = samp_size, mut = 0, num_sims = 40000)
\end{verbatim}
\begin{description}
\item[npops] Number of populations existing in nature. This is really a
``guestimate''. Has to be lower than 100.
\item[nsamples] Number of populations sampled, has to be lower than npops.
\item[fst] Average $F_{st}$.
\item[sample\_size] Average number of individuals sampled on each population.
\item[mut] Mutation model: 0 - Infinite alleles; 1 - Stepwise mutations
\item[num\_sims] Number of simulations to perform. Typically a number around
40000 will be OK, but if you get a confidence interval that looks sharp
(this can be detected when plotting the confidence interval computed
below) the value can be increased (a suggestion would be steps of 10000
simulations).
\end{description}
The confusion in wording between number of samples and sample size
stems from the original application.
A file named out.dat will be created with the simulated heterozygosities
and $F_{st}$s, it will have as many lines as the number of simulations
requested.
Note that fdist returns the average $F_{st}$ that it was \emph{capable} of
simulating, for more details about this issue please read below the paragraph
on approximating the desired average $F_{st}$.
The next (optional) step is to calculate the confidence interval:
\begin{verbatim}
cpl_interval = ctrl.run_cplot(ci=0.99)
\end{verbatim}
You can only call cplot after having run fdist.
This will calculate the confidence intervals (99\% in this case)
for a previous fdist run. A list of quadruples is returned. The
first element represents the heterozygosity, the second the lower
bound of $F_{st}$ confidence interval for that heterozygosity,
the third the average and the fourth the upper bound. This can
be used to trace the confidence interval contour. This list
is also written to a file, out.cpl.
The main purpose of this step is return a set of points which can
be easily used to plot a confidence interval. It can be skipped
if the objective is only to assess the status of each marker against
the simulation, which is the next step...
\begin{verbatim}
pv_data = ctrl.run_pv()
\end{verbatim}
You can only call cplot after having run datacal and fdist.
This will use the simulated markers to assess the status of each
individual real marker. A list, in the same order than the loci\_list
that is on the FDist record (which is in the same order that the GenePop
record) is returned. Each element in the list is a quadruple, the
fundamental member of each quadruple is the last element (regarding the
other elements, please refer to the pv documentation -- for the
sake of simplicity we will not discuss them here) which returns the
probability of the simulated $F_{st}$ being lower than the marker $F_{st}$.
Higher values would indicate a stronger candidate for positive selection,
lower values a candidate for balancing selection, and intermediate values
a possible neutral marker. What is ``higher'', ``lower'' or ``intermediate''
is really a subjective issue, but taking a ``confidence interval'' approach
and considering a 95\% confidence interval, ``higher'' would be between 0.95
and 1.0, ``lower'' between 0.0 and 0.05 and ``intermediate'' between 0.05 and
0.95.
\subsubsection{Approximating the desired average $F_{st}$}
Fdist tries to approximate the desired average $F_{st}$ by doing a
coalescent simulation using migration rates based on the formula
\[ N_{m} = \frac{1 - F_{st}}{4F_{st}} \]
This formula assumes a few premises like an infinite number of populations.
In practice, when the number of populations is low, the mutation model
is stepwise and the sample size increases, fdist will not be able to
simulate an acceptable approximate average $F_{st}$.
To address that, a function is provided to iteratively approach the desired
value by running several fdists in sequence. This approach is computationally
more intensive than running a single fdist run, but yields good results.
The following code runs fdist approximating the desired $F_{st}$:
\begin{verbatim}
sim_fst = ctrl.run_fdist_force_fst(npops = 15, nsamples = fd_rec.num_pops,
fst = fst, sample_size = samp_size, mut = 0, num_sims = 40000,
limit = 0.05)
\end{verbatim}
The only new optional parameter, when comparing with run\_fdist, is limit
which is the desired maximum error. run\_fdist can (and probably should)
be safely replaced with run\_fdist\_force\_fst.
\subsubsection{Final notes}
The process to determine the average $F_{st}$ can be more sophisticated than
the one presented here. For more information we refer you to the FDist
README file. Biopython's code can be used to implement more sophisticated
approaches.
\section{Future Developments}
The most desired future developments would be the ones you add yourself ;) .
That being said, already existing fully functional code is currently being
incorporated in Bio.PopGen, that code covers the applications FDist and
SimCoal2, the HapMap and UCSC Table Browser databases and some simple statistics
like $F_{st}$, or allele counts.
\chapter{Phylogenetics with Bio.Phylo}
\label{sec:Phylo}
The Bio.Phylo module was introduced in Biopython 1.54. Following the lead of SeqIO and AlignIO,
it aims to provide a common way to work with phylogenetic trees independently of the source data
format, as well as a consistent API for I/O operations.
Bio.Phylo is described in an open-access journal article \cite[Talevich
\textit{et al.}, 2012]{talevich2012}, which you might also find helpful.
\section{Demo: What's in a Tree?}
To get acquainted with the module, let's start with a tree that we've already constructed, and
inspect it a few different ways. Then we'll colorize the branches, to use a special phyloXML
feature, and finally save it.
In a terminal, create a simple Newick file using your favorite text editor:
\begin{verbatim}
% cat > simple.dnd <<EOF
> (((A,B),(C,D)),(E,F,G));
> EOF
\end{verbatim}
This tree has no branch lengths, only a topology and labelled terminals. (If you have a real
tree file available, you can follow this demo using that instead.)
Launch the Python interpreter of your choice:
\begin{verbatim}
% ipython -pylab
\end{verbatim}
For interactive work, launching the IPython interpreter with the \verb|-pylab| flag enables
\textbf{matplotlib} integration, so graphics will pop up automatically. We'll use that during
this demo.
Now, within Python, read the tree file, giving the file name and the name of the format.
\begin{verbatim}
>>> from Bio import Phylo
>>> tree = Phylo.read("simple.dnd", "newick")
\end{verbatim}
Printing the tree object as a string gives us a look at the entire object hierarchy.
\begin{verbatim}
>>> print tree
Tree(weight=1.0, rooted=False, name="")
Clade(branch_length=1.0)
Clade(branch_length=1.0)
Clade(branch_length=1.0)
Clade(branch_length=1.0, name="A")
Clade(branch_length=1.0, name="B")
Clade(branch_length=1.0)
Clade(branch_length=1.0, name="C")
Clade(branch_length=1.0, name="D")
Clade(branch_length=1.0)
Clade(branch_length=1.0, name="E")
Clade(branch_length=1.0, name="F")
Clade(branch_length=1.0, name="G")
\end{verbatim}
The \texttt{Tree} object contains global information about the tree, such as whether it's
rooted or unrooted. It has one root clade, and under that, it's nested lists of clades all the
way down to the tips.
The function \verb|draw_ascii| creates a simple ASCII-art (plain text) dendrogram. This is a
convenient visualization for interactive exploration, in case better graphical tools aren't
available.
\begin{verbatim}
>>> Phylo.draw_ascii(tree)
________________________ A
________________________|
| |________________________ B
________________________|
| | ________________________ C
| |________________________|
_| |________________________ D
|
| ________________________ E
| |
|________________________|________________________ F
|
|________________________ G
\end{verbatim}
If you have \textbf{matplotlib} or \textbf{pylab} installed, you can create a graphic
using the \verb|draw| function (see Fig. \ref{fig:phylo-simple-draw}):
\begin{verbatim}
>>> tree.rooted = True
>>> Phylo.draw(tree)
\end{verbatim}
\begin{htmlonly}
\imgsrc[width=666, height=530]{images/phylo-simple-draw.png}
\label{fig:phylo-simple-draw}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[htb]
\centering
\includegraphics[width=0.7\textwidth]{images/phylo-simple-draw.png}
\caption{A rooted tree drawn with {\tt Phylo.draw}.}
\label{fig:phylo-simple-draw}
\end{figure}
\end{latexonly}
\subsection{Coloring branches within a tree}
The functions \verb|draw| and \verb|draw_graphviz| support the display of different
colors and branch widths in a tree.
As of Biopython 1.59, the \verb|color| and \verb|width| attributes are available on the
basic Clade object and there's nothing extra required to use them.
Both attributes refer to the branch leading the given clade, and apply recursively, so
all descendent branches will also inherit the assigned width and color values during
display.
In earlier versions of Biopython, these were special features of PhyloXML trees, and
using the attributes required first converting the tree to a subclass of the basic tree
object called Phylogeny, from the Bio.Phylo.PhyloXML module.
In Biopython 1.55 and later, this is a convenient tree method:
\begin{verbatim}
>>> tree = tree.as_phyloxml()
\end{verbatim}
In Biopython 1.54, you can accomplish the same thing with one extra import:
\begin{verbatim}
>>> from Bio.Phylo.PhyloXML import Phylogeny
>>> tree = Phylogeny.from_tree(tree)
\end{verbatim}
Note that the file formats Newick and Nexus don't support branch colors or widths, so
if you use these attributes in Bio.Phylo, you will only be able to save the values in
PhyloXML format. (You can still save a tree as Newick or Nexus, but the color and width
values will be skipped in the output file.)
Now we can begin assigning colors.
First, we'll color the root clade gray. We can do that by assigning the 24-bit color
value as an RGB triple, an HTML-style hex string, or the name of one of the predefined
colors.
\begin{verbatim}
>>> tree.root.color = (128, 128, 128)
\end{verbatim}
Or:
\begin{verbatim}
>>> tree.root.color = "#808080"
\end{verbatim}
Or:
\begin{verbatim}
>>> tree.root.color = "gray"
\end{verbatim}
Colors for a clade are treated as cascading down through the entire clade, so when we colorize
the root here, it turns the whole tree gray. We can override that by assigning a different
color lower down on the tree.
Let's target the most recent common ancestor (MRCA) of the nodes named ``E'' and ``F''. The
\verb|common_ancestor| method returns a reference to that clade in the original tree, so when
we color that clade ``salmon'', the color will show up in the original tree.
\begin{verbatim}
>>> mrca = tree.common_ancestor({"name": "E"}, {"name": "F"})
>>> mrca.color = "salmon"
\end{verbatim}
If we happened to know exactly where a certain clade is in the tree, in terms of nested list
entries, we can jump directly to that position in the tree by indexing it. Here, the index
\verb|[0,1]| refers to the second child of the first child of the root.
\begin{verbatim}
>>> tree.clade[0,1].color = "blue"
\end{verbatim}
Finally, show our work (see Fig. \ref{fig:phylo-color-draw}):
\begin{verbatim}
>>> Phylo.draw(tree)
\end{verbatim}
\begin{htmlonly}
\imgsrc[width=666, height=530]{images/phylo-color-draw.png}
\label{fig:phylo-color-draw}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[htb]
\centering
\includegraphics[width=0.7\textwidth]{images/phylo-color-draw.png}
\caption{A colorized tree drawn with {\tt Phylo.draw}.}
\label{fig:phylo-color-draw}
\end{figure}
\end{latexonly}
Note that a clade's color includes the branch leading to that clade, as well as its
descendents. The common ancestor of E and F turns out to be just under the root, and with this
coloring we can see exactly where the root of the tree is.
My, we've accomplished a lot! Let's take a break here and save our work. Call the
\texttt{write} function with a file name or handle --- here we use standard output, to see what
would be written --- and the format \texttt{phyloxml}. PhyloXML saves the colors we assigned,
so you can open this phyloXML file in another tree viewer like Archaeopteryx, and the colors
will show up there, too.
\begin{verbatim}
>>> import sys
>>> Phylo.write(tree, sys.stdout, "phyloxml")
<phy:phyloxml xmlns:phy="http://www.phyloxml.org">
<phy:phylogeny rooted="true">
<phy:clade>
<phy:branch_length>1.0</phy:branch_length>
<phy:color>
<phy:red>128</phy:red>
<phy:green>128</phy:green>
<phy:blue>128</phy:blue>
</phy:color>
<phy:clade>
<phy:branch_length>1.0</phy:branch_length>
<phy:clade>
<phy:branch_length>1.0</phy:branch_length>
<phy:clade>
<phy:name>A</phy:name>
...
\end{verbatim}
The rest of this chapter covers the core functionality of Bio.Phylo in greater detail. For more
examples of using Bio.Phylo, see the cookbook page on Biopython.org:
\url{http://biopython.org/wiki/Phylo_cookbook}
\section{I/O functions}
Like SeqIO and AlignIO, Phylo handles file input and output through four functions:
\verb|parse|, \verb|read|, \verb|write| and \verb|convert|,
all of which support the tree file formats Newick, NEXUS, phyloXML and NeXML.
The \verb|read| function parses a single tree in the given file and returns it. Careful; it
will raise an error if the file contains more than one tree, or no trees.
\begin{verbatim}
>>> from Bio import Phylo
>>> tree = Phylo.read("Tests/Nexus/int_node_labels.nwk", "newick")
>>> print tree
\end{verbatim}
(Example files are available in the \texttt{Tests/Nexus/} and \texttt{Tests/PhyloXML/}
directories of the Biopython distribution.)
To handle multiple (or an unknown number of) trees, use the \verb|parse| function iterates
through each of the trees in the given file:
\begin{verbatim}
>>> trees = Phylo.parse("Tests/PhyloXML/phyloxml_examples.xml", "phyloxml")
>>> for tree in trees:
... print tree
\end{verbatim}
Write a tree or iterable of trees back to file with the \verb|write| function:
\begin{verbatim}
>>> trees = list(Phylo.parse("phyloxml_examples.xml", "phyloxml"))
>>> tree1 = trees[0]
>>> others = trees[1:]
>>> Phylo.write(tree1, "tree1.xml", "phyloxml")
1
>>> Phylo.write(others, "other_trees.xml", "phyloxml")
12
\end{verbatim}
Convert files between any of the supported formats with the \verb|convert| function:
\begin{verbatim}
>>> Phylo.convert("tree1.dnd", "newick", "tree1.xml", "nexml")
1
>>> Phylo.convert("other_trees.xml", "phyloxml", "other_trees.nex", 'nexus")
12
\end{verbatim}
To use strings as input or output instead of actual files, use \verb|StringIO| as you would
with SeqIO and AlignIO:
%doctest
\begin{verbatim}
>>> from Bio import Phylo
>>> from StringIO import StringIO
>>> handle = StringIO("(((A,B),(C,D)),(E,F,G));")
>>> tree = Phylo.read(handle, "newick")
\end{verbatim}
\section{View and export trees}
The simplest way to get an overview of a \verb|Tree| object is to \verb|print| it:
\begin{verbatim}
>>> tree = Phylo.read("Tests/PhyloXML/example.xml", "phyloxml")
>>> print tree
Phylogeny(rooted='True', description='phyloXML allows to use either a "branch_length"
attribute...', name='example from Prof. Joe Felsenstein's book "Inferring Phyl...')
Clade()
Clade(branch_length='0.06')
Clade(branch_length='0.102', name='A')
Clade(branch_length='0.23', name='B')
Clade(branch_length='0.4', name='C')
\end{verbatim}
This is essentially an outline of the object hierarchy Biopython uses to represent a tree. But
more likely, you'd want to see a drawing of the tree. There are three functions to do this.
As we saw in the demo, \verb|draw_ascii| prints an ascii-art drawing of the tree (a
rooted phylogram) to standard output, or an open file handle if given. Not all of the
available information about the tree is shown, but it provides a way to quickly view the
tree without relying on any external dependencies.
\begin{verbatim}
>>> tree = Phylo.read("example.xml", "phyloxml")
>>> Phylo.draw_ascii(tree)
__________________ A
__________|
_| |___________________________________________ B
|
|___________________________________________________________________________ C
\end{verbatim}
The \verb|draw| function draws a more attractive image using the matplotlib
library. See the API documentation for details on the arguments it accepts to
customize the output.
\begin{verbatim}
>>> tree = Phylo.read("example.xml", "phyloxml")
>>> Phylo.draw(tree, branch_labels=lambda c: c.branch_length)
\end{verbatim}
\begin{htmlonly}
\imgsrc[width=701, height=465]{images/phylo-draw-example.png}
\label{fig:phylo-draw-example}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[tbp]
\centering
\includegraphics[width=0.7\textwidth]{images/phylo-draw-example.png}
\caption{A simple rooted tree plotted with the {\tt draw} function.}
\label{fig:phylo-draw-example}
\end{figure}
\end{latexonly}
\verb|draw_graphviz| draws an unrooted cladogram, but requires that you have Graphviz,
PyDot or PyGraphviz, NetworkX, and matplotlib (or pylab) installed. Using the same example as
above, and the \verb|dot| program included with Graphviz, let's draw a rooted tree (see
Fig.~\ref{fig:phylo-dot}):
\begin{verbatim}
>>> tree = Phylo.read("example.xml", "phyloxml")
>>> Phylo.draw_graphviz(tree, prog='dot')
>>> import pylab
>>> pylab.show() # Displays the tree in an interactive viewer
>>> pylab.savefig('phylo-dot.png') # Creates a PNG file of the same graphic
\end{verbatim}
\begin{htmlonly}
\imgsrc[width=400, height=312]{images/phylo-dot.png}
\label{fig:phylo-dot}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[tbp]
\centering
\includegraphics[width=0.5\textwidth]{images/phylo-dot.png}
\caption{A simple rooted tree drawn with {\tt draw\_graphviz}, using {\tt dot} for node
layout.}
\label{fig:phylo-dot}
\end{figure}
\end{latexonly}
(Tip: If you execute IPython with the \verb|-pylab| option, calling \verb|draw_graphviz| causes
the matplotlib viewer to launch automatically without manually calling \verb|show()|.)
This exports the tree object to a NetworkX graph, uses Graphviz to lay out the nodes, and
displays it using matplotlib.
There are a number of keyword arguments that can modify the resulting diagram, including
most of those accepted by the NetworkX functions \verb|networkx.draw| and
\verb|networkx.draw_graphviz|.
The display is also affected by the \verb|rooted| attribute of the given tree object.
Rooted trees are shown with a ``head'' on each branch indicating direction (see
Fig.~\ref{fig:phylo-rooted}):
\begin{verbatim}
>>> tree = Phylo.read("simple.dnd", "newick")
>>> tree.rooted = True
>>> Phylo.draw_graphiz(tree)
\end{verbatim}
\begin{htmlonly}
\imgsrc[width=432, height=368]{images/phylo-rooted.png}
\label{fig:phylo-rooted}
\end{htmlonly}
The ``prog'' argument specifies the Graphviz engine used for layout. The default,
\verb|twopi|, behaves well for any size tree, reliably avoiding crossed branches. The
\verb|neato| program may draw more attractive moderately-sized trees, but sometimes will
cross branches (see Fig.~\ref{fig:phylo-color}). The \verb|dot| program may be useful
with small trees, but tends to do surprising things with the layout of larger trees.
\begin{latexonly}
\begin{figure}[ptb]
\centering
\includegraphics[width=0.45\textwidth]{images/phylo-rooted.png}
\caption{A rooted tree drawn with {\tt draw\_graphviz}.
Since we rooted the tree, we can see the root must be along the branch with two
directional ``heads''.
}
\label{fig:phylo-rooted}
\end{figure}
\begin{figure}[ptb]
\centering
\includegraphics[width=0.5\textwidth]{images/phylo-color.png}
\caption{A colorized tree drawn with {\tt draw\_graphviz}, using {\tt neato} for node layout.}
\label{fig:phylo-color}
\end{figure}
\end{latexonly}
\begin{verbatim}
>>> Phylo.draw_graphviz(tree, prog="neato")
\end{verbatim}
\begin{htmlonly}
\imgsrc[width=499, height=348]{images/phylo-color.png}
\label{fig:phylo-color}
\end{htmlonly}
This viewing mode is particularly handy for exploring larger trees, because the matplotlib
viewer can zoom in on a selected region, thinning out a cluttered graphic.
\begin{latexonly}
%Can't reference unless inside a figure
(See Figs.~\ref{fig:phylo-apaf}, \ref{fig:phylo-apaf-zoom}).
\end{latexonly}
\begin{verbatim}
>>> tree = Phylo.read("apaf.xml", "phyloxml")
>>> Phylo.draw_graphviz(tree, prog="neato", node_size=0)
\end{verbatim}
\begin{htmlonly}
\imgsrc[width=519, height=400]{images/phylo-apaf.png}
\label{fig:phylo-apaf}
\imgsrc[width=506, height=400]{images/phylo-apaf-zoom.png}
\label{fig:phylo-apaf-zoom}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[tbp]
\centering
\includegraphics[width=0.65\textwidth]{images/phylo-apaf.png} \\
\caption{A larger tree, using {\tt neato} for layout.}
\label{fig:phylo-apaf}
\end{figure}
\begin{figure}[btp]
\centering
\includegraphics[width=0.6\textwidth]{images/phylo-apaf-zoom.png}
\caption{A zoomed-in portion of the same tree as Fig.~\ref{fig:phylo-apaf}.}
\label{fig:phylo-apaf-zoom}
\end{figure}
\end{latexonly}
Note that branch lengths are not displayed accurately, because Graphviz ignores them when
creating the node layouts. The branch lengths are retained when exporting a tree as a NetworkX
graph object (\verb|to_networkx|), however.
See the Phylo page on the Biopython wiki (\url{http://biopython.org/wiki/Phylo}) for
descriptions and examples of the more advanced functionality in \verb|draw_ascii|,
\verb|draw_graphviz| and \verb|to_networkx|.
\section{Using Tree and Clade objects}
The \verb|Tree| objects produced by \verb|parse| and \verb|read| are containers for recursive
sub-trees, attached to the \verb|Tree| object at the \verb|root| attribute (whether or not the
phylogenic tree is actually considered rooted). A \verb|Tree| has globally applied information
for the phylogeny, such as rootedness, and a reference to a single \verb|Clade|; a
\verb|Clade| has node- and clade-specific information, such as branch length, and a list of
its own descendent \verb|Clade| instances, attached at the \verb|clades| attribute.
So there is a distinction between \verb|tree| and \verb|tree.root|. In practice, though, you
rarely need to worry about it. To smooth over the difference, both \verb|Tree| and
\verb|Clade| inherit from \verb|TreeMixin|, which contains the implementations for methods
that would be commonly used to search, inspect or modify a tree or any of its clades. This
means that almost all of the methods supported by \verb|tree| are also available on
\verb|tree.root| and any clade below it. (\verb|Clade| also has a \verb|root| property, which
returns the clade object itself.)
% TODO - use dia to make a class diagram like images/smcra.png
\subsection{Search and traversal methods}
For convenience, we provide a couple of simplified methods that return all external or internal
nodes directly as a list:
\begin{description}
\item[\texttt{get\_terminals}] makes a list of all of this tree's terminal (leaf) nodes.
\item[\texttt{get\_nonterminals}] makes a list of all of this tree's nonterminal (internal)
nodes.
\end{description}
These both wrap a method with full control over tree traversal, \verb|find_clades|. Two more
traversal methods, \verb|find_elements| and \verb|find_any|, rely on the same core
functionality and accept the same arguments, which we'll call a ``target specification'' for
lack of a better description. These specify which objects in the tree will be matched and
returned during iteration. The first argument can be any of the following types:
\begin{itemize}
\item A \textbf{TreeElement instance}, which tree elements will match by identity --- so
searching with a Clade instance as the target will find that clade in the tree;
\item A \textbf{string}, which matches tree elements' string representation --- in
particular, a clade's \verb|name| \textit{(added in Biopython 1.56)};
\item A \textbf{class} or \textbf{type}, where every tree element of the same type (or
sub-type) will be matched;
\item A \textbf{dictionary} where keys are tree element attributes and values are matched to the
corresponding attribute of each tree element. This one gets even more elaborate:
\begin{itemize}
\item If an \texttt{int} is given, it matches numerically equal attributes, e.g. 1 will
match 1 or 1.0
\item If a boolean is given (True or False), the corresponding attribute value is
evaluated as a boolean and checked for the same
\item \texttt{None} matches \texttt{None}
\item If a string is given, the value is treated as a regular expression (which must
match the whole string in the corresponding element attribute, not just a prefix). A
given string without special regex characters will match string attributes exactly, so
if you don't use regexes, don't worry about it. For example, in a tree with clade
names Foo1, Foo2 and Foo3, \verb|tree.find_clades({"name": "Foo1"})| matches Foo1,
\verb|{"name": "Foo.*"}| matches all three clades, and \verb|{"name": "Foo"}| doesn't
match anything.
\end{itemize}
Since floating-point arithmetic can produce some strange behavior, we don't support
matching \texttt{float}s directly. Instead, use the boolean \texttt{True} to match every
element with a nonzero value in the specified attribute, then filter on that attribute
manually with an inequality (or exact number, if you like living dangerously).
If the dictionary contains multiple entries, a matching element must match each of the
given attribute values --- think ``and'', not ``or''.
\item A \textbf{function} taking a single argument (it will be applied to each element in the
tree), returning True or False. For convenience, LookupError, AttributeError and ValueError
are silenced, so this provides another safe way to search for floating-point values in the
tree, or some more complex characteristic.
\end{itemize}
After the target, there are two optional keyword arguments:
\begin{description}
\item[terminal] --- A boolean value to select for or against terminal clades (a.k.a. leaf
nodes): True searches for only terminal clades, False for non-terminal (internal) clades,
and the default, None, searches both terminal and non-terminal clades, as well as any tree
elements lacking the \verb|is_terminal| method.
\item[order] --- Tree traversal order: \texttt{"preorder"} (default) is depth-first search,
\texttt{"postorder"} is DFS with child nodes preceding parents, and \texttt{"level"} is
breadth-first search.
\end{description}
Finally, the methods accept arbitrary keyword arguments which are treated the same way as a
dictionary target specification: keys indicate the name of the element attribute to search for,
and the argument value (string, integer, None or boolean) is compared to the value of each
attribute found. If no keyword arguments are given, then any TreeElement types are matched.
The code for this is generally shorter than passing a dictionary as the target specification:
\verb|tree.find_clades({"name": "Foo1"})| can be shortened to
\verb|tree.find_clades(name="Foo1")|.
(In Biopython 1.56 or later, this can be even shorter: \verb|tree.find_clades("Foo1")|)
% TODO -- introduce these / segue and clean up the descriptions
Now that we've mastered target specifications, here are the methods used to traverse a tree:
\begin{description}
\item[\texttt{find\_clades}]
Find each clade containing a matching element. That is, find each element as with
\verb|find_elements|, but return the corresponding clade object. (This is usually what you
want.)
The result is an iterable through all matching objects, searching depth-first by default.
This is not necessarily the same order as the elements appear in the Newick, Nexus or XML
source file!
\item[\texttt{find\_elements}]
Find all tree elements matching the given attributes, and return the matching elements
themselves. Simple Newick trees don't have complex sub-elements, so this behaves the same
as \verb|find_clades| on them. PhyloXML trees often do have complex objects attached to
clades, so this method is useful for extracting those.
\item[\texttt{find\_any}]
Return the first element found by \verb|find_elements()|, or None. This is also useful for
checking whether any matching element exists in the tree, and can be used in a conditional.
\end{description}
Two more methods help navigating between nodes in the tree:
\begin{description}
\item[\texttt{get\_path}]
List the clades directly between the tree root (or current clade) and the given target.
Returns a list of all clade objects along this path, ending with the given target, but
excluding the root clade.
\item[\texttt{trace}]
List of all clade object between two targets in this tree. Excluding start, including
finish.
\end{description}
\subsection{Information methods}
These methods provide information about the whole tree (or any clade).
\begin{description}
\item[\texttt{common\_ancestor}]
Find the most recent common ancestor of all the given targets. (This will be a Clade object).
If no target is given, returns the root of the current clade (the one this method is called
from); if 1 target is given, this returns the target itself. However, if any of the
specified targets are not found in the current tree (or clade), an exception is raised.
\item[\texttt{count\_terminals}]
Counts the number of terminal (leaf) nodes within the tree.
\item[\texttt{depths}]
Create a mapping of tree clades to depths. The result is a dictionary where the keys are
all of the Clade instances in the tree, and the values are the distance from the root to
each clade (including terminals). By default the distance is the cumulative branch length
leading to the clade, but with the \verb|unit_branch_lengths=True| option, only the number
of branches (levels in the tree) is counted.
\item[\texttt{distance}]
Calculate the sum of the branch lengths between two targets. If only one target is
specified, the other is the root of this tree.
\item[\texttt{total\_branch\_length}]
Calculate the sum of all the branch lengths in this tree. This is usually just called the
``length'' of the tree in phylogenetics, but we use a more explicit name to avoid confusion
with Python terminology.
\end{description}
The rest of these methods are boolean checks:
\begin{description}
\item[\texttt{is\_bifurcating}]
True if the tree is strictly bifurcating; i.e. all nodes have either 2 or 0 children
(internal or external, respectively). The root may have 3 descendents and still be
considered part of a bifurcating tree.
\item[\texttt{is\_monophyletic}]
Test if all of the given targets comprise a complete subclade --- i.e., there
exists a clade such that its terminals are the same set as the given targets. The targets
should be terminals of the tree. For convenience, this method returns the common ancestor
(MCRA) of the targets if they are monophyletic (instead of the value \verb|True|), and
\verb|False| otherwise.
\item[\texttt{is\_parent\_of}] True if target is a descendent of this tree --- not required
to be a direct descendent. To check direct descendents of a clade, simply use list
membership testing: \verb|if subclade in clade: ...|
\item[\texttt{is\_preterminal}] True if all direct descendents are terminal; False if any
direct descendent is not terminal.
\end{description}
\subsection{Modification methods}
These methods modify the tree in-place. If you want to keep the original tree intact, make a
complete copy of the tree first, using Python's \texttt{copy} module:
\begin{verbatim}
tree = Phylo.read('example.xml', 'phyloxml')
import copy
newtree = copy.deepcopy(tree)
\end{verbatim}
\begin{description}
\item[\texttt{collapse}]
Deletes the target from the tree, relinking its children to its parent.
\item[\texttt{collapse\_all}]
Collapse all the descendents of this tree, leaving only terminals. Branch lengths are
preserved, i.e. the distance to each terminal stays the same. With a target specification
(see above), collapses only the internal nodes matching the specification.
\item[\texttt{ladderize}]
Sort clades in-place according to the number of terminal nodes. Deepest clades are placed
last by default. Use \verb|reverse=True| to sort clades deepest-to-shallowest.
\item[\texttt{prune}]
Prunes a terminal clade from the tree. If taxon is from a bifurcation, the connecting node
will be collapsed and its branch length added to remaining terminal node. This might no
longer be a meaningful value.
\item[\texttt{root\_with\_outgroup}]
Reroot this tree with the outgroup clade containing the given targets, i.e. the common
ancestor of the outgroup. This method is only available on Tree objects, not Clades.
If the outgroup is identical to self.root, no change occurs. If the outgroup clade is
terminal (e.g. a single terminal node is given as the outgroup), a new bifurcating root
clade is created with a 0-length branch to the given outgroup. Otherwise, the internal node
at the base of the outgroup becomes a trifurcating root for the whole tree. If the original
root was bifurcating, it is dropped from the tree.
In all cases, the total branch length of the tree stays the same.
\item[\texttt{root\_at\_midpoint}]
Reroot this tree at the calculated midpoint between the two most distant
tips of the tree. (This uses \verb|root_with_outgroup| under the hood.)
\item[\texttt{split}]
Generate \textit{n} (default 2) new descendants. In a species tree, this is a speciation
event. New clades have the given \verb|branch_length| and the same name as this clade's
root plus an integer suffix (counting from 0) --- for example, splitting a clade named
``A'' produces the sub-clades ``A0'' and ``A1''.
\end{description}
See the Phylo page on the Biopython wiki (\url{http://biopython.org/wiki/Phylo}) for
more examples of using the available methods.
\subsection{Features of PhyloXML trees}
\label{sec:PhyloXML}
The phyloXML file format includes fields for annotating trees with additional data types and
visual cues.
% TODO
% annotations -- see wiki and epydoc pages
% - on wiki, discuss each class
See the PhyloXML page on the Biopython wiki (\url{http://biopython.org/wiki/PhyloXML}) for
descriptions and examples of using the additional annotation features provided by PhyloXML.
% The object hierarchy still looks and behaves similarly:
% \begin{verbatim}
% >>> print tree
% Phylogeny(rooted=True, name="")
% Clade(branch_length=1.0)
% Clade(branch_length=1.0)
% Clade(branch_length=1.0)
% Clade(branch_length=1.0, name="A")
% Clade(branch_length=1.0, name="B")
% Clade(branch_length=1.0)
% Clade(branch_length=1.0, name="C")
% Clade(branch_length=1.0, name="D")
% Clade(branch_length=1.0)
% Clade(branch_length=1.0, name="E")
% Clade(branch_length=1.0, name="F")
% Clade(branch_length=1.0, name="G")
% \end{verbatim}
\section{Running external applications}
\label{sec:PhyloApps}
While Bio.Phylo doesn't infer trees from alignments itself, there are third-party
programs available that do. These are supported through the module
\texttt{Bio.Phylo.Applications}, using the same general framework as
\texttt{Bio.Emboss.Applications}, \texttt{Bio.Align.Applications} and others.
Biopython 1.58 introduced a wrapper for PhyML
(\url{http://www.atgc-montpellier.fr/phyml/}). The program accepts an input alignment in
\texttt{phylip-relaxed} format (that's Phylip format, but without the 10-character limit
on taxon names) and a variety of options. A quick example:
\begin{verbatim}
>>> from Bio import Phylo
>>> from Bio.Phylo.Applications import PhymlCommandline
>>> cmd = PhymlCommandline(input='Tests/Phylip/random.phy')
>>> out_log, err_log = cmd()
\end{verbatim}
This generates a tree file and a stats file with the names
[\textit{input~filename}]\verb|_phyml_tree.txt| and
[\textit{input~filename}]\verb|_phyml_stats.txt|. The tree file is in Newick format:
\begin{verbatim}
>>> tree = Phylo.read('Tests/Phylip/random.phy_phyml_tree.txt', 'newick')
>>> Phylo.draw_ascii(tree)
\end{verbatim}
A similar wrapper for RAxML (\url{http://sco.h-its.org/exelixis/software.html})
was added in Biopython 1.60.
Note that some popular Phylip programs, including \texttt{dnaml} and \texttt{protml},
are already available through the EMBOSS wrappers in \texttt{Bio.Emboss.Applications} if
you have the Phylip extensions to EMBOSS installed on your system.
See Section~\ref{sec:alignment-tools} for some examples and clues on how to use
programs like these.
\section{PAML integration}
\label{sec:PhyloPAML}
Biopython 1.58 brought support for PAML
(\url{http://abacus.gene.ucl.ac.uk/software/paml.html}), a suite of programs for
phylogenetic analysis by maximum likelihood. Currently the programs codeml, baseml and
yn00 are implemented. Due to PAML's usage of control files rather than command line
arguments to control runtime options, usage of this wrapper strays from the format of
other application wrappers in Biopython.
A typical workflow would be to initialize a PAML object, specifying an alignment file, a
tree file, an output file and a working directory. Next, runtime options are set via the
\texttt{set\_options()} method or by reading an existing control file. Finally, the
program is run via the \texttt{run()} method and the output file is automatically parsed
to a results dictionary.
Here is an example of typical usage of codeml:
\begin{verbatim}
>>> from Bio.Phylo.PAML import codeml
>>> cml = codeml.Codeml()
>>> cml.alignment = "Tests/PAML/alignment.phylip"
>>> cml.tree = "Tests/PAML/species.tree"
>>> cml.out_file = "results.out"
>>> cml.working_dir = "./scratch"
>>> cml.set_options(seqtype=1,
... verbose=0,
... noisy=0,
... RateAncestor=0,
... model=0,
... NSsites=[0, 1, 2],
... CodonFreq=2,
... cleandata=1,
... fix_alpha=1,
... kappa=4.54006)
>>> results = cml.run()
>>> ns_sites = results.get("NSsites")
>>> m0 = ns_sites.get(0)
>>> m0_params = m0.get("parameters")
>>> print m0_params.get("omega")
\end{verbatim}
Existing output files may be parsed as well using a module's \texttt{read()} function:
\begin{verbatim}
>>> results = codeml.read("Tests/PAML/Results/codeml/codeml_NSsites_all.out")
>>> print results.get("lnL max")
\end{verbatim}
Detailed documentation for this new module currently lives on the Biopython wiki:
\url{http://biopython.org/wiki/PAML}
\section{Future plans}
\label{sec:PhyloFuture}
Bio.Phylo is under active development. Here are some features we might add in future
releases:
\begin{description}
\item[New methods]
Generally useful functions for operating on Tree or Clade objects appear on the Biopython
wiki first, so that casual users can test them and decide if they're useful before we add
them to Bio.Phylo:
\url{http://biopython.org/wiki/Phylo_cookbook}
\item[Bio.Nexus port]
Much of this module was written during Google Summer of Code 2009, under the auspices of
NESCent, as a project to implement Python support for the phyloXML data format (see
\ref{sec:PhyloXML}). Support for Newick and Nexus formats was added by porting part of the
existing Bio.Nexus module to the new classes used by Bio.Phylo.
Currently, Bio.Nexus contains some useful features that have not yet been ported to
Bio.Phylo classes --- notably, calculating a consensus tree. If you find some functionality
lacking in Bio.Phylo, try poking throught Bio.Nexus to see if it's there instead.
\end{description}
We're open to any suggestions for improving the functionality and usability of this module;
just let us know on the mailing list or our bug database.
\chapter{Sequence motif analysis using Bio.motifs}
This chapter gives an overview of the functionality of the
\verb|Bio.motifs| package included in Biopython distribution. It is intended
for people who are involved in analysis of sequence motif, so I'll
assume that you are familiar with basic notions of motif analysis. In
case something is unclear, please look into Section~\ref{sec:links}
for some relevant links.
Most of this chapter describes the new \verb|Bio.motifs| package included
in Biopython 1.61 onwards, which is replacing the older \verb|Bio.Motif| package
introduced with Biopython 1.50, which was in turn based on two older former
Biopython modules, \verb|Bio.AlignAce| and \verb|Bio.MEME|. It provides
most of their functionality with a unified motif object implementation.
Speaking of other libraries, if you are reading this you might be
interested in the \href{http://fraenkel.mit.edu/TAMO/}{TAMO}, another Python library
designed to deal with sequence motifs. It supports more \emph{de-novo}
motif finders, but it is not a part of Biopython and has some restrictions
on commercial use.
\section{Motif objects}
\label{sec:object}
Since we are interested in motif analysis, we need to take a look at
\verb|Motif| objects in the first place. For that we need to import
the Bio.motifs library:
%doctest ../Tests/Motif
\begin{verbatim}
>>> from Bio import motifs
\end{verbatim}
and we can start creating our first motif objects. We can either create
a \verb+Motif+ object from a list of instances of the motif, or we can
obtain a \verb+Motif+ object by parsing a file from a motif database
or motif finding software.
\subsection{Creating a motif from instances}
Suppose we have these instances of a DNA motif:
%cont-doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> instances = [Seq("TACAA"),
... Seq("TACGC"),
... Seq("TACAC"),
... Seq("TACCC"),
... Seq("AACCC"),
... Seq("AATGC"),
... Seq("AATGC"),
... ]
\end{verbatim}
then we can create a Motif object as follows:
%cont-doctest
\begin{verbatim}
>>> m = motifs.create(instances)
\end{verbatim}
The instances are saved in an attribute \verb+m.instances+, which is essentially a Python list with some added functionality, as described below.
Printing out the Motif object shows the instances from which it was constructed:
%cont-doctest
\begin{verbatim}
>>> print m
TACAA
TACGC
TACAC
TACCC
AACCC
AATGC
AATGC
<BLANKLINE>
\end{verbatim}
The length of the motif defined as the sequence length, which should be the same for all instances:
%cont-doctest
\begin{verbatim}
>>> len(m)
5
\end{verbatim}
The Motif object has an attribute \verb+.counts+ containing the counts of each
nucleotide at each position. Printing this counts matrix shows it in an easily readable format:
%cont-doctest
\begin{verbatim}
>>> print m.counts
0 1 2 3 4
A: 3.00 7.00 0.00 2.00 1.00
C: 0.00 0.00 5.00 2.00 6.00
G: 0.00 0.00 0.00 3.00 0.00
T: 4.00 0.00 2.00 0.00 0.00
<BLANKLINE>
\end{verbatim}
You can access these counts as a dictionary:
%cont-doctest
\begin{verbatim}
>>> m.counts['A']
[3, 7, 0, 2, 1]
\end{verbatim}
but you can also think of it as a 2D array with the nucleotide as the first
dimension and the position as the second dimension:
%cont-doctest
\begin{verbatim}
>>> m.counts['T',0]
4
>>> m.counts['T',2]
2
>>> m.counts['T',3]
0
\end{verbatim}
You can also directly access columns of the counts matrix
%Don't doctest this as dictionary order is platform dependent:
\begin{verbatim}
>>> m.counts[:,3]
{'A': 2, 'C': 2, 'T': 0, 'G': 3}
\end{verbatim}
Instead of the nucleotide itself, you can also use the index of the nucleotide
in the sorted letters in the alphabet of the motif:
%cont-doctest
\begin{verbatim}
>>> m.alphabet
IUPACUnambiguousDNA()
>>> m.alphabet.letters
'GATC'
>>> sorted(m.alphabet.letters)
['A', 'C', 'G', 'T']
>>> m.counts['A',:]
(3, 7, 0, 2, 1)
>>> m.counts[0,:]
(3, 7, 0, 2, 1)
\end{verbatim}
The motif has an associated consensus sequence, defined as the sequence of
letters along the positions of the motif for which the largest value in the
corresponding columns of the \verb+.counts+ matrix is obtained:
%cont-doctest
\begin{verbatim}
>>> m.consensus
Seq('TACGC', IUPACUnambiguousDNA())
\end{verbatim}
as well as an anticonsensus sequence, corresponding to the smallest values in
the columns of the \verb+.counts+ matrix:
%cont-doctest
\begin{verbatim}
>>> m.anticonsensus
Seq('GGGTG', IUPACUnambiguousDNA())
\end{verbatim}
You can also ask for a degenerate consensus sequence, in which ambiguous
nucleotides are used for positions where there are multiple nucleotides with
high counts:
%cont-doctest
\begin{verbatim}
>>> m.degenerate_consensus
Seq('WACVC', IUPACAmbiguousDNA())
\end{verbatim}
Here, W and R follow the IUPAC nucleotide ambiguity codes: W is either A or T, and V is A, C, or G \cite{cornish1985}. The degenerate consensus sequence is constructed followed the rules specified by Cavener \cite{cavener1987}.
We can also get the reverse complement of a motif:
%cont-doctest
\begin{verbatim}
>>> r = m.reverse_complement()
>>> r.consensus
Seq('GCGTA', IUPACUnambiguousDNA())
>>> r.degenerate_consensus
Seq('GBGTW', IUPACAmbiguousDNA())
>>> print r
TTGTA
GCGTA
GTGTA
GGGTA
GGGTT
GCATT
GCATT
<BLANKLINE>
\end{verbatim}
The reverse complement and the degenerate consensus sequence are
only defined for DNA motifs.
\subsection{Reading motifs}
\label{sec:io}
Creating motifs from instances by hand is a bit boring, so it's
useful to have some I/O functions for reading and writing
motifs. There are no really well established standards for storing
motifs, but there's a couple of formats which are more used than
others. The most important distinction is whether the motif
representation is based on instances or on some version of PWM matrix.
\subsubsection*{JASPAR}
One of the most popular motif databases \href{http://jaspar.genereg.net}{JASPAR}
stores motifs either as a list of instances, or as a frequency matrix.
As an example, these are the beginning and ending lines of the JASPAR \verb+Arnt.sites+ file showing known binding sites of the mouse helix-loop-helix transcription factor Arnt:
\begin{verbatim}
>MA0004 ARNT 1
CACGTGatgtcctc
>MA0004 ARNT 2
CACGTGggaggtac
>MA0004 ARNT 3
CACGTGccgcgcgc
...
>MA0004 ARNT 18
AACGTGacagccctcc
>MA0004 ARNT 19
AACGTGcacatcgtcc
>MA0004 ARNT 20
aggaatCGCGTGc
\end{verbatim}
The parts of the sequence in capital letters are the motif instances that were found to align to each other.
We can create a \verb+Motif+ object from these instances as follows:
%cont-doctest
\begin{verbatim}
>>> from Bio import motifs
>>> arnt = motifs.read(open("Arnt.sites"), "sites")
\end{verbatim}
The instances from which this motif was created is stored in the \verb+.instances+ property:
%cont-doctest
\begin{verbatim}
>>> print arnt.instances[:3]
[Seq('CACGTG', IUPACUnambiguousDNA()), Seq('CACGTG', IUPACUnambiguousDNA()), Seq('CACGTG', IUPACUnambiguousDNA())]
>>> for instance in arnt.instances:
... print instance
...
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
CACGTG
AACGTG
AACGTG
AACGTG
AACGTG
CGCGTG
\end{verbatim}
The counts matrix of this motif is automatically calculated from the instances:
%cont-doctest
\begin{verbatim}
>>> print arnt.counts
0 1 2 3 4 5
A: 4.00 19.00 0.00 0.00 0.00 0.00
C: 16.00 0.00 20.00 0.00 0.00 0.00
G: 0.00 1.00 0.00 20.00 0.00 20.00
T: 0.00 0.00 0.00 0.00 20.00 0.00
<BLANKLINE>
\end{verbatim}
The JASPAR database also makes motifs available directly as a count matrix,
without the instances from which it was created.
For example, this is the JASPAR file \verb+SRF.pfm+ containing the count
matrix for the human SRF transcription factor:
\begin{verbatim}
2 9 0 1 32 3 46 1 43 15 2 2
1 33 45 45 1 1 0 0 0 1 0 1
39 2 1 0 0 0 0 0 0 0 44 43
4 2 0 0 13 42 0 45 3 30 0 0
\end{verbatim}
We can create a motif for this count matrix as follows:
%cont-doctest
\begin{verbatim}
>>> srf = motifs.read(open("SRF.pfm"),"pfm")
>>> print srf.counts
0 1 2 3 4 5 6 7 8 9 10 11
A: 2.00 9.00 0.00 1.00 32.00 3.00 46.00 1.00 43.00 15.00 2.00 2.00
C: 1.00 33.00 45.00 45.00 1.00 1.00 0.00 0.00 0.00 1.00 0.00 1.00
G: 39.00 2.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 44.00 43.00
T: 4.00 2.00 0.00 0.00 13.00 42.00 0.00 45.00 3.00 30.00 0.00 0.00
<BLANKLINE>
\end{verbatim}
As this motif was created from the counts matrix directly, it has no instances associated with it:
%cont-doctest
\begin{verbatim}
>>> print srf.instances
None
\end{verbatim}
We can now ask for the consensus sequence of these two motifs:
%cont-doctest
\begin{verbatim}
>>> print arnt.counts.consensus
CACGTG
>>> print srf.counts.consensus
GCCCATATATGG
\end{verbatim}
\subsubsection*{MEME}
MEME \cite{bailey1994} is a tool for discovering motifs in a group of related DNA or protein sequences. It takes as input a group of DNA or protein sequences and outputs as many motifs as requested. Therefore, in contrast to JASPAR files, MEME output files typically contain multiple motifs. This is an example
At the top of an output file generated by MEME shows some background information about the MEME and the version of MEME used:
\begin{verbatim}
********************************************************************************
MEME - Motif discovery tool
********************************************************************************
MEME version 3.0 (Release date: 2004/08/18 09:07:01)
...
\end{verbatim}
Further down, the input set of training sequences is recapitulated:
\begin{verbatim}
********************************************************************************
TRAINING SET
********************************************************************************
DATAFILE= INO_up800.s
ALPHABET= ACGT
Sequence name Weight Length Sequence name Weight Length
------------- ------ ------ ------------- ------ ------
CHO1 1.0000 800 CHO2 1.0000 800
FAS1 1.0000 800 FAS2 1.0000 800
ACC1 1.0000 800 INO1 1.0000 800
OPI3 1.0000 800
********************************************************************************
\end{verbatim}
and the exact command line that was used:
\begin{verbatim}
********************************************************************************
COMMAND LINE SUMMARY
********************************************************************************
This information can also be useful in the event you wish to report a
problem with the MEME software.
command: meme -mod oops -dna -revcomp -nmotifs 2 -bfile yeast.nc.6.freq INO_up800.s
...
\end{verbatim}
Next is detailed information on each motif that was found:
\begin{verbatim}
********************************************************************************
MOTIF 1 width = 12 sites = 7 llr = 95 E-value = 2.0e-001
********************************************************************************
--------------------------------------------------------------------------------
Motif 1 Description
--------------------------------------------------------------------------------
Simplified A :::9:a::::3:
pos.-specific C ::a:9:11691a
probability G ::::1::94:4:
matrix T aa:1::9::11:
\end{verbatim}
To parse this file (stored as \verb+meme.dna.oops.txt+), use
%cont-doctest
\begin{verbatim}
>>> handle = open("meme.dna.oops.txt")
>>> record = motifs.parse(handle, "meme")
>>> handle.close()
\end{verbatim}
The \verb+motifs.parse+ command reads the complete file directly, so you can
close the file after calling \verb+motifs.parse+.
The header information is stored in attributes:
%cont-doctest
\begin{verbatim}
>>> record.version
'3.0'
>>> record.datafile
'INO_up800.s'
>>> record.command
'meme -mod oops -dna -revcomp -nmotifs 2 -bfile yeast.nc.6.freq INO_up800.s'
>>> record.alphabet
IUPACUnambiguousDNA()
>>> record.sequences
['CHO1', 'CHO2', 'FAS1', 'FAS2', 'ACC1', 'INO1', 'OPI3']
\end{verbatim}
The record is an object of the \verb+Bio.motifs.meme.Record+ class.
The class inherits from list, and you can think of \verb+record+ as a list of Motif objects:
%cont-doctest
\begin{verbatim}
>>> len(record)
2
>>> motif = record[0]
>>> print motif.consensus
TTCACATGCCGC
>>> print motif.degenerate_consensus
TTCACATGSCNC
\end{verbatim}
In addition to these generic motif attributes, each motif also stores its
specific information as calculated by MEME. For example,
%cont-doctest
\begin{verbatim}
>>> motif.num_occurrences
7
>>> motif.length
12
>>> evalue = motif.evalue
>>> print "%3.1g" % evalue
0.2
>>> motif.name
'Motif 1'
\end{verbatim}
In addition to using an index into the record, as we did above, you can also find it by its name:
%cont-doctest
\begin{verbatim}
>>> motif = record['Motif 1']
\end{verbatim}
Each motif has an attribute \verb+.instances+ with the sequence instances in which the motif was found, providing some information on each instance
%cont-doctest
\begin{verbatim}
>>> len(motif.instances)
7
>>> motif.instances[0]
Instance('TTCACATGCCGC', IUPACUnambiguousDNA())
>>> motif.instances[0].motif_name
'Motif 1'
>>> motif.instances[0].sequence_name
'INO1'
>>> motif.instances[0].start
620
>>> motif.instances[0].strand
'-'
>>> motif.instances[0].length
12
>>> pvalue = motif.instances[0].pvalue
\end{verbatim}
%Sadly Python 2.5 on Windows gives 1.85e-008 breaking doctest:
\begin{verbatim}
>>> print "%5.3g" % pvalue
1.85e-08
\end{verbatim}
\subsubsection*{MAST}
\subsubsection*{TRANSFAC}
TRANSFAC is a manually curated database of transcription factors, together with their genomic binding sites and DNA binding profiles \cite{matys2003}. While the file format used in the TRANSFAC database is nowadays also used by others, we will refer to it as the TRANSFAC file format.
A minimal file in the TRANSFAC format looks as follows:
\begin{verbatim}
ID motif1
P0 A C G T
01 1 2 2 0 S
02 2 1 2 0 R
03 3 0 1 1 A
04 0 5 0 0 C
05 5 0 0 0 A
06 0 0 4 1 G
07 0 1 4 0 G
08 0 0 0 5 T
09 0 0 5 0 G
10 0 1 2 2 K
11 0 2 0 3 Y
12 1 0 3 1 G
//
\end{verbatim}
This file shows the frequency matrix of motif \verb+motif1+ of 12 nucleotides.
In general, one file in the TRANSFAC format can contain multiple motifs. For
example, this is the contents of the example TRANSFAC file \verb+transfac.dat+:
\begin{verbatim}
VV EXAMPLE January 15, 2013
XX
//
ID motif1
P0 A C G T
01 1 2 2 0 S
02 2 1 2 0 R
03 3 0 1 1 A
...
11 0 2 0 3 Y
12 1 0 3 1 G
//
ID motif2
P0 A C G T
01 2 1 2 0 R
02 1 2 2 0 S
...
09 0 0 0 5 T
10 0 2 0 3 Y
//
\end{verbatim}
To parse a TRANSFAC file, use
%cont-doctest
\begin{verbatim}
>>> handle = open("transfac.dat")
>>> record = motifs.parse(handle, "TRANSFAC")
>>> handle.close()
\end{verbatim}
The overall version number, if available, is stored as \verb+record.version+:
%cont-doctest
\begin{verbatim}
>>> record.version
'EXAMPLE January 15, 2013'
\end{verbatim}
Each motif in \verb+record+ is in instance of the \verb+Bio.motifs.transfac.Motif+ class, which inherits both from the \verb+Bio.motifs.Motif+ class and from a Python dictionary. The dictionary uses the two-letter keys to store any additional information about the motif:
%cont-doctest
\begin{verbatim}
>>> motif = record[0]
>>> motif.degenerate_consensus # Using the Bio.motifs.Motif method
Seq('SRACAGGTGKYG', IUPACAmbiguousDNA())
>>> motif['ID'] # Using motif as a dictionary
'motif1'
\end{verbatim}
TRANSFAC files are typically much more elaborate than this example, containing lots of additional information about the motif. Table \ref{table:transfaccodes} lists the two-letter field codes that are commonly found in TRANSFAC files:
\begin{table}[h]
\label{table:transfaccodes}
\begin{center}
\caption{Fields commonly found in TRANSFAC files}
\begin{tabular}{|l|l||}
\verb+AC+ & Accession number \\
\verb+AS+ & Accession numbers, secondary \\
\verb+BA+ & Statistical basis \\
\verb+BF+ & Binding factors \\
\verb+BS+ & Factor binding sites underlying the matrix \\
\verb+CC+ & Comments \\
\verb+CO+ & Copyright notice \\
\verb+DE+ & Short factor description \\
\verb+DR+ & External databases \\
\verb+DT+ & Date created/updated \\
\verb+HC+ & Subfamilies \\
\verb+HP+ & Superfamilies \\
\verb+ID+ & Identifier \\
\verb+NA+ & Name of the binding factor \\
\verb+OC+ & Taxonomic classification \\
\verb+OS+ & Species/Taxon \\
\verb+OV+ & Older version \\
\verb+PV+ & Preferred version \\
\verb+TY+ & Type \\
\verb+XX+ & Empty line; these are not stored in the Record. \\
\end{tabular}
\end{center}
\end{table}
Each motif also has an attribute \verb+.references+ containing the references associated with the motif, using these two-letter keys:
\begin{table}[h]
\begin{center}
\caption{Fields used to store references in TRANSFAC files}
\begin{tabular}{|l|l||}
\verb+RN+ & Reference number \\
\verb+RA+ & Reference authors \\
\verb+RL+ & Reference data \\
\verb+RT+ & Reference title \\
\verb+RX+ & PubMed ID \\
\end{tabular}
\end{center}
\end{table}
Printing the motifs writes them out in their native TRANSFAC format:
%cont-doctest
\begin{verbatim}
>>> print record
VV EXAMPLE January 15, 2013
XX
//
ID motif1
XX
P0 A C G T
01 1 2 2 0 S
02 2 1 2 0 R
03 3 0 1 1 A
04 0 5 0 0 C
05 5 0 0 0 A
06 0 0 4 1 G
07 0 1 4 0 G
08 0 0 0 5 T
09 0 0 5 0 G
10 0 1 2 2 K
11 0 2 0 3 Y
12 1 0 3 1 G
XX
//
ID motif2
XX
P0 A C G T
01 2 1 2 0 R
02 1 2 2 0 S
03 0 5 0 0 C
04 3 0 1 1 A
05 0 0 4 1 G
06 5 0 0 0 A
07 0 1 4 0 G
08 0 0 5 0 G
09 0 0 0 5 T
10 0 2 0 3 Y
XX
//
<BLANKLINE>
\end{verbatim}
You can export the motifs in the TRANSFAC format by capturing this output
in a string and saving it in a file:
\begin{verbatim}
>>> text = str(record)
>>> handle = open("mytransfacfile.dat", 'w')
>>> handle.write(text)
>>> handle.close()
\end{verbatim}
\subsection{Writing motifs}
Speaking of exporting, let's look at export functions in general.
To export a motif in the JASPAR \verb+.pfm+ format, use
%the tabs in the output confuse doctest; don't test
\begin{verbatim}
>>> print m.format("pfm")
3 7 0 2 1
0 0 5 2 6
0 0 0 3 0
4 0 2 0 0
<BLANKLINE>
\end{verbatim}
To write the motif in a TRANSFAC-like matrix format, use
%cont-doctest
\begin{verbatim}
>>> print m.format("transfac")
P0 A C G T
01 3 0 0 4 W
02 7 0 0 0 A
03 0 5 0 2 C
04 2 2 3 0 V
05 1 6 0 0 C
XX
//
<BLANKLINE>
\end{verbatim}
To write out multiple motifs, you can use \verb+motifs.write+.
This function can be used regardless of whether the motifs originated from a TRANSFAC file. For example,
%cont-doctest
\begin{verbatim}
>>> two_motifs = [arnt, srf]
>>> print motifs.write(two_motifs, 'transfac')
P0 A C G T
01 4 16 0 0 C
02 19 0 1 0 A
03 0 20 0 0 C
04 0 0 20 0 G
05 0 0 0 20 T
06 0 0 20 0 G
XX
//
P0 A C G T
01 2 1 39 4 G
02 9 33 2 2 C
03 0 45 1 0 C
04 1 45 0 0 C
05 32 1 0 13 A
06 3 1 0 42 T
07 46 0 0 0 A
08 1 0 0 45 T
09 43 0 0 3 A
10 15 1 0 30 T
11 2 0 44 0 G
12 2 1 43 0 G
XX
//
<BLANKLINE>
\end{verbatim}
\subsection{Creating a sequence logo}
If we have internet access, we can create a \href{http://weblogo.berkeley.edu}{weblogo}:
\begin{verbatim}
>>> arnt.weblogo("Arnt.png")
\end{verbatim}
We should get our logo saved as a png in the specified file.
\section{Position-Weight Matrices}
The \verb+.counts+ attribute of a Motif object shows how often each nucleotide appeared at each position along the alignment. We can normalize this matrix by dividing by the number of instances in the alignment, resulting in the probability of each nucleotide at each position along the alignment. We refer to these probabilities as the position-weight matrix. However, beware that in the literature this term may also be used to refer to the position-specific scoring matrix, which we discuss below.
Usually, pseudocounts are added to each position before normalizing. This avoids overfitting of the position-weight matrix to the limited number of motif instances in the alignment, and can also prevent probabilities from becoming zero. To add a fixed pseudocount to all nucleotides at all positions, specify a number for the \verb+pseudocounts+ argument:
%cont-doctest
\begin{verbatim}
>>> pwm = m.counts.normalize(pseudocounts=0.5)
>>> print pwm
0 1 2 3 4
A: 0.39 0.83 0.06 0.28 0.17
C: 0.06 0.06 0.61 0.28 0.72
G: 0.06 0.06 0.06 0.39 0.06
T: 0.50 0.06 0.28 0.06 0.06
<BLANKLINE>
\end{verbatim}
Alternatively, \verb+pseudocounts+ can be a dictionary specifying the pseudocounts for each nucleotide. For example, as the GC content of the human genome is about 40\%, you may want to choose the pseudocounts accordingly:
%cont-doctest
\begin{verbatim}
>>> pwm = m.counts.normalize(pseudocounts={'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6})
>>> print pwm
0 1 2 3 4
A: 0.40 0.84 0.07 0.29 0.18
C: 0.04 0.04 0.60 0.27 0.71
G: 0.04 0.04 0.04 0.38 0.04
T: 0.51 0.07 0.29 0.07 0.07
<BLANKLINE>
\end{verbatim}
The position-weight matrix has its own methods to calculate the consensus, anticonsensus, and degenerate consensus sequences:
%cont-doctest
\begin{verbatim}
>>> pwm.consensus
Seq('TACGC', IUPACUnambiguousDNA())
>>> pwm.anticonsensus
Seq('GGGTG', IUPACUnambiguousDNA())
>>> pwm.degenerate_consensus
Seq('WACNC', IUPACAmbiguousDNA())
\end{verbatim}
Note that due to the pseudocounts, the degenerate consensus sequence calculated from the position-weight matrix is slightly different from the degenerate consensus sequence calculated from the instances in the motif:
%cont-doctest
\begin{verbatim}
>>> m.degenerate_consensus
Seq('WACVC', IUPACAmbiguousDNA())
\end{verbatim}
The reverse complement of the position-weight matrix can be calculated directly from the \verb+pwm+:
%cont-doctest
\begin{verbatim}
>>> rpwm = pwm.reverse_complement()
>>> print rpwm
0 1 2 3 4
A: 0.07 0.07 0.29 0.07 0.51
C: 0.04 0.38 0.04 0.04 0.04
G: 0.71 0.27 0.60 0.04 0.04
T: 0.18 0.29 0.07 0.84 0.40
<BLANKLINE>
\end{verbatim}
\section{Position-Specific Scoring Matrices}
Using the background distribution and PWM with pseudo-counts added,
it's easy to compute the log-odds ratios, telling us what are the log
odds of a particular symbol to be coming from a motif against the
background. We can use the \verb|.log_odds()| method on the position-weight
matrix:
%cont-doctest
\begin{verbatim}
>>> pssm = pwm.log_odds()
>>> print pssm
0 1 2 3 4
A: 0.68 1.76 -1.91 0.21 -0.49
C: -2.49 -2.49 1.26 0.09 1.51
G: -2.49 -2.49 -2.49 0.60 -2.49
T: 1.03 -1.91 0.21 -1.91 -1.91
<BLANKLINE>
\end{verbatim}
Here we can see positive values for symbols more frequent in the motif
than in the background and negative for symbols more frequent in the
background. $0.0$ means that it's equally likely to see a symbol in the
background and in the motif.
This assumes that A, C, G, and T are equally likely in the background. To
calculate the position-specific scoring matrix against a background with
unequal probabilities for A, C, G, T, use the \verb+background+ argument.
For example, against a background with a 40\% GC content, use
%cont-doctest
\begin{verbatim}
>>> background = {'A':0.3,'C':0.2,'G':0.2,'T':0.3}
>>> pssm = pwm.log_odds(background)
>>> print pssm
0 1 2 3 4
A: 0.42 1.49 -2.17 -0.05 -0.75
C: -2.17 -2.17 1.58 0.42 1.83
G: -2.17 -2.17 -2.17 0.92 -2.17
T: 0.77 -2.17 -0.05 -2.17 -2.17
<BLANKLINE>
\end{verbatim}
The maximum and minimum score obtainable from the PSSM are stored in the
\verb+.max+ and \verb+.min+ properties:
%cont-doctest
\begin{verbatim}
>>> print "%4.2f" % pssm.max
6.59
>>> print "%4.2f" % pssm.min
-10.85
\end{verbatim}
The mean and standard deviation of the PSSM scores with respect to a specific
background are calculated by the \verb+.mean+ and \verb+.std+ methods.
%cont-doctest
\begin{verbatim}
>>> mean = pssm.mean(background)
>>> std = pssm.std(background)
>>> print "mean = %0.2f, standard deviation = %0.2f" % (mean, std)
mean = 3.21, standard deviation = 2.59
\end{verbatim}
A uniform background is used if \verb+background+ is not specified.
The mean is particularly important, as its value is equal to the
Kullback-Leibler divergence or relative entropy, and is a measure for the
information content of the motif compared to the background. As in Biopython
the base-2 logarithm is used in the calculation of the log-odds scores, the
information content has units of bits.
The \verb+.reverse_complement+, \verb+.consensus+, \verb+.anticonsensus+, and
\verb+.degenerate_consensus+ methods can be applied directly to PSSM objects.
\section{Searching for instances}
\label{sec:search}
The most frequent use for a motif is to find its instances in some
sequence. For the sake of this section, we will use an artificial sequence like this:
%cont-doctest
\begin{verbatim}
>>> test_seq=Seq("TACACTGCATTACAACCCAAGCATTA",m.alphabet)
>>> len(test_seq)
26
\end{verbatim}
\subsection{Searching for exact matches}
The simplest way to find instances, is to look for exact matches of
the true instances of the motif:
%cont-doctest
\begin{verbatim}
>>> for pos,seq in m.instances.search(test_seq):
... print pos, seq
...
0 TACAC
10 TACAA
13 AACCC
\end{verbatim}
We can do the same with the reverse complement (to find instances on the complementary strand):
%cont-doctest
\begin{verbatim}
>>> for pos,seq in r.instances.search(test_seq):
... print pos, seq
...
6 GCATT
20 GCATT
\end{verbatim}
\subsection{Searching for matches using the PSSM score}
It's just as easy to look for positions, giving rise to high log-odds scores against our motif:
%cont-doctest
\begin{verbatim}
>>> for position, score in pssm.search(test_seq, threshold=3.0):
... print "Position %d: score = %5.3f" % (position, score)
...
Position 0: score = 5.622
Position -20: score = 4.601
Position 10: score = 3.037
Position 13: score = 5.738
Position -6: score = 4.601
\end{verbatim}
The negative positions refer to instances of the motif found on the
reverse strand of the test sequence, and follow the Python convention
on negative indices. Therefore, the instance of the motif at \verb|pos|
is located at \verb|test_seq[pos:pos+len(m)]| both for positive and for
negative values of \verb|pos|.
You may notice the threshold parameter, here set arbitrarily to
$3.0$. This is in $log_2$, so we are now looking only for words, which
are eight times more likely to occur under the motif model than in the
background. The default threshold is $0.0$, which selects everything
that looks more like the motif than the background.
You can also calculate the scores at all positions along the sequence:
%Don't use a doc test for this as the spacing can differ
\begin{verbatim}
>>> pssm.calculate(test_seq)
array([ 5.62230396, -5.6796999 , -3.43177247, 0.93827754,
-6.84962511, -2.04066086, -10.84962463, -3.65614533,
-0.03370807, -3.91102552, 3.03734159, -2.14918518,
-0.6016975 , 5.7381525 , -0.50977498, -3.56422281,
-8.73414803, -0.09919716, -0.6016975 , -2.39429784,
-10.84962463, -3.65614533], dtype=float32)
\end{verbatim}
In general, this is the fastest way to calculate PSSM scores.
The scores returned by \verb+pssm.calculate+ are for the forward strand
only. To obtain the scores on the reverse strand, you can take the reverse
complement of the PSSM:
\begin{verbatim}
>>> rpssm = pssm.reverse_complement()
>>> rpssm.calculate(test_seq)
array([ -9.43458748, -3.06172252, -7.18665981, -7.76216221,
-2.04066086, -4.26466274, 4.60124254, -4.2480607 ,
-8.73414803, -2.26503372, -6.49598789, -5.64668512,
-8.73414803, -10.84962463, -4.82356262, -4.82356262,
-5.64668512, -8.73414803, -4.15613794, -5.6796999 ,
4.60124254, -4.2480607 ], dtype=float32)
\end{verbatim}
\subsection{Selecting a score threshold}
If you want to use a less arbitrary way of selecting thresholds, you
can explore the distribution of PSSM scores. Since the space for a score
distribution grows exponentially with motif length, we are using an
approximation with a given precision to keep computation cost manageable:
%cont-doctest
\begin{verbatim}
>>> distribution = pssm.distribution(background=background, precision=10**4)
\end{verbatim}
The \verb+distribution+ object can be used to determine a number of different thresholds.
We can specify the requested false-positive rate (probability of ``finding'' a motif instance in background generated sequence):
%cont-doctest
\begin{verbatim}
>>> threshold = distribution.threshold_fpr(0.01)
>>> print "%5.3f" % threshold
4.009
\end{verbatim}
or the false-negative rate (probability of ``not finding'' an instance generated from the motif):
%cont-doctest
\begin{verbatim}
>>> threshold = distribution.threshold_fnr(0.1)
>>> print "%5.3f" % threshold
-0.510
\end{verbatim}
or a threshold (approximately) satisfying some relation between the false-positive rate and the false-negative rate ($\frac{\textrm{fnr}}{\textrm{fpr}}\simeq t$):
%cont-doctest
\begin{verbatim}
>>> threshold = distribution.threshold_balanced(1000)
>>> print "%5.3f" % threshold
6.241
\end{verbatim}
or a threshold satisfying (roughly) the equality between the
false-positive rate and the $-log$ of the information content (as used
in patser software by Hertz and Stormo):
%cont-doctest
\begin{verbatim}
>>> threshold = distribution.threshold_patser()
>>> print "%5.3f" % threshold
0.346
\end{verbatim}
For example, in case of our motif, you can get the threshold giving
you exactly the same results (for this sequence) as searching for
instances with balanced threshold with rate of $1000$.
%cont-doctest
\begin{verbatim}
>>> threshold = distribution.threshold_fpr(0.01)
>>> print "%5.3f" % threshold
4.009
>>> for position, score in pssm.search(test_seq,threshold=threshold):
... print "Position %d: score = %5.3f" % (position, score)
...
Position 0: score = 5.622
Position -20: score = 4.601
Position 13: score = 5.738
Position -6: score = 4.601
\end{verbatim}
\section{Each motif object has an associated Position-Specific Scoring Matrix}
To facilitate searching for potential TFBSs using PSSMs, both the position-weight matrix and the position-specific scoring matrix are associated with each motif. Using the Arnt motif as an example:
%TODO - Start a new doctest here?
%cont-doctest
\begin{verbatim}
>>> from Bio import motifs
>>> handle = open("Arnt.sites")
>>> motif = motifs.read(handle, 'sites')
>>> print motif.counts
0 1 2 3 4 5
A: 4.00 19.00 0.00 0.00 0.00 0.00
C: 16.00 0.00 20.00 0.00 0.00 0.00
G: 0.00 1.00 0.00 20.00 0.00 20.00
T: 0.00 0.00 0.00 0.00 20.00 0.00
<BLANKLINE>
>>> print motif.pwm
0 1 2 3 4 5
A: 0.20 0.95 0.00 0.00 0.00 0.00
C: 0.80 0.00 1.00 0.00 0.00 0.00
G: 0.00 0.05 0.00 1.00 0.00 1.00
T: 0.00 0.00 0.00 0.00 1.00 0.00
<BLANKLINE>
\end{verbatim}
%Can't use next bit in doctest, Windows Python 2.5 and 2.6 put -1.$ not -inf
\begin{verbatim}
>>> print motif.pssm
0 1 2 3 4 5
A: -0.32 1.93 -inf -inf -inf -inf
C: 1.68 -inf 2.00 -inf -inf -inf
G: -inf -2.32 -inf 2.00 -inf 2.00
T: -inf -inf -inf -inf 2.00 -inf
<BLANKLINE>
\end{verbatim}
The negative infinities appear here because the corresponding entry in the frequency matrix is 0, and we are using zero pseudocounts by default:
%cont-doctest
\begin{verbatim}
>>> for letter in "ACGT":
... print "%s: %4.2f" % (letter, motif.pseudocounts[letter])
...
A: 0.00
C: 0.00
G: 0.00
T: 0.00
\end{verbatim}
If you change the \verb+.pseudocounts+ attribute, the position-frequency matrix and the position-specific scoring matrix are recalculated automatically:
%cont-doctest
\begin{verbatim}
>>> motif.pseudocounts = 3.0
>>> for letter in "ACGT":
... print "%s: %4.2f" % (letter, motif.pseudocounts[letter])
...
A: 3.00
C: 3.00
G: 3.00
T: 3.00
\end{verbatim}
%Can't use this in doctest, Windows Python 2.5 and 2.6 give G/1 as 0.13 not 0.12
%TODO - Check why...
\begin{verbatim}
>>> print motif.pwm
0 1 2 3 4 5
A: 0.22 0.69 0.09 0.09 0.09 0.09
C: 0.59 0.09 0.72 0.09 0.09 0.09
G: 0.09 0.12 0.09 0.72 0.09 0.72
T: 0.09 0.09 0.09 0.09 0.72 0.09
<BLANKLINE>
\end{verbatim}
%cont-doctest
\begin{verbatim}
>>> print motif.pssm
0 1 2 3 4 5
A: -0.19 1.46 -1.42 -1.42 -1.42 -1.42
C: 1.25 -1.42 1.52 -1.42 -1.42 -1.42
G: -1.42 -1.00 -1.42 1.52 -1.42 1.52
T: -1.42 -1.42 -1.42 -1.42 1.52 -1.42
<BLANKLINE>
\end{verbatim}
You can also set the \verb+.pseudocounts+ to a dictionary over the four nucleotides if you want to use different pseudocounts for them. Setting \verb+motif.pseudocounts+ to \verb+None+ resets it to its default value of zero.
The position-specific scoring matrix depends on the background distribution, which is uniform by default:
%cont-doctest
\begin{verbatim}
>>> for letter in "ACGT":
... print "%s: %4.2f" % (letter, motif.background[letter])
...
A: 0.25
C: 0.25
G: 0.25
T: 0.25
\end{verbatim}
Again, if you modify the background distribution, the position-specific scoring matrix is recalculated:
%cont-doctest
\begin{verbatim}
>>> motif.background = {'A': 0.2, 'C': 0.3, 'G': 0.3, 'T': 0.2}
>>> print motif.pssm
0 1 2 3 4 5
A: 0.13 1.78 -1.09 -1.09 -1.09 -1.09
C: 0.98 -1.68 1.26 -1.68 -1.68 -1.68
G: -1.68 -1.26 -1.68 1.26 -1.68 1.26
T: -1.09 -1.09 -1.09 -1.09 1.85 -1.09
<BLANKLINE>
\end{verbatim}
Setting \verb+motif.background+ to \verb+None+ resets it to a uniform distribution:
%cont-doctest
\begin{verbatim}
>>> motif.background = None
>>> for letter in "ACGT":
... print "%s: %4.2f" % (letter, motif.background[letter])
...
A: 0.25
C: 0.25
G: 0.25
T: 0.25
\end{verbatim}
If you set \verb+motif.background+ equal to a single value, it will be interpreted as the GC content:
%cont-doctest
\begin{verbatim}
>>> motif.background = 0.8
>>> for letter in "ACGT":
... print "%s: %4.2f" % (letter, motif.background[letter])
...
A: 0.10
C: 0.40
G: 0.40
T: 0.10
\end{verbatim}
Note that you can now calculate the mean of the PSSM scores over the background against which it was computed:
%cont-doctest
\begin{verbatim}
>>> print "%f" % motif.pssm.mean(motif.background)
4.703928
\end{verbatim}
as well as its standard deviation:
%cont-doctest
\begin{verbatim}
>>> print "%f" % motif.pssm.std(motif.background)
3.290900
\end{verbatim}
and its distribution:
%cont-doctest
\begin{verbatim}
>>> distribution = motif.pssm.distribution(background=motif.background)
>>> threshold = distribution.threshold_fpr(0.01)
>>> print "%f" % threshold
3.854375
\end{verbatim}
Note that the position-weight matrix and the position-specific scoring matrix are recalculated each time you call \verb+motif.pwm+ or \verb+motif.pssm+, respectively. If speed is an issue and you want to use the PWM or PSSM repeatedly, you can save them as a variable, as in
\begin{verbatim}
>>> pssm = motif.pssm
\end{verbatim}
\section{Comparing motifs}
\label{sec:comp}
Once we have more than one motif, we might want to compare them.
Before we start comparing motifs, I should point out that motif
boundaries are usually quite arbitrary. This means we often need
to compare motifs of different lengths, so comparison needs to involve
some kind of alignment. This means we have to take into account two things:
\begin{itemize}
\item alignment of motifs
\item some function to compare aligned motifs
\end{itemize}
To align the motifs, we use ungapped alignment of PSSMs and substitute zeros
for any missing columns at the beginning and end of the matrices. This means
that effectively we are using the background distribution for columns missing
from the PSSM.
The distance function then returns the minimal distance between motifs, as
well as the corresponding offset in their alignment.
To give an exmaple, let us first load another motif,
which is similar to our test motif \verb|m|:
%TODO - Start a new doctest here?
%cont-doctest
\begin{verbatim}
>>> m_reb1 = motifs.read(open("REB1.pfm"), "pfm")
>>> m_reb1.consensus
Seq('GTTACCCGG', IUPACUnambiguousDNA())
>>> print m_reb1.counts
0 1 2 3 4 5 6 7 8
A: 30.00 0.00 0.00 100.00 0.00 0.00 0.00 0.00 15.00
C: 10.00 0.00 0.00 0.00 100.00 100.00 100.00 0.00 15.00
G: 50.00 0.00 0.00 0.00 0.00 0.00 0.00 60.00 55.00
T: 10.00 100.00 100.00 0.00 0.00 0.00 0.00 40.00 15.00
<BLANKLINE>
\end{verbatim}
To make the motifs comparable, we choose the same values for the pseudocounts and the background distribution as our motif \verb|m|:
%cont-doctest
\begin{verbatim}
>>> m_reb1.pseudocounts = {'A':0.6, 'C': 0.4, 'G': 0.4, 'T': 0.6}
>>> m_reb1.background = {'A':0.3,'C':0.2,'G':0.2,'T':0.3}
>>> pssm_reb1 = m_reb1.pssm
>>> print pssm_reb1
0 1 2 3 4 5 6 7 8
A: 0.00 -5.67 -5.67 1.72 -5.67 -5.67 -5.67 -5.67 -0.97
C: -0.97 -5.67 -5.67 -5.67 2.30 2.30 2.30 -5.67 -0.41
G: 1.30 -5.67 -5.67 -5.67 -5.67 -5.67 -5.67 1.57 1.44
T: -1.53 1.72 1.72 -5.67 -5.67 -5.67 -5.67 0.41 -0.97
<BLANKLINE>
\end{verbatim}
We'll compare these motifs using the Pearson correlation.
Since we want it to resemble a distance measure, we actually take
$1-r$, where $r$ is the Pearson correlation coefficient (PCC):
%cont-doctest
\begin{verbatim}
>>> distance, offset = pssm.dist_pearson(pssm_reb1)
>>> print "distance = %5.3g" % distance
distance = 0.239
>>> print offset
-2
\end{verbatim}
This means that the best PCC between motif \verb|m| and \verb|m_reb1| is obtained with the following alignment:
\begin{verbatim}
m: bbTACGCbb
m_reb1: GTTACCCGG
\end{verbatim}
where \verb|b| stands for background distribution. The PCC itself is
roughly $1-0.239=0.761$.
\section{\emph{De novo} motif finding}
\label{sec:find}
Currently, Biopython has only limited support for \emph{de novo} motif
finding. Namely, we support running and parsing of AlignAce and
MEME. Since the number of motif finding tools is growing rapidly,
contributions of new parsers are welcome.
\subsection{MEME}
\label{sec:meme}
Let's assume, you have run MEME on sequences of your choice with your
favorite parameters and saved the output in the file
\verb|meme.out|. You can retrieve the motifs reported by MEME by
running the following piece of code:
%doctest ../Tests/Motif
\begin{verbatim}
>>> from Bio import motifs
>>> motifsM = motifs.parse(open("meme.out"), "meme")
\end{verbatim}
\begin{verbatim}
>>> motifsM
[<Bio.motifs.meme.Motif object at 0xc356b0>]
\end{verbatim}
Besides the most wanted list of motifs, the result object contains more useful information, accessible through properties with self-explanatory names:
\begin{itemize}
\item \verb|.alphabet|
\item \verb|.datafile|
\item \verb|.sequence_names|
\item \verb|.version|
\item \verb|.command|
\end{itemize}
The motifs returned by the MEME Parser can be treated exactly like regular
Motif objects (with instances), they also provide some extra
functionality, by adding additional information about the instances.
%cont-doctest
\begin{verbatim}
>>> motifsM[0].consensus
Seq('CTCAATCGTA', IUPACUnambiguousDNA())
>>> motifsM[0].instances[0].sequence_name
'SEQ10;'
>>> motifsM[0].instances[0].start
3
>>> motifsM[0].instances[0].strand
'+'
\end{verbatim}
\begin{verbatim}
>>> motifsM[0].instances[0].pvalue
8.71e-07
\end{verbatim}
\subsection{AlignAce}
\label{sec:alignace}
We can do very similar things with the AlignACE program. Assume, you have
your output in the file \verb|alignace.out|. You can parse your output
with the following code:
%cont-doctest
\begin{verbatim}
>>> from Bio import motifs
>>> motifsA = motifs.parse(open("alignace.out"),"alignace")
\end{verbatim}
Again, your motifs behave as they should:
%cont-doctest
\begin{verbatim}
>>> motifsA[0].consensus
Seq('TCTACGATTGAG', IUPACUnambiguousDNA())
\end{verbatim}
In fact you can even see, that AlignAce found a very similar motif as
MEME. It is just a longer version of a reverse complement of the MEME
motif:
%cont-doctest
\begin{verbatim}
>>> motifsM[0].reverse_complement().consensus
Seq('TACGATTGAG', IUPACUnambiguousDNA())
\end{verbatim}
If you have AlignAce installed on the same machine, you can also run
it directly from Biopython. A short example of how this can be done is
shown below (other parameters can be specified as keyword parameters):
\begin{verbatim}
>>> command="/opt/bin/AlignACE"
>>> input_file="test.fa"
>>> from Bio.motifs.applications import AlignAceCommandline
>>> cmd = AlignAceCommandline(cmd=command,input=input_file,gcback=0.6,numcols=10)
>>> stdout,stderr= cmd()
\end{verbatim}
Since AlignAce prints all of its output to standard output, you can get
to your motifs by parsing the first part of the result:
\begin{verbatim}
>>> motifs = motifs.parse(stdout,"alignace")
\end{verbatim}
\section{Useful links }
\label{sec:links}
\begin{itemize}
\item \href{http://en.wikipedia.org/wiki/Sequence_motif}{Sequence motif} in wikipedia
\item \href{http://en.wikipedia.org/wiki/Position_weight_matrix}{PWM} in wikipedia
\item \href{http://en.wikipedia.org/wiki/Consensus_sequence}{Consensus sequence} in wikipedia
\item \href{http://bio.cs.washington.edu/assessment/}{Comparison of different motif finding programs}
\end{itemize}
\section{Obsolete Bio.Motif module}
The rest of this chapter above describes the \verb|Bio.motifs| package included
in Biopython 1.61 onwards, which is replacing the older \verb|Bio.Motif| package
introduced with Biopython 1.50, which was in turn based on two older former
Biopython modules, \verb|Bio.AlignAce| and \verb|Bio.MEME|.
To allow for a smooth transition, the older \verb|Bio.Motif| package will be
maintained in parallel with its replacement \verb|Bio.motifs| at least two more
releases, and at least one year.
\subsection{Motif objects}
%TODO - turn these into doctests...
Since we are interested in motif analysis, we need to take a look at
\verb|Motif| objects in the first place. For that we need to import
the Motif library:
%doctest
\begin{verbatim}
>>> from Bio import Motif
\end{verbatim}
and we can start creating our first motif objects. Let's create a DNA motif:
%cont-doctest
\begin{verbatim}
>>> from Bio.Alphabet import IUPAC
>>> m = Motif.Motif(alphabet=IUPAC.unambiguous_dna)
\end{verbatim}
This is for now just an empty container, so let's add some sequences to our newly created motif:
%cont-doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> m.add_instance(Seq("TATAA",m.alphabet))
>>> m.add_instance(Seq("TATTA",m.alphabet))
>>> m.add_instance(Seq("TATAA",m.alphabet))
>>> m.add_instance(Seq("TATAA",m.alphabet))
\end{verbatim}
Now we have a full \verb|Motif| instance, so we can try to get some
basic information about it. Let's start with length and consensus
sequence:
%cont-doctest
\begin{verbatim}
>>> len(m)
5
>>> m.consensus()
Seq('TATAA', IUPACUnambiguousDNA())
\end{verbatim}
In case of DNA motifs, we can also get a reverse complement of a motif:
%>>> m.reverse_complement()
%<Bio.Motif.Motif.Motif object at 0xb39890>
%cont-doctest
\begin{verbatim}
>>> m.reverse_complement().consensus()
Seq('TTATA', IUPACUnambiguousDNA())
>>> for i in m.reverse_complement().instances:
... print i
TTATA
TAATA
TTATA
TTATA
\end{verbatim}
We can also calculate the information content of a motif with a simple call:
%cont-doctest
\begin{verbatim}
>>> print "%0.2f" % m.ic()
5.27
\end{verbatim}
This gives us a number of bits of information provided by the motif,
which tells us how much differs from background.
The most common representation of a motif is a PWM (Position Weight
Matrix). It summarizes the probabilities of finding any symbol (in
this case nucleotide) in any position of a motif. It can be computed by calling the \verb|.pwm()| method:
\begin{verbatim}
>>> m.pwm()
[{'A': 0.05, 'C': 0.05, 'T': 0.85, 'G': 0.05},
{'A': 0.85, 'C': 0.05, 'T': 0.05, 'G': 0.05},
{'A': 0.05, 'C': 0.05, 'T': 0.85, 'G': 0.05},
{'A': 0.65, 'C': 0.05, 'T': 0.25, 'G': 0.05},
{'A': 0.85, 'C': 0.05, 'T': 0.05, 'G': 0.05}]
\end{verbatim}
The probabilities in the motif's PWM are based on the counts in the
instances, but we can see, that even though there were no Gs and no Cs
in the instances, we still have non-zero probabilities assigned to
them. These come from pseudo-counts which are, roughly speaking, a
commonly used way to acknowledge the incompleteness of our knowledge
and avoid technical problems with calculating logarithms of $0$.
We can control the way that pseudo-counts are added with two
properties of Motif objects \verb|.background| is the probability
distribution over all symbols in the alphabet that we assume represents background, non-motif sequences (usually based on the GC content of the respective
genome). It is by default set to a uniform distribution upon creation of a motif:
\begin{verbatim}
>>> m.background
{'A': 0.25, 'C': 0.25, 'T': 0.25, 'G': 0.25}
\end{verbatim}
The other parameter is \verb|.beta|, which states the amount of
pseudo-counts we should add to the PWM. By default it is set to $1.0$,
%cont-doctest
\begin{verbatim}
>>> m.beta
1.0
\end{verbatim}
so that the total input of pseudo-counts is equal to that of one instance.
Using the background distribution and pwm with pseudo-counts added,
it's easy to compute the log-odds ratios, telling us what are the log
odds of a particular symbol to be coming from a motif against the
background. We can use the \verb|.log_odds()| method:
\begin{verbatim}
>>> m.log_odds()
[{'A': -2.3219280948873622,
'C': -2.3219280948873622,
'T': 1.7655347463629771,
'G': -2.3219280948873622},
{'A': 1.7655347463629771,
'C': -2.3219280948873622,
'T': -2.3219280948873622,
'G': -2.3219280948873622},
{'A': -2.3219280948873622,
'C': -2.3219280948873622,
'T': 1.7655347463629771,
'G': -2.3219280948873622},
{'A': 1.3785116232537298,
'C': -2.3219280948873622,
'T': 0.0,
'G': -2.3219280948873622},
{'A': 1.7655347463629771,
'C': -2.3219280948873622,
'T': -2.3219280948873622,
'G': -2.3219280948873622}
]
\end{verbatim}
Here we can see positive values for symbols more frequent in the motif
than in the background and negative for symbols more frequent in the
background. $0.0$ means that it's equally likely to see a symbol in
background and in the motif (e.g. `T' in the second-last position).
\subsubsection{Reading and writing}
Creating motifs from instances by hand is a bit boring, so it's
useful to have some I/O functions for reading and writing
motifs. There are no really well established standards for storing
motifs, but there's a couple of formats which are more used than
others. The most important distinction is whether the motif
representation is based on instances or on some version of PWM matrix.
On of the most popular motif databases \href{http://jaspar.genereg.net}{JASPAR}
stores motifs in both formats, so
let's look at how we can import JASPAR motifs from instances:
%doctest ../Tests/Motif
\begin{verbatim}
>>> from Bio import Motif
>>> arnt = Motif.read(open("Arnt.sites"),"jaspar-sites")
\end{verbatim}
and from a count matrix:
%cont-doctest
\begin{verbatim}
>>> srf = Motif.read(open("SRF.pfm"),"jaspar-pfm")
\end{verbatim}
The \verb|arnt| and \verb|srf| motifs can both do the same things for
us, but they use different internal representations of the motif. We
can tell that by inspecting the \verb|has_counts| and
\verb|has_instances| properties:
%cont-doctest
\begin{verbatim}
>>> arnt.has_instances
True
>>> srf.has_instances
False
>>> srf.has_counts
True
\end{verbatim}
%TODO - sort order and formatting for doctest?
\begin{verbatim}
>>> srf.counts
{'A': [2, 9, 0, 1, 32, 3, 46, 1, 43, 15, 2, 2],
'C': [1, 33, 45, 45, 1, 1, 0, 0, 0, 1, 0, 1],
'G': [39, 2, 1, 0, 0, 0, 0, 0, 0, 0, 44, 43],
'T': [4, 2, 0, 0, 13, 42, 0, 45, 3, 30, 0, 0]}
\end{verbatim}
There are conversion functions, which can help us convert between
different representations:
\begin{verbatim}
>>> arnt.make_counts_from_instances()
{'A': [8, 38, 0, 0, 0, 0],
'C': [32, 0, 40, 0, 0, 0],
'G': [0, 2, 0, 40, 0, 40],
'T': [0, 0, 0, 0, 40, 0]}
>>> srf.make_instances_from_counts()
[Seq('GGGAAAAAAAGG', IUPACUnambiguousDNA()),
Seq('GGCCAAATAAGG', IUPACUnambiguousDNA()),
Seq('GACCAAATAAGG', IUPACUnambiguousDNA()),
....
\end{verbatim}
The important thing to remember here is that the method
\verb|make_instances_from_counts()| creates fake instances, because
usually there are very many possible sets of instances which give rise
to the same pwm, and if we have only the count matrix, we cannot
reconstruct the original one. This does not make any difference if we
are using the PWM as the representation of the motif, but one should
be careful with exporting instances from count-based motifs.
Speaking of exporting, let's look at export functions. We can export to fasta:
\begin{verbatim}
>>> print m.format("fasta")
>instance0
TATAA
>instance1
TATTA
>instance2
TATAA
>instance3
TATAA
\end{verbatim}
or to TRANSFAC-like matrix format (used by some motif processing software)
\begin{verbatim}
>>> print m.format("transfac")
XX
TY Motif
ID
BF undef
P0 G A T C
01 0 0 4 0
02 0 4 0 0
03 0 0 4 0
04 0 3 1 0
05 0 4 0 0
XX
\end{verbatim}
Finally, if we have internet access, we can create a \href{http://weblogo.berkeley.edu}{weblogo}:
\begin{verbatim}
>>> arnt.weblogo("Arnt.png")
\end{verbatim}
We should get our logo saved as a png in the specified file.
\subsection{Searching for instances}
The most frequent use for a motif is to find its instances in some
sequence. For the sake of this section, we will use an artificial sequence like this:
\begin{verbatim}
test_seq=Seq("TATGATGTAGTATAATATAATTATAA",m.alphabet)
\end{verbatim}
The simplest way to find instances, is to look for exact matches of
the true instances of the motif:
\begin{verbatim}
>>> for pos,seq in m.search_instances(test_seq):
... print pos,seq.tostring()
...
10 TATAA
15 TATAA
21 TATAA
\end{verbatim}
We can do the same with the reverse complement (to find instances on the complementary strand):
\begin{verbatim}
>>> for pos,seq in m.reverse_complement().search_instances(test_seq):
... print pos,seq.tostring()
...
12 TAATA
20 TTATA
\end{verbatim}
It's just as easy to look for positions, giving rise to high log-odds scores against our motif:
\begin{verbatim}
>>> for pos,score in m.search_pwm(test_seq,threshold=5.0):
... print pos,score
...
10 8.44065060871
-12 7.06213898545
15 8.44065060871
-20 8.44065060871
21 8.44065060871
\end{verbatim}
You may notice the threshold parameter, here set arbitrarily to
$5.0$. This is in $log_2$, so we are now looking only for words, which
are 32 times more likely to occur under the motif model than in the
background. The default threshold is $0.0$, which selects everything
that looks more like the motif than the background.
If you want to use a less arbitrary way of selecting thresholds, you
can explore the \verb|Motif.score_distribution| class implementing an
distribution of scores for a given motif. Since the space for a score
distribution grows exponentially with motif length, we are using an
approximation with a given precision to keep computation cost manageable:
\begin{verbatim}
>>> sd = Motif.score_distribution(m,precision=10**4)
\end{verbatim}
The sd object can be used to determine a number of different thresholds.
We can specify the requested false-positive rate (probability of ``finding'' a motif instance in background generated sequence):
\begin{verbatim}
>>> sd.threshold_fpr(0.01)
4.3535838726139886
\end{verbatim}
or the false-negative rate (probability of ``not finding'' an instance generated from the motif):
\begin{verbatim}
>>> sd.threshold_fnr(0.1)
0.26651713652234044
\end{verbatim}
or a threshold (approximately) satisfying some relation between fpr
and fnr $\frac{fnr}{fpr}\simeq t$:
\begin{verbatim}
>>> sd.threshold_balanced(1000)
8.4406506087056368
\end{verbatim}
or a threshold satisfying (roughly) the equality between the
false-positive rate and the $-log$ of the information content (as used
in patser software by Hertz and Stormo).
For example, in case of our motif, you can get the threshold giving
you exactly the same results (for this sequence) as searching for
instances with balanced threshold with rate of $1000$.
\begin{verbatim}
>>> for pos,score in m.search_pwm(test_seq,threshold=sd.threshold_balanced(1000)):
... print pos,score
...
10 8.44065060871
15 8.44065060871
-20 8.44065060871
21 8.44065060871
\end{verbatim}
\subsection{Comparing motifs}
Once we have more than one motif, we might want to compare them. For
that, we have currently three different methods of \verb|Bio.Motif|
objects.
Before we start comparing motifs, I should point out that motif
boundaries are usually quite arbitrary. This means, that we often need
to compare motifs of different lengths, so comparison needs to involve
some kind of alignment. This means, that we have to take into account two things:
\begin{itemize}
\item alignment of motifs
\item some function to compare aligned motifs
\end{itemize}
In \verb|Bio.Motif| we have 3 different functions for motif
comparison, which are based on the same idea behind motif alignment,
but use different functions to compare aligned motifs. Briefly
speaking, we are using ungapped alignment of PWMs and substitute the
missing columns at the beginning and end of the matrices with
background distribution. All three comparison functions are written in
such a way, that they can be interpreted as distance measures, however
only one (\verb|dist_dpq|) satisfies the triangle inequality. All of
them return the minimal distance and the corresponding offset between
motifs.
To show how these functions work, let us first load another motif,
which is similar to our test motif \verb|m|:
\begin{verbatim}
>>> ubx=Motif.read(open("Ubx.pfm"),"jaspar-pfm")
<Bio.Motif.Motif.Motif object at 0xc29b90>
>>> ubx.consensus()
Seq('TAAT', IUPACUnambiguousDNA())
\end{verbatim}
The first function we'll use to compare these motifs is based on
Pearson correlation. Since we want it to resemble a distance
measure, we actually take $1-r$, where $r$ is the Pearson correlation
coefficient (PCC):
\begin{verbatim}
>>> m.dist_pearson(ubx)
(0.41740393308237722, 2)
\end{verbatim}
This means, that the best PCC between motif \verb|m| and \verb|Ubx| is obtained with the following alignment:
\begin{verbatim}
bbTAAT
TATAAb
\end{verbatim}
where \verb|b| stands for background distribution. The PCC itself is
roughly $1-0.42=0.58$. If we try the reverse complement of the Ubx motif:
\begin{verbatim}
>>> m.dist_pearson(ubx.reverse_complement())
(0.25784180151584823, 1)
\end{verbatim}
We can see that the PCC is better (almost $0.75$), and the alignment is also different:
\begin{verbatim}
bATTA
TATAA
\end{verbatim}
There are two other functions: \verb|dist_dpq|, which is a true metric (satisfying traingle inequality) based on the Kullback-Leibler divergence
\begin{verbatim}
>>> m.dist_dpq(ubx.reverse_complement())
(0.49292358382899853, 1)
\end{verbatim}
and the \verb|dist_product| method, which is based on the product of
probabilities which can be interpreted as the probability of
independently generating the same instance by both motifs.
\begin{verbatim}
>>> m.dist_product(ubx.reverse_complement())
(0.16224587301064275, 1)
\end{verbatim}
\subsection{\emph{De novo} motif finding}
Currently, Biopython has only limited support for \emph{de novo} motif
finding. Namely, we support running and parsing of AlignAce and
MEME. Since the number of motif finding tools is growing rapidly,
contributions of new parsers are welcome.
\subsubsection{MEME}
Let's assume, you have run MEME on sequences of your choice with your
favorite parameters and saved the output in the file
\verb|meme.out|. You can retrieve the motifs reported by MEME by
running the following piece of code:
\begin{verbatim}
>>> motifsM = list(Motif.parse(open("meme.out"),"MEME"))
>>> motifsM
[<Bio.Motif.MEMEMotif.MEMEMotif object at 0xc356b0>]
\end{verbatim}
Besides the most wanted list of motifs, the result object contains more useful information, accessible through properties with self-explanatory names:
\begin{itemize}
\item \verb|.alphabet|
\item \verb|.datafile|
\item \verb|.sequence_names|
\item \verb|.version|
\item \verb|.command|
\end{itemize}
The motifs returned by MEMEParser can be treated exactly like regular
Motif objects (with instances), they also provide some extra
functionality, by adding additional information about the instances.
\begin{verbatim}
>>> motifsM[0].consensus()
Seq('CTCAATCGTA', IUPACUnambiguousDNA())
>>> motifsM[0].instances[0].pvalue
8.71e-07
>>> motifsM[0].instances[0].sequence_name
'SEQ10;'
>>> motifsM[0].instances[0].start
3
>>> motifsM[0].instances[0].strand
'+'
\end{verbatim}
\subsubsection{AlignAce}
We can do very similar things with AlignACE program. Assume, you have
your output in the file \verb|alignace.out|. You can parse your output
with the following code:
\begin{verbatim}
>>> motifsA=list(Motif.parse(open("alignace.out"),"AlignAce"))
\end{verbatim}
Again, your motifs behave as they should:
\begin{verbatim}
>>> motifsA[0].consensus()
Seq('TCTACGATTGAG', IUPACUnambiguousDNA())
\end{verbatim}
In fact you can even see, that AlignAce found a very similar motif as
MEME, it is just a longer version of a reverse complement of MEME
motif:
\begin{verbatim}
>>> motifsM[0].reverse_complement().consensus()
Seq('TACGATTGAG', IUPACUnambiguousDNA())
\end{verbatim}
If you have AlignAce installed on the same machine, you can also run
it directly from Biopython. Short example of how this can be done is
shown below (other parameters can be specified as keyword parameters):
\begin{verbatim}
>>> command="/opt/bin/AlignACE"
>>> input_file="test.fa"
>>> from Bio.Motif.Applications import AlignAceCommandline
>>> cmd = AlignAceCommandline(cmd=command,input=input_file,gcback=0.6,numcols=10)
>>> stdout,stderr= cmd()
\end{verbatim}
Since AlignAce prints all its output to standard output, you can get
to your motifs by parsing the first part of the result:
\begin{verbatim}
motifs=list(Motif.parse(stdout,"AlignAce"))
\end{verbatim}
\chapter{Cluster analysis}
Cluster analysis is the grouping of items into clusters based on the similarity of the items to each other. In bioinformatics, clustering is widely used in gene expression data analysis to find groups of genes with similar gene expression profiles. This may identify functionally related genes, as well as suggest the function of presently unknown genes.
The Biopython module \verb|Bio.Cluster| provides commonly used clustering algorithms and was designed with the application to gene expression data in mind. However, this module can also be used for cluster analysis of other types of data. \verb|Bio.Cluster| and the underlying C Clustering Library is described by De Hoon \textit{et al.} \cite{dehoon2004}.
The following four clustering approaches are implemented in \verb|Bio.Cluster|:
\begin{itemize}
\item
Hierarchical clustering (pairwise centroid-, single-, complete-, and average-linkage);
\item
$k$-means, $k$-medians, and $k$-medoids clustering;
\item
Self-Organizing Maps;
\item
Principal Component Analysis.
\end{itemize}
\subsection*{Data representation}
The data to be clustered are represented by a $n \times m$ Numerical Python array \verb|data|. Within the context of gene expression data clustering, typically the rows correspond to different genes whereas the columns correspond to different experimental conditions. The clustering algorithms in \verb|Bio.Cluster| can be applied both to rows (genes) and to columns (experiments).
\subsection*{Missing values}
Often in microarray experiments, some of the data values are missing, which is indicated by an additional $n \times m$ Numerical Python integer array \verb|mask|. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing and is ignored in the analysis.
\subsection*{Random number generator}
The $k$-means/medians/medoids clustering algorithms and Self-Organizing Maps (SOMs) include the use of a random number generator. The uniform random number generator in \verb|Bio.Cluster| is based on the algorithm by L'Ecuyer \cite{lecuyer1988}, while random numbers following the binomial distribution are generated using the BTPE algorithm by Kachitvichyanukul and Schmeiser \cite{kachitvichyanukul1988}. The random number generator is initialized automatically during its first call. As this random number generator uses a combination of two multiplicative linear congruential generators, two (integer) seeds are needed for initialization, for which we use the system-supplied random number generator \verb|rand| (in the C standard library). We initialize this generator by calling \verb|srand| with the epoch time in seconds, and use the first two random numbers generated by \verb|rand| as seeds for the uniform random number generator in \verb|Bio.Cluster|.
\section{Distance functions}
\label{sec:distancefunctions}
In order to cluster items into groups based on their similarity, we should first define what exactly we mean by \emph{similar}. \verb|Bio.Cluster| provides eight distance functions, indicated by a single character, to measure similarity, or conversely, distance:
\begin{itemize}
\item \verb|'e'|:
Euclidean distance;
\item \verb|'b'|:
City-block distance.
\item \verb|'c'|:
Pearson correlation coefficient;
\item \verb|'a'|:
Absolute value of the Pearson correlation coefficient;
\item \verb|'u'|:
Uncentered Pearson correlation (equivalent to the cosine of the angle between two data vectors);
\item \verb|'x'|:
Absolute uncentered Pearson correlation;
\item \verb|'s'|:
Spearman's rank correlation;
\item \verb|'k'|:
Kendall's $\tau$.
\end{itemize}
The first two are true distance functions that satisfy the triangle inequality:
$$d\left(\underline{u},\underline{v}\right) \leq d\left(\underline{u},\underline{w}\right) + d\left(\underline{w},\underline{v}\right) \textrm{ for all } \underline{u}, \underline{v}, \underline{w},$$
and are therefore refered to as \emph{metrics}. In everyday language, this means that the shortest distance between two points is a straight line.
The remaining six distance measures are related to the correlation coefficient, where the distance $d$ is defined in terms of the correlation $r$ by $d=1-r$. Note that these distance functions are \emph{semi-metrics} that do not satisfy the triangle inequality. For example, for
$$\underline{u}=\left(1,0,-1\right);$$
$$\underline{v}=\left(1,1,0\right);$$
$$\underline{w}=\left(0,1,1\right);$$
we find a Pearson distance
$d\left(\underline{u},\underline{w}\right) = 1.8660$, while
$d\left(\underline{u},\underline{v}\right)+d\left(\underline{v},\underline{w}\right) = 1.6340$.
\subsection*{Euclidean distance}
In \verb|Bio.Cluster|, we define the Euclidean distance as
$$d = {1 \over n} \sum_{i=1}^{n} \left(x_i-y_i\right)^{2}.$$
Only those terms are included in the summation for which both
$x_i$ and $y_i$ are present, and the denominator $n$ is chosen accordingly.
As the expression data $x_i$ and $y_i$ are subtracted directly from each other, we should make sure that the expression data are properly normalized when using the Euclidean distance.
\subsection*{City-block distance}
The city-block distance, alternatively known as the Manhattan distance, is related to the Euclidean distance. Whereas the Euclidean distance corresponds to the length of the shortest path between two points, the city-block distance is the sum of distances along each dimension. As gene expression data tend to have missing values, in \verb|Bio.Cluster| we define the city-block distance as the sum of distances divided by the number of dimensions:
$$d = {1 \over n} \sum_{i=1}^n \left|x_i-y_i\right|.$$
This is equal to the distance you would have to walk between two points in a city, where you have to walk along city blocks. As for the Euclidean distance,
the expression data are subtracted directly from each other, and we should therefore make sure that they are properly normalized.
\subsection*{The Pearson correlation coefficient}
The Pearson correlation coefficient is defined as
$$r = \frac{1}{n} \sum_{i=1}^n \left( \frac{x_i -\bar{x}}{\sigma_x} \right) \left(\frac{y_i -\bar{y}}{\sigma_y} \right),$$
in which
$\bar{x}, \bar{y}$
are the sample mean of $x$ and $y$ respectively, and
$\sigma_x, \sigma_y$
are the sample standard deviation of $x$ and $y$.
The Pearson correlation coefficient is a measure for how well a straight line can be fitted to a scatterplot of $x$ and $y$.
If all the points in the scatterplot lie on a straight line, the Pearson correlation coefficient is either +1 or -1, depending on whether the slope of line is positive or negative. If the Pearson correlation coefficient is equal to zero, there is no correlation between $x$ and $y$.
The \emph{Pearson distance} is then defined as
$$d_{\textrm{P}} \equiv 1 - r.$$
As the Pearson correlation coefficient lies between -1 and 1, the Pearson distance lies between 0 and 2.
\subsection*{Absolute Pearson correlation}
By taking the absolute value of the Pearson correlation, we find a number between 0 and 1. If the absolute value is 1, all the points in the scatter plot lie on a straight line with either a positive or a negative slope. If the absolute value is equal to zero, there is no correlation between $x$ and $y$.
The corresponding distance is defined as
$$d_{\textrm A} \equiv 1 - \left|r\right|,$$
where $r$ is the Pearson correlation coefficient. As the absolute value of the Pearson correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.
In the context of gene expression experiments, the absolute correlation is equal to 1 if the gene expression profiles of two genes are either exactly the same or exactly opposite. The absolute correlation coefficient should therefore be used with care.
\subsection*{Uncentered correlation (cosine of the angle)}
In some cases, it may be preferable to use the \emph{uncentered correlation} instead of the regular Pearson correlation coefficient. The uncentered correlation is defined as
$$r_{\textrm U} = \frac{1}{n} \sum_{i=1}^{n} \left(\frac{x_i}{\sigma_x^{(0)}} \right) \left(\frac{y_i}{\sigma_y^{(0)}} \right),$$
where
\begin{eqnarray}
\sigma_x^{(0)} & = & \sqrt{{\frac{1}{n}} \sum_{i=1}^{n}x_i^2}; \nonumber \\
\sigma_y^{(0)} & = & \sqrt{{\frac{1}{n}} \sum_{i=1}^{n}y_i^2}. \nonumber
\end{eqnarray}
This is the same expression as for the regular Pearson correlation coefficient, except that the sample means
$\bar{x}, \bar{y}$
are set equal to zero. The uncentered correlation may be appropriate if there is a zero reference state. For instance, in the case of gene expression data given in terms of log-ratios, a log-ratio equal to zero corresponds to the green and red signal being equal, which means that the experimental manipulation did not affect the gene expression.
The distance corresponding to the uncentered correlation coefficient is defined as
$$d_{\mbox{U}} \equiv 1 - r_{\mbox{U}},$$
where
$r_{\mbox{U}}$
is the uncentered correlation.
As the uncentered correlation coefficient lies between -1 and 1, the corresponding distance lies between 0 and 2.
The uncentered correlation is equal to the cosine of the angle of the two data vectors in $n$-dimensional space, and is often referred to as such.
\subsection*{Absolute uncentered correlation}
As for the regular Pearson correlation, we can define a distance measure using the absolute value of the uncentered correlation:
$$d_{\mbox{AU}} \equiv 1 - \left|r_{\mbox{U}}\right|,$$
where
$r_{\mbox{U}}$
is the uncentered correlation coefficient. As the absolute value of the uncentered correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.
Geometrically, the absolute value of the uncentered correlation is equal to the cosine between the supporting lines of the two data vectors (i.e., the angle without taking the direction of the vectors into consideration).
\subsection*{Spearman rank correlation}
The Spearman rank correlation is an example of a non-parametric similarity measure, and tends to be more robust against outliers than the Pearson correlation.
To calculate the Spearman rank correlation, we replace each data value by their rank if we would order the data in each vector by their value. We then calculate the Pearson correlation between the two rank vectors instead of the data vectors.
As in the case of the Pearson correlation, we can define a distance measure corresponding to the Spearman rank correlation as
$$d_{\mbox{S}} \equiv 1 - r_{\mbox{S}},$$
where
$r_{\mbox{S}}$
is the Spearman rank correlation.
\subsection*{Kendall's $\tau$}
Kendall's $\tau$
is another example of a non-parametric similarity measure. It is similar to the Spearman rank correlation, but instead of the ranks themselves only the relative ranks are used to calculate $\tau$ (see Snedecor \& Cochran \cite{snedecor1989}).
We can define a distance measure corresponding to Kendall's $\tau$
as $$d_{\mbox{K}} \equiv 1 - \tau.$$
As Kendall's $\tau$ is always between -1 and 1, the corresponding distance will be between 0 and 2.
\subsection*{Weighting}
For most of the distance functions available in \verb|Bio.Cluster|, a weight vector can be applied. The weight vector contains weights for the items in the data vector. If the weight for item $i$ is $w_i$, then that item is treated as if it occurred $w_i$ times in the data. The weight do not have to be integers.
For the Spearman rank correlation and Kendall's
$\tau$,
weights do not have a well-defined meaning and are therefore not implemented.
\subsection*{Calculating the distance matrix}
\label{subsec:distancematrix}
The distance matrix is a square matrix with all pairwise distances between the items in \verb|data|, and can be calculated by the function \verb|distancematrix| in the \verb|Bio.Cluster| module:
\begin{verbatim}
>>> from Bio.Cluster import distancematrix
>>> matrix = distancematrix(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required)\\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if the distances between the rows of \verb|data| are to be calculated (\verb|transpose==0|), or between the columns of \verb|data| (\verb|transpose==1|).
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
To save memory, the distance matrix is returned as a list of 1D arrays.
The number of columns in each row is equal to the row number. Hence, the first row has zero elements. An example of the return value is
\begin{verbatim}
[array([]),
array([1.]),
array([7., 3.]),
array([4., 2., 6.])]
\end{verbatim}
This corresponds to the distance matrix
$$
\left(
\begin{array}{cccc}
0 & 1 & 7 & 4 \\
1 & 0 & 3 & 2 \\
7 & 3 & 0 & 6 \\
4 & 2 & 6 & 0
\end{array}
\right).
$$
\section{Calculating cluster properties}
\subsection*{Calculating the cluster centroids}
\label{subsec:clustercentroids}
The centroid of a cluster can be defined either as the mean or as the median of each dimension over all cluster items. The function \verb|clustercentroids| in \verb|Bio.Cluster| can be used to calculate either:
\begin{verbatim}
>>> from Bio.Cluster import clustercentroids
>>> cdata, cmask = clustercentroids(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required) \\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|clusterid| (default: \verb|None|) \\
Vector of integers showing to which cluster each item belongs. If \verb|clusterid| is \verb|None|, then all items are assumed to belong to the same cluster.
\item \verb|method| (default: \verb|'a'|) \\
Specifies whether the arithmetic mean (\verb|method=='a'|) or the median (\verb|method=='m'|) is used to calculate the cluster center.
\item \verb|transpose| (default: \verb|0|) \\
Determines if the centroids of the rows of \verb|data| are to be calculated (\verb|transpose==0|), or the centroids of the columns of \verb|data| (\verb|transpose==1|).
\end{itemize}
This function returns the tuple \verb|(cdata, cmask)|. The centroid data are stored in the 2D Numerical Python array \verb|cdata|, with missing data indicated by the 2D Numerical Python integer array \verb|cmask|. The dimensions of these arrays are $\left(\textrm{number of clusters}, \textrm{number of columns}\right)$ if \verb|transpose| is \verb|0|, or $\left(\textrm{number of rows}, \textrm{number of clusters}\right)$ if \verb|transpose| is \verb|1|. Each row (if \verb|transpose| is \verb|0|) or column (if \verb|transpose| is \verb|1|) contains the averaged data corresponding to the centroid of each cluster.
\subsection*{Calculating the distance between clusters}
Given a distance function between \emph{items}, we can define the distance between two \emph{clusters} in several ways. The distance between the arithmetic means of the two clusters is used in pairwise centroid-linkage clustering and in $k$-means clustering. In $k$-medoids clustering, the distance between the medians of the two clusters is used instead. The shortest pairwise distance between items of the two clusters is used in pairwise single-linkage clustering, while the longest pairwise distance is used in pairwise maximum-linkage clustering. In pairwise average-linkage clustering, the distance between two clusters is defined as the average over the pairwise distances.
To calculate the distance between two clusters, use
\begin{verbatim}
>>> from Bio.Cluster import clusterdistance
>>> distance = clusterdistance(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required)\\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|index1| (default: \verb|0|) \\
A list containing the indices of the items belonging to the first cluster. A cluster containing only one item $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|index2| (default: \verb|0|) \\
A list containing the indices of the items belonging to the second cluster. A cluster containing only one items $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|method| (default: \verb|'a'|) \\
Specifies how the distance between clusters is defined:
\begin{itemize}
\item \verb|'a'|: Distance between the two cluster centroids (arithmetic mean);
\item \verb|'m'|: Distance between the two cluster centroids (median);
\item \verb|'s'|: Shortest pairwise distance between items in the two clusters;
\item \verb|'x'|: Longest pairwise distance between items in the two clusters;
\item \verb|'v'|: Average over the pairwise distances between items in the two clusters.
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\item \verb|transpose| (default: \verb|0|) \\
If \verb|transpose==0|, calculate the distance between the rows of \verb|data|. If \verb|transpose==1|, calculate the distance between the columns of \verb|data|.
\end{itemize}
\section{Partitioning algorithms}
Partitioning algorithms divide items into $k$ clusters such that the sum of distances over the items to their cluster centers is minimal.
The number of clusters $k$ is specified by the user.
Three partitioning algorithms are available in \verb|Bio.Cluster|:
\begin{itemize}
\item $k$-means clustering
\item $k$-medians clustering
\item $k$-medoids clustering
\end{itemize}
These algorithms differ in how the cluster center is defined. In $k$-means clustering, the cluster center is defined as the mean data vector averaged over all items in the cluster. Instead of the mean, in $k$-medians clustering the median is calculated for each dimension in the data vector. Finally, in $k$-medoids clustering the cluster center is defined as the item which has the smallest sum of distances to the other items in the cluster. This clustering algorithm is suitable for cases in which the distance matrix is known but the original data matrix is not available, for example when clustering proteins based on their structural similarity.
The expectation-maximization (EM) algorithm is used to find this partitioning into $k$ groups.
In the initialization of the EM algorithm, we randomly assign items to clusters. To ensure that no empty clusters are produced, we use the binomial distribution to randomly choose the number of items in each cluster to be one or more. We then randomly permute the cluster assignments to items such that each item has an equal probability to be in any cluster. Each cluster is thus guaranteed to contain at least one item.
We then iterate:
\begin{itemize}
\item Calculate the centroid of each cluster, defined as either the mean, the median, or the medoid of the cluster;
\item Calculate the distances of each item to the cluster centers;
\item For each item, determine which cluster centroid is closest;
\item Reassign each item to its closest cluster, or stop the iteration if no further item reassignments take place.
\end{itemize}
To avoid clusters becoming empty during the iteration, in $k$-means and $k$-medians clustering the algorithm keeps track of the number of items in each cluster, and prohibits the last remaining item in a cluster from being reassigned to a different cluster. For $k$-medoids clustering, such a check is not needed, as the item that functions as the cluster centroid has a zero distance to itself, and will therefore never be closer to a different cluster.
As the initial assignment of items to clusters is done randomly, usually a different clustering solution is found each time the EM algorithm is executed.
To find the optimal clustering solution, the $k$-means algorithm is repeated many times, each time starting from a different initial random clustering. The sum of distances of the items to their cluster center is saved for each run, and the solution with the smallest value of this sum will be returned as the overall clustering solution.
How often the EM algorithm should be run depends on the number of items being clustered. As a rule of thumb, we can consider how often the optimal solution was found; this number is returned by the partitioning algorithms as implemented in this library. If the optimal solution was found many times, it is unlikely that better solutions exist than the one that was found. However, if the optimal solution was found only once, there may well be other solutions with a smaller within-cluster sum of distances. If the number of items is large (more than several hundreds), it may be difficult to find the globally optimal solution.
The EM algorithm terminates when no further reassignments take place. We noticed that for some sets of initial cluster assignments, the EM algorithm fails to converge due to the same clustering solution reappearing periodically after a small number of iteration steps. We therefore check for the occurrence of such periodic solutions during the iteration. After a given number of iteration steps, the current clustering result is saved as a reference. By comparing the clustering result after each subsequent iteration step to the reference state, we can determine if a previously encountered clustering result is found. In such a case, the iteration is halted. If after a given number of iterations the reference state has not yet been encountered, the current clustering solution is saved to be used as the new reference state. Initially, ten iteration steps are executed before resaving the reference state. This number of iteration steps is doubled each time, to ensure that periodic behavior with longer periods can also be detected.
\subsection*{$k$-means and $k$-medians}
The $k$-means and $k$-medians algorithms are implemented as the function \verb|kcluster| in \verb|Bio.Cluster|:
\begin{verbatim}
>>> from Bio.Cluster import kcluster
>>> clusterid, error, nfound = kcluster(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required)\\
Array containing the data for the items.
\item \verb|nclusters| (default: \verb|2|) \\
The number of clusters $k$.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|npass| (default: \verb|1|) \\
The number of times the $k$-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If \verb|initialid| is given, the value of \verb|npass| is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case.
\item \verb|method| (default: \verb|a|) \\
describes how the center of a cluster is found:
\begin{itemize}
\item \verb|method=='a'|: arithmetic mean ($k$-means clustering);
\item \verb|method=='m'|: median ($k$-medians clustering).
\end{itemize}
For other values of \verb|method|, the arithmetic mean is used.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
Whereas all eight distance measures are accepted by \verb|kcluster|, from a theoretical viewpoint it is best to use the Euclidean distance for the $k$-means algorithm, and the city-block distance for $k$-medians.
\item \verb|initialid| (default: \verb|None|) \\
Specifies the initial clustering to be used for the EM algorithm. If \verb|initialid==None|, then a different random initial clustering is used for each of the \verb|npass| runs of the EM algorithm. If \verb|initialid| is not \verb|None|, then it should be equal to a 1D array containing the cluster number (between \verb|0| and \verb|nclusters-1|) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic.
\end{itemize}
This function returns a tuple \verb|(clusterid, error, nfound)|, where \verb|clusterid| is an integer array containing the number of the cluster to which each row or cluster was assigned, \verb|error| is the within-cluster sum of distances for the optimal clustering solution, and \verb|nfound| is the number of times this optimal solution was found.
\subsection*{$k$-medoids clustering}
The \verb+kmedoids+ routine performs $k$-medoids clustering on a given set of items, using the distance matrix and the number of clusters passed by the user:
\begin{verbatim}
>>> from Bio.Cluster import kmedoids
>>> clusterid, error, nfound = kmedoids(distance)
\end{verbatim}
where the following arguments are defined:
, nclusters=2, npass=1, initialid=None)|
\begin{itemize}
\item{\verb|distance|} (required) \\
The matrix containing the distances between the items; this matrix can be specified in three ways:
\begin{itemize}
\item as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed):
\begin{verbatim}
distance = array([[0.0, 1.1, 2.3],
[1.1, 0.0, 4.5],
[2.3, 4.5, 0.0]])
\end{verbatim}
\item as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix:
\begin{verbatim}
distance = array([1.1, 2.3, 4.5])
\end{verbatim}
\item as a list containing the rows of the left-lower part of the distance matrix:
\begin{verbatim}
distance = [array([]|,
array([1.1]),
array([2.3, 4.5])
]
\end{verbatim}
\end{itemize}
These three expressions correspond to the same distance matrix.
\item \verb|nclusters| (default: \verb|2|) \\
The number of clusters $k$.
\item \verb|npass| (default: \verb|1|) \\
The number of times the $k$-medoids clustering algorithm is performed, each time with a different (random) initial condition. If \verb|initialid| is given, the value of \verb|npass| is ignored, as the clustering algorithm behaves deterministically in that case.
\item \verb|initialid| (default: \verb|None|) \\
Specifies the initial clustering to be used for the EM algorithm. If \verb|initialid==None|, then a different random initial clustering is used for each of the \verb|npass| runs of the EM algorithm. If \verb|initialid| is not \verb|None|, then it should be equal to a 1D array containing the cluster number (between \verb|0| and \verb|nclusters-1|) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic.
\end{itemize}
This function returns a tuple \verb|(clusterid, error, nfound)|, where \verb|clusterid| is an array containing the number of the cluster to which each item was assigned, \verb|error| is the within-cluster sum of distances for the optimal $k$-medoids clustering solution, and \verb|nfound| is the number of times the optimal solution was found. Note that the cluster number in \verb|clusterid| is defined as the item number of the item representing the cluster centroid.
\section{Hierarchical clustering}
Hierarchical clustering methods are inherently different from the $k$-means clustering method. In hierarchical clustering, the similarity in the expression profile between genes or experimental conditions are represented in the form of a tree structure. This tree structure can be shown graphically by programs such as Treeview and Java Treeview, which has contributed to the popularity of hierarchical clustering in the analysis of gene expression data.
The first step in hierarchical clustering is to calculate the distance matrix, specifying all the distances between the items to be clustered. Next, we create a node by joining the two closest items. Subsequent nodes are created by pairwise joining of items or nodes based on the distance between them, until all items belong to the same node. A tree structure can then be created by retracing which items and nodes were merged. Unlike the EM algorithm, which is used in $k$-means clustering, the complete process of hierarchical clustering is deterministic.
Several flavors of hierarchical clustering exist, which differ in how the distance between subnodes is defined in terms of their members. In \verb|Bio.Cluster|, pairwise single, maximum, average, and centroid linkage are available.
\begin{itemize}
\item
In pairwise single-linkage clustering, the distance between two nodes is defined as the shortest distance among the pairwise distances between the members of the two nodes.
\item
In pairwise maximum-linkage clustering, alternatively known as pairwise complete-linkage clustering, the distance between two nodes is defined as the longest distance among the pairwise distances between the members of the two nodes.
\item
In pairwise average-linkage clustering, the distance between two nodes is defined as the average over all pairwise distances between the items of the two nodes.
\item
In pairwise centroid-linkage clustering, the distance between two nodes is defined as the distance between their centroids. The centroids are calculated by taking the mean over all the items in a cluster. As the distance from each newly formed node to existing nodes and items need to be calculated at each step, the computing time of pairwise centroid-linkage clustering may be significantly longer than for the other hierarchical clustering methods. Another peculiarity is that (for a distance measure based on the Pearson correlation), the distances do not necessarily increase when going up in the clustering tree, and may even decrease. This is caused by an inconsistency between the centroid calculation and the distance calculation when using the Pearson correlation: Whereas the Pearson correlation effectively normalizes the data for the distance calculation, no such normalization occurs for the centroid calculation.
\end{itemize}
For pairwise single-, complete-, and average-linkage clustering, the distance between two nodes can be found directly from the distances between the individual items. Therefore, the clustering algorithm does not need access to the original gene expression data, once the distance matrix is known. For pairwise centroid-linkage clustering, however, the centroids of newly formed subnodes can only be calculated from the original data and not from the distance matrix.
The implementation of pairwise single-linkage hierarchical clustering is based on the SLINK algorithm (R. Sibson, 1973), which is much faster and more memory-efficient than a straightforward implementation of pairwise single-linkage clustering. The clustering result produced by this algorithm is identical to the clustering solution found by the conventional single-linkage algorithm. The single-linkage hierarchical clustering algorithm implemented in this library can be used to cluster large gene expression data sets, for which conventional hierarchical clustering algorithms fail due to excessive memory requirements and running time.
\subsection*{Representing a hierarchical clustering solution}
The result of hierarchical clustering consists of a tree of nodes, in which each node joins two items or subnodes. Usually, we are not only interested in which items or subnodes are joined at each node, but also in their similarity (or distance) as they are joined. To store one node in the hierarchical clustering tree, we make use of the class \verb|Node|, which defined in \verb|Bio.Cluster|. An instance of \verb|Node| has three attributes:
\begin{itemize}
\item \verb|left|
\item \verb|right|
\item \verb|distance|
\end{itemize}
Here, \verb|left| and \verb|right| are integers referring to the two items or subnodes that are joined at this node, and \verb|distance| is the distance between them. The items being clustered are numbered from 0 to $\left(\textrm{number of items} - 1\right)$, while clusters are numbered from -1 to $-\left(\textrm{number of items}-1\right)$. Note that the number of nodes is one less than the number of items.
To create a new \verb|Node| object, we need to specify \verb|left| and \verb|right|; \verb|distance| is optional.
\begin{verbatim}
>>> from Bio.Cluster import Node
>>> Node(2,3)
(2, 3): 0
>>> Node(2,3,0.91)
(2, 3): 0.91
\end{verbatim}
The attributes \verb|left|, \verb|right|, and \verb|distance| of an existing \verb|Node| object can be modified directly:
\begin{verbatim}
>>> node = Node(4,5)
>>> node.left = 6
>>> node.right = 2
>>> node.distance = 0.73
>>> node
(6, 2): 0.73
\end{verbatim}
An error is raised if \verb|left| and \verb|right| are not integers, or if \verb|distance| cannot be converted to a floating-point value.
The Python class \verb|Tree| represents a full hierarchical clustering solution. A \verb|Tree| object can be created from a list of \verb|Node| objects:
\begin{verbatim}
>>> from Bio.Cluster import Node, Tree
>>> nodes = [Node(1,2,0.2), Node(0,3,0.5), Node(-2,4,0.6), Node(-1,-3,0.9)]
>>> tree = Tree(nodes)
>>> print tree
(1, 2): 0.2
(0, 3): 0.5
(-2, 4): 0.6
(-1, -3): 0.9
\end{verbatim}
The \verb|Tree| initializer checks if the list of nodes is a valid hierarchical clustering result:
\begin{verbatim}
>>> nodes = [Node(1,2,0.2), Node(0,2,0.5)]
>>> Tree(nodes)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: Inconsistent tree
\end{verbatim}
Individual nodes in a \verb|Tree| object can be accessed using square brackets:
\begin{verbatim}
>>> nodes = [Node(1,2,0.2), Node(0,-1,0.5)]
>>> tree = Tree(nodes)
>>> tree[0]
(1, 2): 0.2
>>> tree[1]
(0, -1): 0.5
>>> tree[-1]
(0, -1): 0.5
\end{verbatim}
As a \verb|Tree| object is read-only, we cannot change individual nodes in a \verb|Tree| object. However, we can convert the tree to a list of nodes, modify this list, and create a new tree from this list:
\begin{verbatim}
>>> tree = Tree([Node(1,2,0.1), Node(0,-1,0.5), Node(-2,3,0.9)])
>>> print tree
(1, 2): 0.1
(0, -1): 0.5
(-2, 3): 0.9
>>> nodes = tree[:]
>>> nodes[0] = Node(0,1,0.2)
>>> nodes[1].left = 2
>>> tree = Tree(nodes)
>>> print tree
(0, 1): 0.2
(2, -1): 0.5
(-2, 3): 0.9
\end{verbatim}
This guarantees that any \verb|Tree| object is always well-formed.
To display a hierarchical clustering solution with visualization programs such as Java Treeview, it is better to scale all node distances such that they are between zero and one. This can be accomplished by calling the \verb|scale| method on an existing \verb|Tree| object:
\begin{verbatim}
>>> tree.scale()
\end{verbatim}
This method takes no arguments, and returns \verb|None|.
After hierarchical clustering, the items can be grouped into $k$ clusters based on the tree structure stored in the \verb|Tree| object by cutting the tree:
\begin{verbatim}
>>> clusterid = tree.cut(nclusters=1)
\end{verbatim}
where \verb|nclusters| (defaulting to \verb|1|) is the desired number of clusters $k$.
This method ignores the top $k-1$ linking events in the tree structure, resulting in $k$ separated clusters of items. The number of clusters $k$ should be positive, and less than or equal to the number of items.
This method returns an array \verb|clusterid| containing the number of the cluster to which each item is assigned.
\subsection*{Performing hierarchical clustering}
To perform hierarchical clustering, use the \verb|treecluster| function in \verb|Bio.Cluster|.
\begin{verbatim}
>>> from Bio.Cluster import treecluster
>>> tree = treecluster(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| \\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose==0|) or columns (\verb|transpose==1|) are to be clustered.
\item \verb|method| (default: \verb|'m'|) \\
defines the linkage method to be used:
\begin{itemize}
\item \verb|method=='s'|: pairwise single-linkage clustering
\item \verb|method=='m'|: pairwise maximum- (or complete-) linkage clustering
\item \verb|method=='c'|: pairwise centroid-linkage clustering
\item \verb|method=='a'|: pairwise average-linkage clustering
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
To apply hierarchical clustering on a precalculated distance matrix, specify the \verb|distancematrix| argument when calling \verb|treecluster| function instead of the \verb|data| argument:
\begin{verbatim}
>>> from Bio.Cluster import treecluster
>>> tree = treecluster(distancematrix=distance)
\end{verbatim}
In this case, the following arguments are defined:
\begin{itemize}
\item \verb|distancematrix| \\
The distance matrix, which can be specified in three ways:
\begin{itemize}
\item as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed):
\begin{verbatim}
distance = array([[0.0, 1.1, 2.3],
[1.1, 0.0, 4.5],
[2.3, 4.5, 0.0]])
\end{verbatim}
\item as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix:
\begin{verbatim}
distance = array([1.1, 2.3, 4.5])
\end{verbatim}
\item as a list containing the rows of the left-lower part of the distance matrix:
\begin{verbatim}
distance = [array([]),
array([1.1]),
array([2.3, 4.5])
\end{verbatim}
\end{itemize}
These three expressions correspond to the same distance matrix.
As \verb|treecluster| may shuffle the values in the distance matrix as part of the clustering algorithm, be sure to save this array in a different variable before calling \verb|treecluster| if you need it later.
\item \verb|method| \\
The linkage method to be used:
\begin{itemize}
\item \verb|method=='s'|: pairwise single-linkage clustering
\item \verb|method=='m'|: pairwise maximum- (or complete-) linkage clustering
\item \verb|method=='a'|: pairwise average-linkage clustering
\end{itemize}
While pairwise single-, maximum-, and average-linkage clustering can be calculated from the distance matrix alone, pairwise centroid-linkage cannot.
\end{itemize}
When calling \verb|treecluster|, either \verb|data| or \verb|distancematrix| should be \verb|None|.
This function returns a \verb|Tree| object. This object contains $\left(\textrm{number of items} - 1\right)$ nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes \verb|left| and \verb|right| each contain the number of one item or subnode, and \verb|distance| the distance between them. Items are numbered from 0 to $\left(\textrm{number of items} - 1\right)$, while clusters are numbered -1 to $-\left(\textrm{number of items}-1\right)$.
\section{Self-Organizing Maps}
Self-Organizing Maps (SOMs) were invented by Kohonen to describe neural networks (see for instance Kohonen, 1997 \cite{kohonen1997}). Tamayo (1999) first applied Self-Organizing Maps to gene expression data \cite{tamayo1999}.
SOMs organize items into clusters that are situated in some topology. Usually a rectangular topology is chosen. The clusters generated by SOMs are such that neighboring clusters in the topology are more similar to each other than clusters far from each other in the topology.
The first step to calculate a SOM is to randomly assign a data vector to each cluster in the topology. If rows are being clustered, then the number of elements in each data vector is equal to the number of columns.
An SOM is then generated by taking rows one at a time, and finding which cluster in the topology has the closest data vector. The data vector of that cluster, as well as those of the neighboring clusters, are adjusted using the data vector of the row under consideration. The adjustment is given by
$$\Delta \underline{x}_{\textrm{cell}} = \tau \cdot \left(\underline{x}_{\textrm{row}} - \underline{x}_{\textrm{cell}} \right).$$
The parameter
$\tau$
is a parameter that decreases at each iteration step. We have used a simple linear function of the iteration step:
$$\tau = \tau_{\textrm{init}} \cdot \left(1 - {i \over n}\right),$$
$\tau_{\textrm{init}}$
is the initial value of $\tau$ as specified by the user, $i$ is the number of the current iteration step, and $n$ is the total number of iteration steps to be performed. While changes are made rapidly in the beginning of the iteration, at the end of iteration only small changes are made.
All clusters within a radius $R$ are adjusted to the gene under consideration. This radius decreases as the calculation progresses as
$$R = R_{\textrm{max}} \cdot \left(1 - {i \over n}\right),$$
in which the maximum radius is defined as
$$R_{\textrm{max}} = \sqrt{N_x^2 + N_y^2},$$
where
$\left(N_x, N_y\right)$
are the dimensions of the rectangle defining the topology.
The function \verb|somcluster| implements the complete algorithm to calculate a Self-Organizing Map on a rectangular grid. First it initializes the random number generator. The node data are then initialized using the random number generator. The order in which genes or microarrays are used to modify the SOM is also randomized. The total number of iterations in the SOM algorithm is specified by the user.
To run \verb|somcluster|, use
\begin{verbatim}
>>> from Bio.Cluster import somcluster
>>> clusterid, celldata = somcluster(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required) \\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
contains the weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|nxgrid, nygrid| (default: \verb|2, 1|) \\
The number of cells horizontally and vertically in the rectangular grid on which the Self-Organizing Map is calculated.
\item \verb|inittau| (default: \verb|0.02|) \\
The initial value for the parameter $\tau$ that is used in the SOM algorithm. The default value for \verb|inittau| is 0.02, which was used in Michael Eisen's Cluster/TreeView program.
\item \verb|niter| (default: \verb|1|) \\
The number of iterations to be performed.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns the tuple \verb|(clusterid, celldata)|:
\begin{itemize}
\item \verb|clusterid|: \\
An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the $x$ and $y$ coordinates of the cell in the rectangular SOM grid to which the item was assigned.
\item \verb|celldata|: \\
An array with dimensions $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of columns}\right)$ if rows are being clustered, or $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of rows}\right)$ if columns are being clustered. Each element \verb|[ix][iy]| of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates \verb|[ix][iy]|.
\end{itemize}
\section{Principal Component Analysis}
Principal Component Analysis (PCA) is a widely used technique for analyzing multivariate data. A practical example of applying Principal Component Analysis to gene expression data is presented by Yeung and Ruzzo (2001) \cite{yeung2001}.
In essence, PCA is a coordinate transformation in which each row in the data matrix is written as a linear sum over basis vectors called principal components, which are ordered and chosen such that each maximally explains the remaining variance in the data vectors. For example, an $n \times 3$ data matrix can be represented as an ellipsoidal cloud of $n$ points in three dimensional space. The first principal component is the longest axis of the ellipsoid, the second principal component the second longest axis of the ellipsoid, and the third principal component is the shortest axis. Each row in the data matrix can be reconstructed as a suitable linear combination of the principal components. However, in order to reduce the dimensionality of the data, usually only the most important principal components are retained. The remaining variance present in the data is then regarded as unexplained variance.
The principal components can be found by calculating the eigenvectors of the covariance matrix of the data. The corresponding eigenvalues determine how much of the variance present in the data is explained by each principal component.
Before applying principal component analysis, typically the mean is subtracted from each column in the data matrix. In the example above, this effectively centers the ellipsoidal cloud around its centroid in 3D space, with the principal components describing the variation of points in the ellipsoidal cloud with respect to their centroid.
The function \verb|pca| below first uses the singular value decomposition to calculate the eigenvalues and eigenvectors of the data matrix. The singular value decomposition is implemented as a translation in C of the Algol procedure \verb|svd| \cite{golub1971}, which uses Householder bidiagonalization and a variant of the QR algorithm. The principal components, the coordinates of each data vector along the principal components, and the eigenvalues corresponding to the principal components are then evaluated and returned in decreasing order of the magnitude of the eigenvalue. If data centering is desired, the mean should be subtracted from each column in the data matrix before calling the \verb|pca| routine.
To apply Principal Component Analysis to a rectangular matrix \verb|data|, use
\begin{verbatim}
>>> from Bio.Cluster import pca
>>> columnmean, coordinates, components, eigenvalues = pca(data)
\end{verbatim}
This function returns a tuple \verb|columnmean, coordinates, components, eigenvalues|:
\begin{itemize}
\item \verb|columnmean| \\
Array containing the mean over each column in \verb|data|.
\item \verb|coordinates| \\
The coordinates of each row in \verb|data| with respect to the principal components.
\item \verb|components| \\
The principal components.
\item \verb|eigenvalues| \\
The eigenvalues corresponding to each of the principal components.
\end{itemize}
The original matrix \verb|data| can be recreated by calculating \verb|columnmean + dot(coordinates, components)|.
\section{Handling Cluster/TreeView-type files}
Cluster/TreeView are GUI-based codes for clustering gene expression data. They were originally written by \href{http://rana.lbl.gov}{Michael Eisen} while at Stanford University. \verb|Bio.Cluster| contains functions for reading and writing data files that correspond to the format specified for Cluster/TreeView. In particular, by saving a clustering result in that format, TreeView can be used to visualize the clustering results. We recommend using Alok Saldanha's \url{http://jtreeview.sourceforge.net/}{Java TreeView program}, which can display hierarchical as well as $k$-means clustering results.
An object of the class \verb|Record| contains all information stored in a Cluster/TreeView-type data file. To store the information contained in the data file in a \verb|Record| object, we first open the file and then read it:
\begin{verbatim}
>>> from Bio import Cluster
>>> handle = open("mydatafile.txt")
>>> record = Cluster.read(handle)
>>> handle.close()
\end{verbatim}
This two-step process gives you some flexibility in the source of the data.
For example, you can use
\begin{verbatim}
>>> import gzip # Python standard library
>>> handle = gzip.open("mydatafile.txt.gz")
\end{verbatim}
to open a gzipped file, or
\begin{verbatim}
>>> import urllib # Python standard library
>>> handle = urllib.urlopen("http://somewhere.org/mydatafile.txt")
\end{verbatim}
to open a file stored on the Internet before calling \verb|read|.
The \verb|read| command reads the tab-delimited text file \verb|mydatafile.txt| containing gene expression data in the format specified for Michael Eisen's Cluster/TreeView program. For a description of this file format, see the manual to Cluster/TreeView. It is available at \href{http://rana.lbl.gov/manuals/ClusterTreeView.pdf}{Michael Eisen's lab website} and at \href{http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/cluster/cluster3.pdf}{our website}.
A \verb|Record| object has the following attributes:
\begin{itemize}
\item \verb|data| \\
The data array containing the gene expression data. Genes are stored row-wise, while microarrays are stored column-wise.
\item \verb|mask| \\
This array shows which elements in the \verb|data| array, if any, are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If no data were found to be missing, \verb|mask| is set to \verb|None|.
\item \verb|geneid| \\
This is a list containing a unique description for each gene (i.e., ORF numbers).
\item \verb|genename| \\
This is a list containing a description for each gene (i.e., gene name). If not present in the data file, \verb|genename| is set to \verb|None|.
\item \verb|gweight| \\
The weights that are to be used to calculate the distance in expression profile between genes. If not present in the data file, \verb|gweight| is set to \verb|None|.
\item \verb|gorder| \\
The preferred order in which genes should be stored in an output file. If not present in the data file, \verb|gorder| is set to \verb|None|.
\item \verb|expid| \\
This is a list containing a description of each microarray, e.g. experimental condition.
\item \verb|eweight| \\
The weights that are to be used to calculate the distance in expression profile between microarrays. If not present in the data file, \verb|eweight| is set to \verb|None|.
\item \verb|eorder| \\
The preferred order in which microarrays should be stored in an output file. If not present in the data file, \verb|eorder| is set to \verb|None|.
\item \verb|uniqid| \\
The string that was used instead of UNIQID in the data file.
\end{itemize}
After loading a \verb|Record| object, each of these attributes can be accessed and modified directly. For example, the data can be log-transformed by taking the logarithm of \verb|record.data|.
\subsection*{Calculating the distance matrix}
To calculate the distance matrix between the items stored in the record, use
\begin{verbatim}
>>> matrix = record.distancematrix()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|transpose| (default: \verb|0|) \\
Determines if the distances between the rows of \verb|data| are to be calculated (\verb|transpose==0|), or between the columns of \verb|data| (\verb|transpose==1|).
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns the distance matrix as a list of rows, where the number of columns of each row is equal to the row number (see section \ref{subsec:distancematrix}).
\subsection*{Calculating the cluster centroids}
To calculate the centroids of clusters of items stored in the record, use
\begin{verbatim}
>>> cdata, cmask = record.clustercentroids()
\end{verbatim}
\begin{itemize}
\item \verb|clusterid| (default: \verb|None|) \\
Vector of integers showing to which cluster each item belongs. If \verb|clusterid| is not given, then all items are assumed to belong to the same cluster.
\item \verb|method| (default: \verb|'a'|) \\
Specifies whether the arithmetic mean (\verb|method=='a'|) or the median (\verb|method=='m'|) is used to calculate the cluster center.
\item \verb|transpose| (default: \verb|0|) \\
Determines if the centroids of the rows of \verb|data| are to be calculated (\verb|transpose==0|), or the centroids of the columns of \verb|data| (\verb|transpose==1|).
\end{itemize}
This function returns the tuple \verb|cdata, cmask|; see section \ref{subsec:clustercentroids} for a description.
\subsection*{Calculating the distance between clusters}
To calculate the distance between clusters of items stored in the record, use
\begin{verbatim}
>>> distance = record.clusterdistance()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|index1| (default: \verb|0|) \\
A list containing the indices of the items belonging to the first cluster. A cluster containing only one item $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|index2| (default: \verb|0|) \\
A list containing the indices of the items belonging to the second cluster. A cluster containing only one item $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|method| (default: \verb|'a'|) \\
Specifies how the distance between clusters is defined:
\begin{itemize}
\item \verb|'a'|: Distance between the two cluster centroids (arithmetic mean);
\item \verb|'m'|: Distance between the two cluster centroids (median);
\item \verb|'s'|: Shortest pairwise distance between items in the two clusters;
\item \verb|'x'|: Longest pairwise distance between items in the two clusters;
\item \verb|'v'|: Average over the pairwise distances between items in the two clusters.
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\item \verb|transpose| (default: \verb|0|) \\
If \verb|transpose==0|, calculate the distance between the rows of \verb|data|. If \verb|transpose==1|, calculate the distance between the columns of \verb|data|.
\end{itemize}
\subsection*{Performing hierarchical clustering}
To perform hierarchical clustering on the items stored in the record, use
\begin{verbatim}
>>> tree = record.treecluster()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose==0|) or columns (\verb|transpose==1|) are to be clustered.
\item \verb|method| (default: \verb|'m'|) \\
defines the linkage method to be used:
\begin{itemize}
\item \verb|method=='s'|: pairwise single-linkage clustering
\item \verb|method=='m'|: pairwise maximum- (or complete-) linkage clustering
\item \verb|method=='c'|: pairwise centroid-linkage clustering
\item \verb|method=='a'|: pairwise average-linkage clustering
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\item \verb|transpose| \\
Determines if genes or microarrays are being clustered. If \verb|transpose==0|, genes (rows) are being clustered. If \verb|transpose==1|, microarrays (columns) are clustered.
\end{itemize}
This function returns a \verb|Tree| object. This object contains $\left(\textrm{number of items} - 1\right)$ nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes \verb|left| and \verb|right| each contain the number of one item or subnode, and \verb|distance| the distance between them. Items are numbered from 0 to $\left(\textrm{number of items} - 1\right)$, while clusters are numbered -1 to $-\left(\textrm{number of items}-1\right)$.
\subsection*{Performing $k$-means or $k$-medians clustering}
To perform $k$-means or $k$-medians clustering on the items stored in the record, use
\begin{verbatim}
>>> clusterid, error, nfound = record.kcluster()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|nclusters| (default: \verb|2|) \\
The number of clusters $k$.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|npass| (default: \verb|1|) \\
The number of times the $k$-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If \verb|initialid| is given, the value of \verb|npass| is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case.
\item \verb|method| (default: \verb|a|) \\
describes how the center of a cluster is found:
\begin{itemize}
\item \verb|method=='a'|: arithmetic mean ($k$-means clustering);
\item \verb|method=='m'|: median ($k$-medians clustering).
\end{itemize}
For other values of \verb|method|, the arithmetic mean is used.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns a tuple \verb|(clusterid, error, nfound)|, where \verb|clusterid| is an integer array containing the number of the cluster to which each row or cluster was assigned, \verb|error| is the within-cluster sum of distances for the optimal clustering solution, and \verb|nfound| is the number of times this optimal solution was found.
\subsection*{Calculating a Self-Organizing Map}
To calculate a Self-Organizing Map of the items stored in the record, use
\begin{verbatim}
>>> clusterid, celldata = record.somcluster()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|nxgrid, nygrid| (default: \verb|2, 1|) \\
The number of cells horizontally and vertically in the rectangular grid on which the Self-Organizing Map is calculated.
\item \verb|inittau| (default: \verb|0.02|) \\
The initial value for the parameter $\tau$ that is used in the SOM algorithm. The default value for \verb|inittau| is 0.02, which was used in Michael Eisen's Cluster/TreeView program.
\item \verb|niter| (default: \verb|1|) \\
The number of iterations to be performed.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns the tuple \verb|(clusterid, celldata)|:
\begin{itemize}
\item \verb|clusterid|: \\
An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the $x$ and $y$ coordinates of the cell in the rectangular SOM grid to which the item was assigned.
\item \verb|celldata|: \\
An array with dimensions $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of columns}\right)$ if rows are being clustered, or $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of rows}\right)$ if columns are being clustered. Each element \verb|[ix][iy]| of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates \verb|[ix][iy]|.
\end{itemize}
\subsection*{Saving the clustering result}
To save the clustering result, use
\begin{verbatim}
>>> record.save(jobname, geneclusters, expclusters)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|jobname| \\
The string \verb|jobname| is used as the base name for names of the files that are to be saved.
\item \verb|geneclusters| \\
This argument describes the gene (row-wise) clustering result. In case of $k$-means clustering, this is a 1D array containing the number of the cluster each gene belongs to. It can be calculated using \verb|kcluster|. In case of hierarchical clustering, \verb|geneclusters| is a \verb|Tree| object.
\item \verb|expclusters| \\
This argument describes the (column-wise) clustering result for the experimental conditions. In case of $k$-means clustering, this is a 1D array containing the number of the cluster each experimental condition belongs to. It can be calculated using \verb|kcluster|. In case of hierarchical clustering, \verb|expclusters| is a \verb|Tree| object.
\end{itemize}
This method writes the text file \verb|jobname.cdt|, \verb|jobname.gtr|, \verb|jobname.atr|, \verb|jobname*.kgg|, and/or \verb|jobname*.kag| for subsequent reading by the Java TreeView program. If \verb|geneclusters| and \verb|expclusters| are both \verb|None|, this method only writes the text file \verb|jobname.cdt|; this file can subsequently be read into a new \verb|Record| object.
\section{Example calculation}
This is an example of a hierarchical clustering calculation, using single linkage clustering for genes and maximum linkage clustering for experimental conditions. As the Euclidean distance is being used for gene clustering, it is necessary to scale the node distances \verb|genetree| such that they are all between zero and one. This is needed for the Java TreeView code to display the tree diagram correctly. To cluster the experimental conditions, the uncentered correlation is being used. No scaling is needed in this case, as the distances in \verb|exptree| are already between zero and two. The example data \verb|cyano.txt| can be found in the \verb|data| subdirectory.
\begin{verbatim}
>>> from Bio import Cluster
>>> handle = open("cyano.txt")
>>> record = Cluster.read(handle)
>>> handle.close()
>>> genetree = record.treecluster(method='s')
>>> genetree.scale()
>>> exptree = record.treecluster(dist='u', transpose=1)
>>> record.save("cyano_result", genetree, exptree)
\end{verbatim}
This will create the files \verb|cyano_result.cdt|, \verb|cyano_result.gtr|, and \verb|cyano_result.atr|.
Similarly, we can save a $k$-means clustering solution:
\begin{verbatim}
>>> from Bio import Cluster
>>> handle = open("cyano.txt")
>>> record = Cluster.read(handle)
>>> handle.close()
>>> (geneclusters, error, ifound) = record.kcluster(nclusters=5, npass=1000)
>>> (expclusters, error, ifound) = record.kcluster(nclusters=2, npass=100, transpose=1)
>>> record.save("cyano_result", geneclusters, expclusters)
\end{verbatim}
This will create the files \verb|cyano_result_K_G2_A2.cdt|, \verb|cyano_result_K_G2.kgg|, and \verb|cyano_result_K_A2.kag|.
\section{Auxiliary functions}
\verb|median(data)|
returns the median of the 1D array \verb|data|.
\verb|mean(data)|
returns the mean of the 1D array \verb|data|.
\verb|version()|
returns the version number of the underlying C Clustering Library as a string.
\chapter{Supervised learning methods}
Note the supervised learning methods described in this chapter all require Numerical Python (numpy) to be installed.
\section{The Logistic Regression Model}
\label{sec:LogisticRegression}
\subsection{Background and Purpose}
Logistic regression is a supervised learning approach that attempts to distinguish $K$ classes from each other using a weighted sum of some predictor variables $x_i$. The logistic regression model is used to calculate the weights $\beta_i$ of the predictor variables. In Biopython, the logistic regression model is currently implemented for two classes only ($K = 2$); the number of predictor variables has no predefined limit.
As an example, let's try to predict the operon structure in bacteria. An operon is a set of adjacent genes on the same strand of DNA that are transcribed into a single mRNA molecule. Translation of the single mRNA molecule then yields the individual proteins. For {\it Bacillus subtilis}, whose data we will be using, the average number of genes in an operon is about 2.4.
As a first step in understanding gene regulation in bacteria, we need to know the operon structure. For about 10\% of the genes in {\it Bacillus subtilis}, the operon structure is known from experiments. A supervised learning method can be used to predict the operon structure for the remaining 90\% of the genes.
For such a supervised learning approach, we need to choose some predictor variables $x_i$ that can be measured easily and are somehow related to the operon structure. One predictor variable might be the distance in base pairs between genes. Adjacent genes belonging to the same operon tend to be separated by a relatively short distance, whereas adjacent genes in different operons tend to have a larger space between them to allow for promoter and terminator sequences. Another predictor variable is based on gene expression measurements. By definition, genes belonging to the same operon have equal gene expression profiles, while genes in different operons are expected to have different expression profiles. In practice, the measured expression profiles of genes in the same operon are not quite identical due to the presence of measurement errors. To assess the similarity in the gene expression profiles, we assume that the measurement errors follow a normal distribution and calculate the corresponding log-likelihood score.
We now have two predictor variables that we can use to predict if two adjacent genes on the same strand of DNA belong to the same operon:
\begin{itemize}
\item $x_1$: the number of base pairs between them;
\item $x_2$: their similarity in expression profile.
\end{itemize}
In a logistic regression model, we use a weighted sum of these two predictors to calculate a joint score $S$:
\begin{equation}
S = \beta_0 + \beta_1 x_1 + \beta_2 x_2.
\end{equation}
The logistic regression model gives us appropriate values for the parameters $\beta_0$, $\beta_1$, $\beta_2$ using two sets of example genes:
\begin{itemize}
\item OP: Adjacent genes, on the same strand of DNA, known to belong to the same operon;
\item NOP: Adjacent genes, on the same strand of DNA, known to belong to different operons.
\end{itemize}
In the logistic regression model, the probability of belonging to a class depends on the score via the logistic function. For the two classes OP and NOP, we can write this as
\begin{eqnarray}
\Pr(\mathrm{OP}|x_1, x_2) & = & \frac{\exp(\beta_0 + \beta_1 x_1 + \beta_2 x_2)}{1+\exp(\beta_0 + \beta_1 x_1 + \beta_2 x_2)} \label{eq:OP} \\
\Pr(\mathrm{NOP}|x_1, x_2) & = & \frac{1}{1+\exp(\beta_0 + \beta_1 x_1 + \beta_2 x_2)} \label{eq:NOP}
\end{eqnarray}
Using a set of gene pairs for which it is known whether they belong to the same operon (class OP) or to different operons (class NOP), we can calculate the weights $\beta_0$, $\beta_1$, $\beta_2$ by maximizing the log-likelihood corresponding to the probability functions (\ref{eq:OP}) and (\ref{eq:NOP}).
\subsection{Training the logistic regression model}
\label{subsec:LogisticRegressionTraining}
\begin{table}[h]
\begin{center}
\caption{Adjacent gene pairs known to belong to the same operon (class OP) or to different operons (class NOP). Intergene distances are negative if the two genes overlap.}
\begin{tabular}{|c|c|c|c|}
\hline
Gene pair & Intergene distance ($x_1$) & Gene expression score ($x_2$) & Class\\
\hline
{\it cotJA} --- {\it cotJB} & -53 & -200.78 & OP\\
{\it yesK} --- {\it yesL} & 117 & -267.14 & OP\\
{\it lplA} --- {\it lplB} & 57 & -163.47 & OP\\
{\it lplB} --- {\it lplC} & 16 & -190.30 & OP\\
{\it lplC} --- {\it lplD} & 11 & -220.94 & OP\\
{\it lplD} --- {\it yetF} & 85 & -193.94 & OP\\
{\it yfmT} --- {\it yfmS} & 16 & -182.71 & OP\\
{\it yfmF} --- {\it yfmE} & 15 & -180.41 & OP\\
{\it citS} --- {\it citT} & -26 & -181.73 & OP\\
{\it citM} --- {\it yflN} & 58 & -259.87 & OP\\
{\it yfiI} --- {\it yfiJ} & 126 & -414.53 & NOP\\
{\it lipB} --- {\it yfiQ} & 191 & -249.57 & NOP\\
{\it yfiU} --- {\it yfiV} & 113 & -265.28 & NOP\\
{\it yfhH} --- {\it yfhI} & 145 & -312.99 & NOP\\
{\it cotY} --- {\it cotX} & 154 & -213.83 & NOP\\
{\it yjoB} --- {\it rapA} & 147 & -380.85 & NOP\\
{\it ptsI} --- {\it splA} & 93 & -291.13 & NOP \\
\hline
\end{tabular}
\label{table:training}
\end{center}
\end{table}
Table \ref{table:training} lists some of the {\it Bacillus subtilis} gene pairs for which the operon structure is known.
Let's calculate the logistic regression model from these data:
%NOTE - can't use this as a doctest in case NumPy is missing (Jython).
%Also the ... are missing but that means the user can copy/paste the example.
\begin{verbatim}
>>> from Bio import LogisticRegression
>>> xs = [[-53, -200.78],
[117, -267.14],
[57, -163.47],
[16, -190.30],
[11, -220.94],
[85, -193.94],
[16, -182.71],
[15, -180.41],
[-26, -181.73],
[58, -259.87],
[126, -414.53],
[191, -249.57],
[113, -265.28],
[145, -312.99],
[154, -213.83],
[147, -380.85],
[93, -291.13]]
>>> ys = [1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0]
>>> model = LogisticRegression.train(xs, ys)
\end{verbatim}
Here, \verb+xs+ and \verb+ys+ are the training data: \verb+xs+ contains the predictor variables for each gene pair, and \verb+ys+ specifies if the gene pair belongs to the same operon (\verb+1+, class OP) or different operons (\verb+0+, class NOP). The resulting logistic regression model is stored in \verb+model+, which contains the weights $\beta_0$, $\beta_1$, and $\beta_2$:
\begin{verbatim}
>>> model.beta
[8.9830290157144681, -0.035968960444850887, 0.02181395662983519]
\end{verbatim}
Note that $\beta_1$ is negative, as gene pairs with a shorter intergene distance have a higher probability of belonging to the same operon (class OP). On the other hand, $\beta_2$ is positive, as gene pairs belonging to the same operon typically have a higher similarity score of their gene expression profiles.
The parameter $\beta_0$ is positive due to the higher prevalence of operon gene pairs than non-operon gene pairs in the training data.
The function \verb+train+ has two optional arguments: \verb+update_fn+ and \verb+typecode+. The \verb+update_fn+ can be used to specify a callback function, taking as arguments the iteration number and the log-likelihood. With the callback function, we can for example track the progress of the model calculation (which uses a Newton-Raphson iteration to maximize the log-likelihood function of the logistic regression model):
\begin{verbatim}
>>> def show_progress(iteration, loglikelihood):
print "Iteration:", iteration, "Log-likelihood function:", loglikelihood
>>>
>>> model = LogisticRegression.train(xs, ys, update_fn=show_progress)
Iteration: 0 Log-likelihood function: -11.7835020695
Iteration: 1 Log-likelihood function: -7.15886767672
Iteration: 2 Log-likelihood function: -5.76877209868
Iteration: 3 Log-likelihood function: -5.11362294338
Iteration: 4 Log-likelihood function: -4.74870642433
Iteration: 5 Log-likelihood function: -4.50026077146
Iteration: 6 Log-likelihood function: -4.31127773737
Iteration: 7 Log-likelihood function: -4.16015043396
Iteration: 8 Log-likelihood function: -4.03561719785
Iteration: 9 Log-likelihood function: -3.93073282192
Iteration: 10 Log-likelihood function: -3.84087660929
Iteration: 11 Log-likelihood function: -3.76282560605
Iteration: 12 Log-likelihood function: -3.69425027154
Iteration: 13 Log-likelihood function: -3.6334178602
Iteration: 14 Log-likelihood function: -3.57900855837
Iteration: 15 Log-likelihood function: -3.52999671386
Iteration: 16 Log-likelihood function: -3.48557145163
Iteration: 17 Log-likelihood function: -3.44508206139
Iteration: 18 Log-likelihood function: -3.40799948447
Iteration: 19 Log-likelihood function: -3.3738885624
Iteration: 20 Log-likelihood function: -3.3423876581
Iteration: 21 Log-likelihood function: -3.31319343769
Iteration: 22 Log-likelihood function: -3.2860493346
Iteration: 23 Log-likelihood function: -3.2607366863
Iteration: 24 Log-likelihood function: -3.23706784091
Iteration: 25 Log-likelihood function: -3.21488073614
Iteration: 26 Log-likelihood function: -3.19403459259
Iteration: 27 Log-likelihood function: -3.17440646052
Iteration: 28 Log-likelihood function: -3.15588842703
Iteration: 29 Log-likelihood function: -3.13838533947
Iteration: 30 Log-likelihood function: -3.12181293595
Iteration: 31 Log-likelihood function: -3.10609629966
Iteration: 32 Log-likelihood function: -3.09116857282
Iteration: 33 Log-likelihood function: -3.07696988017
Iteration: 34 Log-likelihood function: -3.06344642288
Iteration: 35 Log-likelihood function: -3.05054971191
Iteration: 36 Log-likelihood function: -3.03823591619
Iteration: 37 Log-likelihood function: -3.02646530573
Iteration: 38 Log-likelihood function: -3.01520177394
Iteration: 39 Log-likelihood function: -3.00441242601
Iteration: 40 Log-likelihood function: -2.99406722296
Iteration: 41 Log-likelihood function: -2.98413867259
\end{verbatim}
The iteration stops once the increase in the log-likelihood function is less than 0.01. If no convergence is reached after 500 iterations, the \verb+train+ function returns with an \verb+AssertionError+.
The optional keyword \verb+typecode+ can almost always be ignored. This keyword allows the user to choose the type of Numeric matrix to use. In particular, to avoid memory problems for very large problems, it may be necessary to use single-precision floats (Float8, Float16, etc.) rather than double, which is used by default.
\subsection{Using the logistic regression model for classification}
Classification is performed by calling the \verb+classify+ function. Given a logistic regression model and the values for $x_1$ and $x_2$ (e.g. for a gene pair of unknown operon structure), the \verb+classify+ function returns \verb+1+ or \verb+0+, corresponding to class OP and class NOP, respectively. For example, let's consider the gene pairs {\it yxcE}, {\it yxcD} and {\it yxiB}, {\it yxiA}:
\begin{table}[h]
\begin{center}
\caption{Adjacent gene pairs of unknown operon status.}
\begin{tabular}{|c|c|c|}
\hline
Gene pair & Intergene distance $x_1$ & Gene expression score $x_2$ \\
\hline
{\it yxcE} --- {\it yxcD} & 6 & -173.143442352 \\
{\it yxiB} --- {\it yxiA} & 309 & -271.005880394 \\
\hline
\end{tabular}
\end{center}
\end{table}
The logistic regression model classifies {\it yxcE}, {\it yxcD} as belonging to the same operon (class OP), while {\it yxiB}, {\it yxiA} are predicted to belong to different operons:
\begin{verbatim}
>>> print "yxcE, yxcD:", LogisticRegression.classify(model, [6,-173.143442352])
yxcE, yxcD: 1
>>> print "yxiB, yxiA:", LogisticRegression.classify(model, [309, -271.005880394])
yxiB, yxiA: 0
\end{verbatim}
(which, by the way, agrees with the biological literature).
To find out how confident we can be in these predictions, we can call the \verb+calculate+ function to obtain the probabilities (equations (\ref{eq:OP}) and \ref{eq:NOP}) for class OP and NOP. For {\it yxcE}, {\it yxcD} we find
\begin{verbatim}
>>> q, p = LogisticRegression.calculate(model, [6,-173.143442352])
>>> print "class OP: probability =", p, "class NOP: probability =", q
class OP: probability = 0.993242163503 class NOP: probability = 0.00675783649744
\end{verbatim}
and for {\it yxiB}, {\it yxiA}
\begin{verbatim}
>>> q, p = LogisticRegression.calculate(model, [309, -271.005880394])
>>> print "class OP: probability =", p, "class NOP: probability =", q
class OP: probability = 0.000321211251817 class NOP: probability = 0.999678788748
\end{verbatim}
To get some idea of the prediction accuracy of the logistic regression model, we can apply it to the training data:
\begin{verbatim}
>>> for i in range(len(ys)):
print "True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i])
True: 1 Predicted: 1
True: 1 Predicted: 0
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
\end{verbatim}
showing that the prediction is correct for all but one of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted:
\begin{verbatim}
>>> for i in range(len(ys)):
model = LogisticRegression.train(xs[:i]+xs[i+1:], ys[:i]+ys[i+1:])
print "True:", ys[i], "Predicted:", LogisticRegression.classify(model, xs[i])
True: 1 Predicted: 1
True: 1 Predicted: 0
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 1
True: 0 Predicted: 0
True: 0 Predicted: 0
\end{verbatim}
The leave-one-out analysis shows that the prediction of the logistic regression model is incorrect for only two of the gene pairs, which corresponds to a prediction accuracy of 88\%.
\subsection{Logistic Regression, Linear Discriminant Analysis, and Support Vector Machines}
The logistic regression model is similar to linear discriminant analysis. In linear discriminant analysis, the class probabilities also follow equations (\ref{eq:OP}) and (\ref{eq:NOP}). However, instead of estimating the coefficients $\beta$ directly, we first fit a normal distribution to the predictor variables $x$. The coefficients $\beta$ are then calculated from the means and covariances of the normal distribution. If the distribution of $x$ is indeed normal, then we expect linear discriminant analysis to perform better than the logistic regression model. The logistic regression model, on the other hand, is more robust to deviations from normality.
Another similar approach is a support vector machine with a linear kernel. Such an SVM also uses a linear combination of the predictors, but estimates the coefficients $\beta$ from the predictor variables $x$ near the boundary region between the classes. If the logistic regression model (equations (\ref{eq:OP}) and (\ref{eq:NOP})) is a good description for $x$ away from the boundary region, we expect the logistic regression model to perform better than an SVM with a linear kernel, as it relies on more data. If not, an SVM with a linear kernel may perform better.
Trevor Hastie, Robert Tibshirani, and Jerome Friedman: {\it The Elements of Statistical Learning. Data Mining, Inference, and Prediction}. Springer Series in Statistics, 2001. Chapter 4.4.
\section{$k$-Nearest Neighbors}
\subsection{Background and purpose}
The $k$-nearest neighbors method is a supervised learning approach that does not need to fit a model to the data. Instead, data points are classified based on the categories of the $k$ nearest neighbors in the training data set.
In Biopython, the $k$-nearest neighbors method is available in \verb+Bio.kNN+. To illustrate the use of the $k$-nearest neighbor method in Biopython, we will use the same operon data set as in section \ref{sec:LogisticRegression}.
\subsection{Initializing a $k$-nearest neighbors model}
Using the data in Table \ref{table:training}, we create and initialize a $k$-nearest neighbors model as follows:
\begin{verbatim}
>>> from Bio import kNN
>>> k = 3
>>> model = kNN.train(xs, ys, k)
\end{verbatim}
where \verb+xs+ and \verb+ys+ are the same as in Section \ref{subsec:LogisticRegressionTraining}. Here, \verb+k+ is the number of neighbors $k$ that will be considered for the classification. For classification into two classes, choosing an odd number for $k$ lets you avoid tied votes. The function name \verb+train+ is a bit of a misnomer, since no model training is done: this function simply stores \verb+xs+, \verb+ys+, and \verb+k+ in \verb+model+.
\subsection{Using a $k$-nearest neighbors model for classification}
To classify new data using the $k$-nearest neighbors model, we use the \verb+classify+ function. This function takes a data point $(x_1,x_2)$ and finds the $k$-nearest neighbors in the training data set \verb+xs+. The data point $(x_1, x_2)$ is then classified based on which category (\verb+ys+) occurs most among the $k$ neighbors.
For the example of the gene pairs {\it yxcE}, {\it yxcD} and {\it yxiB}, {\it yxiA}, we find:
\begin{verbatim}
>>> x = [6, -173.143442352]
>>> print "yxcE, yxcD:", kNN.classify(model, x)
yxcE, yxcD: 1
>>> x = [309, -271.005880394]
>>> print "yxiB, yxiA:", kNN.classify(model, x)
yxiB, yxiA: 0
\end{verbatim}
In agreement with the logistic regression model, {\it yxcE}, {\it yxcD} are classified as belonging to the same operon (class OP), while {\it yxiB}, {\it yxiA} are predicted to belong to different operons.
The \verb+classify+ function lets us specify both a distance function and a weight function as optional arguments. The distance function affects which $k$ neighbors are chosen as the nearest neighbors, as these are defined as the neighbors with the smallest distance to the query point $(x, y)$. By default, the Euclidean distance is used. Instead, we could for example use the city-block (Manhattan) distance:
\begin{verbatim}
>>> def cityblock(x1, x2):
... assert len(x1)==2
... assert len(x2)==2
... distance = abs(x1[0]-x2[0]) + abs(x1[1]-x2[1])
... return distance
...
>>> x = [6, -173.143442352]
>>> print "yxcE, yxcD:", kNN.classify(model, x, distance_fn = cityblock)
yxcE, yxcD: 1
\end{verbatim}
The weight function can be used for weighted voting. For example, we may want to give closer neighbors a higher weight than neighbors that are further away:
\begin{verbatim}
>>> def weight(x1, x2):
... assert len(x1)==2
... assert len(x2)==2
... return exp(-abs(x1[0]-x2[0]) - abs(x1[1]-x2[1]))
...
>>> x = [6, -173.143442352]
>>> print "yxcE, yxcD:", kNN.classify(model, x, weight_fn = weight)
yxcE, yxcD: 1
\end{verbatim}
By default, all neighbors are given an equal weight.
To find out how confident we can be in these predictions, we can call the \verb+calculate+ function, which will calculate the total weight assigned to the classes OP and NOP. For the default weighting scheme, this reduces to the number of neighbors in each category. For {\it yxcE}, {\it yxcD}, we find
\begin{verbatim}
>>> x = [6, -173.143442352]
>>> weight = kNN.calculate(model, x)
>>> print "class OP: weight =", weight[0], "class NOP: weight =", weight[1]
class OP: weight = 0.0 class NOP: weight = 3.0
\end{verbatim}
which means that all three neighbors of \verb+x1+, \verb+x2+ are in the NOP class. As another example, for {\it yesK}, {\it yesL} we find
\begin{verbatim}
>>> x = [117, -267.14]
>>> weight = kNN.calculate(model, x)
>>> print "class OP: weight =", weight[0], "class NOP: weight =", weight[1]
class OP: weight = 2.0 class NOP: weight = 1.0
\end{verbatim}
which means that two neighbors are operon pairs and one neighbor is a non-operon pair.
To get some idea of the prediction accuracy of the $k$-nearest neighbors approach, we can apply it to the training data:
\begin{verbatim}
>>> for i in range(len(ys)):
print "True:", ys[i], "Predicted:", kNN.classify(model, xs[i])
True: 1 Predicted: 1
True: 1 Predicted: 0
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
\end{verbatim}
showing that the prediction is correct for all but two of the gene pairs. A more reliable estimate of the prediction accuracy can be found from a leave-one-out analysis, in which the model is recalculated from the training data after removing the gene to be predicted:
\begin{verbatim}
>>> for i in range(len(ys)):
model = kNN.train(xs[:i]+xs[i+1:], ys[:i]+ys[i+1:])
print "True:", ys[i], "Predicted:", kNN.classify(model, xs[i])
True: 1 Predicted: 1
True: 1 Predicted: 0
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 1
True: 1 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 1
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 0
True: 0 Predicted: 1
\end{verbatim}
The leave-one-out analysis shows that $k$-nearest neighbors model is correct for 13 out of 17 gene pairs, which corresponds to a prediction accuracy of 76\%.
\section{Na\"ive Bayes}
This section will describe the \verb|Bio.NaiveBayes| module.
\section{Maximum Entropy}
This section will describe the \verb|Bio.MaximumEntropy| module.
\section{Markov Models}
This section will describe the \verb|Bio.MarkovModel| and/or \verb|Bio.HMM.MarkovModel| modules.
\chapter{Graphics including GenomeDiagram}
\label{chapter:graphics}
The \verb|Bio.Graphics| module depends on the third party Python library
\href{http://www.reportlab.org}{ReportLab}. Although focused on producing PDF files,
ReportLab can also create encapsulated postscript (EPS) and (SVG) files. In addition
to these vector based images, provided certain further dependencies such as the
\href{http://www.pythonware.com/products/pil/}{Python Imaging Library (PIL)} are
installed, ReportLab can also output bitmap images (including JPEG, PNG, GIF, BMP
and PICT formats).
\section{GenomeDiagram}
\label{sec:genomediagram}
\subsection{Introduction}
The \verb|Bio.Graphics.GenomeDiagram| module was added to Biopython 1.50,
having previously been available as a separate Python module dependent on Biopython.
GenomeDiagram is described in the Bioinformatics journal publication by Pritchard et al. (2006) \cite{pritchard2006},
which includes some examples images. There is a PDF copy of the old manual here,
\url{http://biopython.org/DIST/docs/GenomeDiagram/userguide.pdf} which has some
more examples.
%TODO - Leighton's old website is AWOL, put this link back later if possible.
%http://bioinf.scri.ac.uk/lp/programs.php#genomediagram
As the name might suggest, GenomeDiagram was designed for drawing whole genomes, in
particular prokaryotic genomes, either as linear diagrams (optionally broken up into
fragments to fit better) or as circular wheel diagrams. Have a look at Figure 2 in
Toth \textit{et al.} (2006) \cite{toth2006}
for a good example. It proved also well suited to drawing quite detailed figures for
smaller genomes such as phage, plasmids or mitochrondia, for example see Figures 1
and 2 in Van der Auwera \textit{et al.} (2009) \cite{vanderauwera2009}
(shown with additional manual editing).
This module is easiest to use if you have your genome loaded as a \verb|SeqRecord|
object containing lots of \verb|SeqFeature| objects - for example as loaded from a
GenBank file (see Chapters~\ref{chapter:SeqRecord} and~\ref{chapter:Bio.SeqIO}).
\subsection{Diagrams, tracks, feature-sets and features}
GenomeDiagram uses a nested set of objects. At the top level, you have a diagram
object representing a sequence (or sequence region) along the horizontal axis (or
circle). A diagram can contain one or more tracks, shown stacked vertically (or
radially on circular diagrams). These will typically all have the same length
and represent the same sequence region. You might use one track to show the gene
locations, another to show regulatory regions, and a third track to show the GC
percentage. %Talk about cross-links here? Maybe better later...
The most commonly used type of track will contain features, bundled together in
feature-sets. You might choose to use one feature-set for all your CDS features,
and another for tRNA features. This isn't required - they can all go in the same
feature-set, but it makes it easier to update the properties of just selected
features (e.g. make all the tRNA features red).
There are two main ways to build up a complete diagram. Firstly, the top down
approach where you create a diagram object, and then using its methods add
track(s), and use the track methods to add feature-set(s), and use their
methods to add the features. Secondly, you can create the individual objects
separately (in whatever order suits your code), and then combine them.
\subsection{A top down example}
\label{sec:gd_top_down}
We're going to draw a whole genome from a \verb|SeqRecord| object read in from
a GenBank file (see Chapter~\ref{chapter:Bio.SeqIO}). This example uses the
pPCP1 plasmid from \textit{Yersinia pestis biovar Microtus}, the file is
included with the Biopython unit tests under the GenBank folder, or online
\href{http://biopython.org/SRC/biopython/Tests/GenBank/NC_005816.gb}
{\texttt{NC\_005816.gb}} from our website.
\begin{verbatim}
from reportlab.lib import colors
from reportlab.lib.units import cm
from Bio.Graphics import GenomeDiagram
from Bio import SeqIO
record = SeqIO.read("NC_005816.gb", "genbank")
\end{verbatim}
We're using a top down approach, so after loading in our sequence we next
create an empty diagram, then add an (empty) track, and to that add an
(empty) feature set:
\begin{verbatim}
gd_diagram = GenomeDiagram.Diagram("Yersinia pestis biovar Microtus plasmid pPCP1")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
\end{verbatim}
Now the fun part - we take each gene \verb|SeqFeature| object in our
\verb|SeqRecord|, and use it to generate a feature on the diagram. We're
going to color them blue, alternating between a dark blue and a light blue.
\begin{verbatim}
for feature in record.features:
if feature.type != "gene":
#Exclude this feature
continue
if len(gd_feature_set) % 2 == 0:
color = colors.blue
else:
color = colors.lightblue
gd_feature_set.add_feature(feature, color=color, label=True)
\end{verbatim}
Now we come to actually making the output file. This happens in two steps,
first we call the \verb|draw| method, which creates all the shapes using
ReportLab objects. Then we call the \verb|write| method which renders these
to the requested file format. Note you can output in multiple file formats:
\begin{verbatim}
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
fragments=4, start=0, end=len(record))
gd_diagram.write("plasmid_linear.pdf", "PDF")
gd_diagram.write("plasmid_linear.eps", "EPS")
gd_diagram.write("plasmid_linear.svg", "SVG")
\end{verbatim}
Also, provided you have the dependencies installed, you can also do bitmaps,
for example:
\begin{verbatim}
gd_diagram.write("plasmid_linear.png", "PNG")
\end{verbatim}
\begin{htmlonly}
%The blank line below is important to start a new paragraph
\imgsrc[width=550, height=400]{images/plasmid_linear.png}
\end{htmlonly}
\begin{latexonly}
The expected output is shown in Figure~\ref{fig:plasmid_linear}.
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/plasmid_linear.png}
\caption{Simple linear diagram for \textit{Yersinia pestis biovar Microtus} plasmid pPCP1.}
\label{fig:plasmid_linear}
\end{figure}
\end{latexonly}
Notice that the \verb|fragments| argument which we set to four controls how
many pieces the genome gets broken up into.
If you want to do a circular figure, then try this:
\begin{verbatim}
gd_diagram.draw(format="circular", circular=True, pagesize=(20*cm,20*cm),
start=0, end=len(record), circle_core=0.7)
gd_diagram.write("plasmid_circular.pdf", "PDF")
\end{verbatim}
\begin{htmlonly}
%The blank line below is important to start a new paragraph
\imgsrc[width=400, height=400]{images/plasmid_circular.png}
\end{htmlonly}
\begin{latexonly}
The expected output is shown in Figure~\ref{fig:plasmid_circular}.
\begin{figure}[htbp]
\centering
\includegraphics[width=8cm,height=8cm]{images/plasmid_circular.png}
\caption{Simple circular diagram for \textit{Yersinia pestis biovar Microtus} plasmid pPCP1.}
\label{fig:plasmid_circular}
\end{figure}
\end{latexonly}
These figures are not very exciting, but we've only just got started.
\subsection{A bottom up example}
Now let's produce exactly the same figures, but using the bottom up approach.
This means we create the different objects directly (and this can be done in
almost any order) and then combine them.
\begin{verbatim}
from reportlab.lib import colors
from reportlab.lib.units import cm
from Bio.Graphics import GenomeDiagram
from Bio import SeqIO
record = SeqIO.read("NC_005816.gb", "genbank")
#Create the feature set and its feature objects,
gd_feature_set = GenomeDiagram.FeatureSet()
for feature in record.features:
if feature.type != "gene":
#Exclude this feature
continue
if len(gd_feature_set) % 2 == 0:
color = colors.blue
else:
color = colors.lightblue
gd_feature_set.add_feature(feature, color=color, label=True)
#(this for loop is the same as in the previous example)
#Create a track, and a diagram
gd_track_for_features = GenomeDiagram.Track(name="Annotated Features")
gd_diagram = GenomeDiagram.Diagram("Yersinia pestis biovar Microtus plasmid pPCP1")
#Now have to glue the bits together...
gd_track_for_features.add_set(gd_feature_set)
gd_diagram.add_track(gd_track_for_features, 1)
\end{verbatim}
You can now call the \verb|draw| and \verb|write| methods as before to produce
a linear or circular diagram, using the code at the end of the top-down example
above. The figures should be identical.
\subsection{Features without a SeqFeature}
\label{sec:gd_features_without_seqfeatures}
In the above example we used a \verb|SeqRecord|'s \verb|SeqFeature| objects
to build our diagram (see also Section~\ref{sec:seq_features}).
Sometimes you won't have \verb|SeqFeature| objects,
but just the coordinates for a feature you want to draw. You have to create
minimal \verb|SeqFeature| object, but this is easy:
\begin{verbatim}
from Bio.SeqFeature import SeqFeature, FeatureLocation
my_seq_feature = SeqFeature(FeatureLocation(50,100),strand=+1)
\end{verbatim}
For strand, use \texttt{+1} for the forward strand, \texttt{-1} for the
reverse strand, and \texttt{None} for both. Here is a short self contained
example:
\begin{verbatim}
from Bio.SeqFeature import SeqFeature, FeatureLocation
from Bio.Graphics import GenomeDiagram
from reportlab.lib.units import cm
gdd = GenomeDiagram.Diagram('Test Diagram')
gdt_features = gdd.new_track(1, greytrack=False)
gds_features = gdt_features.new_set()
#Add three features to show the strand options,
feature = SeqFeature(FeatureLocation(25, 125), strand=+1)
gds_features.add_feature(feature, name="Forward", label=True)
feature = SeqFeature(FeatureLocation(150, 250), strand=None)
gds_features.add_feature(feature, name="Strandless", label=True)
feature = SeqFeature(FeatureLocation(275, 375), strand=-1)
gds_features.add_feature(feature, name="Reverse", label=True)
gdd.draw(format='linear', pagesize=(15*cm,4*cm), fragments=1,
start=0, end=400)
gdd.write("GD_labels_default.pdf", "pdf")
\end{verbatim}
\begin{htmlonly}
The top part of the image in the next subsection shows the output
\end{htmlonly}
\begin{latexonly}
The output is shown at the top of Figure~\ref{fig:gd_sigil_labels}
\end{latexonly}
(in the default feature color, pale green).
Notice that we have used the \texttt{name} argument here to specify the
caption text for these features. This is discussed in more detail next.
\subsection{Feature captions}
\label{sec:gd_feature_captions}
Recall we used the following (where \texttt{feature} was a
\verb|SeqFeature| object) to add a feature to the diagram:
\begin{verbatim}
gd_feature_set.add_feature(feature, color=color, label=True)
\end{verbatim}
In the example above the \verb|SeqFeature| annotation was used to pick a
sensible caption for the features. By default the following possible entries
under the \verb|SeqFeature| object's qualifiers dictionary are used:
\texttt{gene}, \texttt{label}, \texttt{name}, \texttt{locus\_tag}, and
\texttt{product}. More simply, you can specify a name directly:
\begin{verbatim}
gd_feature_set.add_feature(feature, color=color, label=True, name="My Gene")
\end{verbatim}
In addition to the caption text for each feature's label, you can also choose
the font, position (this defaults to the start of the sigil, you can also
choose the middle or at the end) and orientation (for linear diagrams only,
where this defaults to rotated by $45$ degrees):
\begin{verbatim}
#Large font, parallel with the track
gd_feature_set.add_feature(feature, label=True, color="green",
label_size=25, label_angle=0)
#Very small font, perpendicular to the track (towards it)
gd_feature_set.add_feature(feature, label=True, color="purple",
label_position="end",
label_size=4, label_angle=90)
#Small font, perpendicular to the track (away from it)
gd_feature_set.add_feature(feature, label=True, color="blue",
label_position="middle",
label_size=6, label_angle=-90)
\end{verbatim}
\noindent Combining each of these three fragments with the complete example
in the previous section should give something like
\begin{htmlonly}
this:
%The blank lines above and below are important to trigger paragraph breaks
\imgsrc[width=600, height=700]{images/GD_sigil_labels.png}
\label{fig:gd_sigil_labels}
\end{htmlonly}
\begin{latexonly}
the tracks in Figure~\ref{fig:gd_sigil_labels}.
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/GD_sigil_labels.png}
\caption{Simple GenomeDiagram showing label options.
The top plot in pale green shows the default label settings (see
Section~\ref{sec:gd_features_without_seqfeatures}) while the rest show
variations in the label size, position and orientation (see
Section~\ref{sec:gd_feature_captions}).
}
\label{fig:gd_sigil_labels}
\end{figure}
\end{latexonly}
We've not shown it here, but you can also set \texttt{label\_color} to
control the label's color (used in Section~\ref{sec:gd_nice_example}).
You'll notice the default font is quite small - this makes sense because
you will usually be drawing many (small) features on a page, not just a
few large ones as shown here.
\subsection{Feature sigils}
\label{sec:gd_sigils}
The examples above have all just used the default sigil for the feature, a
plain box, which was all that was available in the last publicly released standalone version of GenomeDiagram. Arrow sigils were included when
GenomeDiagram was added to Biopython 1.50:
\begin{verbatim}
#Default uses a BOX sigil
gd_feature_set.add_feature(feature)
#You can make this explicit:
gd_feature_set.add_feature(feature, sigil="BOX")
#Or opt for an arrow:
gd_feature_set.add_feature(feature, sigil="ARROW")
\end{verbatim}
\noindent
Biopython 1.61 added three more sigils,
\begin{verbatim}
#Box with corners cut off (making it an octagon)
gd_feature_set.add_feature(feature, sigil="OCTO")
#Box with jagged edges (useful for showing breaks in contains)
gd_feature_set.add_feature(feature, sigil="JAGGY")
#Arrow which spans the axis with strand used only for direction
gd_feature_set.add_feature(feature, sigil="BIGARROW")
\end{verbatim}
These are shown
\begin{htmlonly}
below.
\end{htmlonly}
\begin{latexonly}in Figure~\ref{fig:gd_sigils}.
\end{latexonly}
Most sigils fit into a bounding box (as given by the default BOX sigil),
either above or below the axis for the forward or reverse strand, or
straddling it (double the height) for strand-less features.
The BIGARROW sigil is different, always straddling the axis with the
direction taken from the feature's stand.
\begin{htmlonly}
\imgsrc[width=425, height=600]{images/GD_sigils.png}
\end{htmlonly}
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/GD_sigils.png}
\caption{Simple GenomeDiagram showing different sigils
(see Section~\ref{sec:gd_sigils})}
\label{fig:gd_sigils}
\end{figure}
\end{latexonly}
\subsection{Arrow sigils}
\label{sec:gd_arrow_sigils}
We introduced the arrow sigils in the previous section.
There are two additional options to adjust the shapes of the arrows, firstly
the thickness of the arrow shaft, given as a proportion of the height of the
bounding box:
\begin{verbatim}
#Full height shafts, giving pointed boxes:
gd_feature_set.add_feature(feature, sigil="ARROW", color="brown",
arrowshaft_height=1.0)
#Or, thin shafts:
gd_feature_set.add_feature(feature, sigil="ARROW", color="teal",
arrowshaft_height=0.2)
#Or, very thin shafts:
gd_feature_set.add_feature(feature, sigil="ARROW", color="darkgreen",
arrowshaft_height=0.1)
\end{verbatim}
\begin{htmlonly}
\noindent The results are shown below:
\imgsrc[width=600, height=700]{images/GD_sigil_arrow_shafts.png}
\end{htmlonly}
\begin{latexonly}
\noindent The results are shown in Figure~\ref{fig:gd_sigil_arrow_shafts}.
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/GD_sigil_arrow_shafts.png}
\caption{Simple GenomeDiagram showing arrow shaft options
(see Section~\ref{sec:gd_arrow_sigils})}
\label{fig:gd_sigil_arrow_shafts}
\end{figure}
\end{latexonly}
Secondly, the length of the arrow head - given as a proportion of the height
of the bounding box (defaulting to $0.5$, or $50\%$):
\begin{verbatim}
#Short arrow heads:
gd_feature_set.add_feature(feature, sigil="ARROW", color="blue",
arrowhead_length=0.25)
#Or, longer arrow heads:
gd_feature_set.add_feature(feature, sigil="ARROW", color="orange",
arrowhead_length=1)
#Or, very very long arrow heads (i.e. all head, no shaft, so triangles):
gd_feature_set.add_feature(feature, sigil="ARROW", color="red",
arrowhead_length=10000)
\end{verbatim}
\begin{htmlonly}
\noindent The results are shown below:
\imgsrc[width=600, height=700]{images/GD_sigil_arrow_heads.png}
\end{htmlonly}
\begin{latexonly}
\noindent The results are shown in Figure~\ref{fig:gd_sigil_arrow_heads}.
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/GD_sigil_arrow_heads.png}
\caption{Simple GenomeDiagram showing arrow head options
(see Section~\ref{sec:gd_arrow_sigils})}
\label{fig:gd_sigil_arrow_heads}
\end{figure}
\end{latexonly}
Biopython 1.61 adds a new \verb|BIGARROW| sigil which always stradles
the axis, pointing left for the reverse strand or right otherwise:
\begin{verbatim}
#A large arrow straddling the axis:
gd_feature_set.add_feature(feature, sigil="BIGARROW")
\end{verbatim}
\noindent All the shaft and arrow head options shown above for the
\verb|ARROW| sigil can be used for the \verb|BIGARROW| sigil too.
\subsection{A nice example}
\label{sec:gd_nice_example}
Now let's return to the pPCP1 plasmid from \textit{Yersinia pestis biovar
Microtus}, and the top down approach used in Section~\ref{sec:gd_top_down},
but take advantage of the sigil options we've now discussed. This time
we'll use arrows for the genes, and overlay them with strand-less features
(as plain boxes) showing the position of some restriction digest sites.
%NOTE - This *just* fits on one page in the PDF output :)
\begin{verbatim}
from reportlab.lib import colors
from reportlab.lib.units import cm
from Bio.Graphics import GenomeDiagram
from Bio import SeqIO
from Bio.SeqFeature import SeqFeature, FeatureLocation
record = SeqIO.read("NC_005816.gb", "genbank")
gd_diagram = GenomeDiagram.Diagram(record.id)
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
for feature in record.features:
if feature.type != "gene":
#Exclude this feature
continue
if len(gd_feature_set) % 2 == 0:
color = colors.blue
else:
color = colors.lightblue
gd_feature_set.add_feature(feature, sigil="ARROW",
color=color, label=True,
label_size = 14, label_angle=0)
#I want to include some strandless features, so for an example
#will use EcoRI recognition sites etc.
for site, name, color in [("GAATTC","EcoRI",colors.green),
("CCCGGG","SmaI",colors.orange),
("AAGCTT","HindIII",colors.red),
("GGATCC","BamHI",colors.purple)]:
index = 0
while True:
index = record.seq.find(site, start=index)
if index == -1 : break
feature = SeqFeature(FeatureLocation(index, index+len(site)))
gd_feature_set.add_feature(feature, color=color, name=name,
label=True, label_size = 10,
label_color=color)
index += len(site)
gd_diagram.draw(format="linear", pagesize='A4', fragments=4,
start=0, end=len(record))
gd_diagram.write("plasmid_linear_nice.pdf", "PDF")
gd_diagram.write("plasmid_linear_nice.eps", "EPS")
gd_diagram.write("plasmid_linear_nice.svg", "SVG")
gd_diagram.draw(format="circular", circular=True, pagesize=(20*cm,20*cm),
start=0, end=len(record), circle_core = 0.5)
gd_diagram.write("plasmid_circular_nice.pdf", "PDF")
gd_diagram.write("plasmid_circular_nice.eps", "EPS")
gd_diagram.write("plasmid_circular_nice.svg", "SVG")
\end{verbatim}
\begin{htmlonly}
\noindent And the output:
\imgsrc[width=550, height=400]{images/plasmid_linear_nice.png}
\imgsrc[width=591, height=591]{images/plasmid_circular_nice.png}
\end{htmlonly}
\begin{latexonly}
\noindent The expected output is shown in Figures~\ref{fig:plasmid_linear_nice}
and~\ref{fig:plasmid_circular_nice}.
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/plasmid_linear_nice.png}
\caption{Linear diagram for \textit{Yersinia pestis biovar Microtus} plasmid
pPCP1 showing selected restriction digest sites (see
Section~\ref{sec:gd_nice_example}).}
\label{fig:plasmid_linear_nice}
\end{figure}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/plasmid_circular_nice.png}
\caption{Circular diagram for \textit{Yersinia pestis biovar Microtus} plasmid
pPCP1 showing selected restriction digest sites (see
Section~\ref{sec:gd_nice_example}).}
\label{fig:plasmid_circular_nice}
\end{figure}
\end{latexonly}
\subsection{Multiple tracks}
\label{sec:gd_multiple_tracks}
All the examples so far have used a single track, but you can have more than
one track -- for example show the genes on one, and repeat regions on another.
In this example we're going to show three phage genomes side by side to scale,
inspired by Figure 6 in Proux {\textit et al.} (2002) \cite{proux2002}.
We'll need the GenBank files for the following three phage:
\begin{itemize}
\item \verb|NC_002703| -- Lactococcus phage Tuc2009, complete genome ($38347$ bp)
\item \verb|AF323668| -- Bacteriophage bIL285, complete genome ($35538$ bp)
\item \verb|NC_003212| -- \textit{Listeria innocua} Clip11262, complete genome,
of which we are focussing only on integrated prophage 5 (similar length).
\end{itemize}
You can download these using Entrez if you like, see Section~\ref{sec:efetch}
for more details. For the third record we've worked out where the phage is
integrated into the genome, and slice the record to extract it (with the
features preserved, see Section~\ref{sec:SeqRecord-slicing}), and must also
reverse complement to match the orientation of the first two phage (again
preserving the features, see Section~\ref{sec:SeqRecord-reverse-complement}):
\begin{verbatim}
from Bio import SeqIO
A_rec = SeqIO.read("NC_002703.gbk", "gb")
B_rec = SeqIO.read("AF323668.gbk", "gb")
C_rec = SeqIO.read("NC_003212.gbk", "gb")[2587879:2625807].reverse_complement(name=True)
\end{verbatim}
The figure we are imitating used different colors for different gene functions.
One way to do this is to edit the GenBank file to record color preferences for
each feature - something \href{http://www.sanger.ac.uk/resources/software/artemis/}
{Sanger's Artemis editor} does, and which GenomeDiagram should understand. Here
however, we'll just hard code three lists of colors.
Note that the annotation in the GenBank files doesn't exactly match that shown
in Proux \textit{et al.}, they have drawn some unannotated genes.
\begin{verbatim}
from reportlab.lib.colors import red, grey, orange, green, brown, blue, lightblue, purple
A_colors = [red]*5 + [grey]*7 + [orange]*2 + [grey]*2 + [orange] + [grey]*11 + [green]*4 \
+ [grey] + [green]*2 + [grey, green] + [brown]*5 + [blue]*4 + [lightblue]*5 \
+ [grey, lightblue] + [purple]*2 + [grey]
B_colors = [red]*6 + [grey]*8 + [orange]*2 + [grey] + [orange] + [grey]*21 + [green]*5 \
+ [grey] + [brown]*4 + [blue]*3 + [lightblue]*3 + [grey]*5 + [purple]*2
C_colors = [grey]*30 + [green]*5 + [brown]*4 + [blue]*2 + [grey, blue] + [lightblue]*2 \
+ [grey]*5
\end{verbatim}
Now to draw them -- this time we add three tracks to the diagram, and also notice they
are given different start/end values to reflect their different lengths (this requires
Biopython 1.59 or later).
\begin{verbatim}
from Bio.Graphics import GenomeDiagram
name = "Proux Fig 6"
gd_diagram = GenomeDiagram.Diagram(name)
max_len = 0
for record, gene_colors in zip([A_rec, B_rec, C_rec], [A_colors, B_colors, C_colors]):
max_len = max(max_len, len(record))
gd_track_for_features = gd_diagram.new_track(1,
name=record.name,
greytrack=True,
start=0, end=len(record))
gd_feature_set = gd_track_for_features.new_set()
i = 0
for feature in record.features:
if feature.type != "gene":
#Exclude this feature
continue
gd_feature_set.add_feature(feature, sigil="ARROW",
color=gene_colors[i], label=True,
name = str(i+1),
label_position="start",
label_size = 6, label_angle=0)
i+=1
gd_diagram.draw(format="linear", pagesize='A4', fragments=1,
start=0, end=max_len)
gd_diagram.write(name + ".pdf", "PDF")
gd_diagram.write(name + ".eps", "EPS")
gd_diagram.write(name + ".svg", "SVG")
\end{verbatim}
\begin{htmlonly}
\noindent The result:
\imgsrc[width=565, height=400]{images/three_track_simple.png}
\end{htmlonly}
\begin{latexonly}
\noindent The expected output is shown in Figure~\ref{fig:three_track_simple}.
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{images/three_track_simple.png}
\caption{Linear diagram with three tracks for Lactococcus phage Tuc2009
(NC\_002703), bacteriophage bIL285 (AF323668), and prophage 5 from
\textit{Listeria innocua} Clip11262 (NC\_003212)
(see Section~\ref{sec:gd_multiple_tracks}).}
\label{fig:three_track_simple}
\end{figure}
\end{latexonly}
I did wonder why in the original manuscript there were no red or orange genes
marked in the bottom phage. Another important point is here the phage are
shown with different lengths - this is because they are all drawn to the same
scale (they \emph{are} different lengths).
The key difference from the published figure is they have color-coded links
between similar proteins -- which is what we will do in the next section.
\subsection{Cross-Links between tracks}
\label{sec:gd_cross_links}
Biopython 1.59 added the ability to draw cross links between tracks - both
simple linear diagrams as we will show here, but also linear diagrams split
into fragments and circular diagrams.
Continuing the example from the previous section inspired by Figure 6 from
Proux \textit{et al.} 2002 \cite{proux2002},
we would need a list of cross links between pairs of genes, along with a score
or color to use. Realistically you might extract this from a BLAST file
computationally, but here I have manually typed them in.
My naming convention continues to refer to the three phage as A, B and C.
Here are the links we want to show between A and B, given as a list of
tuples (percentage similarity score, gene in A, gene in B).
\begin{verbatim}
#Tuc2009 (NC_002703) vs bIL285 (AF323668)
A_vs_B = [
(99, "Tuc2009_01", "int"),
(33, "Tuc2009_03", "orf4"),
(94, "Tuc2009_05", "orf6"),
(100,"Tuc2009_06", "orf7"),
(97, "Tuc2009_07", "orf8"),
(98, "Tuc2009_08", "orf9"),
(98, "Tuc2009_09", "orf10"),
(100,"Tuc2009_10", "orf12"),
(100,"Tuc2009_11", "orf13"),
(94, "Tuc2009_12", "orf14"),
(87, "Tuc2009_13", "orf15"),
(94, "Tuc2009_14", "orf16"),
(94, "Tuc2009_15", "orf17"),
(88, "Tuc2009_17", "rusA"),
(91, "Tuc2009_18", "orf20"),
(93, "Tuc2009_19", "orf22"),
(71, "Tuc2009_20", "orf23"),
(51, "Tuc2009_22", "orf27"),
(97, "Tuc2009_23", "orf28"),
(88, "Tuc2009_24", "orf29"),
(26, "Tuc2009_26", "orf38"),
(19, "Tuc2009_46", "orf52"),
(77, "Tuc2009_48", "orf54"),
(91, "Tuc2009_49", "orf55"),
(95, "Tuc2009_52", "orf60"),
]
\end{verbatim}
Likewise for B and C:
\begin{verbatim}
#bIL285 (AF323668) vs Listeria innocua prophage 5 (in NC_003212)
B_vs_C = [
(42, "orf39", "lin2581"),
(31, "orf40", "lin2580"),
(49, "orf41", "lin2579"), #terL
(54, "orf42", "lin2578"), #portal
(55, "orf43", "lin2577"), #protease
(33, "orf44", "lin2576"), #mhp
(51, "orf46", "lin2575"),
(33, "orf47", "lin2574"),
(40, "orf48", "lin2573"),
(25, "orf49", "lin2572"),
(50, "orf50", "lin2571"),
(48, "orf51", "lin2570"),
(24, "orf52", "lin2568"),
(30, "orf53", "lin2567"),
(28, "orf54", "lin2566"),
]
\end{verbatim}
For the first and last phage these identifiers are locus tags, for the middle
phage there are no locus tags so I've used gene names instead. The following
little helper function lets us lookup a feature using either a locus tag or
gene name:
\begin{verbatim}
def get_feature(features, id, tags=["locus_tag", "gene"]):
"""Search list of SeqFeature objects for an identifier under the given tags."""
for f in features:
for key in tags:
#tag may not be present in this feature
for x in f.qualifiers.get(key, []):
if x == id:
return f
raise KeyError(id)
\end{verbatim}
We can now turn those list of identifier pairs into SeqFeature pairs, and thus
find their location co-ordinates. We can now add all that code and the following
snippet to the previous example (just before the \verb|gd_diagram.draw(...)|
line -- see the finished example script
\href{http://biopython.org/SRC/biopython/Doc/examples/Proux_et_al_2002_Figure_6.py}{Proux\_et\_al\_2002\_Figure\_6.py}
included in the \texttt{Doc/examples} folder of the Biopython source code)
to add cross links to the figure:
\begin{verbatim}
from Bio.Graphics.GenomeDiagram import CrossLink
from reportlab.lib import colors
#Note it might have been clearer to assign the track numbers explicitly...
for rec_X, tn_X, rec_Y, tn_Y, X_vs_Y in [(A_rec, 3, B_rec, 2, A_vs_B),
(B_rec, 2, C_rec, 1, B_vs_C)]:
track_X = gd_diagram.tracks[tn_X]
track_Y = gd_diagram.tracks[tn_Y]
for score, id_X, id_Y in X_vs_Y:
feature_X = get_feature(rec_X.features, id_X)
feature_Y = get_feature(rec_Y.features, id_Y)
color = colors.linearlyInterpolatedColor(colors.white, colors.firebrick, 0, 100, score)
link_xy = CrossLink((track_X, feature_X.location.start, feature_X.location.end),
(track_Y, feature_Y.location.start, feature_Y.location.end),
color, colors.lightgrey)
gd_diagram.cross_track_links.append(link_xy)
\end{verbatim}
There are several important pieces to this code. First the \verb|GenomeDiagram| object
has a \verb|cross_track_links| attribute which is just a list of \verb|CrossLink| objects.
Each \verb|CrossLink| object takes two sets of track-specific co-ordinates (here given
as tuples, you can alternatively use a \verb|GenomeDiagram.Feature| object instead).
You can optionally supply a colour, border color, and say if this link should be drawn
flipped (useful for showing inversions).
You can also see how we turn the BLAST percentage identity score into a colour,
interpolating between white ($0\%$) and a dark red ($100\%$). In this example
we don't have any problems with overlapping cross-links. One way to tackle that
is to use transparency in ReportLab, by using colors with their alpha channel set.
However, this kind of shaded color scheme combined with overlap transparency
would be difficult to interpret.
%Again, HTML and PDF versions for the figure
\begin{htmlonly}
\noindent The result:
\imgsrc[width=565, height=400]{images/three_track_cl.png}
\end{htmlonly}
\begin{latexonly}
\noindent The expected output is shown in Figure~\ref{fig:three_track_cl}.
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{images/three_track_cl.png}
\caption{Linear diagram with three tracks for Lactococcus phage Tuc2009
(NC\_002703), bacteriophage bIL285 (AF323668), and prophage 5 from
\textit{Listeria innocua} Clip11262 (NC\_003212) plus basic cross-links
shaded by percentage identity (see Section~\ref{sec:gd_cross_links}).}
\label{fig:three_track_cl}
\end{figure}
\end{latexonly}
There is still a lot more that can be done within Biopython to help
improve this figure. First of all, the cross links in this case are
between proteins which are drawn in a strand specific manor. It can
help to add a background region (a feature using the `BOX' sigil) on the
feature track to extend the cross link. Also, we could reduce the vertical
height of the feature tracks to allocate more to the links instead -- one
way to do that is to allocate space for empty tracks. Furthermore,
in cases like this where there are no large gene overlaps, we can use
the axis-straddling \verb|BIGARROW| sigil, which allows us to further
reduce the vertical space needed for the track. These improvements
are demonstrated in the example script
\href{http://biopython.org/SRC/biopython/Doc/examples/Proux_et_al_2002_Figure_6.py}{Proux\_et\_al\_2002\_Figure\_6.py}
included in the \texttt{Doc/examples} folder of the Biopython source code.
%TODO - Add a link get the file directly (for Windows users etc).
\begin{htmlonly}
\noindent The result:
\imgsrc[width=565, height=400]{images/three_track_cl2a.png}
\end{htmlonly}
\begin{latexonly}
\noindent The expected output is shown in Figure~\ref{fig:three_track_cl2}.
\begin{figure}[htbp]
\centering
\includegraphics[width=\textwidth]{images/three_track_cl2a.png}
\caption{Linear diagram with three tracks for Lactococcus phage Tuc2009
(NC\_002703), bacteriophage bIL285 (AF323668), and prophage 5 from
\textit{Listeria innocua} Clip11262 (NC\_003212) plus cross-links
shaded by percentage identity (see Section~\ref{sec:gd_cross_links}).}
\label{fig:three_track_cl2}
\end{figure}
\end{latexonly}
Beyond that, finishing touches you might want to do manually in a vector
image editor include fine tuning the placement of gene labels, and adding
other custom annotation such as highlighting particular regions.
Although not really necessary in this example since none of the cross-links
overlap, using a transparent color in ReportLab is a very useful technique
for superimposing multiple links. However, in this case a shaded color
scheme should be avoided.
\subsection{Further options}
You can control the tick marks to show the scale -- after all every graph
should show its units, and the number of the grey-track labels.
Also, we have only used the \verb|FeatureSet| so far. GenomeDiagram also has
a \verb|GraphSet| which can be used for show line graphs, bar charts and heat
plots (e.g. to show plots of GC\% on a track parallel to the features).
These options are not covered here yet, so for now we refer you to the
\href{http://biopython.org/DIST/docs/GenomeDiagram/userguide.pdf}
%\href{http://bioinf.scri.ac.uk/lp/downloads/programs/genomediagram/userguide.pdf}
{User Guide (PDF)} included with the standalone version of GenomeDiagram (but
please read the next section first), and the docstrings.
\subsection{Converting old code}
If you have old code written using the standalone version of GenomeDiagram, and
you want to switch it over to using the new version included with Biopython then
you will have to make a few changes - most importantly to your import statements.
Also, the older version of GenomeDiagram used only the UK spellings of color and
center (colour and centre). As part of the integration into Biopython, both
forms can now be used for argument names. However, at some point in the future the
UK spellings may be deprecated.
For example, if you used to have:
\begin{verbatim}
from GenomeDiagram import GDFeatureSet, GDDiagram
gdd = GDDiagram("An example")
...
\end{verbatim}
you could just switch the import statements like this:
\begin{verbatim}
from Bio.Graphics.GenomeDiagram import FeatureSet as GDFeatureSet, Diagram as GDDiagram
gdd = GDDiagram("An example")
...
\end{verbatim}
and hopefully that should be enough. In the long term you might want to
switch to the new names, but you would have to change more of your code:
\begin{verbatim}
from Bio.Graphics.GenomeDiagram import FeatureSet, Diagram
gdd = Diagram("An example")
...
\end{verbatim}
or:
\begin{verbatim}
from Bio.Graphics import GenomeDiagram
gdd = GenomeDiagram.Diagram("An example")
...
\end{verbatim}
If you run into difficulties, please ask on the Biopython mailing list for
advice. One catch is that we have not included the old module
\verb|GenomeDiagram.GDUtilities| yet. This included a number of
GC\% related functions, which will probably be merged under
\verb|Bio.SeqUtils| later on.
%TODO - Deal with GenomeDiagram.GDUtilities
\section{Chromosomes}
The \verb|Bio.Graphics.BasicChromosome| module allows drawing of chromosomes.
There is an example in Jupe \textit{et al.} (2012) \cite{jupe2012}
(open access) using colors to highlight different gene families.
\subsection{Simple Chromosomes}
Here is a very simple example - for which we'll use \textit{Arabidopsis thaliana}.
\begin{latexonly}
\begin{figure}[p]
\centering
\includegraphics[scale=0.45]{images/simple_chrom.pdf}
\caption{Simple chromosome diagram for \textit{Arabidopsis thaliana}.}
\label{fig:simplechromosome}
\end{figure}
\begin{figure}[p]
\centering
\includegraphics[scale=0.45]{images/tRNA_chrom.pdf}
\caption{Chromosome diagram for \textit{Arabidopsis thaliana} showing tRNA genes.}
\label{fig:trnachromosome}
\end{figure}
\end{latexonly}
You can skip this bit, but first I downloaded the five sequenced chromosomes
from the NCBI's FTP site
\url{ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana} and then parsed
them with \verb|Bio.SeqIO| to find out their lengths. You could use the
GenBank files for this, but it is faster to use the FASTA files for the
whole chromosomes:
\begin{verbatim}
from Bio import SeqIO
entries = [("Chr I", "CHR_I/NC_003070.fna"),
("Chr II", "CHR_II/NC_003071.fna"),
("Chr III", "CHR_III/NC_003074.fna"),
("Chr IV", "CHR_IV/NC_003075.fna"),
("Chr V", "CHR_V/NC_003076.fna")]
for (name, filename) in entries:
record = SeqIO.read(filename,"fasta")
print name, len(record)
\end{verbatim}
\noindent This gave the lengths of the five chromosomes, which we'll now use in
the following short demonstration of the \verb|BasicChromosome| module:
\begin{verbatim}
from reportlab.lib.units import cm
from Bio.Graphics import BasicChromosome
entries = [("Chr I", 30432563),
("Chr II", 19705359),
("Chr III", 23470805),
("Chr IV", 18585042),
("Chr V", 26992728)]
max_len = 30432563 #Could compute this
telomere_length = 1000000 #For illustration
chr_diagram = BasicChromosome.Organism()
chr_diagram.page_size = (29.7*cm, 21*cm) #A4 landscape
for name, length in entries:
cur_chromosome = BasicChromosome.Chromosome(name)
#Set the scale to the MAXIMUM length plus the two telomeres in bp,
#want the same scale used on all five chromosomes so they can be
#compared to each other
cur_chromosome.scale_num = max_len + 2 * telomere_length
#Add an opening telomere
start = BasicChromosome.TelomereSegment()
start.scale = telomere_length
cur_chromosome.add(start)
#Add a body - using bp as the scale length here.
body = BasicChromosome.ChromosomeSegment()
body.scale = length
cur_chromosome.add(body)
#Add a closing telomere
end = BasicChromosome.TelomereSegment(inverted=True)
end.scale = telomere_length
cur_chromosome.add(end)
#This chromosome is done
chr_diagram.add(cur_chromosome)
chr_diagram.draw("simple_chrom.pdf", "Arabidopsis thaliana")
\end{verbatim}
This should create a very simple PDF file, shown
\begin{htmlonly}
here:
%The blank lines above and below are important to trigger paragraph breaks
\imgsrc[width=650, height=460]{images/simple_chrom.png}
\end{htmlonly}
\begin{latexonly}
in Figure~\ref{fig:simplechromosome}.
\end{latexonly}
This example is deliberately short and sweet. The next example shows the
location of features of interest.
\subsection{Annotated Chromosomes}
Continuing from the previous example, let's also show the tRNA genes.
We'll get their locations by parsing the GenBank files for the five
\textit{Arabidopsis thaliana} chromosomes. You'll need to download these
files from the NCBI FTP site
\url{ftp://ftp.ncbi.nlm.nih.gov/genomes/Arabidopsis_thaliana},
and preserve the subdirectory names or edit the paths below:
\begin{verbatim}
from reportlab.lib.units import cm
from Bio import SeqIO
from Bio.Graphics import BasicChromosome
entries = [("Chr I", "CHR_I/NC_003070.gbk"),
("Chr II", "CHR_II/NC_003071.gbk"),
("Chr III", "CHR_III/NC_003074.gbk"),
("Chr IV", "CHR_IV/NC_003075.gbk"),
("Chr V", "CHR_V/NC_003076.gbk")]
max_len = 30432563 #Could compute this
telomere_length = 1000000 #For illustration
chr_diagram = BasicChromosome.Organism()
chr_diagram.page_size = (29.7*cm, 21*cm) #A4 landscape
for index, (name, filename) in enumerate(entries):
record = SeqIO.read(filename,"genbank")
length = len(record)
features = [f for f in record.features if f.type=="tRNA"]
#Record an Artemis style integer color in the feature's qualifiers,
#1 = Black, 2 = Red, 3 = Green, 4 = blue, 5 =cyan, 6 = purple
for f in features: f.qualifiers["color"] = [index+2]
cur_chromosome = BasicChromosome.Chromosome(name)
#Set the scale to the MAXIMUM length plus the two telomeres in bp,
#want the same scale used on all five chromosomes so they can be
#compared to each other
cur_chromosome.scale_num = max_len + 2 * telomere_length
#Add an opening telomere
start = BasicChromosome.TelomereSegment()
start.scale = telomere_length
cur_chromosome.add(start)
#Add a body - again using bp as the scale length here.
body = BasicChromosome.AnnotatedChromosomeSegment(length, features)
body.scale = length
cur_chromosome.add(body)
#Add a closing telomere
end = BasicChromosome.TelomereSegment(inverted=True)
end.scale = telomere_length
cur_chromosome.add(end)
#This chromosome is done
chr_diagram.add(cur_chromosome)
chr_diagram.draw("tRNA_chrom.pdf", "Arabidopsis thaliana")
\end{verbatim}
It might warn you about the labels being too close together - have a look
at the forward strand (right hand side) of Chr I, but it should create a
colorful PDF file, shown
\begin{htmlonly}
here:
%The blank lines above and below are important to trigger paragraph breaks
\imgsrc[width=650, height=460]{images/tRNA_chrom.png}
\end{htmlonly}
\begin{latexonly}
in Figure~\ref{fig:simplechromosome}.
\end{latexonly}
\chapter{Cookbook -- Cool things to do with it}
\label{chapter:cookbook}
Biopython now has two collections of ``cookbook'' examples -- this chapter
(which has been included in this tutorial for many years and has gradually
grown), and \url{http://biopython.org/wiki/Category:Cookbook} which is a
user contributed collection on our wiki.
We're trying to encourage Biopython users to contribute their own examples
to the wiki. In addition to helping the community, one direct benefit of
sharing an example like this is that you could also get some feedback on
the code from other Biopython users and developers - which could help you
improve all your Python code.
In the long term, we may end up moving all of the examples in this chapter
to the wiki, or elsewhere within the tutorial.
\section{Working with sequence files}
\label{seq:cookbook-sequences}
This section shows some more examples of sequence input/output, using the
\verb|Bio.SeqIO| module described in Chapter~\ref{chapter:Bio.SeqIO}.
\subsection{Filtering a sequence file}
Often you'll have a large file with many sequences in it (e.g. FASTA file
or genes, or a FASTQ or SFF file of reads), a separate shorter list of
the IDs for a subset of sequences of interest, and want to make a new
sequence file for this subset.
Let's say the list of IDs is in a simple text file, as the first word on
each line. This could be a tabular file where the first column is the ID.
Try something like this:
%not a doctest to avoid temp files being left behind, also no >>>
%makes it easier to copy and paste the example to a script file.
\begin{verbatim}
from Bio import SeqIO
input_file = "big_file.sff"
id_file = "short_list.txt"
output_file = "short_list.sff"
wanted = set(line.rstrip("\n").split(None,1)[0] for line in open(id_file))
print "Found %i unique identifiers in %s" % (len(wanted), id_file)
records = (r for r in SeqIO.parse(input_file, "sff") if r.id in wanted)
count = SeqIO.write(records, output_file, "sff")
print "Saved %i records from %s to %s" % (count, input_file, output_file)
if count < len(wanted):
print "Warning %i IDs not found in %s" % (len(wanted)-count, input_file)
\end{verbatim}
Note that we use a Python \verb|set| rather than a \verb|list|, this makes
testing membership faster.
\subsection{Producing randomised genomes}
Let's suppose you are looking at genome sequence, hunting for some sequence
feature -- maybe extreme local GC\% bias, or possible restriction digest sites.
Once you've got your Python code working on the real genome it may be sensible
to try running the same search on randomised versions of the same genome for
statistical analysis (after all, any ``features'' you've found could just be
there just by chance).
For this discussion, we'll use the GenBank file for the pPCP1 plasmid from
\textit{Yersinia pestis biovar Microtus}. The file is included with the
Biopython unit tests under the GenBank folder, or you can get it from our
website, \href{http://biopython.org/SRC/biopython/Tests/GenBank/NC_005816.gb}
{\texttt{NC\_005816.gb}}.
This file contains one and only one record, so we can read it in as a
\verb|SeqRecord| using the \verb|Bio.SeqIO.read()| function:
%doctest ../Tests/GenBank
\begin{verbatim}
>>> from Bio import SeqIO
>>> original_rec = SeqIO.read("NC_005816.gb","genbank")
\end{verbatim}
So, how can we generate a shuffled versions of the original sequence? I would
use the built in Python \verb|random| module for this, in particular the function
\verb|random.shuffle| -- but this works on a Python list. Our sequence is a
\verb|Seq| object, so in order to shuffle it we need to turn it into a list:
%cont-doctest
\begin{verbatim}
>>> import random
>>> nuc_list = list(original_rec.seq)
>>> random.shuffle(nuc_list) #acts in situ!
\end{verbatim}
Now, in order to use \verb|Bio.SeqIO| to output the shuffled sequence, we need
to construct a new \verb|SeqRecord| with a new \verb|Seq| object using this
shuffled list. In order to do this, we need to turn the list of nucleotides
(single letter strings) into a long string -- the standard Python way to do
this is with the string object's join method.
%cont-doctest
\begin{verbatim}
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord
>>> shuffled_rec = SeqRecord(Seq("".join(nuc_list), original_rec.seq.alphabet),
... id="Shuffled", description="Based on %s" % original_rec.id)
\end{verbatim}
Let's put all these pieces together to make a complete Python script which
generates a single FASTA file containing 30 randomly shuffled versions of
the original sequence.
This first version just uses a big for loop and writes out the records one by one
(using the \verb|SeqRecord|'s format method described in
Section~\ref{sec:Bio.SeqIO-and-StringIO}):
\begin{verbatim}
import random
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
original_rec = SeqIO.read("NC_005816.gb","genbank")
handle = open("shuffled.fasta", "w")
for i in range(30):
nuc_list = list(original_rec.seq)
random.shuffle(nuc_list)
shuffled_rec = SeqRecord(Seq("".join(nuc_list), original_rec.seq.alphabet), \
id="Shuffled%i" % (i+1), \
description="Based on %s" % original_rec.id)
handle.write(shuffled_rec.format("fasta"))
handle.close()
\end{verbatim}
Personally I prefer the following version using a function to shuffle the record
and a generator expression instead of the for loop:
\begin{verbatim}
import random
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio import SeqIO
def make_shuffle_record(record, new_id):
nuc_list = list(record.seq)
random.shuffle(nuc_list)
return SeqRecord(Seq("".join(nuc_list), record.seq.alphabet), \
id=new_id, description="Based on %s" % original_rec.id)
original_rec = SeqIO.read("NC_005816.gb","genbank")
shuffled_recs = (make_shuffle_record(original_rec, "Shuffled%i" % (i+1)) \
for i in range(30))
handle = open("shuffled.fasta", "w")
SeqIO.write(shuffled_recs, handle, "fasta")
handle.close()
\end{verbatim}
\subsection{Translating a FASTA file of CDS entries}
\label{sec:SeqIO-translate}
Suppose you've got an input file of CDS entries for some organism, and you
want to generate a new FASTA file containing their protein sequences. i.e.
Take each nucleotide sequence from the original file, and translate it.
Back in Section~\ref{sec:translation} we saw how to use the \verb|Seq|
object's \verb|translate method|, and the optional \verb|cds| argument
which enables correct translation of alternative start codons.
We can combine this with \verb|Bio.SeqIO| as
shown in the reverse complement example in Section~\ref{sec:SeqIO-reverse-complement}.
The key point is that for each nucleotide \verb|SeqRecord|, we need to create
a protein \verb|SeqRecord| - and take care of naming it.
You can write you own function to do this, choosing suitable protein identifiers
for your sequences, and the appropriate genetic code. In this example we just
use the default table and add a prefix to the identifier:
\begin{verbatim}
from Bio.SeqRecord import SeqRecord
def make_protein_record(nuc_record):
"""Returns a new SeqRecord with the translated sequence (default table)."""
return SeqRecord(seq = nuc_record.seq.translate(cds=True), \
id = "trans_" + nuc_record.id, \
description = "translation of CDS, using default table")
\end{verbatim}
We can then use this function to turn the input nucleotide records into protein
records ready for output. An elegant way and memory efficient way to do this
is with a generator expression:
\begin{verbatim}
from Bio import SeqIO
proteins = (make_protein_record(nuc_rec) for nuc_rec in \
SeqIO.parse("coding_sequences.fasta", "fasta"))
SeqIO.write(proteins, "translations.fasta", "fasta")
\end{verbatim}
This should work on any FASTA file of complete coding sequences.
If you are working on partial coding sequences, you may prefer to use
\verb|nuc_record.seq.translate(to_stop=True)| in the example above, as
this wouldn't check for a valid start codon etc.
\subsection{Making the sequences in a FASTA file upper case}
Often you'll get data from collaborators as FASTA files, and sometimes the
sequences can be in a mixture of upper and lower case. In some cases this is
deliberate (e.g. lower case for poor quality regions), but usually it is not
important. You may want to edit the file to make everything consistent (e.g.
all upper case), and you can do this easily using the \verb|upper()| method
of the \verb|SeqRecord| object (added in Biopython 1.55):
\begin{verbatim}
from Bio import SeqIO
records = (rec.upper() for rec in SeqIO.parse("mixed.fas", "fasta"))
count = SeqIO.write(records, "upper.fas", "fasta")
print "Converted %i records to upper case" % count
\end{verbatim}
How does this work? The first line is just importing the \verb|Bio.SeqIO|
module. The second line is the interesting bit -- this is a Python
generator expression which gives an upper case version of each record
parsed from the input file (\texttt{mixed.fas}). In the third line we give
this generator expression to the \verb|Bio.SeqIO.write()| function and it
saves the new upper cases records to our output file (\texttt{upper.fas}).
The reason we use a generator expression (rather than a list or list
comprehension) is this means only one record is kept in memory at a time.
This can be really important if you are dealing with large files with
millions of entries.
\subsection{Sorting a sequence file}
\label{sec:SeqIO-sort}
Suppose you wanted to sort a sequence file by length (e.g. a set of
contigs from an assembly), and you are working with a file format like
FASTA or FASTQ which \verb|Bio.SeqIO| can read, write (and index).
If the file is small enough, you can load it all into memory at once
as a list of \verb|SeqRecord| objects, sort the list, and save it:
\begin{verbatim}
from Bio import SeqIO
records = list(SeqIO.parse("ls_orchid.fasta","fasta"))
records.sort(cmp=lambda x,y: cmp(len(x),len(y)))
SeqIO.write(records, "sorted_orchids.fasta", "fasta")
\end{verbatim}
The only clever bit is specifying a comparison function for how to
sort the records (here we sort them by length). If you wanted the
longest records first, you could flip the comparison or use the
reverse argument:
\begin{verbatim}
from Bio import SeqIO
records = list(SeqIO.parse("ls_orchid.fasta","fasta"))
records.sort(cmp=lambda x,y: cmp(len(y),len(x)))
SeqIO.write(records, "sorted_orchids.fasta", "fasta")
\end{verbatim}
Now that's pretty straight forward - but what happens if you have a
very large file and you can't load it all into memory like this?
For example, you might have some next-generation sequencing reads
to sort by length. This can be solved using the
\verb|Bio.SeqIO.index()| function.
\begin{verbatim}
from Bio import SeqIO
#Get the lengths and ids, and sort on length
len_and_ids = sorted((len(rec), rec.id) for rec in \
SeqIO.parse("ls_orchid.fasta","fasta"))
ids = reversed([id for (length, id) in len_and_ids])
del len_and_ids #free this memory
record_index = SeqIO.index("ls_orchid.fasta", "fasta")
records = (record_index[id] for id in ids)
SeqIO.write(records, "sorted.fasta", "fasta")
\end{verbatim}
First we scan through the file once using \verb|Bio.SeqIO.parse()|,
recording the record identifiers and their lengths in a list of tuples.
We then sort this list to get them in length order, and discard the lengths.
Using this sorted list of identifiers \verb|Bio.SeqIO.index()| allows us to
retrieve the records one by one, and we pass them to \verb|Bio.SeqIO.write()|
for output.
These examples all use \verb|Bio.SeqIO| to parse the records into
\verb|SeqRecord| objects which are output using \verb|Bio.SeqIO.write()|.
What if you want to sort a file format which \verb|Bio.SeqIO.write()| doesn't
support, like the plain text SwissProt format? Here is an alternative
solution using the \verb|get_raw()| method added to \verb|Bio.SeqIO.index()|
in Biopython 1.54 (see Section~\ref{sec:seqio-index-getraw}).
\begin{verbatim}
from Bio import SeqIO
#Get the lengths and ids, and sort on length
len_and_ids = sorted((len(rec), rec.id) for rec in \
SeqIO.parse("ls_orchid.fasta","fasta"))
ids = reversed([id for (length, id) in len_and_ids])
del len_and_ids #free this memory
record_index = SeqIO.index("ls_orchid.fasta", "fasta")
handle = open("sorted.fasta", "w")
for id in ids:
handle.write(record_index.get_raw(id))
handle.close()
\end{verbatim}
As a bonus, because it doesn't parse the data into \verb|SeqRecord| objects
a second time it should be faster.
\subsection{Simple quality filtering for FASTQ files}
\label{sec:FASTQ-filtering-example}
The FASTQ file format was introduced at Sanger and is now widely used for
holding nucleotide sequencing reads together with their quality scores.
FASTQ files (and the related QUAL files) are an excellent example of
per-letter-annotation, because for each nucleotide in the sequence there is
an associated quality score. Any per-letter-annotation is held in a
\verb|SeqRecord| in the \verb|letter_annotations| dictionary as a list,
tuple or string (with the same number of elements as the sequence length).
One common task is taking a large set of sequencing reads and filtering them
(or cropping them) based on their quality scores.
The following example is very simplistic, but should illustrate the basics of
working with quality data in a \verb|SeqRecord| object. All we are going to
do here is read in a file of FASTQ data, and filter it to pick out only those
records whose PHRED quality scores are all above some threshold (here 20).
For this example we'll use some real data downloaded from the ENA sequence
read archive,
\url{ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz}
(2MB) which unzips to a 19MB file \texttt{SRR020192.fastq}. This is some
Roche 454 GS FLX single end data from virus infected California sea lions
(see \url{http://www.ebi.ac.uk/ena/data/view/SRS004476} for details).
First, let's count the reads:
\begin{verbatim}
from Bio import SeqIO
count = 0
for rec in SeqIO.parse("SRR020192.fastq", "fastq"):
count += 1
print "%i reads" % count
\end{verbatim}
\noindent Now let's do a simple filtering for a minimum PHRED quality of 20:
\begin{verbatim}
from Bio import SeqIO
good_reads = (rec for rec in \
SeqIO.parse("SRR020192.fastq", "fastq") \
if min(rec.letter_annotations["phred_quality"]) >= 20)
count = SeqIO.write(good_reads, "good_quality.fastq", "fastq")
print "Saved %i reads" % count
\end{verbatim}
\noindent This pulled out only $14580$ reads out of the $41892$ present.
A more sensible thing to do would be to quality trim the reads, but this
is intended as an example only.
FASTQ files can contain millions of entries, so it is best to avoid loading
them all into memory at once. This example uses a generator expression, which
means only one \verb|SeqRecord| is created at a time - avoiding any memory
limitations.
\subsection{Trimming off primer sequences}
\label{sec:FASTQ-slicing-off-primer}
For this example we're going to pretend that \texttt{GATGACGGTGT} is a 5' primer
sequence we want to look for in some FASTQ formatted read data. As in the example
above, we'll use the \texttt{SRR020192.fastq} file downloaded from the ENA
(\url{ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz}).
The same approach would work with any other supported file format (e.g. FASTA files).
This code uses \verb|Bio.SeqIO| with a generator expression (to avoid loading
all the sequences into memory at once), and the \verb|Seq| object's
\verb|startswith| method to see if the read starts with the primer sequence:
\begin{verbatim}
from Bio import SeqIO
primer_reads = (rec for rec in \
SeqIO.parse("SRR020192.fastq", "fastq") \
if rec.seq.startswith("GATGACGGTGT"))
count = SeqIO.write(primer_reads, "with_primer.fastq", "fastq")
print "Saved %i reads" % count
\end{verbatim}
\noindent That should find $13819$ reads from \texttt{SRR014849.fastq} and save them to
a new FASTQ file, \texttt{with\_primer.fastq}.
Now suppose that instead you wanted to make a FASTQ file containing these reads
but with the primer sequence removed? That's just a small change as we can slice the
\verb|SeqRecord| (see Section~\ref{sec:SeqRecord-slicing}) to remove the first eleven
letters (the length of our primer):
\begin{verbatim}
from Bio import SeqIO
trimmed_primer_reads = (rec[11:] for rec in \
SeqIO.parse("SRR020192.fastq", "fastq") \
if rec.seq.startswith("GATGACGGTGT"))
count = SeqIO.write(trimmed_primer_reads, "with_primer_trimmed.fastq", "fastq")
print "Saved %i reads" % count
\end{verbatim}
\noindent Again, that should pull out the $13819$ reads from \texttt{SRR020192.fastq},
but this time strip off the first ten characters, and save them to another new
FASTQ file, \texttt{with\_primer\_trimmed.fastq}.
Finally, suppose you want to create a new FASTQ file where these reads have
their primer removed, but all the other reads are kept as they were?
If we want to still use a generator expression, it is probably clearest to
define our own trim function:
\begin{verbatim}
from Bio import SeqIO
def trim_primer(record, primer):
if record.seq.startswith(primer):
return record[len(primer):]
else:
return record
trimmed_reads = (trim_primer(record, "GATGACGGTGT") for record in \
SeqIO.parse("SRR020192.fastq", "fastq"))
count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq")
print "Saved %i reads" % count
\end{verbatim}
This takes longer, as this time the output file contains all $41892$ reads.
Again, we're used a generator expression to avoid any memory problems.
You could alternatively use a generator function rather than a generator
expression.
\begin{verbatim}
from Bio import SeqIO
def trim_primers(records, primer):
"""Removes perfect primer sequences at start of reads.
This is a generator function, the records argument should
be a list or iterator returning SeqRecord objects.
"""
len_primer = len(primer) #cache this for later
for record in records:
if record.seq.startswith(primer):
yield record[len_primer:]
else:
yield record
original_reads = SeqIO.parse("SRR020192.fastq", "fastq")
trimmed_reads = trim_primers(original_reads, "GATGACGGTGT")
count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq")
print "Saved %i reads" % count
\end{verbatim}
This form is more flexible if you want to do something more complicated
where only some of the records are retained -- as shown in the next example.
\subsection{Trimming off adaptor sequences}
\label{sec:FASTQ-slicing-off-adaptor}
This is essentially a simple extension to the previous example. We are going
to going to pretend \texttt{GATGACGGTGT} is an adaptor sequence in some FASTQ
formatted read data, again the \texttt{SRR020192.fastq} file from the NCBI
(\url{ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz}).
This time however, we will look for the sequence \emph{anywhere} in the reads,
not just at the very beginning:
\begin{verbatim}
from Bio import SeqIO
def trim_adaptors(records, adaptor):
"""Trims perfect adaptor sequences.
This is a generator function, the records argument should
be a list or iterator returning SeqRecord objects.
"""
len_adaptor = len(adaptor) #cache this for later
for record in records:
index = record.seq.find(adaptor)
if index == -1:
#adaptor not found, so won't trim
yield record
else:
#trim off the adaptor
yield record[index+len_adaptor:]
original_reads = SeqIO.parse("SRR020192.fastq", "fastq")
trimmed_reads = trim_adaptors(original_reads, "GATGACGGTGT")
count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq")
print "Saved %i reads" % count
\end{verbatim}
Because we are using a FASTQ input file in this example, the \verb|SeqRecord|
objects have per-letter-annotation for the quality scores. By slicing the
\verb|SeqRecord| object the appropriate scores are used on the trimmed
records, so we can output them as a FASTQ file too.
Compared to the output of the previous example where we only looked for
a primer/adaptor at the start of each read, you may find some of the
trimmed reads are quite short after trimming (e.g. if the adaptor was
found in the middle rather than near the start). So, let's add a minimum
length requirement as well:
\begin{verbatim}
from Bio import SeqIO
def trim_adaptors(records, adaptor, min_len):
"""Trims perfect adaptor sequences, checks read length.
This is a generator function, the records argument should
be a list or iterator returning SeqRecord objects.
"""
len_adaptor = len(adaptor) #cache this for later
for record in records:
len_record = len(record) #cache this for later
if len(record) < min_len:
#Too short to keep
continue
index = record.seq.find(adaptor)
if index == -1:
#adaptor not found, so won't trim
yield record
elif len_record - index - len_adaptor >= min_len:
#after trimming this will still be long enough
yield record[index+len_adaptor:]
original_reads = SeqIO.parse("SRR020192.fastq", "fastq")
trimmed_reads = trim_adaptors(original_reads, "GATGACGGTGT", 100)
count = SeqIO.write(trimmed_reads, "trimmed.fastq", "fastq")
print "Saved %i reads" % count
\end{verbatim}
By changing the format names, you could apply this to FASTA files instead.
This code also could be extended to do a fuzzy match instead of an exact
match (maybe using a pairwise alignment, or taking into account the read
quality scores), but that will be much slower.
\subsection{Converting FASTQ files}
\label{sec:SeqIO-fastq-conversion}
Back in Section~\ref{sec:SeqIO-conversion} we showed how to use
\verb|Bio.SeqIO| to convert between two file formats. Here we'll go into a
little more detail regarding FASTQ files which are used in second generation
DNA sequencing. Please refer to Cock \textit{et al.} (2009) \cite{cock2010}
for a longer description. FASTQ files store both the DNA sequence (as a string)
and the associated read qualities.
PHRED scores (used in most FASTQ files, and also in QUAL files, ACE files
and SFF files) have become a \textit{de facto} standard for representing
the probability of a sequencing error (here denoted by $P_e$) at a given
base using a simple base ten log transformation:
\begin{equation}
Q_{\textrm{PHRED}} = - 10 \times \textrm{log}_{10} ( P_e )
\end{equation}
This means a wrong read ($P_e = 1$) gets a PHRED quality of $0$, while a very
good read like $P_e = 0.00001$ gets a PHRED quality of $50$. While for raw
sequencing data qualities higher than this are rare, with post processing
such as read mapping or assembly, qualities of up to about $90$ are possible
(indeed, the MAQ tool allows for PHRED scores in the range 0 to 93 inclusive).
The FASTQ format has the potential to become a \textit{de facto} standard for
storing the letters and quality scores for a sequencing read in a single plain
text file. The only fly in the ointment is that there are at least three
versions of the FASTQ format which are incompatible and difficult to
distinguish...
\begin{enumerate}
\item The original Sanger FASTQ format uses PHRED qualities encoded with an
ASCII offset of 33. The NCBI are using this format in their Short Read
Archive. We call this the \texttt{fastq} (or \texttt{fastq-sanger}) format
in \verb|Bio.SeqIO|.
\item Solexa (later bought by Illumina) introduced their own version using
Solexa qualities encoded with an ASCII offset of 64. We call this the
\texttt{fastq-solexa} format.
\item Illumina pipeline 1.3 onwards produces FASTQ files with PHRED qualities
(which is more consistent), but encoded with an ASCII offset of 64. We call
this the \texttt{fastq-illumina} format.
\end{enumerate}
The Solexa quality scores are defined using a different log transformation:
\begin{equation}
Q_{\textrm{Solexa}} = - 10 \times \textrm{log}_{10} \left( \frac{P_e}{1-P_e} \right)
\end{equation}
Given Solexa/Illumina have now moved to using PHRED scores in version 1.3 of
their pipeline, the Solexa quality scores will gradually fall out of use.
If you equate the error estimates ($P_e$) these two equations allow conversion
between the two scoring systems - and Biopython includes functions to do this
in the \verb|Bio.SeqIO.QualityIO| module, which are called if you use
\verb|Bio.SeqIO| to convert an old Solexa/Illumina file into a standard Sanger
FASTQ file:
\begin{verbatim}
from Bio import SeqIO
SeqIO.convert("solexa.fastq", "fastq-solexa", "standard.fastq", "fastq")
\end{verbatim}
If you want to convert a new Illumina 1.3+ FASTQ file, all that gets changed
is the ASCII offset because although encoded differently the scores are all
PHRED qualities:
\begin{verbatim}
from Bio import SeqIO
SeqIO.convert("illumina.fastq", "fastq-illumina", "standard.fastq", "fastq")
\end{verbatim}
Note that using \verb|Bio.SeqIO.convert()| like this is \emph{much} faster
than combining \verb|Bio.SeqIO.parse()| and \verb|Bio.SeqIO.write()|
because optimised code is used for converting between FASTQ variants
(and also for FASTQ to FASTA conversion).
For good quality reads, PHRED and Solexa scores are approximately equal,
which means since both the \texttt{fasta-solexa} and \texttt{fastq-illumina}
formats use an ASCII offset of 64 the files are almost the same. This was a
deliberate design choice by Illumina, meaning applications expecting the old
\texttt{fasta-solexa} style files will probably be OK using the newer
\texttt{fastq-illumina} files (on good data). Of course, both variants are
very different from the original FASTQ standard as used by Sanger,
the NCBI, and elsewhere (format name \texttt{fastq} or \texttt{fastq-sanger}).
For more details, see the built in help (also \href{http://www.biopython.org/DIST/docs/api/Bio.SeqIO.QualityIO-module.html}{online}):
\begin{verbatim}
>>> from Bio.SeqIO import QualityIO
>>> help(QualityIO)
...
\end{verbatim}
\subsection{Converting FASTA and QUAL files into FASTQ files}
\label{sec:SeqIO-fasta-qual-conversion}
FASTQ files hold \emph{both} sequences and their quality strings.
FASTA files hold \emph{just} sequences, while QUAL files hold \emph{just}
the qualities. Therefore a single FASTQ file can be converted to or from
\emph{paired} FASTA and QUAL files.
Going from FASTQ to FASTA is easy:
\begin{verbatim}
from Bio import SeqIO
SeqIO.convert("example.fastq", "fastq", "example.fasta", "fasta")
\end{verbatim}
Going from FASTQ to QUAL is also easy:
\begin{verbatim}
from Bio import SeqIO
SeqIO.convert("example.fastq", "fastq", "example.qual", "qual")
\end{verbatim}
However, the reverse is a little more tricky. You can use \verb|Bio.SeqIO.parse()|
to iterate over the records in a \emph{single} file, but in this case we have
two input files. There are several strategies possible, but assuming that the
two files are really paired the most memory efficient way is to loop over both
together. The code is a little fiddly, so we provide a function called
\verb|PairedFastaQualIterator| in the \verb|Bio.SeqIO.QualityIO| module to do
this. This takes two handles (the FASTA file and the QUAL file) and returns
a \verb|SeqRecord| iterator:
\begin{verbatim}
from Bio.SeqIO.QualityIO import PairedFastaQualIterator
for record in PairedFastaQualIterator(open("example.fasta"), open("example.qual")):
print record
\end{verbatim}
This function will check that the FASTA and QUAL files are consistent (e.g.
the records are in the same order, and have the same sequence length).
You can combine this with the \verb|Bio.SeqIO.write()| function to convert a
pair of FASTA and QUAL files into a single FASTQ files:
\begin{verbatim}
from Bio import SeqIO
from Bio.SeqIO.QualityIO import PairedFastaQualIterator
handle = open("temp.fastq", "w") #w=write
records = PairedFastaQualIterator(open("example.fasta"), open("example.qual"))
count = SeqIO.write(records, handle, "fastq")
handle.close()
print "Converted %i records" % count
\end{verbatim}
\subsection{Indexing a FASTQ file}
\label{sec:fastq-indexing}
FASTQ files are often very large, with millions of reads in them. Due to the
sheer amount of data, you can't load all the records into memory at once.
This is why the examples above (filtering and trimming) iterate over the file
looking at just one \verb|SeqRecord| at a time.
However, sometimes you can't use a big loop or an iterator - you may need
random access to the reads. Here the \verb|Bio.SeqIO.index()| function
may prove very helpful, as it allows you to access any read in the FASTQ file
by its name (see Section~\ref{sec:SeqIO-index}).
Again we'll use the \texttt{SRR020192.fastq} file from the ENA
(\url{ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR020/SRR020192/SRR020192.fastq.gz}),
although this is actually quite a small FASTQ file with less than $50,000$ reads:
\begin{verbatim}
>>> from Bio import SeqIO
>>> fq_dict = SeqIO.index("SRR020192.fastq", "fastq")
>>> len(fq_dict)
41892
>>> fq_dict.keys()[:4]
['SRR020192.38240', 'SRR020192.23181', 'SRR020192.40568', 'SRR020192.23186']
>>> fq_dict["SRR020192.23186"].seq
Seq('GTCCCAGTATTCGGATTTGTCTGCCAAAACAATGAAATTGACACAGTTTACAAC...CCG', SingleLetterAlphabet())
\end{verbatim}
When testing this on a FASTQ file with seven million reads,
indexing took about a minute, but record access was almost instant.
The example in Section~\ref{sec:SeqIO-sort} show how you can use the
\verb|Bio.SeqIO.index()| function to sort a large FASTA file -- this
could also be used on FASTQ files.
\subsection{Converting SFF files}
\label{sec:SeqIO-sff-conversion}
If you work with 454 (Roche) sequence data, you will probably have access
to the raw data as a Standard Flowgram Format (SFF) file. This contains
the sequence reads (called bases) with quality scores and the original
flow information.
A common task is to convert from SFF to a pair of FASTA and QUAL files,
or to a single FASTQ file. These operations are trivial using the
\verb|Bio.SeqIO.convert()| function (see Section~\ref{sec:SeqIO-conversion}):
\begin{verbatim}
>>> from Bio import SeqIO
>>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff", "reads.fasta", "fasta")
10
>>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff", "reads.qual", "qual")
10
>>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff", "reads.fastq", "fastq")
10
\end{verbatim}
\noindent Remember the convert function returns the number of records, in
this example just ten. This will give you the \emph{untrimmed} reads, where
the leading and trailing poor quality sequence or adaptor will be in lower
case. If you want the \emph{trimmed} reads (using the clipping information
recorded within the SFF file) use this:
\begin{verbatim}
>>> from Bio import SeqIO
>>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff-trim", "trimmed.fasta", "fasta")
10
>>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff-trim", "trimmed.qual", "qual")
10
>>> SeqIO.convert("E3MFGYR02_random_10_reads.sff", "sff-trim", "trimmed.fastq", "fastq")
10
\end{verbatim}
If you run Linux, you could ask Roche for a copy of their ``off instrument''
tools (often referred to as the Newbler tools). This offers an alternative way to
do SFF to FASTA or QUAL conversion at the command line (but currently FASTQ output
is not supported), e.g.
\begin{verbatim}
$ sffinfo -seq -notrim E3MFGYR02_random_10_reads.sff > reads.fasta
$ sffinfo -qual -notrim E3MFGYR02_random_10_reads.sff > reads.qual
$ sffinfo -seq -trim E3MFGYR02_random_10_reads.sff > trimmed.fasta
$ sffinfo -qual -trim E3MFGYR02_random_10_reads.sff > trimmed.qual
\end{verbatim}
\noindent The way Biopython uses mixed case sequence strings to represent
the trimming points deliberately mimics what the Roche tools do.
For more information on the Biopython SFF support, consult the built in help:
\begin{verbatim}
>>> from Bio.SeqIO import SffIO
>>> help(SffIO)
...
\end{verbatim}
\subsection{Identifying open reading frames}
A very simplistic first step at identifying possible genes is to look for
open reading frames (ORFs). By this we mean look in all six frames for long
regions without stop codons -- an ORF is just a region of nucleotides with
no in frame stop codons.
Of course, to find a gene you would also need to worry about locating a start
codon, possible promoters -- and in Eukaryotes there are introns to worry about
too. However, this approach is still useful in viruses and Prokaryotes.
To show how you might approach this with Biopython, we'll need a sequence to
search, and as an example we'll again use the bacterial plasmid -- although
this time we'll start with a plain FASTA file with no pre-marked genes:
\href{http://biopython.org/SRC/biopython/Tests/GenBank/NC_005816.fna}
{\texttt{NC\_005816.fna}}. This is a bacterial sequence, so we'll want to use
NCBI codon table 11 (see Section~\ref{sec:translation} about translation).
%doctest ../Tests/GenBank
\begin{verbatim}
>>> from Bio import SeqIO
>>> record = SeqIO.read("NC_005816.fna","fasta")
>>> table = 11
>>> min_pro_len = 100
\end{verbatim}
Here is a neat trick using the \verb|Seq| object's \verb|split| method to
get a list of all the possible ORF translations in the six reading frames:
%cont-doctest
\begin{verbatim}
>>> for strand, nuc in [(+1, record.seq), (-1, record.seq.reverse_complement())]:
... for frame in range(3):
... length = 3 * ((len(record)-frame) // 3) #Multiple of three
... for pro in nuc[frame:frame+length].translate(table).split("*"):
... if len(pro) >= min_pro_len:
... print "%s...%s - length %i, strand %i, frame %i" \
... % (pro[:30], pro[-3:], len(pro), strand, frame)
GCLMKKSSIVATIITILSGSANAASSQLIP...YRF - length 315, strand 1, frame 0
KSGELRQTPPASSTLHLRLILQRSGVMMEL...NPE - length 285, strand 1, frame 1
GLNCSFFSICNWKFIDYINRLFQIIYLCKN...YYH - length 176, strand 1, frame 1
VKKILYIKALFLCTVIKLRRFIFSVNNMKF...DLP - length 165, strand 1, frame 1
NQIQGVICSPDSGEFMVTFETVMEIKILHK...GVA - length 355, strand 1, frame 2
RRKEHVSKKRRPQKRPRRRRFFHRLRPPDE...PTR - length 128, strand 1, frame 2
TGKQNSCQMSAIWQLRQNTATKTRQNRARI...AIK - length 100, strand 1, frame 2
QGSGYAFPHASILSGIAMSHFYFLVLHAVK...CSD - length 114, strand -1, frame 0
IYSTSEHTGEQVMRTLDEVIASRSPESQTR...FHV - length 111, strand -1, frame 0
WGKLQVIGLSMWMVLFSQRFDDWLNEQEDA...ESK - length 125, strand -1, frame 1
RGIFMSDTMVVNGSGGVPAFLFSGSTLSSY...LLK - length 361, strand -1, frame 1
WDVKTVTGVLHHPFHLTFSLCPEGATQSGR...VKR - length 111, strand -1, frame 1
LSHTVTDFTDQMAQVGLCQCVNVFLDEVTG...KAA - length 107, strand -1, frame 2
RALTGLSAPGIRSQTSCDRLRELRYVPVSL...PLQ - length 119, strand -1, frame 2
\end{verbatim}
Note that here we are counting the frames from the 5' end (start) of
\emph{each} strand. It is sometimes easier to always count from the 5' end
(start) of the \emph{forward} strand.
You could easily edit the above loop based code to build up a list of the
candidate proteins, or convert this to a list comprehension. Now, one thing
this code doesn't do is keep track of where the proteins are.
You could tackle this in several ways. For example, the following code tracks
the locations in terms of the protein counting, and converts back to the
parent sequence by multiplying by three, then adjusting for the frame and
strand:
\begin{verbatim}
from Bio import SeqIO
record = SeqIO.read("NC_005816.gb","genbank")
table = 11
min_pro_len = 100
def find_orfs_with_trans(seq, trans_table, min_protein_length):
answer = []
seq_len = len(seq)
for strand, nuc in [(+1, seq), (-1, seq.reverse_complement())]:
for frame in range(3):
trans = str(nuc[frame:].translate(trans_table))
trans_len = len(trans)
aa_start = 0
aa_end = 0
while aa_start < trans_len:
aa_end = trans.find("*", aa_start)
if aa_end == -1:
aa_end = trans_len
if aa_end-aa_start >= min_protein_length:
if strand == 1:
start = frame+aa_start*3
end = min(seq_len,frame+aa_end*3+3)
else:
start = seq_len-frame-aa_end*3-3
end = seq_len-frame-aa_start*3
answer.append((start, end, strand,
trans[aa_start:aa_end]))
aa_start = aa_end+1
answer.sort()
return answer
orf_list = find_orfs_with_trans(record.seq, table, min_pro_len)
for start, end, strand, pro in orf_list:
print "%s...%s - length %i, strand %i, %i:%i" \
% (pro[:30], pro[-3:], len(pro), strand, start, end)
\end{verbatim}
\noindent And the output:
\begin{verbatim}
NQIQGVICSPDSGEFMVTFETVMEIKILHK...GVA - length 355, strand 1, 41:1109
WDVKTVTGVLHHPFHLTFSLCPEGATQSGR...VKR - length 111, strand -1, 491:827
KSGELRQTPPASSTLHLRLILQRSGVMMEL...NPE - length 285, strand 1, 1030:1888
RALTGLSAPGIRSQTSCDRLRELRYVPVSL...PLQ - length 119, strand -1, 2830:3190
RRKEHVSKKRRPQKRPRRRRFFHRLRPPDE...PTR - length 128, strand 1, 3470:3857
GLNCSFFSICNWKFIDYINRLFQIIYLCKN...YYH - length 176, strand 1, 4249:4780
RGIFMSDTMVVNGSGGVPAFLFSGSTLSSY...LLK - length 361, strand -1, 4814:5900
VKKILYIKALFLCTVIKLRRFIFSVNNMKF...DLP - length 165, strand 1, 5923:6421
LSHTVTDFTDQMAQVGLCQCVNVFLDEVTG...KAA - length 107, strand -1, 5974:6298
GCLMKKSSIVATIITILSGSANAASSQLIP...YRF - length 315, strand 1, 6654:7602
IYSTSEHTGEQVMRTLDEVIASRSPESQTR...FHV - length 111, strand -1, 7788:8124
WGKLQVIGLSMWMVLFSQRFDDWLNEQEDA...ESK - length 125, strand -1, 8087:8465
TGKQNSCQMSAIWQLRQNTATKTRQNRARI...AIK - length 100, strand 1, 8741:9044
QGSGYAFPHASILSGIAMSHFYFLVLHAVK...CSD - length 114, strand -1, 9264:9609
\end{verbatim}
If you comment out the sort statement, then the protein sequences will be
shown in the same order as before, so you can check this is doing the same
thing. Here we have sorted them by location to make it easier to compare
to the actual annotation in the GenBank file (as visualised in
Section~\ref{sec:gd_nice_example}).
If however all you want to find are the locations of the open reading frames,
then it is a waste of time to translate every possible codon, including doing
the reverse complement to search the reverse strand too. All you need to do
is search for the possible stop codons (and their reverse complements). Using
regular expressions is an obvious approach here (see the Python module
\verb|re|). These are an extremely powerful (but rather complex) way of
describing search strings, which are supported in lots of programming
languages and also command line tools like \texttt{grep} as well). You can
find whole books about this topic!
\section{Sequence parsing plus simple plots}
\label{seq:sequence-parsing-plus-pylab}
This section shows some more examples of sequence parsing, using the \verb|Bio.SeqIO|
module described in Chapter~\ref{chapter:Bio.SeqIO}, plus the Python library matplotlib's \verb|pylab| plotting interface (see \href{http://matplotlib.sourceforge.net/}{the matplotlib website for a tutorial}). Note that to follow these examples you will need matplotlib installed - but without it you can still try the data parsing bits.
\subsection{Histogram of sequence lengths}
There are lots of times when you might want to visualise the distribution of sequence
lengths in a dataset -- for example the range of contig sizes in a genome assembly
project. In this example we'll reuse our orchid FASTA file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{\tt ls\_orchid.fasta} which has only 94 sequences.
First of all, we will use \verb|Bio.SeqIO| to parse the FASTA file and compile a list
of all the sequence lengths. You could do this with a for loop, but I find a list
comprehension more pleasing:
\begin{verbatim}
>>> from Bio import SeqIO
>>> sizes = [len(rec) for rec in SeqIO.parse("ls_orchid.fasta", "fasta")]
>>> len(sizes), min(sizes), max(sizes)
(94, 572, 789)
>>> sizes
[740, 753, 748, 744, 733, 718, 730, 704, 740, 709, 700, 726, ..., 592]
\end{verbatim}
Now that we have the lengths of all the genes (as a list of integers), we can use the
matplotlib histogram function to display it.
\begin{verbatim}
from Bio import SeqIO
sizes = [len(rec) for rec in SeqIO.parse("ls_orchid.fasta", "fasta")]
import pylab
pylab.hist(sizes, bins=20)
pylab.title("%i orchid sequences\nLengths %i to %i" \
% (len(sizes),min(sizes),max(sizes)))
pylab.xlabel("Sequence length (bp)")
pylab.ylabel("Count")
pylab.show()
\end{verbatim}
%
% Have a HTML version and a PDF version to display nicely...
%
\begin{htmlonly}
\noindent That should pop up a new window containing the following graph:
\imgsrc[width=600, height=450]{images/hist_plot.png}
\end{htmlonly}
%
% Now the PDF equivalent where we cannot always expect the figure
% to be positioned right next to the text, so will use a reference.
%
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/hist_plot.png}
\caption{Histogram of orchid sequence lengths.}
\label{fig:seq-len-hist}
\end{figure}
\noindent That should pop up a new window containing the graph
shown in Figure~\ref{fig:seq-len-hist}.
\end{latexonly}
%
% The text now continues...
%
Notice that most of these orchid sequences are about $740$ bp long, and there could be
two distinct classes of sequence here with a subset of shorter sequences.
\emph{Tip:} Rather than using \verb|pylab.show()| to show the plot in a window, you can also use \verb|pylab.savefig(...)| to save the figure to a file (e.g. as a PNG or PDF).
\subsection{Plot of sequence GC\%}
Another easily calculated quantity of a nucleotide sequence is the GC\%. You might
want to look at the GC\% of all the genes in a bacterial genome for example, and
investigate any outliers which could have been recently acquired by horizontal gene
transfer. Again, for this example we'll reuse our orchid FASTA file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{\tt ls\_orchid.fasta}.
First of all, we will use \verb|Bio.SeqIO| to parse the FASTA file and compile a list
of all the GC percentages. Again, you could do this with a for loop, but I prefer this:
\begin{verbatim}
from Bio import SeqIO
from Bio.SeqUtils import GC
gc_values = sorted(GC(rec.seq) for rec in SeqIO.parse("ls_orchid.fasta", "fasta"))
\end{verbatim}
Having read in each sequence and calculated the GC\%, we then sorted them into ascending
order. Now we'll take this list of floating point values and plot them with matplotlib:
\begin{verbatim}
import pylab
pylab.plot(gc_values)
pylab.title("%i orchid sequences\nGC%% %0.1f to %0.1f" \
% (len(gc_values),min(gc_values),max(gc_values)))
pylab.xlabel("Genes")
pylab.ylabel("GC%")
pylab.show()
\end{verbatim}
%
% Have an HTML version and a PDF version to display nicely...
%
\begin{htmlonly}
\noindent As in the previous example, that should pop up a new window containing a graph:
\imgsrc[width=600, height=450]{images/gc_plot.png}
\end{htmlonly}
%
% Now the PDF equivalent where we cannot always expect the figure
% to be positioned right next to the text, so we'll use a reference.
%
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/gc_plot.png}
\caption{Histogram of orchid sequence lengths.}
\label{fig:seq-gc-plot}
\end{figure}
\noindent As in the previous example, that should pop up a new window with the graph shown in Figure~\ref{fig:seq-gc-plot}.
\end{latexonly}
%
% The text now continues...
%
If you tried this on the full set of genes from one organism, you'd probably get a much
smoother plot than this.
\subsection{Nucleotide dot plots}
A dot plot is a way of visually comparing two nucleotide sequences for similarity to
each other. A sliding window is used to compare short sub-sequences to each other,
often with a mis-match threshold. Here for simplicity we'll only look for perfect
matches (shown in black
\begin{latexonly}
in Figure~\ref{fig:nuc-dot-plot}).
\end{latexonly}
\begin{htmlonly}
in the plot below).
\end{htmlonly}
%
% Now the PDF equivalent where we cannot always expect the figure
% to be positioned right next to the text, so we'll use a reference.
%
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/dot_plot.png}
\caption{Nucleotide dot plot of two orchid sequence lengths (using pylab's imshow function).}
\label{fig:nuc-dot-plot}
\end{figure}
\end{latexonly}
To start off, we'll need two sequences. For the sake of argument, we'll just take
the first two from our orchid FASTA file \href{http://biopython.org/DIST/docs/tutorial/examples/ls_orchid.fasta}{\tt ls\_orchid.fasta}:
\begin{verbatim}
from Bio import SeqIO
handle = open("ls_orchid.fasta")
record_iterator = SeqIO.parse(handle, "fasta")
rec_one = record_iterator.next()
rec_two = record_iterator.next()
handle.close()
\end{verbatim}
We're going to show two approaches. Firstly, a simple naive implementation
which compares all the window sized sub-sequences to each other to compiles a
similarity matrix. You could construct a matrix or array object, but here we
just use a list of lists of booleans created with a nested list
comprehension:
\begin{verbatim}
window = 7
seq_one = str(rec_one.seq).upper()
seq_two = str(rec_two.seq).upper()
data = [[(seq_one[i:i+window] <> seq_two[j:j+window]) \
for j in range(len(seq_one)-window)] \
for i in range(len(seq_two)-window)]
\end{verbatim}
Note that we have \emph{not} checked for reverse complement matches here.
Now we'll use the matplotlib's \verb|pylab.imshow()| function to display this
data, first requesting the gray color scheme so this is done in black and
white:
\begin{verbatim}
import pylab
pylab.gray()
pylab.imshow(data)
pylab.xlabel("%s (length %i bp)" % (rec_one.id, len(rec_one)))
pylab.ylabel("%s (length %i bp)" % (rec_two.id, len(rec_two)))
pylab.title("Dot plot using window size %i\n(allowing no mis-matches)" % window)
pylab.show()
\end{verbatim}
%pylab.savefig("dot_plot.png", dpi=75)
%pylab.savefig("dot_plot.pdf")
%
% Have a HTML version and a PDF version to display nicely...
%
\begin{htmlonly}
\noindent That should pop up a new window containing a graph like this:
\imgsrc[width=600, height=450]{images/dot_plot.png}
\end{htmlonly}
\begin{latexonly}
\noindent That should pop up a new window showing the graph in Figure~\ref{fig:nuc-dot-plot}.
\end{latexonly}
%
% The text now continues...
%
As you might have expected, these two sequences are very similar with a
partial line of window sized matches along the diagonal. There are no off
diagonal matches which would be indicative of inversions or other interesting
events.
The above code works fine on small examples, but there are two problems
applying this to larger sequences, which we will address below.
First off all, this brute force approach to the all against all comparisons
is very slow. Instead, we'll compile dictionaries mapping the window sized
sub-sequences to their locations, and then take the set intersection to find
those sub-sequences found in both sequences. This uses more memory, but is
\emph{much} faster. Secondly, the \verb|pylab.imshow()| function is limited
in the size of matrix it can display. As an alternative, we'll use the
\verb|pylab.scatter()| function.
We start by creating dictionaries mapping the window-sized sub-sequences to locations:
\begin{verbatim}
window = 7
dict_one = {}
dict_two = {}
for (seq, section_dict) in [(str(rec_one.seq).upper(), dict_one),
(str(rec_two.seq).upper(), dict_two)]:
for i in range(len(seq)-window):
section = seq[i:i+window]
try:
section_dict[section].append(i)
except KeyError:
section_dict[section] = [i]
#Now find any sub-sequences found in both sequences
#(Python 2.3 would require slightly different code here)
matches = set(dict_one).intersection(dict_two)
print "%i unique matches" % len(matches)
\end{verbatim}
\noindent In order to use the \verb|pylab.scatter()| we need separate lists for the $x$ and $y$ co-ordinates:
\begin{verbatim}
#Create lists of x and y co-ordinates for scatter plot
x = []
y = []
for section in matches:
for i in dict_one[section]:
for j in dict_two[section]:
x.append(i)
y.append(j)
\end{verbatim}
\noindent We are now ready to draw the revised dot plot as a scatter plot:
\begin{verbatim}
import pylab
pylab.cla() #clear any prior graph
pylab.gray()
pylab.scatter(x,y)
pylab.xlim(0, len(rec_one)-window)
pylab.ylim(0, len(rec_two)-window)
pylab.xlabel("%s (length %i bp)" % (rec_one.id, len(rec_one)))
pylab.ylabel("%s (length %i bp)" % (rec_two.id, len(rec_two)))
pylab.title("Dot plot using window size %i\n(allowing no mis-matches)" % window)
pylab.show()
\end{verbatim}
%pylab.savefig("dot_plot.png", dpi=75)
%pylab.savefig("dot_plot.pdf")
%
% Have a HTML version and a PDF version to display nicely...
%
\begin{htmlonly}
\noindent That should pop up a new window containing a graph like this:
\imgsrc[width=600, height=450]{images/dot_plot_scatter.png}
\end{htmlonly}
\begin{latexonly}
\noindent That should pop up a new window showing the graph in Figure~\ref{fig:nuc-dot-plot-scatter}.
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/dot_plot_scatter.png}
\caption{Nucleotide dot plot of two orchid sequence lengths (using pylab's scatter function).}
\label{fig:nuc-dot-plot-scatter}
\end{figure}\end{latexonly}
Personally I find this second plot much easier to read!
Again note that we have \emph{not} checked for reverse complement matches here
-- you could extend this example to do this, and perhaps plot the forward
matches in one color and the reverse matches in another.
\subsection{Plotting the quality scores of sequencing read data}
If you are working with second generation sequencing data, you may want to try plotting
the quality data. Here is an example using two FASTQ files containing paired end reads,
\texttt{SRR001666\_1.fastq} for the forward reads, and \texttt{SRR001666\_2.fastq} for
the reverse reads. These were downloaded from the ENA sequence read archive FTP site
(\url{ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR001/SRR001666/SRR001666_1.fastq.gz} and
\url{ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR001/SRR001666/SRR001666_2.fastq.gz}), and
are from \textit{E. coli} -- see \url{http://www.ebi.ac.uk/ena/data/view/SRR001666}
for details.
%Originally from ftp://ftp.ncbi.nlm.nih.gov/sra/static/SRX000/SRX000430/
In the following code the \verb|pylab.subplot(...)| function is used in order to show
the forward and reverse qualities on two subplots, side by side. There is also a little
bit of code to only plot the first fifty reads.
\begin{verbatim}
import pylab
from Bio import SeqIO
for subfigure in [1,2]:
filename = "SRR001666_%i.fastq" % subfigure
pylab.subplot(1, 2, subfigure)
for i,record in enumerate(SeqIO.parse(filename, "fastq")):
if i >= 50 : break #trick!
pylab.plot(record.letter_annotations["phred_quality"])
pylab.ylim(0,45)
pylab.ylabel("PHRED quality score")
pylab.xlabel("Position")
pylab.savefig("SRR001666.png")
print "Done"
\end{verbatim}
You should note that we are using the \verb|Bio.SeqIO| format name \texttt{fastq}
here because the NCBI has saved these reads using the standard Sanger FASTQ format
with PHRED scores. However, as you might guess from the read lengths, this data was
from an Illumina Genome Analyzer and was probably originally in one of the two
Solexa/Illumina FASTQ variant file formats instead.
This example uses the \verb|pylab.savefig(...)| function instead of
\verb|pylab.show(...)|, but as mentioned before both are useful.
\begin{latexonly}
\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{images/SRR001666.png}
\caption{Quality plot for some paired end reads.}
\label{fig:paired-end-qual-plot}
\end{figure}
The result is shown in Figure~\ref{fig:paired-end-qual-plot}.
\end{latexonly}
\begin{htmlonly}
Here is the result:
%Blank lines here are important!
\imgsrc[width=600, height=600]{images/SRR001666.png}
\end{htmlonly}
\section{Dealing with alignments}
This section can been seen as a follow on to Chapter~\ref{chapter:Bio.AlignIO}.
\subsection{Calculating summary information}
\label{sec:summary_info}
Once you have an alignment, you are very likely going to want to find out information about it. Instead of trying to have all of the functions that can generate information about an alignment in the alignment object itself, we've tried to separate out the functionality into separate classes, which act on the alignment.
Getting ready to calculate summary information about an object is quick to do. Let's say we've got an alignment object called \verb|alignment|, for example read in using \verb|Bio.AlignIO.read(...)| as described in Chapter~\ref{chapter:Bio.AlignIO}. All we need to do to get an object that will calculate summary information is:
\begin{verbatim}
from Bio.Align import AlignInfo
summary_align = AlignInfo.SummaryInfo(alignment)
\end{verbatim}
The \verb|summary_align| object is very useful, and will do the following neat things for you:
\begin{enumerate}
\item Calculate a quick consensus sequence -- see section~\ref{sec:consensus}
\item Get a position specific score matrix for the alignment -- see section~\ref{sec:pssm}
\item Calculate the information content for the alignment -- see section~\ref{sec:getting_info_content}
\item Generate information on substitutions in the alignment -- section~\ref{sec:sub_matrix} details using this to generate a substitution matrix.
\end{enumerate}
\subsection{Calculating a quick consensus sequence}
\label{sec:consensus}
The \verb|SummaryInfo| object, described in section~\ref{sec:summary_info}, provides functionality to calculate a quick consensus of an alignment. Assuming we've got a \verb|SummaryInfo| object called \verb|summary_align| we can calculate a consensus by doing:
\begin{verbatim}
consensus = summary_align.dumb_consensus()
\end{verbatim}
As the name suggests, this is a really simple consensus calculator, and will just add up all of the residues at each point in the consensus, and if the most common value is higher than some threshold value will add the common residue to the consensus. If it doesn't reach the threshold, it adds an ambiguity character to the consensus. The returned consensus object is Seq object whose alphabet is inferred from the alphabets of the sequences making up the consensus. So doing a \verb|print consensus| would give:
\begin{verbatim}
consensus Seq('TATACATNAAAGNAGGGGGATGCGGATAAATGGAAAGGCGAAAGAAAGAAAAAAATGAAT
...', IUPACAmbiguousDNA())
\end{verbatim}
You can adjust how \verb|dumb_consensus| works by passing optional parameters:
\begin{description}
\item[the threshold] This is the threshold specifying how common a particular residue has to be at a position before it is added. The default is $0.7$ (meaning $70\%$).
\item[the ambiguous character] This is the ambiguity character to use. The default is 'N'.
\item[the consensus alphabet] This is the alphabet to use for the consensus sequence. If an alphabet is not specified than we will try to guess the alphabet based on the alphabets of the sequences in the alignment.
\end{description}
\subsection{Position Specific Score Matrices}
\label{sec:pssm}
Position specific score matrices (PSSMs) summarize the alignment information in a different way than a consensus, and may be useful for different tasks. Basically, a PSSM is a count matrix. For each column in the alignment, the number of each alphabet letters is counted and totaled. The totals are displayed relative to some representative sequence along the left axis. This sequence may be the consesus sequence, but can also be any sequence in the alignment. For instance for the alignment,
\begin{verbatim}
GTATC
AT--C
CTGTC
\end{verbatim}
\noindent the PSSM is:
\begin{verbatim}
G A T C
G 1 1 0 1
T 0 0 3 0
A 1 1 0 0
T 0 0 2 0
C 0 0 0 3
\end{verbatim}
Let's assume we've got an alignment object called \verb|c_align|. To get a PSSM with the consensus sequence along the side we first get a summary object and calculate the consensus sequence:
\begin{verbatim}
summary_align = AlignInfo.SummaryInfo(c_align)
consensus = summary_align.dumb_consensus()
\end{verbatim}
Now, we want to make the PSSM, but ignore any \verb|N| ambiguity residues when calculating this:
\begin{verbatim}
my_pssm = summary_align.pos_specific_score_matrix(consensus,
chars_to_ignore = ['N'])
\end{verbatim}
Two notes should be made about this:
\begin{enumerate}
\item To maintain strictness with the alphabets, you can only include characters along the top of the PSSM that are in the alphabet of the alignment object. Gaps are not included along the top axis of the PSSM.
\item The sequence passed to be displayed along the left side of the axis does not need to be the consensus. For instance, if you wanted to display the second sequence in the alignment along this axis, you would need to do:
\begin{verbatim}
second_seq = alignment.get_seq_by_num(1)
my_pssm = summary_align.pos_specific_score_matrix(second_seq
chars_to_ignore = ['N'])
\end{verbatim}
\end{enumerate}
The command above returns a \verb|PSSM| object. To print out the PSSM as we showed above, we simply need to do a \verb|print my_pssm|, which gives:
\begin{verbatim}
A C G T
T 0.0 0.0 0.0 7.0
A 7.0 0.0 0.0 0.0
T 0.0 0.0 0.0 7.0
A 7.0 0.0 0.0 0.0
C 0.0 7.0 0.0 0.0
A 7.0 0.0 0.0 0.0
T 0.0 0.0 0.0 7.0
T 1.0 0.0 0.0 6.0
...
\end{verbatim}
You can access any element of the PSSM by subscripting like \verb|your_pssm[sequence_number][residue_count_name]|. For instance, to get the counts for the 'A' residue in the second element of the above PSSM you would do:
\begin{verbatim}
>>> print my_pssm[1]["A"]
7.0
\end{verbatim}
The structure of the PSSM class hopefully makes it easy both to access elements and to pretty print the matrix.
\subsection{Information Content}
\label{sec:getting_info_content}
A potentially useful measure of evolutionary conservation is the information content of a sequence.
A useful introduction to information theory targeted towards molecular biologists can be found at \url{http://www.lecb.ncifcrf.gov/~toms/paper/primer/}. For our purposes, we will be looking at the information content of a consesus sequence, or a portion of a consensus sequence. We calculate information content at a particular column in a multiple sequence alignment using the following formula:
\begin{displaymath}
IC_{j} = \sum_{i=1}^{N_{a}} P_{ij} \mathrm{log}\left(\frac{P_{ij}}{Q_{i}}\right)
\end{displaymath}
\noindent where:
\begin{itemize}
\item $IC_{j}$ -- The information content for the $j$-th column in an alignment.
\item $N_{a}$ -- The number of letters in the alphabet.
\item $P_{ij}$ -- The frequency of a particular letter $i$ in the $j$-th column (i.~e.~if G occurred 3 out of 6 times in an aligment column, this would be 0.5)
\item $Q_{i}$ -- The expected frequency of a letter $i$. This is an
optional argument, usage of which is left at the user's
discretion. By default, it is automatically assigned to $0.05 = 1/20$ for a
protein alphabet, and $0.25 = 1/4$ for a nucleic acid alphabet. This is for
geting the information content without any assumption of prior
distributions. When assuming priors, or when using a non-standard
alphabet, you should supply the values for $Q_{i}$.
\end{itemize}
Well, now that we have an idea what information content is being calculated in Biopython, let's look at how to get it for a particular region of the alignment.
First, we need to use our alignment to get an alignment summary object, which we'll assume is called \verb|summary_align| (see section~\ref{sec:summary_info}) for instructions on how to get this. Once we've got this object, calculating the information content for a region is as easy as:
\begin{verbatim}
info_content = summary_align.information_content(5, 30,
chars_to_ignore = ['N'])
\end{verbatim}
Wow, that was much easier then the formula above made it look! The variable \verb|info_content| now contains a float value specifying the information content over the specified region (from 5 to 30 of the alignment). We specifically ignore the ambiguity residue 'N' when calculating the information content, since this value is not included in our alphabet (so we shouldn't be interested in looking at it!).
As mentioned above, we can also calculate relative information content by supplying the expected frequencies:
\begin{verbatim}
expect_freq = {
'A' : .3,
'G' : .2,
'T' : .3,
'C' : .2}
\end{verbatim}
The expected should not be passed as a raw dictionary, but instead by passed as a \verb|SubsMat.FreqTable| object (see section~\ref{sec:freq_table} for more information about FreqTables). The FreqTable object provides a standard for associating the dictionary with an Alphabet, similar to how the Biopython Seq class works.
To create a FreqTable object, from the frequency dictionary you just need to do:
\begin{verbatim}
from Bio.Alphabet import IUPAC
from Bio.SubsMat import FreqTable
e_freq_table = FreqTable.FreqTable(expect_freq, FreqTable.FREQ,
IUPAC.unambiguous_dna)
\end{verbatim}
Now that we've got that, calculating the relative information content for our region of the alignment is as simple as:
\begin{verbatim}
info_content = summary_align.information_content(5, 30,
e_freq_table = e_freq_table,
chars_to_ignore = ['N'])
\end{verbatim}
Now, \verb|info_content| will contain the relative information content over the region in relation to the expected frequencies.
The value return is calculated using base 2 as the logarithm base in the formula above. You can modify this by passing the parameter \verb|log_base| as the base you want:
\begin{verbatim}
info_content = summary_align.information_content(5, 30, log_base = 10,
chars_to_ignore = ['N'])
\end{verbatim}
Well, now you are ready to calculate information content. If you want to try applying this to some real life problems, it would probably be best to dig into the literature on information content to get an idea of how it is used. Hopefully your digging won't reveal any mistakes made in coding this function!
\section{Substitution Matrices}
\label{sec:sub_matrix}
Substitution matrices are an extremely important part of everyday bioinformatics work. They provide the scoring terms for classifying how likely two different residues are to substitute for each other. This is essential in doing sequence comparisons. The book ``Biological Sequence Analysis'' by Durbin et al. provides a really nice introduction to Substitution Matrices and their uses. Some famous substitution matrices are the PAM and BLOSUM series of matrices.
Biopython provides a ton of common substitution matrices, and also provides functionality for creating your own substitution matrices.
\subsection{Using common substitution matrices}
\subsection{Creating your own substitution matrix from an alignment}
\label{sec:subs_mat_ex}
A very cool thing that you can do easily with the substitution matrix
classes is to create your own substitution matrix from an
alignment. In practice, this is normally done with protein
alignments. In this example, we'll first get a Biopython alignment
object and then get a summary object to calculate info about the
alignment. The file containing \href{examples/protein.aln}{protein.aln}
(also available online
\href{http://biopython.org/DIST/docs/tutorial/examples/protein.aln}{here})
contains the Clustalw alignment output.
%doctest examples
\begin{verbatim}
>>> from Bio import AlignIO
>>> from Bio import Alphabet
>>> from Bio.Alphabet import IUPAC
>>> from Bio.Align import AlignInfo
>>> filename = "protein.aln"
>>> alpha = Alphabet.Gapped(IUPAC.protein)
>>> c_align = AlignIO.read(filename, "clustal", alphabet=alpha)
>>> summary_align = AlignInfo.SummaryInfo(c_align)
\end{verbatim}
Sections~\ref{sec:align_clustal} and~\ref{sec:summary_info} contain
more information on doing this.
Now that we've got our \verb|summary_align| object, we want to use it
to find out the number of times different residues substitute for each
other. To make the example more readable, we'll focus on only amino
acids with polar charged side chains. Luckily, this can be done easily
when generating a replacement dictionary, by passing in all of the
characters that should be ignored. Thus we'll create a dictionary of
replacements for only charged polar amino acids using:
%cont-doctest
\begin{verbatim}
>>> replace_info = summary_align.replacement_dictionary(["G", "A", "V", "L", "I",
... "M", "P", "F", "W", "S",
... "T", "N", "Q", "Y", "C"])
\end{verbatim}
This information about amino acid replacements is represented as a
python dictionary which will look something like (the order can vary):
\begin{verbatim}
{('R', 'R'): 2079.0, ('R', 'H'): 17.0, ('R', 'K'): 103.0, ('R', 'E'): 2.0,
('R', 'D'): 2.0, ('H', 'R'): 0, ('D', 'H'): 15.0, ('K', 'K'): 3218.0,
('K', 'H'): 24.0, ('H', 'K'): 8.0, ('E', 'H'): 15.0, ('H', 'H'): 1235.0,
('H', 'E'): 18.0, ('H', 'D'): 0, ('K', 'D'): 0, ('K', 'E'): 9.0,
('D', 'R'): 48.0, ('E', 'R'): 2.0, ('D', 'K'): 1.0, ('E', 'K'): 45.0,
('K', 'R'): 130.0, ('E', 'D'): 241.0, ('E', 'E'): 3305.0,
('D', 'E'): 270.0, ('D', 'D'): 2360.0}
\end{verbatim}
This information gives us our accepted number of replacements, or how
often we expect different things to substitute for each other. It
turns out, amazingly enough, that this is all of the information we
need to go ahead and create a substitution matrix. First, we use the
replacement dictionary information to create an Accepted Replacement
Matrix (ARM):
%cont-doctest
\begin{verbatim}
>>> from Bio import SubsMat
>>> my_arm = SubsMat.SeqMat(replace_info)
\end{verbatim}
With this accepted replacement matrix, we can go right ahead and
create our log odds matrix (i.~e.~a standard type Substitution Matrix):
%cont-doctest
\begin{verbatim}
>>> my_lom = SubsMat.make_log_odds_matrix(my_arm)
\end{verbatim}
The log odds matrix you create is customizable with the following
optional arguments:
\begin{itemize}
\item \verb|exp_freq_table| -- You can pass a table of expected
frequencies for each alphabet. If supplied, this will be used
instead of the passed accepted replacement matrix when calculate
expected replacments.
\item \verb|logbase| - The base of the logarithm taken to create the
log odd matrix. Defaults to base 10.
\item \verb|factor| - The factor to multiply each matrix entry
by. This defaults to 10, which normally makes the matrix numbers
easy to work with.
\item \verb|round_digit| - The digit to round to in the matrix. This
defaults to 0 (i.~e.~no digits).
\end{itemize}
Once you've got your log odds matrix, you can display it prettily
using the function \verb|print_mat|. Doing this on our created matrix
gives:
%cont-doctest
\begin{verbatim}
>>> my_lom.print_mat()
D 2
E -1 1
H -5 -4 3
K -10 -5 -4 1
R -4 -8 -4 -2 2
D E H K R
\end{verbatim}
Very nice. Now we've got our very own substitution matrix to play with!
\section{BioSQL -- storing sequences in a relational database}
\label{sec:BioSQL}
\href{http://www.biosql.org/}{BioSQL} is a joint effort between the
\href{http://open-bio.org/}{OBF} projects (BioPerl, BioJava etc) to support a
shared database schema for storing sequence data. In theory, you could load a
GenBank file into the database with BioPerl, then using Biopython extract this
from the database as a record object with features - and get more or less the same
thing as if you had loaded the GenBank file directly as a SeqRecord using
\verb|Bio.SeqIO| (Chapter~\ref{chapter:Bio.SeqIO}).
Biopython's BioSQL module is currently documented at
\url{http://biopython.org/wiki/BioSQL} which is part of our wiki pages.
\chapter{The Biopython testing framework}
\label{sec:regr_test}
Biopython has a regression testing framework (the file
\verb|run_tests.py|) based on
\href{http://docs.python.org/library/unittest.html}{unittest},
the standard unit testing framework for Python. Providing comprehensive
tests for modules is one of the most important aspects of making sure that
the Biopython code is as bug-free as possible before going out.
It also tends to be one of the most undervalued aspects of contributing.
This chapter is designed to make running the Biopython tests and
writing good test code as easy as possible.
Ideally, every module that goes into Biopython
should have a test (and should also have documentation!).
All our developers, and anyone installing Biopython from source,
are strongly encouraged to run the unit tests.
\section{Running the tests}
When you download the Biopython source code, or check it out from
our source code repository, you should find a subdirectory call
\verb|Tests|. This contains the key script \verb|run_tests.py|,
lots of individual scripts named \verb|test_XXX.py|, a subdirectory
called \verb|output| and lots of other subdirectories which
contain input files for the test suite.
As part of building and installing Biopython you will typically
run the full test suite at the command line from the Biopython
source top level directory using the following:
\begin{verbatim}
python setup.py test
\end{verbatim}
This is actually equivalent to going to the \verb|Tests|
subdirectory and running:
\begin{verbatim}
python run_tests.py
\end{verbatim}
You'll often want to run just some of the tests, and this is done
like this:
\begin{verbatim}
python run_tests.py test_SeqIO.py test_AlignIO.py
\end{verbatim}
When giving the list of tests, the \verb|.py| extension is optional,
so you can also just type:
\begin{verbatim}
python run_tests.py test_SeqIO test_AlignIO
\end{verbatim}
To run the docstring tests (see section \ref{section:doctest}), you can use
\begin{verbatim}
python run_tests.py doctest
\end{verbatim}
By default, \verb|run_tests.py| runs all tests, including the docstring tests.
If an individual test is failing, you can also try running it
directly, which may give you more information.
Importantly, note that the individual unit tests come in two types:
\begin{itemize}
\item Simple print-and-compare scripts. These unit tests are
essentially short example Python programs, which print out
various output text. For a test file named \verb|test_XXX.py|
there will be a matching text file called \verb|test_XXX| under
the \verb|output| subdirectory which contains the expected
output. All that the test framework does to is run the script,
and check the output agrees.
\item Standard \verb|unittest|- based tests. These will \verb|import unittest|
and then define \verb|unittest.TestCase| classes, each with one
or more sub-tests as methods starting with \verb|test_| which
check some specific aspect of the code.
These tests should not print any output directly.
\end{itemize}
Currently, about half of the Biopython tests are \verb|unittest|-style tests, and half are print-and-compare tests.
Running a simple print-and-compare test directly will usually give lots
of output on screen, but does not check the output matches the expected
output. If the test is failing with an exception error, it should be
very easy to locate where exactly the script is failing.
For an example of a print-and-compare test, try:
\begin{verbatim}
python test_SeqIO.py
\end{verbatim}
The \verb|unittest|-based tests instead show you exactly which sub-section(s) of
the test are failing. For example,
\begin{verbatim}
python test_Cluster.py
\end{verbatim}
\section{Writing tests}
Let's say you want to write some tests for a module called \verb|Biospam|.
This can be a module you wrote, or an existing module that doesn't have
any tests yet. In the examples below, we assume that
\verb|Biospam| is a module that does simple math.
Each Biopython test can have three important files and directories involved with it:
\begin{enumerate}
\item \verb|test_Biospam.py| -- The actual test code for your module.
\item \verb|Biospam| [optional]-- A directory where any necessary input files
will be located. Any output files that will be generated should also
be written here (and preferably cleaned up after the tests are
done) to prevent clogging up the main Tests directory.
\item \verb|output/Biospam| -- [for print-and-compare tests only] This
file contains the expected output from running \verb|test_Biospam.py|.
This file is not needed for \verb|unittest|-style tests, since there
the validation is done in the test script \verb|test_Biospam.py| itself.
\end{enumerate}
It's up to you to decide whether you want to write a print-and-compare test script or a \verb|unittest|-style test script. The important thing is that you cannot mix these two styles in a single test script. Particularly, don't use \verb|unittest| features in a print-and-compare test.
Any script with a \verb|test_| prefix in the \verb|Tests| directory will be found and run by \verb|run_tests.py|. Below, we show an example test script \verb|test_Biospam.py| both for a print-and-compare test and for a \verb|unittest|-based test. If you put this script in the Biopython \verb|Tests| directory, then \verb|run_tests.py| will find it and execute the tests contained in it:
\begin{verbatim}
$ python run_tests.py
test_Ace ... ok
test_AlignIO ... ok
test_BioSQL ... ok
test_BioSQL_SeqIO ... ok
test_Biospam ... ok
test_CAPS ... ok
test_Clustalw ... ok
\end{verbatim}
\ldots
\begin{verbatim}
----------------------------------------------------------------------
Ran 107 tests in 86.127 seconds
\end{verbatim}
\subsection{Writing a print-and-compare test}
A print-and-compare style test should be much simpler for beginners
or novices to write - essentially it is just an example script using
your new module.
Here is what you should do to make a print-and-compare test for the
\verb|Biospam| module.
\begin{enumerate}
\item Write a script called \verb|test_Biospam.py|
\begin{itemize}
\item This script should live in the Tests directory
\item The script should test all of the important functionality
of the module (the more you test the better your test is, of course!).
\item Try to avoid anything which might be platform specific,
such as printing floating point numbers without using an explicit
formatting string to avoid having too many decimal places
(different platforms can give very slightly different values).
\end{itemize}
\item If the script requires files to do the testing, these should go in
the directory Tests/Biospam (if you just need something generic, like
a FASTA sequence file, or a GenBank record, try and use an existing
sample input file instead).
\item Write out the test output and verify the output to be correct.
There are two ways to do this:
\begin{enumerate}
\item The long way:
\begin{itemize}
\item Run the script and write its output to a file. On UNIX (including
Linux and Mac OS X) machines, you would do something like:
\verb|python test_Biospam.py > test_Biospam| which would write the
output to the file \verb|test_Biospam|.
\item Manually look at the file \verb|test_Biospam| to make sure the output is correct. When you are sure it is all right and there are no bugs, you need to quickly edit the \verb|test_Biospam| file so that the first line is: `\verb|test_Biospam|' (no quotes).
\item copy the \verb|test_Biospam| file to the directory Tests/output
\end{itemize}
\item The quick way:
\begin{itemize}
\item Run \verb|python run_tests.py -g test_Biospam.py|. The
regression testing framework is nifty enough that it'll put
the output in the right place in just the way it likes it.
\item Go to the output (which should be in \verb|Tests/output/test_Biospam|) and double check the output to make sure it is all correct.
\end{itemize}
\end{enumerate}
\item Now change to the Tests directory and run the regression tests
with \verb|python run_tests.py|. This will run all of the tests, and
you should see your test run (and pass!).
\item That's it! Now you've got a nice test for your module ready to check in,
or submit to Biopython. Congratulations!
\end{enumerate}
As an example, the \verb|test_Biospam.py| test script to test the
\verb|addition| and \verb|multiplication| functions in the \verb|Biospam|
module could look as follows:
\begin{verbatim}
from Bio import Biospam
print "2 + 3 =", Biospam.addition(2, 3)
print "9 - 1 =", Biospam.addition(9, -1)
print "2 * 3 =", Biospam.multiplication(2, 3)
print "9 * (- 1) =", Biospam.multiplication(9, -1)
\end{verbatim}
We generate the corresponding output with \verb|python run_tests.py -g test_Biospam.py|, and check the output file \verb|output/test_Biospam|:
\begin{verbatim}
test_Biospam
2 + 3 = 5
9 - 1 = 8
2 * 3 = 6
9 * (- 1) = -9
\end{verbatim}
Often, the difficulty with larger print-and-compare tests is to keep track which line in the output corresponds to which command in the test script. For this purpose, it is important to print out some markers to help you match lines in the input script with the generated output.
\subsection{Writing a unittest-based test}
We want all the modules in Biopython to have unit tests, and a simple
print-and-compare test is better than no test at all. However, although
there is a steeper learning curve, using the \verb|unittest| framework
gives a more structured result, and if there is a test failure this can
clearly pinpoint which part of the test is going wrong. The sub-tests can
also be run individually which is helpful for testing or debugging.
The \verb|unittest|-framework has been included with Python since version
2.1, and is documented in the Python Library Reference (which I know you
are keeping under your pillow, as recommended). There is also
\href{http://docs.python.org/library/unittest.html}{online documentaion
for unittest}.
If you are familiar with the \verb|unittest| system (or something similar
like the nose test framework), you shouldn't have any trouble. You may
find looking at the existing example within Biopython helpful too.
Here's a minimal \verb|unittest|-style test script for \verb|Biospam|,
which you can copy and paste to get started:
\begin{verbatim}
import unittest
from Bio import Biospam
class BiospamTestAddition(unittest.TestCase):
def test_addition1(self):
result = Biospam.addition(2, 3)
self.assertEqual(result, 5)
def test_addition2(self):
result = Biospam.addition(9, -1)
self.assertEqual(result, 8)
class BiospamTestDivision(unittest.TestCase):
def test_division1(self):
result = Biospam.division(3.0, 2.0)
self.assertAlmostEqual(result, 1.5)
def test_division2(self):
result = Biospam.division(10.0, -2.0)
self.assertAlmostEqual(result, -5.0)
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity = 2)
unittest.main(testRunner=runner)
\end{verbatim}
In the division tests, we use \verb|assertAlmostEqual| instead of \verb|assertEqual| to avoid tests failing due to roundoff errors; see the \verb|unittest| chapter in the Python documentation for details and for other functionality available in \verb|unittest| (\href{http://docs.python.org/library/unittest.html}{online reference}).
These are the key points of \verb|unittest|-based tests:
\begin{itemize}
\item Test cases are stored in classes that derive from
\verb|unittest.TestCase| and cover one basic aspect of your code
\item You can use methods \verb|setUp| and \verb|tearDown| for any repeated
code which should be run before and after each test method. For example,
the \verb|setUp| method might be used to create an instance of the object
you are testing, or open a file handle. The \verb|tearDown| should do any
``tidying up'', for example closing the file handle.
\item The tests are prefixed with \verb|test_| and each test should cover
one specific part of what you are trying to test. You can have as
many tests as you want in a class.
\item At the end of the test script, you can use
\begin{verbatim}
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity = 2)
unittest.main(testRunner=runner)
\end{verbatim}
to execute the tests when the script is run by itself (rather than
imported from \verb|run_tests.py|).
If you run this script, then you'll see something like the following:
\begin{verbatim}
$ python test_BiospamMyModule.py
test_addition1 (__main__.TestAddition) ... ok
test_addition2 (__main__.TestAddition) ... ok
test_division1 (__main__.TestDivision) ... ok
test_division2 (__main__.TestDivision) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.059s
OK
\end{verbatim}
\item To indicate more clearly what each test is doing, you can add
docstrings to each test. These are shown when running the tests,
which can be useful information if a test is failing.
\begin{verbatim}
import unittest
from Bio import Biospam
class BiospamTestAddition(unittest.TestCase):
def test_addition1(self):
"""An addition test"""
result = Biospam.addition(2, 3)
self.assertEqual(result, 5)
def test_addition2(self):
"""A second addition test"""
result = Biospam.addition(9, -1)
self.assertEqual(result, 8)
class BiospamTestDivision(unittest.TestCase):
def test_division1(self):
"""Now let's check division"""
result = Biospam.division(3.0, 2.0)
self.assertAlmostEqual(result, 1.5)
def test_division2(self):
"""A second division test"""
result = Biospam.division(10.0, -2.0)
self.assertAlmostEqual(result, -5.0)
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity = 2)
unittest.main(testRunner=runner)
\end{verbatim}
Running the script will now show you:
\begin{verbatim}
$ python test_BiospamMyModule.py
An addition test ... ok
A second addition test ... ok
Now let's check division ... ok
A second division test ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
\end{verbatim}
\end{itemize}
If your module contains docstring tests (see section \ref{section:doctest}),
you may want to include those in the tests to be run. You can do so as
follows by modifying the code under \verb|if __name__ == "__main__":|
to look like this:
\begin{verbatim}
if __name__ == "__main__":
unittest_suite = unittest.TestLoader().loadTestsFromName("test_Biospam")
doctest_suite = doctest.DocTestSuite(Biospam)
suite = unittest.TestSuite((unittest_suite, doctest_suite))
runner = unittest.TextTestRunner(sys.stdout, verbosity = 2)
runner.run(suite)
\end{verbatim}
This is only relevant if you want to run the docstring tests when you
execute \verb|python test_Biospam.py|; with
\verb|python run_tests.py|, the docstring tests are run automatically
(assuming they are included in the list of docstring tests in
\verb|run_tests.py|, see the section below).
\section{Writing doctests}
\label{section:doctest}
Python modules, classes and functions support built in documentation using
docstrings. The \href{http://docs.python.org/library/doctest.html}{doctest
framework} (included with Python) allows the developer to embed working
examples in the docstrings, and have these examples automatically tested.
Currently only a small part of Biopython includes doctests. The
\verb|run_tests.py| script takes care of running the doctests.
For this purpose, at the top of the \verb|run_tests.py| script is a
manually compiled list of modules to test, which
allows us to skip modules with optional external dependencies which may
not be installed (e.g. the Reportlab and NumPy libraries). So, if you've
added some doctests to the docstrings in a Biopython module, in order to
have them included in the Biopython test suite, you must update
\verb|run_tests.py| to include your module. Currently, the relevant part
of \verb|run_tests.py| looks as follows:
\begin{verbatim}
# This is the list of modules containing docstring tests.
# If you develop docstring tests for other modules, please add
# those modules here.
DOCTEST_MODULES = ["Bio.Seq",
"Bio.SeqRecord",
"Bio.SeqIO",
"...",
]
#Silently ignore any doctests for modules requiring numpy!
try:
import numpy
DOCTEST_MODULES.extend(["Bio.Statistics.lowess"])
except ImportError:
pass
\end{verbatim}
Note that we regard doctests primarily as documentation, so you should
stick to typical usage. Generally complicated examples dealing with error
conditions and the like would be best left to a dedicated unit test.
Note that if you want to write doctests involving file parsing, defining
the file location complicates matters. Ideally use relative paths assuming
the code will be run from the \verb|Tests| directory, see the
\verb|Bio.SeqIO| doctests for an example of this.
To run the docstring tests only, use
\begin{verbatim}
$ python run_tests.py doctest
\end{verbatim}
\chapter{Advanced}
\label{chapter:advanced}
\section{Parser Design}
Many of the older Biopython parsers were built around an event-oriented
design that includes Scanner and Consumer objects.
Scanners take input from a data source and analyze it line by line,
sending off an event whenever it recognizes some information in the
data. For example, if the data includes information about an organism
name, the scanner may generate an \verb|organism_name| event whenever it
encounters a line containing the name.
Consumers are objects that receive the events generated by Scanners.
Following the previous example, the consumer receives the
\verb|organism_name| event, and the processes it in whatever manner
necessary in the current application.
This is a very flexible framework, which is advantageous if you want to
be able to parse a file format into more than one representation. For
example, the \verb|Bio.GenBank| module uses this to construct either
\verb|SeqRecord| objects or file-format-specific record objects.
More recently, many of the parsers added for \verb|Bio.SeqIO| and
\verb|Bio.AlignIO| take a much simpler approach, but only generate a
single object representation (\verb|SeqRecord| and
\verb|MultipleSeqAlignment| objects respectively). In some cases the
\verb|Bio.SeqIO| parsers actually wrap
another Biopython parser - for example, the \verb|Bio.SwissProt| parser
produces SwissProt format specific record objects, which get converted
into \verb|SeqRecord| objects.
\section{Substitution Matrices}
\subsection{SubsMat}
This module provides a class and a few routines for generating substitution matrices, similar to BLOSUM or PAM matrices, but based on user-provided data. Additionally, you may select a matrix from MatrixInfo.py, a collection of established substitution matrices. The \verb+SeqMat+ class derives from a dictionary:
\begin{verbatim}
class SeqMat(dict)
\end{verbatim}
The dictionary is of the form \verb|{(i1,j1):n1, (i1,j2):n2,...,(ik,jk):nk}| where i, j are alphabet letters, and n is a value.
\begin{enumerate}
\item Attributes
\begin{enumerate}
\item \verb|self.alphabet|: a class as defined in Bio.Alphabet
\item \verb|self.ab_list|: a list of the alphabet's letters, sorted. Needed mainly for internal purposes
\end{enumerate}
\item Methods
\begin{enumerate}
\item
\begin{verbatim}
__init__(self,data=None,alphabet=None, mat_name='', build_later=0):
\end{verbatim}
\begin{enumerate}
\item \verb|data|: can be either a dictionary, or another SeqMat instance.
\item \verb|alphabet|: a Bio.Alphabet instance. If not provided, construct an alphabet from data.
\item \verb|mat_name|: matrix name, such as "BLOSUM62" or "PAM250"
\item \verb|build_later|: default false. If true, user may supply only alphabet and empty dictionary, if intending to build the matrix later. this skips the sanity check of alphabet size vs. matrix size.
\end{enumerate}
\item
\begin{verbatim}
entropy(self,obs_freq_mat)
\end{verbatim}
\begin{enumerate}
\item \verb|obs_freq_mat|: an observed frequency matrix. Returns the matrix's entropy, based on the frequency in \verb|obs_freq_mat|. The matrix instance should be LO or SUBS.
\end{enumerate}
\item
\begin{verbatim}
sum(self)
\end{verbatim}
Calculates the sum of values for each letter in the matrix's alphabet, and returns it as a dictionary of the form \verb|{i1: s1, i2: s2,...,in:sn}|, where:
\begin{itemize}
\item i: an alphabet letter;
\item s: sum of all values in a half-matrix for that letter;
\item n: number of letters in alphabet.
\end{itemize}
\item
\begin{verbatim}
print_mat(self,f,format="%4d",bottomformat="%4s",alphabet=None)
\end{verbatim}
prints the matrix to file handle f. \verb|format| is the format field for the matrix values; \verb|bottomformat| is the format field for the bottom row, containing matrix letters. Example output for a 3-letter alphabet matrix:
\begin{verbatim}
A 23
B 12 34
C 7 22 27
A B C
\end{verbatim}
The \verb|alphabet| optional argument is a string of all characters in the alphabet. If supplied, the order of letters along the axes is taken from the string, rather than by alphabetical order.
\end{enumerate}
\item Usage
The following section is laid out in the order by which most people wish to generate a log-odds matrix. Of course, interim matrices can be generated and
investigated. Most people just want a log-odds matrix, that's all.
\begin{enumerate}
\item Generating an Accepted Replacement Matrix
Initially, you should generate an accepted replacement matrix (ARM) from your data. The values in ARM are the counted number of replacements according to your data. The data could be a set of pairs or multiple alignments. So for instance if Alanine was replaced by Cysteine 10 times, and Cysteine by Alanine 12 times, the corresponding ARM entries would be:
\begin{verbatim}
('A','C'): 10, ('C','A'): 12
\end{verbatim}
as order doesn't matter, user can already provide only one entry:
\begin{verbatim}
('A','C'): 22
\end{verbatim}
A SeqMat instance may be initialized with either a full (first method of counting: 10, 12) or half (the latter method, 22) matrices. A full protein
alphabet matrix would be of the size 20x20 = 400. A half matrix of that alphabet would be 20x20/2 + 20/2 = 210. That is because same-letter entries don't
change. (The matrix diagonal). Given an alphabet size of N:
\begin{enumerate}
\item Full matrix size:N*N
\item Half matrix size: N(N+1)/2
\end{enumerate}
The SeqMat constructor automatically generates a half-matrix, if a full matrix is passed. If a half matrix is passed, letters in the key should be provided in alphabetical order: ('A','C') and not ('C',A').
At this point, if all you wish to do is generate a log-odds matrix, please go to the section titled Example of Use. The following text describes the nitty-gritty of internal functions, to be used by people who wish to investigate their nucleotide/amino-acid frequency data more thoroughly.
\item Generating the observed frequency matrix (OFM)
Use:
\begin{verbatim}
OFM = SubsMat._build_obs_freq_mat(ARM)
\end{verbatim}
The OFM is generated from the ARM, only instead of replacement counts, it contains replacement frequencies.
\item Generating an expected frequency matrix (EFM)
Use:
\begin{verbatim}
EFM = SubsMat._build_exp_freq_mat(OFM,exp_freq_table)
\end{verbatim}
\begin{enumerate}
\item \verb|exp_freq_table|: should be a FreqTable instance. See section~\ref{sec:freq_table} for detailed information on FreqTable. Briefly, the expected frequency table has the frequencies of appearance for each member of the alphabet. It is
implemented as a dictionary with the alphabet letters as keys, and each letter's frequency as a value. Values sum to 1.
\end{enumerate}
The expected frequency table can (and generally should) be generated from the observed frequency matrix. So in most cases you will generate \verb|exp_freq_table| using:
\begin{verbatim}
>>> exp_freq_table = SubsMat._exp_freq_table_from_obs_freq(OFM)
>>> EFM = SubsMat._build_exp_freq_mat(OFM,exp_freq_table)
\end{verbatim}
But you can supply your own \verb|exp_freq_table|, if you wish
\item Generating a substitution frequency matrix (SFM)
Use:
\begin{verbatim}
SFM = SubsMat._build_subs_mat(OFM,EFM)
\end{verbatim}
Accepts an OFM, EFM. Provides the division product of the corresponding values.
\item Generating a log-odds matrix (LOM)
Use:
\begin{verbatim}
LOM=SubsMat._build_log_odds_mat(SFM[,logbase=10,factor=10.0,round_digit=1])
\end{verbatim}
\begin{enumerate}
\item Accepts an SFM.
\item \verb|logbase|: base of the logarithm used to generate the log-odds values.
\item \verb|factor|: factor used to multiply the log-odds values. Each entry is generated by log(LOM[key])*factor And rounded to the \verb|round_digit| place after the decimal point, if required.
\end{enumerate}
\end{enumerate}
\item Example of use
As most people would want to generate a log-odds matrix, with minimum hassle, SubsMat provides one function which does it all:
\begin{verbatim}
make_log_odds_matrix(acc_rep_mat,exp_freq_table=None,logbase=10,
factor=10.0,round_digit=0):
\end{verbatim}
\begin{enumerate}
\item \verb|acc_rep_mat|: user provided accepted replacements matrix
\item \verb|exp_freq_table|: expected frequencies table. Used if provided, if not, generated from the \verb|acc_rep_mat|.
\item \verb|logbase|: base of logarithm for the log-odds matrix. Default base 10.
\item \verb|round_digit|: number after decimal digit to which result should be rounded. Default zero.
\end{enumerate}
\end{enumerate}
\subsection{FreqTable}
\label{sec:freq_table}
\begin{verbatim}
FreqTable.FreqTable(UserDict.UserDict)
\end{verbatim}
\begin{enumerate}
\item Attributes:
\begin{enumerate}
\item \verb|alphabet|: A Bio.Alphabet instance.
\item \verb|data|: frequency dictionary
\item \verb|count|: count dictionary (in case counts are provided).
\end{enumerate}
\item Functions:
\begin{enumerate}
\item \verb|read_count(f)|: read a count file from stream f. Then convert to frequencies
\item \verb|read_freq(f)|: read a frequency data file from stream f. Of course, we then don't have the counts, but it is usually the letter frquencies which are interesting.
\end{enumerate}
\item Example of use:
The expected count of the residues in the database is sitting in a file, whitespace delimited, in the following format (example given for a 3-letter alphabet):
\begin{verbatim}
A 35
B 65
C 100
\end{verbatim}
And will be read using the \verb|FreqTable.read_count(file_handle)| function.
An equivalent frequency file:
\begin{verbatim}
A 0.175
B 0.325
C 0.5
\end{verbatim}
Conversely, the residue frequencies or counts can be passed as a dictionary.
Example of a count dictionary (3-letter alphabet):
\begin{verbatim}
{'A': 35, 'B': 65, 'C': 100}
\end{verbatim}
Which means that an expected data count would give a 0.5 frequency
for 'C', a 0.325 probability of 'B' and a 0.175 probability of 'A'
out of 200 total, sum of A, B and C)
A frequency dictionary for the same data would be:
\begin{verbatim}
{'A': 0.175, 'B': 0.325, 'C': 0.5}
\end{verbatim}
Summing up to 1.
When passing a dictionary as an argument, you should indicate whether it is a count or a frequency dictionary. Therefore the FreqTable class constructor requires two arguments: the dictionary itself, and FreqTable.COUNT or FreqTable.FREQ indicating counts or frequencies, respectively.
Read expected counts. readCount will already generate the frequencies
Any one of the following may be done to geerate the frequency table (ftab):
\begin{verbatim}
>>> from SubsMat import *
>>> ftab = FreqTable.FreqTable(my_frequency_dictionary,FreqTable.FREQ)
>>> ftab = FreqTable.FreqTable(my_count_dictionary,FreqTable.COUNT)
>>> ftab = FreqTable.read_count(open('myCountFile'))
>>> ftab = FreqTable.read_frequency(open('myFrequencyFile'))
\end{verbatim}
\end{enumerate}
\chapter{Where to go from here -- contributing to Biopython}
\section{Bug Reports + Feature Requests}
Getting feedback on the Biopython modules is very important to us. Open-source projects like this benefit greatly from feedback, bug-reports (and patches!) from a wide variety of contributors.
The main forums for discussing feature requests and potential bugs are the
\href{http://biopython.org/wiki/Mailing_lists}{Biopython mailing lists}:
\begin{itemize}
\item \mailto{[email protected]} -- An unmoderated list for discussion of anything to do with Biopython.
\item \mailto{[email protected]} -- A more development oriented list that is mainly used by developers (but anyone is free to contribute!).
\end{itemize}
Additionally, if you think you've found a bug, you can submit it to our
bug-tracking page at \url{http://redmine.open-bio.org/projects/biopython}.
This way, it won't get buried in anyone's Inbox and forgotten about.
\section{Mailing lists and helping newcomers}
We encourage all our uses to sign up to the main Biopython mailing list.
Once you've got the hang of an area of Biopython, we'd encourage you to
help answer questions from beginners. After all, you were a beginner once.
\section{Contributing Documentation}
We're happy to take feedback or contributions - either via a bug-report or on the Mailing List.
While reading this tutorial, perhaps you noticed some topics you were interested in which were missing, or not clearly explained. There is also Biopython's built in documentation (the docstrings, these are also
\href{http://biopython.org/DIST/docs/api}{online}), where again, you may be able to help fill in any blanks.
\section{Contributing cookbook examples}
As explained in Chapter~\ref{chapter:cookbook}, Biopython now has a wiki
collection of user contributed ``cookbook'' examples,
\url{http://biopython.org/wiki/Category:Cookbook} -- maybe you can add
to this?
\section{Maintaining a distribution for a platform}
\label{sec:maintain_dist}
We currently provide source code archives (suitable for any OS, if you have the right build tools installed), and Windows Installers which are just click and run. This covers all the major operating systems.
Most major Linux distributions have volunteers who take these source code releases, and compile them into packages for Linux users to easily install (taking care of dependencies etc). This is really great and we are of course very grateful. If you would like to contribute to this work, please find out more about how your Linux distribution handles this.
Below are some tips for certain platforms to maybe get people started with helping out:
\begin{description}
\item[Windows] -- Windows products typically have a nice graphical installer that installs all of the essential components in the right place. We use Distutils to create a installer of this type fairly easily.
You must first make sure you have a C compiler on your Windows computer, and that you can compile and install things (this is the hard bit - see the Biopython installation instructions for info on how to do this).
Once you are setup with a C compiler, making the installer just requires doing:
\begin{verbatim}
python setup.py bdist_wininst
\end{verbatim}
Now you've got a Windows installer. Congrats! At the moment we have no trouble shipping installers built on 32 bit windows. If anyone would like to look into supporting 64 bit Windows that would be great.
\item[RPMs] -- RPMs are pretty popular package systems on some Linux platforms. There is lots of documentation on RPMs available at \url{http://www.rpm.org} to help you get started with them. To create an RPM for your platform is really easy. You just need to be able to build the package from source (having a C compiler that works is thus essential) -- see the Biopython installation instructions for more info on this.
To make the RPM, you just need to do:
\begin{verbatim}
python setup.py bdist_rpm
\end{verbatim}
This will create an RPM for your specific platform and a source RPM in the directory \verb|dist|. This RPM should be good and ready to go, so this is all you need to do! Nice and easy.
\item[Macintosh] -- Since Apple moved to Mac OS X, things have become much easier on the Mac. We generally
treat it as just another Unix variant, and installing Biopython from source is just as easy as on Linux.
The easiest way to get all the GCC compilers etc installed is to install Apple's X-Code.
We might be able to provide click and run installers for Mac OS X, but to date there hasn't been any demand.
\end{description}
Once you've got a package, please test it on your system to make sure it installs everything in a good way and seems to work properly. Once you feel good about it, send it off to one of the Biopython developers (write to our main mailing list at [email protected] if you're not sure who to send it to) and you've done it. Thanks!
\section{Contributing Unit Tests}
Even if you don't have any new functionality to add to Biopython, but you want to write some code, please
consider extending our unit test coverage. We've devoted all of Chapter~\ref{sec:regr_test} to this topic.
\section{Contributing Code}
There are no barriers to joining Biopython code development other
than an interest in creating biology-related code in Python. The
best place to express an interest is on the Biopython mailing lists
-- just let us know you are interested in coding and what kind of
stuff you want to work on. Normally, we try to have some discussion
on modules before coding them, since that helps generate good ideas
-- then just feel free to jump right in and start coding!
The main Biopython release tries to be fairly uniform and interworkable,
to make it easier for users. You can read about some of (fairly
informal) coding style guidelines we try to use in Biopython in the
contributing documentation at
\url{http://biopython.org/wiki/Contributing}. We also try to add code to the distribution along with tests (see Chapter~\ref{sec:regr_test} for more info on the regression testing framework) and documentation, so that everything can stay as workable and well documented as possible (including docstrings). This is, of course, the most ideal situation, under many situations you'll be able to find other people on the list who will be willing to help add documentation or more tests for your code once you make it available. So, to end this paragraph like the last, feel free to start working!
Please note that to make a code contribution you must have the legal right to contribute it and license it under the Biopython license. If you wrote it all yourself, and it is not based on any other code, this shouldn't be a problem. However, there are issues if you want to contribute a derivative work - for example something based on GPL or LPGL licenced code would not be compatible with our license. If you have any queries on this, please discuss the issue on the biopython-dev mailing list.
Another point of concern for any additions to Biopython regards any build time or run time dependencies. Generally speaking, writing code to interact with a standalone tool (like BLAST, EMBOSS or ClustalW) doesn't present a big problem. However, any dependency on another library - even a Python library (especially one needed in order to compile and install Biopython like NumPy) would need further discussion.
Additionally, if you have code that you don't think fits in the
distribution, but that you want to make available, we maintain Script
Central (\url{http://biopython.org/wiki/Scriptcentral})
which has pointers to freely available code in Python for bioinformatics.
Hopefully this documentation has got you excited enough about
Biopython to try it out (and most importantly, contribute!). Thanks
for reading all the way through!
\chapter{Appendix: Useful stuff about Python}
\label{sec:appendix}
If you haven't spent a lot of time programming in Python, many
questions and problems that come up in using Biopython are often
related to Python itself. This section tries to present some ideas and
code that come up often (at least for us!) while using the Biopython
libraries. If you have any suggestions for useful pointers that could
go here, please contribute!
\section{What the heck is a handle?}
\label{sec:appendix-handles}
Handles are mentioned quite frequently throughout this documentation,
and are also fairly confusing (at least to me!). Basically, you can
think of a handle as being a ``wrapper'' around text information.
Handles provide (at least) two benefits over plain text information:
\begin{enumerate}
\item They provide a standard way to deal with information stored in
different ways. The text information can be in a file, or in a
string stored in memory, or the output from a command line program,
or at some remote website, but the handle provides a common way of
dealing with information in all of these formats.
\item They allow text information to be read incrementally, instead
of all at once. This is really important when you are dealing with
huge text files which would use up all of your memory if you had to
load them all.
\end{enumerate}
Handles can deal with text information that is being read (e.~g.~reading
from a file) or written (e.~g.~writing information to a file). In the
case of a ``read'' handle, commonly used functions are \verb|read()|,
which reads the entire text information from the handle, and
\verb|readline()|, which reads information one line at a time. For
``write'' handles, the function \verb|write()| is regularly used.
The most common usage for handles is reading information from a file,
which is done using the built-in Python function \verb|open|. Here, we open a
handle to the file \href{examples/m\_cold.fasta}{m\_cold.fasta}
(also available online
\href{http://biopython.org/DIST/docs/tutorial/examples/m\_cold.fasta}{here}):
\begin{verbatim}
>>> handle = open("m_cold.fasta", "r")
>>> handle.readline()
">gi|8332116|gb|BE037100.1|BE037100 MP14H09 MP Mesembryanthemum ...\n"
\end{verbatim}
Handles are regularly used in Biopython for passing information to parsers.
For example, since Biopython 1.54 the main functions in \verb|Bio.SeqIO|
and \verb|Bio.AlignIO| have allowed you to use a filename instead of a
handle:
\begin{verbatim}
from Bio import SeqIO
for record in SeqIO.parse("m_cold.fasta", "fasta"):
print record.id, len(record)
\end{verbatim}
On older versions of Biopython you had to use a handle, e.g.
\begin{verbatim}
from Bio import SeqIO
handle = open("m_cold.fasta", "r")
for record in SeqIO.parse(handle, "fasta"):
print record.id, len(record)
handle.close()
\end{verbatim}
This pattern is still useful - for example suppose you have a gzip
compressed FASTA file you want to parse:
\begin{verbatim}
import gzip
from Bio import SeqIO
handle = gzip.open("m_cold.fasta.gz")
for record in SeqIO.parse(handle, "fasta"):
print record.id, len(record)
handle.close()
\end{verbatim}
See Section~\ref{sec:SeqIO_compressed} for more examples like this,
including reading bzip2 compressed files.
\subsection{Creating a handle from a string}
One useful thing is to be able to turn information contained in a
string into a handle. The following example shows how to do this using
\verb|cStringIO| from the Python standard library:
%doctest
\begin{verbatim}
>>> my_info = 'A string\n with multiple lines.'
>>> print my_info
A string
with multiple lines.
>>> from StringIO import StringIO
>>> my_info_handle = StringIO(my_info)
>>> first_line = my_info_handle.readline()
>>> print first_line
A string
<BLANKLINE>
>>> second_line = my_info_handle.readline()
>>> print second_line
with multiple lines.
\end{verbatim}
\begin{thebibliography}{99}
\bibitem{cock2009}
Peter J. A. Cock, Tiago Antao, Jeffrey T. Chang, Brad A. Chapman, Cymon J. Cox, Andrew Dalke, Iddo Friedberg, Thomas Hamelryck, Frank Kauff, Bartek Wilczynski, Michiel J. L. de Hoon: ``Biopython: freely available Python tools for computational molecular biology and bioinformatics''. {\it Bioinformatics} {\bf 25} (11), 1422--1423 (2009). \href{http://dx.doi.org/10.1093/bioinformatics/btp163}{doi:10.1093/bioinformatics/btp163},
\bibitem{pritchard2006}
Leighton Pritchard, Jennifer A. White, Paul R.J. Birch, Ian K. Toth: ``GenomeDiagram: a python package for the visualization of large-scale genomic data''. {\it Bioinformatics} {\bf 22} (5): 616--617 (2006).
\href{http://dx.doi.org/10.1093/bioinformatics/btk021}{doi:10.1093/bioinformatics/btk021},
\bibitem{toth2006}
Ian K. Toth, Leighton Pritchard, Paul R. J. Birch: ``Comparative genomics reveals what makes an enterobacterial plant pathogen''. {\it Annual Review of Phytopathology} {\bf 44}: 305--336 (2006).
\href{http://dx.doi.org/10.1146/annurev.phyto.44.070505.143444}{doi:10.1146/annurev.phyto.44.070505.143444},
\bibitem{vanderauwera2009}
G\'eraldine A. van der Auwera, Jaroslaw E. Kr\'ol, Haruo Suzuki, Brian Foster, Rob van Houdt, Celeste J. Brown, Max Mergeay, Eva M. Top: ``Plasmids captured in C. metallidurans CH34: defining the PromA family of broad-host-range plasmids''.
\textit{Antonie van Leeuwenhoek} {\bf 96} (2): 193--204 (2009).
\href{http://dx.doi.org/10.1007/s10482-009-9316-9}{doi:10.1007/s10482-009-9316-9}
\bibitem{proux2002}
Caroline Proux, Douwe van Sinderen, Juan Suarez, Pilar Garcia, Victor Ladero, Gerald F. Fitzgerald, Frank Desiere, Harald Br\"ussow:
``The dilemma of phage taxonomy illustrated by comparative genomics of Sfi21-Like Siphoviridae in lactic acid bacteria''. \textit{Journal of Bacteriology} {\bf 184} (21): 6026--6036 (2002).
\href{http://dx.doi.org/10.1128/JB.184.21.6026-6036.2002}{http://dx.doi.org/10.1128/JB.184.21.6026-6036.2002}
\bibitem{jupe2012}
Florian Jupe, Leighton Pritchard, Graham J. Etherington, Katrin MacKenzie, Peter JA Cock, Frank Wright, Sanjeev Kumar Sharma1, Dan Bolser, Glenn J Bryan, Jonathan DG Jones, Ingo Hein: ``Identification and localisation of the NB-LRR gene family within the potato genome''. \textit{BMC Genomics} {\bf 13}: 75 (2012).
\href{http://dx.doi.org/10.1186/1471-2164-13-75}{http://dx.doi.org/10.1186/1471-2164-13-75}
\bibitem{cock2010}
Peter J. A. Cock, Christopher J. Fields, Naohisa Goto, Michael L. Heuer, Peter M. Rice: ``The Sanger FASTQ file format for sequences with quality scores, and the Solexa/Illumina FASTQ variants''. \textit{Nucleic Acids Research} {\bf 38} (6): 1767--1771 (2010). \href{http://dx.doi.org/10.1093/nar/gkp1137}{doi:10.1093/nar/gkp1137}
\bibitem{brown1999}
Patrick O. Brown, David Botstein: ``Exploring the new world of the genome with DNA microarrays''. \textit{Nature Genetics} {\bf 21} (Supplement 1), 33--37 (1999). \href{http://dx.doi.org/10.1038/4462}{doi:10.1038/4462}
\bibitem{talevich2012}
Eric Talevich, Brandon M. Invergo, Peter J.A. Cock, Brad A. Chapman: ``Bio.Phylo: A unified toolkit for processing, analyzing and visualizing phylogenetic trees in Biopython''. \textit{BMC Bioinformatics} {\bf 13}: 209 (2012). \href{http://dx.doi.org/10.1186/1471-2105-13-209}{doi:10.1186/1471-2105-13-209}
\bibitem{cornish1985}
Athel Cornish-Bowden: ``Nomenclature for incompletely specified bases in nucleic acid sequences: Recommendations 1984.'' \textit{Nucleic Acids Research} {\bf 13} (9): 3021--3030 (1985). \href{http://dx.doi.org/10.1093/nar/13.9.3021}{doi:10.1093/nar/13.9.3021}
\bibitem{cavener1987}
Douglas R. Cavener: ``Comparison of the consensus sequence flanking translational start sites in Drosophila and vertebrates.'' \textit{Nucleic Acids Research} {\bf 15} (4): 1353--1361 (1987). \href{http://dx.doi.org/10.1093/nar/15.4.1353}{doi:10.1093/nar/15.4.1353}
\bibitem{bailey1994}
Timothy L. Bailey and Charles Elkan: ``Fitting a mixture model by expectation maximization to discover motifs in biopolymers'', \textit{Proceedings of the Second International Conference on Intelligent Systems for Molecular Biology} 28--36. AAAI Press, Menlo Park, California (1994).
\bibitem{chapman2000}
Brad Chapman and Jeff Chang: ``Biopython: Python tools for computational biology''. \textit{ACM SIGBIO Newsletter} {\bf 20} (2): 15--19 (August 2000).
\bibitem{dehoon2004}
Michiel J. L. de Hoon, Seiya Imoto, John Nolan, Satoru Miyano: ``Open source clustering software''. \textit{Bioinformatics} {\bf 20} (9): 1453--1454 (2004). \href{http://dx.doi.org/10.1093/bioinformatics/bth078}{doi:10.1093/bioinformatics/bth078}
\bibitem{eisen1998}
Michiel B. Eisen, Paul T. Spellman, Patrick O. Brown, David Botstein: ``Cluster analysis and display of genome-wide expression patterns''. \textit{Proceedings of the National Academy of Science USA} {\bf 95} (25): 14863--14868 (1998). \href{http://dx.doi.org/10.1073/pnas.96.19.10943-c}{doi:10.1073/pnas.96.19.10943-c}
\bibitem{golub1971}
Gene H. Golub, Christian Reinsch: ``Singular value decomposition and least squares solutions''. In \textit{Handbook for Automatic Computation}, {\bf 2}, (Linear Algebra) (J. H. Wilkinson and C. Reinsch, eds), 134--151. New York: Springer-Verlag (1971).
\bibitem{golub1989}
Gene H. Golub, Charles F. Van Loan: \textit{Matrix computations}, 2nd edition (1989).
\bibitem{hamelryck2003a}
Thomas Hamelryck and Bernard Manderick: 11PDB parser and structure class
implemented in Python''. \textit{Bioinformatics}, \textbf{19} (17): 2308--2310 (2003) \href{http://dx.doi.org/10.1093/bioinformatics/btg299}{doi: 10.1093/bioinformatics/btg299}.
\bibitem{hamelryck2003b}
Thomas Hamelryck: ``Efficient identification of side-chain patterns using a multidimensional index tree''. \textit{Proteins} {\bf 51} (1): 96--108 (2003). \href{http://dx.doi.org/10.1002/prot.10338}{doi:10.1002/prot.10338}
\bibitem{hamelryck2005}
Thomas Hamelryck: ``An amino acid has two sides; A new 2D measure provides a different view of solvent exposure''. \textit{Proteins} {\bf 59} (1): 29--48 (2005). \href{http://dx.doi.org/10.1002/prot.20379}{doi:10.1002/prot.20379}.
\bibitem{hartigan1975}
John A. Hartiga. \textit{Clustering algorithms}. New York: Wiley (1975).
\bibitem{jain1988}
Anil L. Jain, Richard C. Dubes: \textit{Algorithms for clustering data}. Englewood Cliffs, N.J.: Prentice Hall (1988).
\bibitem{kachitvichyanukul1988}
Voratas Kachitvichyanukul, Bruce W. Schmeiser: Binomial Random Variate Generation. \textit{Communications of the ACM} {\bf 31} (2): 216--222 (1988). \href{http://dx.doi.org/10.1145/42372.42381}{doi:10.1145/42372.42381}
\bibitem{kohonen1997}
Teuvo Kohonen: ``Self-organizing maps'', 2nd Edition. Berlin; New York: Springer-Verlag (1997).
\bibitem{lecuyer1988}
Pierre L'Ecuyer: ``Efficient and Portable Combined Random Number Generators.''
\textit{Communications of the ACM} {\bf 31} (6): 742--749,774 (1988). \href{http://dx.doi.org/10.1145/62959.62969}{doi:10.1145/62959.62969}
\bibitem{majumdar2005}
Indraneel Majumdar, S. Sri Krishna, Nick V. Grishin: ``PALSSE: A program to delineate linear secondary structural elements from protein structures.'' \textit{BMC Bioinformatics}, {\bf 6}: 202 (2005). \href{http://dx.doi.org/10.1186/1471-2105-6-202}{doi:10.1186/1471-2105-6-202}.
\bibitem{matys2003}
V. Matys, E. Fricke, R. Geffers, E. G\"ossling, M. Haubrock, R. Hehl, K. Hornischer, D. Karas, A.E. Kel, O.V. Kel-Margoulis, D.U. Kloos, S. Land, B. Lewicki-Potapov, H. Michael, R. M\"unch, I. Reuter, S. Rotert, H. Saxel, M. Scheer, S. Thiele, E. Wingender E: ``TRANSFAC: transcriptional regulation, from patterns to profiles.'' Nucleic Acids Research {\bf 31} (1): 374--378 (2003). \href{http://dx.doi.org/10.1093/nar/gkg108}{doi:10.1093/nar/gkg108}
\bibitem{sibson1973}
Robin Sibson: ``SLINK: An optimally efficient algorithm for the single-link cluster method''. \textit{The Computer Journal} {\bf 16} (1): 30--34 (1973). \href{http://dx.doi.org/10.1093/comjnl/16.1.30}{doi:10.1093/comjnl/16.1.30}
\bibitem{snedecor1989}
George W. Snedecor, William G. Cochran: \textit{Statistical methods}. Ames, Iowa: Iowa State University Press (1989).
\bibitem{tamayo1999}
Pablo Tamayo, Donna Slonim, Jill Mesirov, Qing Zhu, Sutisak Kitareewan, Ethan Dmitrovsky, Eric S. Lander, Todd R. Golub: ``Interpreting patterns of gene expression with self-organizing maps: Methods and application to hematopoietic differentiation''. \textit{Proceedings of the National Academy of Science USA} {\bf 96} (6): 2907--2912 (1999). \href{http://dx.doi.org/10.1073/pnas.96.6.2907}{doi:10.1073/pnas.96.6.2907}
\bibitem{tryon1970}
Robert C. Tryon, Daniel E. Bailey: \textit{Cluster analysis}. New York: McGraw-Hill (1970).
\bibitem{tukey1977}
John W. Tukey: ``Exploratory data analysis''. Reading, Mass.: Addison-Wesley Pub. Co. (1977).
\bibitem{yeung2001}
Ka Yee Yeung, Walter L. Ruzzo: ``Principal Component Analysis for clustering gene expression data''. \textit{Bioinformatics} {\bf 17} (9): 763--774 (2001). \href{http://dx.doi.org/10.1093/bioinformatics/17.9.763}{doi:10.1093/bioinformatics/17.9.763}
\bibitem{saldanha2004}
Alok Saldanha: ``Java Treeview---extensible visualization of microarray data''. \textit{Bioinformatics} {\bf 20} (17): 3246--3248 (2004).
\href{http://dx.doi.org/10.1093/bioinformatics/bth349}{http://dx.doi.org/10.1093/bioinformatics/bth349}
\end{thebibliography}
\end{document}
|
[STATEMENT]
lemma separatedin_Un [simp]:
"separatedin X S (T \<union> U) \<longleftrightarrow> separatedin X S T \<and> separatedin X S U"
"separatedin X (S \<union> T) U \<longleftrightarrow> separatedin X S U \<and> separatedin X T U"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. separatedin X S (T \<union> U) = (separatedin X S T \<and> separatedin X S U) &&& separatedin X (S \<union> T) U = (separatedin X S U \<and> separatedin X T U)
[PROOF STEP]
by (auto simp: separatedin_def) |
theory Sorting_Heapsort
imports Sorting_Setup
begin
(*
TODO: Fix section structure
*)
locale heap_range_context =
fixes l h :: nat
assumes ran_not_empty[arith,simp]: "l\<le>h"
begin
(*lemma l_le_h[arith,simp]: "l\<le>h" by simp*)
definition "in_heap i \<equiv> i\<in>{l..<h}"
definition parent where "parent i \<equiv> (i-1-l) div 2 + l"
definition lchild where "lchild i \<equiv> 2*(i-l) + 1 + l"
definition rchild where "rchild i \<equiv> 2*(i-l) + 2+ l"
definition has_parent where "has_parent i \<equiv> in_heap i \<and> i>l"
definition has_lchild where "has_lchild i \<equiv> in_heap i \<and> in_heap (lchild i)"
definition has_rchild where "has_rchild i \<equiv> in_heap i \<and> in_heap (rchild i)"
context begin
private method prove = (
unfold in_heap_def parent_def has_parent_def lchild_def rchild_def has_lchild_def has_rchild_def,
auto)
text \<open>Optimized checks, normalize to i-l, for index shift\<close>
lemma has_rchild_ihs: "in_heap i \<Longrightarrow> has_rchild i \<longleftrightarrow> i-l<(h-l-1) div 2"
by prove
lemma has_lchild_ihs: "in_heap i \<Longrightarrow> has_lchild i \<longleftrightarrow> (i-l) < (h-l) div 2"
by prove
lemma has_parent_ihs: "in_heap i \<Longrightarrow> has_parent i \<longleftrightarrow> i-l > 0"
by prove
lemma lchild_ihs: "lchild i - l = 2*(i-l)+1"
by prove
lemma rchild_ihs: "rchild i - l = 2*(i-l)+2"
by prove
lemma parent_ihs: "parent i - l = (i-l-1) div 2"
by prove
lemma in_heapI: "\<lbrakk> l\<le>i; i<h \<rbrakk> \<Longrightarrow> in_heap i" by prove
lemma in_heap_bounds[simp]:
assumes "in_heap i"
shows "l\<le>i" and "i<h"
using assms by prove
lemma in_heap_triv[simp]:
"has_parent i \<Longrightarrow> in_heap i"
"has_lchild i \<Longrightarrow> in_heap i"
"has_rchild i \<Longrightarrow> in_heap i"
by prove
lemma parent_in_heap[simp]:
"has_parent i \<Longrightarrow> in_heap (parent i)"
"has_parent i \<Longrightarrow> has_lchild (parent i)"
by prove
lemma children_in_heap[simp]:
"has_lchild i \<Longrightarrow> in_heap (lchild i)"
"has_rchild i \<Longrightarrow> in_heap (rchild i)"
by prove
lemmas in_heap_simps = in_heap_triv parent_in_heap children_in_heap
lemma parent_of_child[simp]:
"has_lchild i \<Longrightarrow> parent (lchild i) = i"
"has_rchild i \<Longrightarrow> parent (rchild i) = i"
by prove
lemma children_differ[simp]:
"lchild i \<noteq> rchild i"
"rchild i \<noteq> lchild i"
by prove
lemma parent_less[simp]: "has_parent i \<Longrightarrow> parent i < i" by prove
lemma children_greater[simp]:
"lchild i > i"
"rchild i > i"
by prove
lemma children_diff_add_simps[iff]:
"lchild i \<noteq> i"
"i \<noteq> lchild i"
"rchild i \<noteq> i"
"i \<noteq> rchild i"
by prove
lemma parent_diff_add_simps[simp]:
assumes "has_parent i" shows "i \<noteq> parent i" and "parent i \<noteq> i"
using assms by prove
lemma rchild_imp_lchild[simp, intro]: "has_rchild i \<Longrightarrow> has_lchild i" by prove
lemma no_parent_is_root: "in_heap i \<Longrightarrow> \<not>has_parent i \<longleftrightarrow> i=l" by prove
lemma root_no_parent[iff]: "\<not>has_parent l" by prove
lemma root_in_heap: "in_heap l\<longleftrightarrow>l<h" using ran_not_empty by prove
lemma child_of_parent: "has_parent i \<Longrightarrow> lchild (parent i) = i \<or> has_rchild (parent i) \<and> rchild (parent i) = i" by prove
lemma children_of_parent_cases[consumes 1]:
assumes "has_parent i"
obtains (left) "has_parent i" "lchild (parent i) = i"
| (right) "has_parent i" "has_rchild (parent i)" "rchild (parent i) = i"
using assms child_of_parent by blast
lemma lchild_of_no_rchild_term: "\<lbrakk>\<not>has_rchild i; has_lchild i\<rbrakk> \<Longrightarrow> \<not>has_lchild (lchild i)" by prove
end
lemmas heap_context_defs[no_atp] = in_heap_def parent_def lchild_def rchild_def has_parent_def has_lchild_def has_rchild_def
end
locale heap_context = weak_ordering + heap_range_context begin
definition is_heap :: "'a list \<Rightarrow> bool"
where "is_heap xs \<equiv> (h\<le>length xs) \<and> (\<forall>i. has_parent i \<longrightarrow> xs!parent i \<^bold>\<ge> xs!i)"
subsection \<open>Heap Property implies Minimal Element at Top\<close>
context
fixes xs
assumes H: "is_heap xs"
begin
lemma parent_el_greater[simp]: "has_parent i \<Longrightarrow> xs!i \<^bold>\<le> xs!parent i"
using H
unfolding is_heap_def
by simp
lemma root_greatest:
assumes "in_heap i"
shows "xs!i \<^bold>\<le> xs!l"
using assms
proof (induction i rule: less_induct)
case (less i)
note [simp] = \<open>in_heap i\<close>
show ?case proof cases
assume [simp]: "has_parent i"
have "xs!i \<^bold>\<le> xs!parent i" by simp
also from less.IH[of "parent i"] have "xs!parent i \<^bold>\<le> xs!l" by simp
finally show ?case .
next
assume "\<not>has_parent i"
hence "i=l" by (simp add: no_parent_is_root)
thus ?case by simp
qed
qed
end
subsection \<open>Sift-Up Lemmas\<close>
definition is_heap_except_up :: "nat \<Rightarrow> 'a list \<Rightarrow> bool"
where "is_heap_except_up j xs \<equiv>
(h\<le>length xs)
\<and> (\<forall>i. has_parent i \<and> i\<noteq>j \<longrightarrow> xs!parent i \<^bold>\<ge> xs!i)
\<and> (has_parent j \<and> has_lchild j \<longrightarrow> xs!parent j \<^bold>\<ge> xs!lchild j)
\<and> (has_parent j \<and> has_rchild j \<longrightarrow> xs!parent j \<^bold>\<ge> xs!rchild j)"
lemma is_heap_except_up_len_bound[simp, intro]:
assumes "is_heap_except_up i xs"
shows "h\<le>length xs"
using assms unfolding is_heap_except_up_def
by auto
lemma sift_up_lemma:
assumes HP: "has_parent i"
assumes IHE: "is_heap_except_up i xs"
assumes GE: "xs!i \<^bold>\<ge> xs!parent i"
shows "is_heap_except_up (parent i) (swap xs i (parent i))"
proof -
from assms(2) have [simp, arith]: "h\<le>length xs" unfolding is_heap_except_up_def by auto
have X[simp]: "i<length xs" if "in_heap i" for i
using in_heap_bounds(2)[OF that] by simp
have HPROP: "xs!j \<^bold>\<le> xs!parent j" if "has_parent j" "j\<noteq>i" for j
using that IHE unfolding is_heap_except_up_def by simp
show ?thesis using HP
unfolding is_heap_except_up_def
apply (clarsimp; safe)
subgoal
apply (clarsimp simp: swap_nth HPROP GE; safe)
subgoal by (metis GE HPROP trans)
by (metis IHE child_of_parent is_heap_except_up_def parent_in_heap(2))
subgoal
by (smt HPROP X children_greater(1) has_lchild_def in_heap_bounds(1) parent_of_child(1) trans nat_less_le no_parent_is_root parent_in_heap(2) parent_less less_le_trans swap_indep swap_nth)
subgoal
by (smt HPROP X children_greater(2) has_parent_def has_rchild_def parent_less parent_of_child(2) less_le trans less_trans swap_nth)
done
qed
text \<open>Terminate when reached root\<close>
lemma sift_up_term1: "is_heap_except_up l xs \<Longrightarrow> is_heap xs"
unfolding is_heap_def is_heap_except_up_def by auto
text \<open>Terminate when parent is greater or equal\<close>
lemma sift_up_term2: "\<lbrakk>is_heap_except_up i xs; xs!i\<^bold>\<le>xs!parent i\<rbrakk> \<Longrightarrow> is_heap xs"
unfolding is_heap_def is_heap_except_up_def by auto
lemma grow_heap_context: "heap_range_context l (Suc h)"
apply unfold_locales using ran_not_empty by linarith
text \<open>Initializes a sift-up cycle by extending the heap by one element to the right\<close>
lemma sift_up_init:
assumes "is_heap xs"
assumes "h<length xs"
shows "heap_context.is_heap_except_up (\<^bold>\<le>) l (Suc h) h xs"
proof -
interpret N: heap_range_context l "Suc h" using grow_heap_context .
interpret N: heap_context "(\<^bold>\<le>)" "(\<^bold><)" l "Suc h" by unfold_locales
show ?thesis
using assms
unfolding is_heap_def is_heap_except_up_def N.is_heap_except_up_def
unfolding N.heap_context_defs heap_context_defs
by auto
qed
subsection \<open>Sift-Down Lemmas\<close>
definition is_heap_except_down :: "nat \<Rightarrow> 'a list \<Rightarrow> bool"
where "is_heap_except_down j xs \<equiv>
(h\<le>length xs)
\<and> (\<forall>i. has_parent i \<and> parent i \<noteq> j \<longrightarrow> xs!parent i \<^bold>\<ge> xs!i)
\<and> (\<forall>i. has_parent i \<and> has_parent j \<and> parent i = j \<longrightarrow> xs!parent j \<^bold>\<ge> xs!i)"
lemma is_heap_except_down_len_bound[simp, intro]:
assumes "is_heap_except_down i xs"
shows "h\<le>length xs"
using assms unfolding is_heap_except_down_def
by auto
lemma sift_down_lemma_left:
assumes HRC: "has_rchild i"
assumes IHE: "is_heap_except_down i xs"
assumes GE: "xs!lchild i \<^bold>\<ge> xs!i" "xs!lchild i \<^bold>\<ge> xs!rchild i"
shows "is_heap_except_down (lchild i) (swap xs i (lchild i))"
proof -
show ?thesis
using IHE HRC GE
unfolding is_heap_except_down_def
apply (clarsimp)
by (smt child_of_parent children_greater(1) children_in_heap(1) dual_order.trans has_parent_def parent_diff_add_simps(1) in_heap_bounds(2) leD order_less_le parent_of_child(1) rchild_imp_lchild swap_indep swap_nth1 swap_nth2)
qed
lemma sift_down_lemma_right:
assumes HRC: "has_rchild i"
assumes IHE: "is_heap_except_down i xs"
assumes GE: "xs!rchild i \<^bold>\<ge> xs!i" "xs!lchild i \<^bold>\<le> xs!rchild i"
shows "is_heap_except_down (rchild i) (swap xs i (rchild i))"
proof -
show ?thesis
using IHE HRC GE
unfolding is_heap_except_down_def
apply (clarsimp)
by (smt child_of_parent children_greater(2) children_in_heap(2) dual_order.trans eq_iff heap_range_context.has_parent_def heap_range_context_axioms in_heap_bounds(2) less_le parent_less parent_of_child(2) swap_nth)
qed
lemma sift_down_lemma_left_no_right_child:
assumes HRC: "has_lchild i" "\<not>has_rchild i"
assumes IHE: "is_heap_except_down i xs"
assumes GE: "xs!lchild i \<^bold>\<ge> xs!i"
shows "is_heap_except_down (lchild i) (swap xs i (lchild i))"
proof -
from IHE have [simp, arith]: "h\<le>length xs" unfolding is_heap_except_down_def by auto
have X[simp]: "i<length xs" if "in_heap i" for i
using in_heap_bounds(2)[OF that] by simp
show ?thesis
using IHE HRC GE
unfolding is_heap_except_down_def
apply clarsimp
by (smt X child_of_parent children_greater(1) children_in_heap(1) heap_range_context.has_parent_def heap_range_context.parent_of_child(1) heap_range_context_axioms le_less_trans less_imp_le_nat parent_in_heap(1) swap_nth)
qed
lemma sift_down_term1: "\<not>has_lchild j \<Longrightarrow> is_heap_except_down j xs \<longleftrightarrow> is_heap xs"
unfolding is_heap_except_down_def is_heap_def
by auto
lemma sift_down_term2: "\<lbrakk>is_heap_except_down j xs; has_rchild j; xs!j\<^bold>\<ge>xs!lchild j; xs!j\<^bold>\<ge>xs!rchild j \<rbrakk> \<Longrightarrow> is_heap xs"
unfolding is_heap_except_down_def is_heap_def
apply (clarsimp)
by (metis children_of_parent_cases)
lemma sift_down_term3: "\<lbrakk>is_heap_except_down j xs; has_lchild j; \<not>has_rchild j; xs!j\<^bold>\<ge>xs!lchild j \<rbrakk> \<Longrightarrow> is_heap xs"
unfolding is_heap_except_down_def is_heap_def
apply (clarsimp)
by (metis children_of_parent_cases)
lemma shrink_heap_context: "Suc l<h \<Longrightarrow> heap_range_context l (h-Suc 0)"
apply unfold_locales using ran_not_empty by linarith
text \<open>Initializes a sift-down cycle by swapping the first and last element, and then shrinking the heap by one element\<close>
lemma sift_down_init:
assumes "is_heap xs"
assumes LT: "Suc l < h"
shows "heap_context.is_heap_except_down (\<^bold>\<le>) l (h-Suc 0) l (swap xs l (h-Suc 0))"
proof -
interpret N: heap_context "(\<^bold>\<le>)" "(\<^bold><)" l "h-Suc 0"
apply intro_locales
using shrink_heap_context[OF LT] .
show ?thesis
using assms
unfolding is_heap_def is_heap_except_down_def N.is_heap_except_down_def
unfolding N.heap_context_defs heap_context_defs
by (auto simp: swap_nth)
qed
subsection \<open>Bottom-up Heapify\<close>
text \<open>The nodes from index \<open>l'\<close> upwards satisfy the heap criterion\<close>
definition is_heap_btu :: "nat \<Rightarrow> 'a list \<Rightarrow> bool" where "is_heap_btu l' xs \<equiv>
(l'\<le>h \<and> h\<le>length xs)
\<and> (\<forall>i. has_parent i \<and> parent i \<ge> l' \<longrightarrow> xs!parent i \<^bold>\<ge> xs!i)"
text \<open>Bottom-up heapify starts with only the last element being a heap\<close>
lemma btu_heapify_init: "h\<le>length xs \<Longrightarrow> is_heap_btu (h-Suc 0) xs"
unfolding is_heap_btu_def
apply auto
by (meson dual_order.trans in_heap_bounds(2) in_heap_triv(1) nat_le_Suc_less_imp not_le parent_less)
text \<open>When we have reached the lower index, we have a complete heap\<close>
lemma btu_heapify_term: "is_heap_btu l xs \<longleftrightarrow> is_heap xs"
unfolding is_heap_btu_def is_heap_def
by (auto simp: less_imp_le_nat)
text \<open>All nodes in between l' and h form a valid heap, with downwards-hole at j\<close>
definition is_heap_except_down_btu :: "nat \<Rightarrow> nat \<Rightarrow> 'a list \<Rightarrow> bool"
where "is_heap_except_down_btu l' j xs \<equiv>
(l'\<le>j \<and> j<h \<and> h\<le>length xs)
\<and> (\<forall>i. has_parent i \<and> parent i \<ge> l' \<and> parent i \<noteq> j \<longrightarrow> xs!parent i \<^bold>\<ge> xs!i)
\<and> (\<forall>i. has_parent i \<and> has_parent j \<and> parent j \<ge>l' \<and> parent i = j \<longrightarrow> xs!parent j \<^bold>\<ge> xs!i)"
lemma is_heap_except_down_btu_lenD: "is_heap_except_down_btu l' j xs \<Longrightarrow> h\<le>length xs"
unfolding is_heap_except_down_btu_def by auto
text \<open>A sift-down round starts by including one more left element, and marking it as a hole\<close>
lemma btu_sift_down_init: "\<lbrakk>is_heap_btu l' xs; l'>l\<rbrakk> \<Longrightarrow> is_heap_except_down_btu (l'-1) (l'-1) xs"
unfolding is_heap_except_down_btu_def is_heap_btu_def
apply auto
using leD parent_less by blast
text \<open>Sift-down completed, we have a complete heap from \<open>l'\<close> upwards\<close>
lemma btu_sift_down_term1: "\<not>has_lchild j \<Longrightarrow> is_heap_except_down_btu l' j xs \<Longrightarrow> is_heap_btu l' xs"
unfolding is_heap_except_down_btu_def is_heap_btu_def
by auto
lemma btu_sift_down_term2: "\<lbrakk>is_heap_except_down_btu l' j xs; has_rchild j; xs!j\<^bold>\<ge>xs!lchild j; xs!j\<^bold>\<ge>xs!rchild j \<rbrakk>
\<Longrightarrow> is_heap_btu l' xs"
unfolding is_heap_except_down_btu_def is_heap_btu_def
apply (clarsimp)
by (smt dual_order.trans child_of_parent in_heap_bounds(2) in_heap_triv(3) le_cases not_le)
lemma btu_sift_down_term3: "\<lbrakk>is_heap_except_down_btu l' j xs; has_lchild j; \<not>has_rchild j; xs!j\<^bold>\<ge>xs!lchild j \<rbrakk> \<Longrightarrow> is_heap_btu l' xs"
unfolding is_heap_except_down_btu_def is_heap_btu_def
apply (clarsimp)
by (metis child_of_parent dual_order.trans in_heap_bounds(2) in_heap_triv(2) less_imp_le)
lemma btu_heapify_down_left:
assumes HRC: "has_rchild i"
assumes IHE: "is_heap_except_down_btu l' i xs"
assumes GE: "xs!lchild i \<^bold>\<ge> xs!i" "xs!lchild i \<^bold>\<ge> xs!rchild i"
shows "is_heap_except_down_btu l' (lchild i) (swap xs i (lchild i))"
proof -
from IHE have [simp, arith]: "h\<le>length xs" unfolding is_heap_except_down_btu_def by auto
have X[simp]: "i<length xs" if "in_heap i" for i
using in_heap_bounds(2)[OF that] by simp
show ?thesis
using HRC IHE GE
unfolding is_heap_except_down_btu_def
apply (clarsimp simp: swap_nth)
by (smt child_of_parent children_greater(1) children_in_heap(1) heap_range_context.has_parent_def heap_range_context_axioms leD le_cases less_le_trans parent_of_child(1) rchild_imp_lchild)
qed
lemma btu_heapify_down_right:
assumes HRC: "has_rchild i"
assumes IHE: "is_heap_except_down_btu l' i xs"
assumes GE: "xs!rchild i \<^bold>\<ge> xs!i" "xs!lchild i \<^bold>\<le> xs!rchild i"
shows "is_heap_except_down_btu l' (rchild i) (swap xs i (rchild i))"
proof -
from IHE have [simp, arith]: "h\<le>length xs" unfolding is_heap_except_down_btu_def by auto
have X[simp]: "i<length xs" if "in_heap i" for i
using in_heap_bounds(2)[OF that] by simp
show ?thesis
using HRC IHE GE
unfolding is_heap_except_down_btu_def
apply (clarsimp simp: swap_nth)
by (smt child_of_parent children_greater(2) children_in_heap(2) dual_order.strict_trans2 heap_range_context.has_parent_def heap_range_context_axioms less_imp_le_nat parent_of_child(2))
qed
lemma btu_heapify_down_left_no_right_child:
assumes HRC: "has_lchild i" "\<not>has_rchild i"
assumes IHE: "is_heap_except_down_btu l' i xs"
assumes GE: "xs!lchild i \<^bold>\<ge> xs!i"
shows "is_heap_except_down_btu l' (lchild i) (swap xs i (lchild i))"
proof -
from IHE have [simp, arith]: "h\<le>length xs" unfolding is_heap_except_down_btu_def by auto
have X[simp]: "i<length xs" if "in_heap i" for i
using in_heap_bounds(2)[OF that] by simp
show ?thesis
using HRC IHE GE
unfolding is_heap_except_down_btu_def
apply (clarsimp simp: swap_nth)
by (smt child_of_parent children_greater(1) children_in_heap(1) heap_range_context.has_parent_def heap_range_context_axioms leD le_cases less_le_trans parent_of_child(1))
qed
definition "sift_up_invar xs\<^sub>0 i xs \<equiv>
slice_eq_mset l h xs xs\<^sub>0
\<and> is_heap_except_up i xs"
lemma sift_up_invar_init:
assumes "is_heap xs" "slice_eq_mset l h xs xs\<^sub>0" "h<length xs"
shows "heap_context.sift_up_invar (\<^bold>\<le>) l (Suc h) xs\<^sub>0 h xs"
proof -
interpret N: heap_context "(\<^bold>\<le>)" "(\<^bold><)" l "Suc h" by intro_locales (simp add: grow_heap_context)
show ?thesis
using assms
by (meson N.sift_up_invar_def le_eq_less_or_eq nat_in_between_eq(1) ran_not_empty sift_up_init slice_eq_mset_subslice)
qed
lemma sift_up_invar_step: "\<lbrakk>sift_up_invar xs\<^sub>0 i xs; has_parent i; xs!i\<^bold>\<ge>xs!parent i \<rbrakk>
\<Longrightarrow> sift_up_invar xs\<^sub>0 (parent i) (swap xs i (parent i))"
unfolding sift_up_invar_def
by (auto simp: sift_up_lemma)
lemma sift_up_invar_term1: "\<lbrakk>sift_up_invar xs\<^sub>0 l xs\<rbrakk> \<Longrightarrow> is_heap xs \<and> slice_eq_mset l h xs xs\<^sub>0"
unfolding sift_up_invar_def
using sift_up_term1 by blast
lemma sift_up_invar_term2: "\<lbrakk>sift_up_invar xs\<^sub>0 i xs; xs!i\<^bold>\<le>xs!parent i\<rbrakk>
\<Longrightarrow> is_heap xs \<and> slice_eq_mset l h xs xs\<^sub>0"
unfolding sift_up_invar_def
using sift_up_term2 by blast
definition "sift_down_invar xs\<^sub>0 i xs \<equiv>
slice_eq_mset l h xs xs\<^sub>0
\<and> is_heap_except_down i xs"
lemma sift_down_invar_step:
assumes "sift_down_invar xs\<^sub>0 i xs"
shows "\<lbrakk>has_rchild i; xs!i\<^bold>\<le>xs!lchild i; xs!lchild i \<^bold>\<ge> xs!rchild i\<rbrakk> \<Longrightarrow> sift_down_invar xs\<^sub>0 (lchild i) (swap xs i (lchild i))"
and "\<lbrakk>has_rchild i; xs!i\<^bold>\<le>xs!rchild i; xs!lchild i \<^bold>\<le> xs!rchild i\<rbrakk> \<Longrightarrow> sift_down_invar xs\<^sub>0 (rchild i) (swap xs i (rchild i))"
and "\<lbrakk>has_lchild i; \<not>has_rchild i; xs!i\<^bold>\<le>xs!lchild i\<rbrakk> \<Longrightarrow> sift_down_invar xs\<^sub>0 (lchild i) (swap xs i (lchild i))"
using assms unfolding sift_down_invar_def
by (auto simp: sift_down_lemma_left sift_down_lemma_right sift_down_lemma_left_no_right_child)
thm sift_down_init (*xxx, ctd here: we need to initialize from heapsort loop invariant*)
lemma sift_down_invar_init:
assumes "is_heap xs" "Suc l < h"
shows "heap_context.sift_down_invar (\<^bold>\<le>) l (h-Suc 0) (swap xs l (h-Suc 0)) l (swap xs l (h-Suc 0))"
proof -
interpret N: heap_context "(\<^bold>\<le>)" "(\<^bold><)" l "h-Suc 0" apply intro_locales using assms shrink_heap_context by auto
show ?thesis using sift_down_init assms unfolding N.sift_down_invar_def
by (auto simp: sift_down_init)
qed
definition "heapify_btu_invar xs\<^sub>0 l' xs \<equiv>
slice_eq_mset l h xs xs\<^sub>0
\<and> is_heap_btu l' xs"
definition "sift_down_btu_invar xs\<^sub>0 l' i xs \<equiv>
slice_eq_mset l h xs xs\<^sub>0
\<and> is_heap_except_down_btu l' i xs"
end
context weak_ordering begin
sublocale singleton_heap_context: heap_context "(\<^bold>\<le>)" "(\<^bold><)" l "(Suc l)"
by unfold_locales auto
lemma singleton_no_relatives[simp, intro!]:
"\<not>singleton_heap_context.has_parent l i"
"\<not>singleton_heap_context.has_lchild l i"
"\<not>singleton_heap_context.has_rchild l i"
unfolding singleton_heap_context.heap_context_defs
by auto
lemma singleton_heap: "l<length xs \<Longrightarrow> singleton_heap_context.is_heap l xs"
unfolding singleton_heap_context.is_heap_def
by auto
end
context heap_context begin
definition sift_down :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a list nres" where "sift_down i\<^sub>0 xs \<equiv> doN {
ASSERT (in_heap i\<^sub>0 \<and> i\<^sub>0<length xs);
(xs,i,_) \<leftarrow> WHILEIT (\<lambda>(xs,i,ctd). in_heap i \<and> i\<ge>i\<^sub>0)
(\<lambda>(xs,i,ctd). has_rchild i \<and> ctd)
(\<lambda>(xs,i,ctd). doN {
lc \<leftarrow> mop_list_get xs (lchild i);
rc \<leftarrow> mop_list_get xs (rchild i);
v \<leftarrow> mop_list_get xs i;
if lc \<^bold>< rc then
if v \<^bold>< rc then doN {
xs \<leftarrow> mop_list_swap xs i (rchild i);
RETURN (xs,rchild i,True)
} else RETURN (xs,i,False)
else if v \<^bold>< lc then doN {
xs \<leftarrow> mop_list_swap xs i (lchild i);
RETURN (xs,lchild i,True)
} else RETURN (xs,i,False)
})
(xs,i\<^sub>0,True);
ASSERT (in_heap i \<and> i\<ge>i\<^sub>0);
ASSERT (has_lchild i \<longrightarrow> lchild i < length xs);
if has_lchild i \<and> xs!i \<^bold>< xs!lchild i then
mop_list_swap xs i (lchild i)
else
RETURN xs
}"
lemma in_heap_len_bound: "in_heap i \<Longrightarrow> h\<le>length xs \<Longrightarrow> i<length xs"
using in_heap_bounds(2) less_le_trans by blast
lemma sift_down_btu_correct:
assumes "heapify_btu_invar xs\<^sub>0 l' xs" "l<l'"
shows "sift_down (l'-Suc 0) xs \<le> SPEC (\<lambda>xs'. heapify_btu_invar xs\<^sub>0 (l'-Suc 0) xs')"
unfolding sift_down_def
apply (refine_vcg WHILEIT_rule_amend_invar[where
I="\<lambda>(xs,i,ctd).
sift_down_btu_invar xs\<^sub>0 (l'-Suc 0) i xs
\<and> h\<le>length xs
\<and> (\<not>ctd \<longrightarrow> has_rchild i \<and> xs!i\<^bold>\<ge>xs!lchild i \<and> xs!i\<^bold>\<ge>xs!rchild i)"
and
R = "measure (\<lambda>(xs,i,ctd). (if ctd then 1 else 0) + h - i)"
])
using assms
unfolding heapify_btu_invar_def sift_down_btu_invar_def
apply (simp_all del: in_heap_simps)
apply (all \<open>(auto simp: in_heap_len_bound diff_less_mono2 wo_leI; fail)?\<close>)
subgoal unfolding is_heap_btu_def by (auto intro!: in_heapI)
subgoal unfolding is_heap_btu_def by auto
subgoal using btu_sift_down_init by auto
subgoal unfolding is_heap_btu_def by auto
subgoal by (force simp: asym wo_leI simp: btu_heapify_down_right)
subgoal using children_greater(2) le_trans less_imp_le_nat by blast
subgoal by (simp add: diff_less_mono2 less_Suc_eq)
subgoal by simp (metis wo_leI wo_less_trans)
subgoal by (simp add: diff_less_mono less_imp_le)
subgoal by (force simp add: btu_heapify_down_left asym wo_leI)
subgoal using children_greater(1) dual_order.strict_trans2 less_imp_le by blast
subgoal by (simp add: diff_less_mono2 less_Suc_eq)
subgoal apply simp using local.trans wo_leI by blast
subgoal by (simp add: diff_less_mono less_imp_le)
subgoal
apply clarsimp
using btu_heapify_down_left_no_right_child btu_sift_down_term1 connex lchild_of_no_rchild_term wo_leD by blast
subgoal
apply clarsimp
using btu_sift_down_term1 btu_sift_down_term2 btu_sift_down_term3 wo_leI by blast
done
lemma sift_down_restore_correct:
assumes A: "l<h" "sift_down_invar xs\<^sub>0 l xs"
shows "sift_down l xs \<le> SPEC (\<lambda>xs'. slice_eq_mset l h xs' xs\<^sub>0 \<and> is_heap xs')"
unfolding sift_down_def
apply (refine_vcg WHILEIT_rule_amend_invar[where
I="\<lambda>(xs,i,ctd).
sift_down_invar xs\<^sub>0 i xs
\<and> h\<le>length xs
\<and> (\<not>ctd \<longrightarrow> has_rchild i \<and> xs!i\<^bold>\<ge>xs!lchild i \<and> xs!i\<^bold>\<ge>xs!rchild i)"
and
R = "measure (\<lambda>(xs,i,ctd). (if ctd then 1 else 0) + h - i)"
])
apply clarsimp_all
apply (all \<open>(auto simp: in_heap_len_bound diff_less_mono2 A sift_down_invar_step wo_leI root_in_heap; fail)?\<close>)
subgoal using A unfolding sift_down_invar_def is_heap_except_down_def by auto
subgoal using A unfolding sift_down_invar_def is_heap_except_down_def by auto
subgoal using asym sift_down_invar_step(2) wo_leI by blast
subgoal by (simp add: diff_less_mono2 less_SucI)
subgoal using wo_less_trans wo_not_le_imp_less by blast
subgoal by (simp add: Suc_diff_le less_imp_le)
subgoal using asym sift_down_invar_step(1) wo_leI by blast
subgoal by (simp add: diff_less_mono2 less_Suc_eq)
subgoal using itrans wo_leI by blast
subgoal by (simp add: Suc_diff_le less_imp_le)
subgoal unfolding sift_down_invar_def by simp
subgoal by (meson lchild_of_no_rchild_term sift_down_invar_def sift_down_invar_step(3) sift_down_term1 wo_leD wo_leI wo_less_not_sym)
subgoal by (meson lchild_of_no_rchild_term less_imp_le not_le sift_down_invar_def sift_down_lemma_left_no_right_child sift_down_term1)
(*subgoal unfolding sift_down_invar_def by simp*)
subgoal unfolding sift_down_invar_def by (meson wo_leI sift_down_term1 sift_down_term2 sift_down_term3)
done
text \<open>Deferred swap optimization\<close>
definition sift_down1 :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a list nres" where "sift_down1 i\<^sub>0 xs \<equiv> doN {
ASSERT (in_heap i\<^sub>0);
v \<leftarrow> mop_list_get xs i\<^sub>0;
(xs,i,_) \<leftarrow> WHILEIT (\<lambda>(xs,i,ctd). in_heap i \<and> i\<ge>i\<^sub>0) (\<lambda>(xs,i,ctd). has_rchild i \<and> ctd) (\<lambda>(xs,i,ctd). doN {
lc \<leftarrow> mop_list_get xs (lchild i);
rc \<leftarrow> mop_list_get xs (rchild i);
if lc \<^bold>< rc then
if v \<^bold>< rc then doN {
t \<leftarrow> mop_list_get xs (rchild i);
xs \<leftarrow> mop_list_set xs i t;
RETURN (xs,rchild i,True)
} else RETURN (xs,i,False)
else if v \<^bold>< lc then doN {
t \<leftarrow> mop_list_get xs (lchild i);
xs \<leftarrow> mop_list_set xs i t;
RETURN (xs,lchild i,True)
} else RETURN (xs,i,False)
}) (xs,i\<^sub>0,True);
ASSERT (in_heap i \<and> i\<ge>i\<^sub>0);
ASSERT (has_lchild i \<longrightarrow> lchild i < length xs);
xs \<leftarrow> (if has_lchild i \<and> v \<^bold>< xs!lchild i then doN {
t \<leftarrow> mop_list_get xs (lchild i);
xs \<leftarrow> mop_list_set xs i t;
xs \<leftarrow> mop_list_set xs (lchild i) v;
RETURN xs
} else doN {
xs \<leftarrow> mop_list_set xs i v;
RETURN xs
});
RETURN xs
}"
definition "swap_opt_rel v \<equiv> {((xs,i,ctd),(xs',i',ctd')). xs' = xs[i:=v] \<and> i<length xs \<and> i'=i \<and> ctd'=ctd }"
lemma sift_down1_refine: "sift_down1 i\<^sub>0 xs \<le>\<Down>Id (sift_down i\<^sub>0 xs)"
unfolding sift_down1_def sift_down_def
apply (intro refine0)
subgoal by simp
apply (rule specify_left_pw, simp)
subgoal for v
apply (rule refine)
apply (rule WHILEIT_refine[where R="swap_opt_rel v"])
subgoal by (auto simp: swap_opt_rel_def)
subgoal by (auto simp: swap_opt_rel_def)
subgoal by (auto simp: swap_opt_rel_def)
subgoal for s s'
apply (clarsimp simp: swap_opt_rel_def split del: if_split)
apply (intro refine0 if_refine)
apply (all \<open>(auto; auto simp: swap_def;fail)?\<close>)
done
subgoal for s s'
supply [simp del] = conc_Id
apply (clarsimp simp: swap_opt_rel_def split del: if_split)
apply (intro refine0 if_refine)
apply (all \<open>(auto; auto simp: swap_def;fail)?\<close>)
(*apply simp apply refine_rcg
apply (auto simp: swap_def)*)
done
done
done
text \<open>Index shift optimization\<close>
definition "ihs_opt_rel \<equiv> {((xs,i,ctd),(xs',i',ctd')). xs' = xs \<and> i' = i+l \<and> ctd'=ctd }"
lemma ihs_opt_rel_alt: "((xs,i,ctd), (xs',i',ctd'))\<in>ihs_opt_rel \<longleftrightarrow> xs'=xs \<and> (i',i)\<in>idx_shift_rel l \<and> ctd'=ctd"
unfolding ihs_opt_rel_def idx_shift_rel_def by auto
definition [simp]: "mop_lchild2 i \<equiv> doN { ASSERT (2*i+1<h); RETURN (2*i+1) }"
definition [simp]: "mop_rchild2 i \<equiv> doN { ASSERT (2*i+2<h); RETURN (2*i+2) }"
definition [simp]: "has_rchild2 i \<equiv> i<(h-l-1) div 2"
definition [simp]: "has_lchild2 i \<equiv> i<(h-l) div 2"
end
concrete_definition mop_lchild3 is heap_context.mop_lchild2_def
concrete_definition mop_rchild3 is heap_context.mop_rchild2_def
concrete_definition has_rchild3 is heap_context.has_rchild2_def
concrete_definition has_lchild3 is heap_context.has_lchild2_def
lemmas h_aux_refines = mop_lchild3.refine mop_rchild3.refine has_rchild3.refine
has_lchild3.refine
context heap_context begin
definition sift_down2 :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a list nres" where "sift_down2 i\<^sub>0 xs \<equiv> doN {
ASSERT (l\<le>i\<^sub>0 \<and> i\<^sub>0<h);
let i\<^sub>1 = i\<^sub>0 - l;
v \<leftarrow> mop_list_get xs (i\<^sub>1+l);
(xs,i,_) \<leftarrow> WHILEIT (\<lambda>(xs,i,ctd). i<h-l \<and> i\<ge>i\<^sub>1) (\<lambda>(xs,i,ctd). has_rchild3 l h i \<and> ctd) (\<lambda>(xs,i,ctd). doN {
lci \<leftarrow> mop_lchild3 h i;
rci \<leftarrow> mop_rchild3 h i;
ASSERT (lci+l<h \<and> rci+l<h);
ASSERT (lci\<noteq>i \<and> rci\<noteq>i \<and> lci\<noteq>rci);
lc \<leftarrow> mop_list_get xs (lci+l);
rc \<leftarrow> mop_list_get xs (rci+l);
ASSERT (i+l<h);
if lc \<^bold>< rc then
if v \<^bold>< rc then doN {
xs \<leftarrow> mop_list_set xs (i+l) rc;
RETURN (xs,rci,True)
} else RETURN (xs,i,False)
else if v \<^bold>< lc then doN {
xs \<leftarrow> mop_list_set xs (i+l) lc;
RETURN (xs,lci,True)
} else RETURN (xs,i,False)
}) (xs,i\<^sub>1,True);
ASSERT (i\<ge>i\<^sub>1 \<and> i+l<h);
if has_lchild3 l h i then doN {
lci \<leftarrow> mop_lchild3 h i;
ASSERT (lci+l<h);
ASSERT (lci\<noteq>i);
lc \<leftarrow> mop_list_get xs (lci+l);
if v \<^bold>< lc then doN {
xs \<leftarrow> mop_list_set xs (i+l) lc;
xs \<leftarrow> mop_list_set xs (lci+l) v;
RETURN xs
} else doN {
xs \<leftarrow> mop_list_set xs (i+l) v;
RETURN xs
}
} else doN {
xs \<leftarrow> mop_list_set xs (i+l) v;
RETURN xs
}
}"
lemma idx_shift_adjust:
assumes "(i',i)\<in>idx_shift_rel l"
shows
"in_heap i' \<longleftrightarrow> i<h-l"
"has_lchild i' \<longleftrightarrow> i<(h-l) div 2"
"has_rchild i' \<longleftrightarrow> i<(h-l-1) div 2"
"lchild i' = 2*i+1+l"
"rchild i' = 2*i+2+l"
"i+l = i'"
"i'<x \<longleftrightarrow> i<x-l"
"i'\<le>h \<longleftrightarrow> i\<le>h-l"
"x\<le>i' \<longleftrightarrow> x-l\<le>i"
using assms
thm lchild_ihs
unfolding idx_shift_rel_def
in_heap_def
has_rchild_def rchild_def
has_lchild_def lchild_def
by auto
lemma sift_down2_refine: "sift_down2 i xs \<le> \<Down>Id (sift_down1 i xs)"
unfolding sift_down1_def sift_down2_def
unfolding h_aux_refines[OF heap_context_axioms, symmetric]
supply [simp del] = conc_Id
apply (simp cong: if_cong)
apply (rewrite at "let i=i-l in _" Let_def)
apply (intro refine0)
apply (all \<open>unfold in_heap_def; simp_all; fail \<close>) [2]
apply (rule bind_refine)
focus
apply refine_rcg
supply [refine_dref_RELATES] = RELATESI[of ihs_opt_rel]
apply refine_dref_type
apply (simp_all add: ihs_opt_rel_alt)
apply (all \<open>(determ \<open>elim conjE\<close>)?; simp?\<close>)
apply (clarsimp_all simp: idx_shift_adjust ihs_opt_rel_alt simp del: in_heap_simps) (** Takes loooong *)
unfolding in_heap_def idx_shift_rel_def ihs_opt_rel_alt
apply (auto simp: algebra_simps)
solved
subgoal for s s'
supply [split del] = if_split
apply (cases s; simp)
apply (cases s'; simp)
apply (intro refine0)
subgoal by (clarsimp simp: idx_shift_adjust ihs_opt_rel_alt)
apply (split if_split; intro conjI impI)
subgoal
apply refine_rcg
apply (simp_all add: ihs_opt_rel_alt)
apply (all \<open>determ \<open>elim conjE\<close>; simp?\<close>)
apply (auto simp: algebra_simps idx_shift_adjust)
done
subgoal
apply (split if_split, intro impI conjI refine0)
apply (simp_all add: ihs_opt_rel_alt)
apply (all \<open>determ \<open>elim conjE\<close>; simp?\<close>)
apply (auto simp: ihs_opt_rel_alt idx_shift_adjust algebra_simps)
done
done
done
(* Auxiliary definitions to reduce proof complexity in sepref-step.
TODO: Without these, the sepref step gets really slow, which is another indication that we
should separate the bound-proofs from the actual transfer step!
*)
definition [simp]: "mop_geth2 xs i \<equiv> doN { ASSERT(l+i\<le>h); mop_eo_extract xs (l+i) }"
definition [simp]: "mop_seth2 xs i x \<equiv> doN { ASSERT(l+i\<le>h); mop_eo_set xs (l+i) x }"
end
concrete_definition mop_geth3 is heap_context.mop_geth2_def
concrete_definition mop_seth3 is heap_context.mop_seth2_def
lemmas h_aux_refines2 = mop_geth3.refine mop_seth3.refine
context heap_context begin
definition sift_down3 :: "nat \<Rightarrow> 'a list \<Rightarrow> 'a list nres" where "sift_down3 i\<^sub>0 xs \<equiv> doN {
ASSERT (l\<le>i\<^sub>0 \<and> i\<^sub>0<h);
let i\<^sub>1 = i\<^sub>0 - l;
xs \<leftarrow> mop_to_eo_conv xs;
(v,xs) \<leftarrow> mop_geth3 l h xs i\<^sub>1;
(xs,i,_) \<leftarrow> WHILEIT (\<lambda>(xs,i,ctd). i<h-l \<and> i\<ge>i\<^sub>1) (\<lambda>(xs,i,ctd). has_rchild3 l h i \<and> ctd) (\<lambda>(xs,i,ctd). doN {
lci \<leftarrow> mop_lchild3 h i;
rci \<leftarrow> mop_rchild3 h i;
ASSERT (l+lci<h \<and> l+rci<h \<and> l+lci \<noteq> l+rci);
b \<leftarrow> mop_cmpo_idxs xs (l+lci) (l+rci);
if b then doN {
b \<leftarrow> mop_cmpo_v_idx xs v (l+rci);
if b then doN {
(rc,xs) \<leftarrow> mop_geth3 l h xs rci;
xs \<leftarrow> mop_seth3 l h xs i rc;
RETURN (xs,rci,True)
} else RETURN (xs,i,False)
} else doN {
b \<leftarrow> mop_cmpo_v_idx xs v (l+lci);
if b then doN {
(lc,xs) \<leftarrow> mop_geth3 l h xs lci;
xs \<leftarrow> mop_seth3 l h xs i lc;
RETURN (xs,lci,True)
} else RETURN (xs,i,False)
}
}) (xs,i\<^sub>1,True);
ASSERT (i\<ge>i\<^sub>1);
if has_lchild3 l h i then doN {
lci \<leftarrow> mop_lchild3 h i;
ASSERT (l+lci<h);
b \<leftarrow> mop_cmpo_v_idx xs v (l+lci);
if b then doN {
(lc,xs) \<leftarrow> mop_geth3 l h xs lci;
xs \<leftarrow> mop_seth3 l h xs i lc;
xs \<leftarrow> mop_seth3 l h xs lci v;
xs \<leftarrow> mop_to_wo_conv xs;
RETURN xs
} else doN {
xs \<leftarrow> mop_seth3 l h xs i v;
xs \<leftarrow> mop_to_wo_conv xs;
RETURN xs
}
} else doN {
xs \<leftarrow> mop_seth3 l h xs i v;
xs \<leftarrow> mop_to_wo_conv xs;
RETURN xs
}
}"
(* TODO: Move. Use also in insort. Maybe generalize to index set? *)
definition "woe_eq_except i xs' xs \<equiv> length xs' = length xs \<and> xs'!i=None \<and> (\<forall>j\<in>{0..<length xs}-{i}. xs'!j = Some (xs!j))"
lemma woe_eq_except_init: "i<length xs \<Longrightarrow> woe_eq_except i ((map Some xs)[i := None]) xs"
unfolding woe_eq_except_def by auto
lemma woe_eq_except_length[simp]: "woe_eq_except i xs' xs \<Longrightarrow> length xs'=length xs"
unfolding woe_eq_except_def by auto
lemma woe_eq_except_nth_eq_Some: "\<lbrakk>woe_eq_except i xs' xs; j<length xs\<rbrakk> \<Longrightarrow> xs'!j = Some v \<longleftrightarrow> (j\<noteq>i \<and> v = xs!j)"
unfolding woe_eq_except_def
by force
lemma woe_eq_except_nth: "\<lbrakk>woe_eq_except i xs' xs; j<length xs; j\<noteq>i\<rbrakk> \<Longrightarrow> xs'!j = Some (xs!j)"
unfolding woe_eq_except_def
by force
lemma woe_eq_except_ith[simp]: "\<lbrakk>woe_eq_except i xs' xs\<rbrakk> \<Longrightarrow> xs'!i = None"
unfolding woe_eq_except_def
by force
lemma woe_eq_except_upd:
assumes "woe_eq_except i xs' xs" "i'<length xs" "i<length xs" "i\<noteq>i'"
shows "woe_eq_except i' (xs'[i':=None,i:=Some v]) (xs[i:=v])"
using assms unfolding woe_eq_except_def by (auto simp: nth_list_update)
definition "sd23_rel \<equiv> {((xs',i',ctd'),(xs,i,ctd)). i'=i \<and> ctd'=ctd \<and> i+l<length xs \<and> woe_eq_except (i+l) xs' xs }"
lemma in_sd23_rel_conv: "((xs',i',ctd'),(xs,i,ctd))\<in>sd23_rel \<longleftrightarrow> i'=i \<and> ctd'=ctd \<and> i+l<length xs \<and> woe_eq_except (i+l) xs' xs"
by (auto simp: sd23_rel_def)
lemma sift_down3_refine: "sift_down3 i xs \<le>\<Down>Id (sift_down2 i xs)"
unfolding sift_down3_def sift_down2_def
supply [simp del] = conc_Id
apply (simp add: Let_def mop_geth3_def cong: if_cong)
apply (intro refine0)
apply clarsimp_all [3]
apply (rule bind_refine)
apply (rule WHILEIT_refine)
apply (rule introR[where R=sd23_rel])
apply (auto simp: sd23_rel_def woe_eq_except_init) []
apply (auto simp: sd23_rel_def) []
apply (auto simp: sd23_rel_def) []
subgoal
apply clarsimp
apply (intro refine0 bind_refine')
apply refine_dref_type
supply [[put_named_ss Main_ss]]
apply (auto simp: conc_Id in_sd23_rel_conv woe_eq_except_length woe_eq_except_nth) [4]
(*apply (use [[put_named_ss Main_ss]] in \<open>auto simp: conc_Id in_sd23_rel_conv woe_eq_except_length woe_eq_except_nth\<close>) [4]*)
unfolding mop_seth3_def
apply refine_vcg
apply (auto simp: in_sd23_rel_conv woe_eq_except_length woe_eq_except_nth algebra_simps woe_eq_except_ith woe_eq_except_upd)
done
subgoal
apply (clarsimp split: prod.splits split del: if_split cong: if_cong simp: mop_seth3_def)
apply refine_rcg
apply refine_dref_type
supply [[put_named_ss Main_ss]]
apply (auto simp: conc_Id in_sd23_rel_conv woe_eq_except_length woe_eq_except_nth algebra_simps woe_eq_except_ith woe_eq_except_upd in_set_conv_nth nth_list_update list_eq_iff_nth_eq)
done
done
end
concrete_definition sift_down4 is heap_context.sift_down3_def
context heap_context begin
lemma sift_down4_full_refine: "sift_down4 (\<^bold><) l h i xs \<le> sift_down i xs"
proof -
note sift_down4.refine[OF heap_context_axioms, symmetric, THEN meta_eq_to_obj_eq]
also note sift_down3_refine
also note sift_down2_refine
also note sift_down1_refine
finally show ?thesis by simp
qed
lemmas sift_down4_btu_correct = order_trans[OF sift_down4_full_refine sift_down_btu_correct]
lemmas sift_down4_restore_correct = order_trans[OF sift_down4_full_refine sift_down_restore_correct]
definition "heapify_btu xs\<^sub>0 \<equiv> doN {
ASSERT(h>0);
(xs,l') \<leftarrow> WHILET
(\<lambda>(xs,l'). l'>l)
(\<lambda>(xs,l'). doN {
ASSERT (l'>0);
let l'=l'-1;
xs \<leftarrow> sift_down4 (\<^bold><) l h l' xs;
RETURN (xs,l')
})
(xs\<^sub>0,h-1);
RETURN xs
}"
lemma heapify_btu_correct: "\<lbrakk> l<h; h\<le>length xs\<^sub>0 \<rbrakk> \<Longrightarrow> heapify_btu xs\<^sub>0 \<le> SPEC (\<lambda>xs. slice_eq_mset l h xs xs\<^sub>0 \<and> is_heap xs)"
unfolding heapify_btu_def
apply simp
apply (refine_vcg WHILET_rule[where I="\<lambda>(xs,l'). heapify_btu_invar xs\<^sub>0 l' xs \<and> l'\<ge>l" and R="measure snd"] sift_down4_btu_correct)
apply (all \<open>(auto;fail)?\<close>)
apply clarsimp_all (* Required to get rid of local variables that will obfuscate locale abbreviations! *)
subgoal by (simp add: heapify_btu_invar_def btu_heapify_init)
subgoal by (auto simp: heapify_btu_invar_def)
subgoal by (auto simp: heapify_btu_invar_def btu_heapify_term)
done
end
concrete_definition heapify_btu1 for less l h xs\<^sub>0 is heap_context.heapify_btu_def
context heap_context begin
lemmas heapify_btu1_correct = heapify_btu_correct[unfolded heapify_btu1.refine[OF heap_context_axioms]]
end
context weak_ordering begin
(* TODO: We keep \<le> out of the definition (although it occurs in invariants).
Otherwise, getting rid of the \<le> ghost parameter is difficult!
*)
definition heapsort :: "'a list \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> 'a list nres" where "heapsort xs\<^sub>0 l h\<^sub>0 \<equiv> doN {
ASSERT (l\<le>h\<^sub>0);
if h\<^sub>0-l > 1 then doN {
xs \<leftarrow> heapify_btu1 (\<^bold><) l h\<^sub>0 xs\<^sub>0;
(xs,h)\<leftarrow>WHILEIT (\<lambda>(xs,h).
l<h \<and> h\<le>h\<^sub>0
\<and> heap_context.is_heap (le_by_lt (\<^bold><)) l h xs
\<and> slice_eq_mset l h\<^sub>0 xs xs\<^sub>0
\<and> sorted_wrt_lt (\<^bold><) (slice h h\<^sub>0 xs)
\<and> (\<forall>a\<in>set (slice l h xs). \<forall>b\<in>set (slice h h\<^sub>0 xs). (le_by_lt (\<^bold><)) a b)
)
(\<lambda>(xs,h). Suc l < h)
(\<lambda>(xs,h). doN {
ASSERT (h>0 \<and> l\<noteq>h-1);
xs \<leftarrow> mop_list_swap xs l (h-1);
xs \<leftarrow> sift_down4 (\<^bold><) l (h-1) l xs;
RETURN (xs,h-1)
})
(xs,h\<^sub>0);
RETURN xs
} else
RETURN xs\<^sub>0
}"
lemma heapsort_correct:
assumes "l\<le>h\<^sub>0" "h\<^sub>0\<le>length xs\<^sub>0"
shows "heapsort xs\<^sub>0 l h\<^sub>0 \<le> SPEC (\<lambda>xs. slice_eq_mset l h\<^sub>0 xs xs\<^sub>0 \<and> sorted_wrt_lt (\<^bold><) (slice l h\<^sub>0 xs))"
proof -
interpret initial: heap_context "(\<^bold>\<le>)" "(\<^bold><)" l h\<^sub>0 by unfold_locales fact
show ?thesis
using assms unfolding heapsort_def le_by_lt
apply (refine_vcg WHILEIT_rule[where R="measure snd"] initial.heapify_btu1_correct )
apply (all \<open>(auto dest: slice_eq_mset_eq_length;fail)?\<close>)
apply clarsimp
subgoal premises prems for xs\<^sub>1 xs h proof -
(* TODO: This is the argument that swapping the max-element to the end will preserve the
sortedness criteria. Though apparently simple, the reasoning seems to be much too complex here.
Try to improve on that!
*)
interpret heap_context "(\<^bold>\<le>)" "(\<^bold><)" l h using prems by (unfold_locales) auto
interpret N: heap_context "(\<^bold>\<le>)" "(\<^bold><)" l "h-Suc 0" using prems by (unfold_locales) auto
from prems have
[simp]: "length xs = length xs\<^sub>0"
and [simp, arith]: "h\<^sub>0 \<le> length xs\<^sub>0"
by (auto simp: slice_eq_mset_eq_length)
{
fix xs'
assume A: "slice_eq_mset l (h - Suc 0) xs' (swap xs l (h - Suc 0))"
hence "slice_eq_mset l h\<^sub>0 xs' (swap xs l (h - Suc 0))"
apply (rule slice_eq_mset_subslice)
using prems by auto
from this[symmetric] have "slice_eq_mset l h\<^sub>0 xs' xs"
apply -
apply (drule slice_eq_mset_swap(2)[THEN iffD1, rotated -1])
using prems by (auto dest: slice_eq_mset_sym)
also note \<open>slice_eq_mset l h\<^sub>0 xs xs\<^sub>0\<close>
finally have G1: "slice_eq_mset l h\<^sub>0 xs' xs\<^sub>0" .
note [simp] = slice_eq_mset_eq_length[OF G1]
have [simp]: "slice (h - Suc 0) h\<^sub>0 xs' = (xs'!(h-Suc 0))#slice h h\<^sub>0 xs'"
apply (rule slice_extend1_left)
using prems by (auto)
have "slice h h\<^sub>0 xs' = slice h h\<^sub>0 (swap xs l (h - Suc 0))"
apply (rule slice_eq_mset_eq_outside(2)[OF A]) using prems by auto
also have "\<dots> = slice h h\<^sub>0 xs"
by (metis Suc_lessD atLeastLessThan_iff leI le_antisym le_zero_eq nat_less_le nz_le_conv_less \<open>Suc l < h\<close> slice_swap_outside)
finally have [simp]: "slice h h\<^sub>0 xs' = slice h h\<^sub>0 xs" .
have [arith,simp]: "h - Suc 0 < length xs\<^sub>0" "l<length xs\<^sub>0" using prems by (auto)
have [simp]: "xs' ! (h - Suc 0) = xs!l"
using slice_eq_mset_nth_outside[OF A, of "h-Suc 0"]
by auto
have "xs!l \<in> set (slice l h xs)" using prems by (auto simp: set_slice_conv)
then have G2: "sorted_wrt (\<^bold>\<le>) (slice (h - Suc 0) h\<^sub>0 xs')"
using prems
by (auto)
have [simp]: "slice l (h - Suc 0) (swap xs l (h - Suc 0)) = xs!(h-Suc 0)#(slice (Suc l) (h-Suc 0) xs)"
apply (rule nth_equalityI)
apply (auto simp: nth_list_update slice_nth swap_nth Suc_diff_Suc \<open>Suc l < h\<close>)
done
have "in_heap (h - Suc 0)"
unfolding in_heap_def apply simp
using \<open>Suc l < h\<close> by linarith
have G3: "\<forall>a \<in> set (slice l (h - Suc 0) xs'). \<forall>b \<in> set (slice (h - Suc 0) h\<^sub>0 xs'). a\<^bold>\<le>b"
thm slice_eq_mset_set_inside[OF A]
apply (simp add: slice_eq_mset_set_inside[OF A])
using \<open>\<forall>x\<in>set (slice l h xs). \<forall>_\<in>_. _\<close>
apply (auto simp: set_slice_conv root_greatest[OF \<open>is_heap xs\<close> \<open>in_heap (h-Suc 0)\<close>])
subgoal using N.ran_not_empty \<open>in_heap (h - Suc 0)\<close> in_heap_bounds(2) by blast
subgoal for j
apply (subgoal_tac "in_heap j")
using root_greatest[OF \<open>is_heap xs\<close>, of j] apply blast
unfolding in_heap_def by simp
subgoal by (metis Suc_le_lessD diff_le_self less_imp_le less_le_trans)
done
note G1 G2 G3
} note aux=this
note rl = N.sift_down4_restore_correct[OF _ sift_down_invar_init[OF \<open>is_heap xs\<close> \<open>Suc l < h\<close>]]
show ?thesis
apply (refine_vcg rl)
using \<open>Suc l < h\<close> \<open>h\<le>h\<^sub>0\<close>
apply (auto simp: aux)
done
qed
apply clarsimp
subgoal premises prems for xs\<^sub>1 xs h
proof -
have [simp]: "h=l+1" using prems by auto
from prems have [simp]: "length xs = length xs\<^sub>0"
and [simp, arith]: "l<length xs\<^sub>0" "h<length xs\<^sub>0"
by (auto dest: slice_eq_mset_eq_length)
have "set (slice l (Suc l) xs) = {xs!l}" by simp
show ?thesis using prems
by (auto simp: slice_split_hd le_by_lt)
qed
subgoal
by (simp add: sorted_wrt01)
done
qed
lemma heapsort_correct': "\<lbrakk>(xs,xs')\<in>Id; (l,l')\<in>Id; (h,h')\<in>Id\<rbrakk> \<Longrightarrow> heapsort xs l h \<le>\<Down>Id (slice_sort_spec (\<^bold><) xs' l' h')"
unfolding slice_sort_spec_alt
apply (refine_vcg heapsort_correct)
apply (auto simp: slice_eq_mset_alt)
done
end
concrete_definition heapsort1 for less xs\<^sub>0 l h\<^sub>0 is weak_ordering.heapsort_def
context weak_ordering begin
lemmas heapsort1_correct = heapsort_correct[unfolded heapsort1.refine[OF weak_ordering_axioms]]
end
sepref_register mop_lchild3 mop_rchild3 has_rchild3 has_lchild3 mop_geth3 mop_seth3
sepref_def mop_lchild_impl [llvm_inline] is "uncurry mop_lchild3" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k \<rightarrow>\<^sub>a size_assn"
unfolding mop_lchild3_def apply (annot_snat_const "TYPE (size_t)") by sepref
sepref_def mop_rchild_impl [llvm_inline] is "uncurry mop_rchild3" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k \<rightarrow>\<^sub>a size_assn"
unfolding mop_rchild3_def apply (annot_snat_const "TYPE (size_t)") by sepref
sepref_def has_lchild_impl [llvm_inline] is "uncurry2 (RETURN ooo has_lchild3)" :: "[\<lambda>((l,h),i). l\<le>h]\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k \<rightarrow> bool1_assn"
unfolding has_lchild3_def apply (annot_snat_const "TYPE (size_t)") by sepref
sepref_def has_rchild_impl [llvm_inline] is "uncurry2 (RETURN ooo has_rchild3)" :: "[\<lambda>((l,h),i). l<h]\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k \<rightarrow> bool1_assn"
unfolding has_rchild3_def apply (annot_snat_const "TYPE (size_t)") by sepref
sepref_def mop_geth_impl [llvm_inline] is "uncurry3 mop_geth3" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a (eoarray_assn elem_assn)\<^sup>d *\<^sub>a size_assn\<^sup>k \<rightarrow>\<^sub>a elem_assn \<times>\<^sub>a eoarray_assn elem_assn"
unfolding mop_geth3_def by sepref
sepref_def mop_seth_impl [llvm_inline] is "uncurry4 mop_seth3" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a (eoarray_assn elem_assn)\<^sup>d *\<^sub>a size_assn\<^sup>k *\<^sub>a elem_assn\<^sup>d \<rightarrow>\<^sub>a eoarray_assn elem_assn"
unfolding mop_seth3_def by sepref
context sort_impl_context begin
sepref_register "sift_down4 (\<^bold><)"
sepref_def sift_down_impl is "uncurry3 (PR_CONST (sift_down4 (\<^bold><)))" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a (woarray_assn elem_assn)\<^sup>d \<rightarrow>\<^sub>a (woarray_assn elem_assn)"
unfolding sift_down4_def PR_CONST_def
by sepref (* Takes loooong! *)
sepref_register "heapify_btu1 (\<^bold><)"
sepref_def heapify_btu_impl is "uncurry2 (PR_CONST (heapify_btu1 (\<^bold><)))" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a (woarray_assn elem_assn)\<^sup>d \<rightarrow>\<^sub>a (woarray_assn elem_assn)"
unfolding heapify_btu1_def PR_CONST_def
apply (annot_snat_const "TYPE (size_t)")
by sepref
sepref_register "heapsort1 (\<^bold><)"
sepref_def heapsort_impl is "uncurry2 (PR_CONST (heapsort1 (\<^bold><)))" :: "(woarray_assn elem_assn)\<^sup>d *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k \<rightarrow>\<^sub>a (woarray_assn elem_assn)"
unfolding heapsort1_def PR_CONST_def
apply (rewrite at "sift_down4 _ _ _ \<hole> _" fold_COPY)
apply (annot_snat_const "TYPE (size_t)")
by sepref
sepref_register heapsort
lemmas heapsort_hnr[sepref_fr_rules] = heapsort_impl.refine[unfolded heapsort1.refine[OF weak_ordering_axioms,symmetric]]
end
subsection \<open>Parameterized Comparison\<close>
context parameterized_weak_ordering begin
definition sift_down_param :: "'cparam \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> 'a list \<Rightarrow> 'a list nres"
where "sift_down_param cparam l h i\<^sub>0 xs \<equiv> doN {
ASSERT (l\<le>i\<^sub>0 \<and> i\<^sub>0<h);
let i\<^sub>1 = i\<^sub>0 - l;
xs \<leftarrow> mop_to_eo_conv xs;
(v,xs) \<leftarrow> mop_geth3 l h xs i\<^sub>1;
(xs,i,_) \<leftarrow> WHILEIT (\<lambda>(xs,i,ctd). i<h-l \<and> i\<ge>i\<^sub>1) (\<lambda>(xs,i,ctd). has_rchild3 l h i \<and> ctd) (\<lambda>(xs,i,ctd). doN {
lci \<leftarrow> mop_lchild3 h i;
rci \<leftarrow> mop_rchild3 h i;
ASSERT (l+lci<h \<and> l+rci<h \<and> l+lci \<noteq> l+rci);
b \<leftarrow> pcmpo_idxs2 cparam xs (l+lci) (l+rci);
if b then doN {
b \<leftarrow> pcmpo_v_idx2 cparam xs v (l+rci);
if b then doN {
(rc,xs) \<leftarrow> mop_geth3 l h xs rci;
xs \<leftarrow> mop_seth3 l h xs i rc;
RETURN (xs,rci,True)
} else RETURN (xs,i,False)
} else doN {
b \<leftarrow> pcmpo_v_idx2 cparam xs v (l+lci);
if b then doN {
(lc,xs) \<leftarrow> mop_geth3 l h xs lci;
xs \<leftarrow> mop_seth3 l h xs i lc;
RETURN (xs,lci,True)
} else RETURN (xs,i,False)
}
}) (xs,i\<^sub>1,True);
ASSERT (i\<ge>i\<^sub>1);
if has_lchild3 l h i then doN {
lci \<leftarrow> mop_lchild3 h i;
ASSERT (l+lci<h);
b \<leftarrow> pcmpo_v_idx2 cparam xs v (l+lci);
if b then doN {
(lc,xs) \<leftarrow> mop_geth3 l h xs lci;
xs \<leftarrow> mop_seth3 l h xs i lc;
xs \<leftarrow> mop_seth3 l h xs lci v;
xs \<leftarrow> mop_to_wo_conv xs;
RETURN xs
} else doN {
xs \<leftarrow> mop_seth3 l h xs i v;
xs \<leftarrow> mop_to_wo_conv xs;
RETURN xs
}
} else doN {
xs \<leftarrow> mop_seth3 l h xs i v;
xs \<leftarrow> mop_to_wo_conv xs;
RETURN xs
}
}"
lemma mop_geth3_cdom_refine: "\<lbrakk>
(l',l)\<in>Id; (h',h)\<in>Id; (i',i)\<in>Id; (xs',xs)\<in>cdom_olist_rel cparam
\<rbrakk> \<Longrightarrow> mop_geth3 l' h' xs' i'
\<le> \<Down>(br id (\<lambda>x. x \<in> cdom cparam) \<times>\<^sub>r cdom_olist_rel cparam) (mop_geth3 l h xs i)"
unfolding mop_geth3_def
apply refine_rcg
by auto
lemma mop_seth3_cdom_refine: "\<lbrakk>
(l',l)\<in>Id; (h',h)\<in>Id; (i',i)\<in>Id; (xs',xs)\<in>cdom_olist_rel cparam; (v',v)\<in>Id; v\<in>cdom cparam
\<rbrakk> \<Longrightarrow> mop_seth3 l' h' xs' i' v'
\<le> \<Down>(cdom_olist_rel cparam) (mop_seth3 l h xs i v)"
unfolding mop_seth3_def
apply refine_rcg
by auto
lemma sift_down_param_refine[refine]: "\<lbrakk> (l',l)\<in>Id; (h',h)\<in>Id; (i\<^sub>0',i\<^sub>0)\<in>Id; (xs',xs)\<in>cdom_list_rel cparam \<rbrakk>
\<Longrightarrow> sift_down_param cparam l' h' i\<^sub>0' xs' \<le> \<Down>(cdom_list_rel cparam) (sift_down4 (less' cparam) l h i\<^sub>0 xs)"
unfolding sift_down_param_def sift_down4_def
apply (refine_rcg mop_geth3_cdom_refine mop_seth3_cdom_refine)
apply (all \<open>(intro IdI)?;(elim conjE IdE Pair_inject)?;(assumption)?\<close>)
supply [refine_dref_RELATES] = RELATESI[of "cdom_list_rel cparam"] RELATESI[of "cdom_olist_rel cparam"]
apply refine_dref_type
(* Note: The 3 simps below are an optimization for speed. Just a simp_all on the 65 subgoals takes too long.*)
apply (simp_all named_ss HOL_ss: IdI split in_br_conv prod_rel_iff cdom_olist_rel_def id_def)
apply simp_all
apply (simp_all split: prod.splits)
done
definition "heapify_btu_param cparam l h xs\<^sub>0 \<equiv> doN {
ASSERT(h>0);
(xs,l') \<leftarrow> WHILET
(\<lambda>(xs,l'). l'>l)
(\<lambda>(xs,l'). doN {
ASSERT (l'>0);
let l'=l'-1;
xs \<leftarrow> sift_down_param cparam l h l' xs;
RETURN (xs,l')
})
(xs\<^sub>0,h-1);
RETURN xs
}"
lemma heapify_btu_param_refine[refine]:
"\<lbrakk> (l',l)\<in>Id; (h',h)\<in>Id; (xs',xs)\<in>cdom_list_rel cparam\<rbrakk>
\<Longrightarrow> heapify_btu_param cparam l' h' xs' \<le> \<Down>(cdom_list_rel cparam) (heapify_btu1 (less' cparam) l h xs)"
unfolding heapify_btu_param_def heapify_btu1_def
apply (refine_rcg prod_relI)
supply [refine_dref_RELATES] = RELATESI[of "cdom_list_rel cparam"]
apply refine_dref_type
by auto
term heapsort1
definition heapsort_param :: "'cparam \<Rightarrow> 'a list \<Rightarrow> nat \<Rightarrow> nat \<Rightarrow> 'a list nres"
where "heapsort_param cparam xs\<^sub>0 l h\<^sub>0 \<equiv> doN {
ASSERT (l\<le>h\<^sub>0);
if h\<^sub>0-l > 1 then doN {
xs \<leftarrow> heapify_btu_param cparam l h\<^sub>0 xs\<^sub>0;
(xs,h)\<leftarrow>WHILET
(\<lambda>(xs,h). Suc l < h)
(\<lambda>(xs,h). doN {
ASSERT (h>0 \<and> l\<noteq>h-1);
xs \<leftarrow> mop_list_swap xs l (h-1);
xs \<leftarrow> sift_down_param cparam l (h-1) l xs;
RETURN (xs,h-1)
})
(xs,h\<^sub>0);
RETURN xs
} else
RETURN xs\<^sub>0
}"
lemma heapsort_param_refine[refine]: "\<lbrakk>
(l',l)\<in>Id; (h',h)\<in>Id; (xs',xs)\<in>cdom_list_rel cparam
\<rbrakk> \<Longrightarrow> heapsort_param cparam xs' l' h' \<le> \<Down>(cdom_list_rel cparam) (heapsort1 (less' cparam) xs l h)"
unfolding heapsort_param_def heapsort1_def mop_list_swap_alt (* TODO: inlined mop-list-swap refinement proof! *)
apply refine_rcg
supply [refine_dref_RELATES] = RELATESI[of "cdom_list_rel cparam"]
apply refine_dref_type
apply (auto simp: in_br_conv cdom_list_rel_alt)
done
lemma heapsort_param_correct:
assumes "(xs',xs)\<in>Id" "(l',l)\<in>Id" "(h',h)\<in>Id"
shows "heapsort_param cparam xs' l' h' \<le> pslice_sort_spec cdom pless cparam xs l h"
proof -
note heapsort_param_refine[unfolded heapsort1.refine[OF WO.weak_ordering_axioms, symmetric]]
also note WO.heapsort_correct'
also note slice_sort_spec_xfer
finally show ?thesis
unfolding pslice_sort_spec_def
apply refine_vcg
using assms unfolding cdom_list_rel_alt
by (simp add: in_br_conv)
qed
lemma heapsort_param_correct':
shows "(PR_CONST heapsort_param, PR_CONST (pslice_sort_spec cdom pless)) \<in> Id \<rightarrow> Id \<rightarrow> Id \<rightarrow> Id \<rightarrow> \<langle>Id\<rangle>nres_rel"
using heapsort_param_correct
apply (intro fun_relI nres_relI)
by simp
end
context parameterized_sort_impl_context begin
sepref_def mop_geth_impl [llvm_inline] is "uncurry3 mop_geth3" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a eo_assn\<^sup>d *\<^sub>a size_assn\<^sup>k \<rightarrow>\<^sub>a elem_assn \<times>\<^sub>a eo_assn"
unfolding mop_geth3_def by sepref
sepref_def mop_seth_impl [llvm_inline] is "uncurry4 mop_seth3" :: "size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a eo_assn\<^sup>d *\<^sub>a size_assn\<^sup>k *\<^sub>a elem_assn\<^sup>d \<rightarrow>\<^sub>a eo_assn"
unfolding mop_seth3_def by sepref
end
context parameterized_sort_impl_context
begin
sepref_register "sift_down_param"
sepref_def sift_down_impl is "uncurry4 (PR_CONST sift_down_param)"
:: "cparam_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a wo_assn\<^sup>d \<rightarrow>\<^sub>a wo_assn"
unfolding sift_down_param_def PR_CONST_def
by sepref (* Takes loooong! *)
sepref_register "heapify_btu_param"
sepref_def heapify_btu_impl is "uncurry3 (PR_CONST heapify_btu_param)"
:: "cparam_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k *\<^sub>a wo_assn\<^sup>d \<rightarrow>\<^sub>a wo_assn"
unfolding heapify_btu_param_def PR_CONST_def
apply (annot_snat_const "TYPE (size_t)")
by sepref
sepref_register "heapsort_param"
sepref_def heapsort_param_impl is "uncurry3 (PR_CONST heapsort_param)"
:: "cparam_assn\<^sup>k *\<^sub>a wo_assn\<^sup>d *\<^sub>a size_assn\<^sup>k *\<^sub>a size_assn\<^sup>k \<rightarrow>\<^sub>a wo_assn"
unfolding heapsort_param_def PR_CONST_def
apply (rewrite at "sift_down_param _ _ _ \<hole> _" fold_COPY)
apply (annot_snat_const "TYPE (size_t)")
by sepref
(*
TODO: Show that this refines a param_sort_spec!
lemmas heapsort_hnr[sepref_fr_rules] = heapsort_param_impl.refine[unfolded heapsort_param.refine[OF weak_ordering_axioms,symmetric]]
*)
lemmas heapsort_param_hnr
= heapsort_param_impl.refine[FCOMP heapsort_param_correct']
end
(*
global_interpretation heapsort_interp: pure_sort_impl_context "(\<le>)" "(<)" ll_icmp_ult unat_assn
defines heapsort_interp_mop_lchild_impl = heapsort_interp.mop_lchild_impl
and heapsort_interp_mop_rchild_impl = heapsort_interp.mop_rchild_impl
and heapsort_interp_has_rchild_impl = heapsort_interp.has_rchild_impl
and heapsort_interp_has_lchild_impl = heapsort_interp.has_lchild_impl
and heapsort_interp_mop_geth_impl = heapsort_interp.mop_geth_impl
and heapsort_interp_mop_seth_impl = heapsort_interp.mop_seth_impl
and heapsort_interp_sift_down_impl = heapsort_interp.sift_down_impl
and heapsort_interp_heapify_btu_impl = heapsort_interp.heapify_btu_impl
and heapsort_interp_heapsort_impl = heapsort_interp.heapsort_impl
by (rule unat_sort_impl_context)
export_llvm "heapsort_interp_heapsort_impl :: 64 word ptr \<Rightarrow> _" is "uint64_t* heapsort(uint64_t*, int64_t,int64_t)"
file "../code/heapsort.ll"
*)
end
|
State Before: Ξ± : Type u
Ξ² : Type v
Ξ³ : Type w
a : Ξ±
cβ : Computation Ξ±
β’ destruct (HOrElse.hOrElse (pure a) fun x => cβ) = Sum.inl a State After: Ξ± : Type u
Ξ² : Type v
Ξ³ : Type w
a : Ξ±
cβ : Computation Ξ±
β’ destruct ({ hOrElse := fun a b => OrElse.orElse a b }.1 (pure a) fun x => cβ) = Sum.inl a Tactic: unfold HOrElse.hOrElse instHOrElse State Before: Ξ± : Type u
Ξ² : Type v
Ξ³ : Type w
a : Ξ±
cβ : Computation Ξ±
β’ destruct ({ hOrElse := fun a b => OrElse.orElse a b }.1 (pure a) fun x => cβ) = Sum.inl a State After: Ξ± : Type u
Ξ² : Type v
Ξ³ : Type w
a : Ξ±
cβ : Computation Ξ±
β’ destruct
({
hOrElse := fun a b =>
{
orElse :=
(let src := monad;
Alternative.mk empty @orElse).3 }.1
a b }.1
(pure a) fun x => cβ) =
Sum.inl a Tactic: unfold OrElse.orElse instOrElse Alternative.orElse instAlternativeComputation State Before: Ξ± : Type u
Ξ² : Type v
Ξ³ : Type w
a : Ξ±
cβ : Computation Ξ±
β’ destruct
({
hOrElse := fun a b =>
{
orElse :=
(let src := monad;
Alternative.mk empty @orElse).3 }.1
a b }.1
(pure a) fun x => cβ) =
Sum.inl a State After: no goals Tactic: simp [orElse] |
Require Import HoTT.Basics.Decidable HoTT.Basics.Trunc.
Require Import
HoTT.Classes.interfaces.abstract_algebra
HoTT.Classes.interfaces.orders
HoTT.Classes.theory.apartness.
Generalizable Variables A.
Lemma irrefl_neq `{R : Relation A} `{!Irreflexive R}
: forall x y, R x y -> ~ x = y.
Proof.
intros ?? E e;rewrite e in E. apply (irreflexivity _ _ E).
Qed.
Lemma le_flip `{Le A} `{!TotalRelation (β€)} x y : ~y β€ x -> x β€ y.
Proof.
intros nle.
destruct (total _ x y) as [?|le];auto.
destruct (nle le).
Qed.
Section partial_order.
Context `{PartialOrder A}.
Lemma eq_le x y : x = y -> x β€ y.
Proof.
intros E.
rewrite E.
apply reflexivity.
Qed.
Lemma eq_le_flip x y : x = y -> y β€ x.
Proof.
intros E.
rewrite E.
apply reflexivity.
Qed.
Lemma not_le_ne x y : ~x β€ y -> x <> y.
Proof.
intros E1 E2.
apply E1.
rewrite E2.
apply reflexivity.
Qed.
Lemma eq_iff_le x y : x = y <-> x β€ y /\ y β€ x.
Proof.
split; intros E.
- rewrite E. split;apply reflexivity.
- apply (antisymmetry (β€) x y);apply E.
Qed.
End partial_order.
Section strict_order.
Context `{StrictOrder A}.
Lemma lt_flip x y : x < y -> ~y < x.
Proof.
intros E1 E2.
apply (irreflexivity (<) x).
transitivity y;assumption.
Qed.
Lemma lt_antisym x y : ~(x < y < x).
Proof.
intros [E1 E2].
destruct (lt_flip x y);assumption.
Qed.
Lemma lt_ne x y : x < y -> x <> y.
Proof.
intros E1 E2.
rewrite E2 in E1.
apply (irreflexivity (<) y). assumption.
Qed.
Lemma lt_ne_flip x y : x < y -> y <> x.
Proof.
intro.
apply symmetric_neq, lt_ne.
assumption.
Qed.
Lemma eq_not_lt x y : x = y -> ~x < y.
Proof.
intros E.
rewrite E.
apply (irreflexivity (<)).
Qed.
End strict_order.
Section pseudo_order.
Context `{PseudoOrder A}.
Local Existing Instance pseudo_order_apart.
Lemma apart_total_lt x y : x βΆ y -> x < y |_| y < x.
Proof.
intros.
apply apart_iff_total_lt.
assumption.
Qed.
Lemma pseudo_order_lt_apart x y : x < y -> x βΆ y.
Proof.
intros.
apply apart_iff_total_lt.
auto.
Qed.
Lemma pseudo_order_lt_apart_flip x y : x < y -> y βΆ x.
Proof.
intros.
apply apart_iff_total_lt.
auto.
Qed.
Lemma not_lt_apart_lt_flip x y : ~x < y -> x βΆ y -> y < x.
Proof.
intros nlt neq. apply apart_iff_total_lt in neq.
destruct neq.
- destruct nlt;auto.
- auto.
Qed.
Lemma pseudo_order_cotrans_twice xβ yβ xβ yβ
: xβ < yβ -> merely (xβ < yβ |_| xβ < xβ |_| yβ < yβ).
Proof.
intros E1.
apply (merely_destruct (cotransitive E1 xβ));intros [?|E2];
try solve [apply tr;auto].
apply (merely_destruct (cotransitive E2 yβ));intros [?|?];apply tr;auto.
Qed.
Lemma pseudo_order_lt_ext xβ yβ xβ yβ : xβ < yβ ->
merely (xβ < yβ |_| xβ βΆ xβ |_| yβ βΆ yβ).
Proof.
intros E.
apply (merely_destruct (pseudo_order_cotrans_twice xβ yβ xβ yβ E));
intros [?|[?|?]];apply tr;
auto using pseudo_order_lt_apart.
Qed.
Global Instance pseudoorder_strictorder : StrictOrder (_ : Lt A).
Proof.
split.
- apply _.
- intros x E.
destruct (pseudo_order_antisym x x); auto.
- intros x y z E1 E2.
apply (merely_destruct (cotransitive E1 z));intros [?|?]; trivial.
destruct (pseudo_order_antisym y z); auto.
Qed.
Global Instance nlt_trans : Transitive (complement (<)).
Proof.
intros x y z.
intros E1 E2 E3.
apply (merely_destruct (cotransitive E3 y));
intros [?|?]; contradiction.
Qed.
Global Instance nlt_antisymm : AntiSymmetric (complement (<)).
Proof.
intros x y H1 H2.
apply tight_apart. intros nap. apply apart_iff_total_lt in nap.
destruct nap;auto.
Qed.
Lemma ne_total_lt `{!TrivialApart A} x y : x <> y -> x < y |_| y < x.
Proof.
intros neq;apply trivial_apart in neq.
apply apart_total_lt. assumption.
Qed.
Global Instance lt_trichotomy `{!TrivialApart A} `{DecidablePaths A}
: Trichotomy (<).
Proof.
intros x y.
destruct (dec (x = y)) as [?|?]; try auto.
destruct (ne_total_lt x y); auto.
Qed.
End pseudo_order.
Section full_partial_order.
Context `{FullPartialOrder A}.
Local Existing Instance strict_po_apart.
(* Duplicate of strong_setoids.apart_ne. This is useful because a
StrongSetoid is not defined as a substructure of a FullPartialOrder *)
Instance strict_po_apart_ne x y : PropHolds (x βΆ y) -> PropHolds (x <> y).
Proof.
intros; apply _.
Qed.
Global Instance fullpartialorder_strictorder : StrictOrder (<).
Proof.
split; try apply _.
- apply strict_po_mere_lt.
- intros x. red. intros E;apply lt_iff_le_apart in E.
destruct E as [_ ?].
apply (irreflexivity (βΆ) x).
assumption.
Qed.
Lemma lt_le x y : PropHolds (x < y) -> PropHolds (x β€ y).
Proof.
intro.
apply lt_iff_le_apart.
assumption.
Qed.
Lemma not_le_not_lt x y : ~x β€ y -> ~x < y.
Proof.
intros E1 E2.
apply E1. apply lt_le. assumption.
Qed.
Lemma lt_apart x y : x < y -> x βΆ y.
Proof.
intro.
apply lt_iff_le_apart.
assumption.
Qed.
Lemma lt_apart_flip x y : x < y -> y βΆ x.
Proof.
intro.
apply symmetry, lt_iff_le_apart.
assumption.
Qed.
Lemma le_not_lt_flip x y : y β€ x -> ~x < y.
Proof.
intros E1 E2;apply lt_iff_le_apart in E2.
destruct E2 as [E2a E2b].
revert E2b. apply tight_apart.
apply (antisymmetry (β€));assumption.
Qed.
Lemma lt_not_le_flip x y : y < x -> ~x β€ y.
Proof.
intros E1 E2.
apply (le_not_lt_flip y x);assumption.
Qed.
Lemma lt_le_trans x y z : x < y -> y β€ z -> x < z.
Proof.
intros E1 E2.
apply lt_iff_le_apart. apply lt_iff_le_apart in E1.
destruct E1 as [E1a E1b].
split.
- transitivity y;assumption.
- apply (merely_destruct (cotransitive E1b z));intros [E3 | E3]; trivial.
apply lt_apart. apply symmetry in E3.
transitivity y;apply lt_iff_le_apart; auto.
Qed.
Lemma le_lt_trans x y z : x β€ y -> y < z -> x < z.
Proof.
intros E2 E1.
apply lt_iff_le_apart. apply lt_iff_le_apart in E1.
destruct E1 as [E1a E1b].
split.
- transitivity y;auto.
- apply (merely_destruct (cotransitive E1b x));intros [E3 | E3]; trivial.
apply lt_apart. apply symmetry in E3.
transitivity y; apply lt_iff_le_apart; auto.
Qed.
Lemma lt_iff_le_ne `{!TrivialApart A} x y : x < y <-> x β€ y /\ x <> y.
Proof.
transitivity (x <= y /\ apart x y).
- apply lt_iff_le_apart.
- split;intros [E1 E2];split;trivial;apply trivial_apart;trivial.
Qed.
Lemma le_equiv_lt `{!TrivialApart A} `{forall x y : A, Decidable (x = y)} x y
: x β€ y -> x = y |_| x < y.
Proof.
intros.
destruct (dec (x = y)); try auto.
right.
apply lt_iff_le_ne; auto.
Qed.
Instance dec_from_lt_dec `{!TrivialApart A} `{forall x y, Decidable (x β€ y)}
: DecidablePaths A.
Proof.
intros x y.
destruct (decide_rel (<=) x y) as [E1|E1];
[destruct (decide_rel (<=) y x) as [E2|E2]|].
- left. apply (antisymmetry (<=));assumption.
- right. intros E3;apply E2.
pattern y. apply (transport _ E3).
apply reflexivity.
- right. intros E3;apply E1.
pattern y; apply (transport _ E3).
apply reflexivity.
Defined.
Definition lt_dec_slow `{!TrivialApart A} `{forall x y, Decidable (x β€ y)} :
forall x y, Decidable (x < y).
Proof.
intros x y.
destruct (dec (x β€ y));
[destruct (dec (x = y))|].
- right. apply eq_not_lt. assumption.
- left. apply lt_iff_le_ne. auto.
- right. apply not_le_not_lt. assumption.
Defined.
End full_partial_order.
(* Due to bug #2528 *)
Hint Extern 5 (PropHolds (_ <> _)) =>
eapply @strict_po_apart_ne : typeclass_instances.
Hint Extern 10 (PropHolds (_ β€ _)) =>
eapply @lt_le : typeclass_instances.
Hint Extern 20 (Decidable (_ < _)) =>
eapply @lt_dec_slow : typeclass_instances.
Section full_pseudo_order.
Context `{FullPseudoOrder A}.
Local Existing Instance pseudo_order_apart.
Lemma not_lt_le_flip x y : ~y < x -> x β€ y.
Proof.
intros.
apply le_iff_not_lt_flip.
assumption.
Qed.
Instance fullpseudo_partial : PartialOrder (β€) | 10.
Proof.
repeat split.
- apply _.
- apply _.
- intros x. apply not_lt_le_flip, (irreflexivity (<)).
- intros x y z E1 E2.
apply le_iff_not_lt_flip;
apply le_iff_not_lt_flip in E1;
apply le_iff_not_lt_flip in E2.
change (complement (<) z x).
transitivity y;assumption.
- intros x y E1 E2.
apply le_iff_not_lt_flip in E1;
apply le_iff_not_lt_flip in E2.
apply (antisymmetry (complement (<)));assumption.
Qed.
Lemma fullpseudo_fullpartial' : FullPartialOrder Ale Alt.
Proof.
split; try apply _.
intros x y.
split.
- intros E. split.
+ apply not_lt_le_flip. apply lt_flip;assumption.
+ apply pseudo_order_lt_apart. assumption.
- intros [? E]. apply not_lt_apart_lt_flip;[|symmetry;trivial].
apply le_iff_not_lt_flip. trivial.
Qed.
Global Instance fullpseudo_fullpartial@{i} : FullPartialOrder Ale Alt
:= ltac:(first [exact fullpseudo_fullpartial'@{i i Set Set Set}|
exact fullpseudo_fullpartial'@{i i}]).
Global Instance le_stable : forall x y, Stable (x β€ y).
Proof.
intros x y. unfold Stable.
intros dn. apply le_iff_not_lt_flip.
intros E. apply dn.
intros E';apply le_iff_not_lt_flip in E';auto.
Qed.
Lemma le_or_lt `{!TrivialApart A} `{DecidablePaths A} x y : x β€ y |_| y < x.
Proof.
destruct (trichotomy (<) x y) as [|[|]]; try auto.
- left. apply lt_le;trivial.
- left. apply eq_le;trivial.
Qed.
Global Instance le_total `{!TrivialApart A} `{DecidablePaths A}
: TotalOrder (β€).
Proof.
split; try apply _.
intros x y.
destruct (le_or_lt x y); auto.
right. apply lt_le.
trivial.
Qed.
Lemma not_le_lt_flip `{!TrivialApart A} `{DecidablePaths A} x y
: ~y β€ x -> x < y.
Proof.
intros.
destruct (le_or_lt y x); auto.
contradiction.
Qed.
Existing Instance dec_from_lt_dec.
Definition lt_dec `{!TrivialApart A} `{forall x y, Decidable (x β€ y)}
: forall x y, Decidable (x < y).
Proof.
intros.
destruct (decide_rel (<=) y x).
- right;apply le_not_lt_flip;assumption.
- left; apply not_le_lt_flip;assumption.
Defined.
End full_pseudo_order.
Hint Extern 8 (Decidable (_ < _)) => eapply @lt_dec : typeclass_instances.
(*
The following instances would be tempting, but turn out to be a bad idea.
Hint Extern 10 (PropHolds (_ <> _)) => eapply @le_ne : typeclass_instances.
Hint Extern 10 (PropHolds (_ <> _)) => eapply @le_ne_flip : typeclass_instances.
It will then loop like:
semirings.lt_0_1 -> lt_ne_flip -> ...
*)
Section dec_strict_setoid_order.
Context `{StrictOrder A} `{Apart A} `{!TrivialApart A} `{DecidablePaths A}.
Instance: IsApart A := dec_strong_setoid.
Context `{!Trichotomy (<)}.
Instance dec_strict_pseudo_order: PseudoOrder (<).
Proof.
split; try apply _.
- intros x y [??].
destruct (lt_antisym x y); auto.
- intros x y Exy z.
destruct (trichotomy (<) x z) as [? | [Exz | Exz]];apply tr; try auto.
right. rewrite <-Exz. assumption.
- intros x y. transitivity (~ x = y);[split;apply trivial_apart|].
split.
+ destruct (trichotomy (<) x y) as [?|[?|?]]; auto.
intros E;contradiction E.
+ intros [?|?];[apply lt_ne|apply lt_ne_flip];trivial.
Qed.
End dec_strict_setoid_order.
Section dec_partial_order.
Context `{PartialOrder A} `{DecidablePaths A}.
Definition dec_lt: Lt A := fun x y => x β€ y /\ x <> y.
Context `{Alt : Lt A} `{is_mere_relation A lt}
(lt_correct : forall x y, x < y <-> x β€ y /\ x <> y).
Instance dec_order: StrictOrder (<).
Proof.
split.
- apply _.
- intros x E. apply lt_correct in E. destruct E as [_ []];trivial.
- intros x y z E1 E2.
apply lt_correct;
apply lt_correct in E1;
apply lt_correct in E2.
destruct E1 as [E1a E1b],E2 as [E2a E2b].
split.
+ transitivity y;trivial.
+ intros E3. destruct E2b.
apply (antisymmetry (β€)); trivial.
rewrite <-E3. assumption.
Qed.
Context `{Apart A} `{!TrivialApart A}.
Instance: IsApart A := dec_strong_setoid.
Instance dec_full_partial_order: FullPartialOrder (β€) (<).
Proof.
split;try apply _.
intros. transitivity (x <= y /\ ~ x = y);[|
split;intros [? ?];split;trivial;apply trivial_apart;trivial].
apply lt_correct.
Qed.
Context `{!TotalRelation (β€)}.
Instance: Trichotomy (<).
Proof.
intros x y.
destruct (dec (x = y)); try auto.
destruct (total (β€) x y);[left|right;right];
apply lt_correct;auto.
split;auto.
intro E;apply symmetry in E;auto.
Qed.
Instance dec_pseudo_order: PseudoOrder (<) := dec_strict_pseudo_order.
Instance dec_full_pseudo_order: FullPseudoOrder (β€) (<).
Proof.
split; try apply _.
intros x y.
split.
- intros ? E. apply lt_correct in E;destruct E as [? []].
apply (antisymmetry (β€));assumption.
- intros E1.
destruct (total (β€) x y); trivial.
destruct (dec (x = y)) as [E2|E2].
+ rewrite E2. apply reflexivity.
+ destruct E1. apply lt_correct;split;auto.
apply symmetric_neq;assumption.
Qed.
End dec_partial_order.
Lemma lt_eq_trans `{Lt A} : forall x y z, x < y -> y = z -> x < z.
Proof.
intros ???? [];trivial.
Qed.
|
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
instβ : PartialOrder Ξ±
F : CFilter Ξ± Ο
E : Ο β Ο
f : Ο β Ξ±
p : Ο
g : Ο β Ο β Ο
hβ : β (a b : Ο), f (g a b) β€ f a
hβ : β (a b : Ο), f (g a b) β€ f b
a b : Ο
β’ (fun a => f (βE.symm a)) ((fun a b => βE (g (βE.symm a) (βE.symm b))) a b) β€ (fun a => f (βE.symm a)) a
[PROOFSTEP]
simpa using hβ (E.symm a) (E.symm b)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
instβ : PartialOrder Ξ±
F : CFilter Ξ± Ο
E : Ο β Ο
f : Ο β Ξ±
p : Ο
g : Ο β Ο β Ο
hβ : β (a b : Ο), f (g a b) β€ f a
hβ : β (a b : Ο), f (g a b) β€ f b
a b : Ο
β’ (fun a => f (βE.symm a)) ((fun a b => βE (g (βE.symm a) (βE.symm b))) a b) β€ (fun a => f (βE.symm a)) b
[PROOFSTEP]
simpa using hβ (E.symm a) (E.symm b)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
instβ : PartialOrder Ξ±
Fβ : CFilter Ξ± Ο
E : Ο β Ο
F : CFilter Ξ± Ο
a : Ο
β’ f (ofEquiv E F) a = f F (βE.symm a)
[PROOFSTEP]
cases F
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
instβ : PartialOrder Ξ±
F : CFilter Ξ± Ο
E : Ο β Ο
a : Ο
fβ : Ο β Ξ±
ptβ : Ο
infβ : Ο β Ο β Ο
inf_le_leftβ : β (a b : Ο), fβ (infβ a b) β€ fβ a
inf_le_rightβ : β (a b : Ο), fβ (infβ a b) β€ fβ b
β’ f (ofEquiv E { f := fβ, pt := ptβ, inf := infβ, inf_le_left := inf_le_leftβ, inf_le_right := inf_le_rightβ }) a =
f { f := fβ, pt := ptβ, inf := infβ, inf_le_left := inf_le_leftβ, inf_le_right := inf_le_rightβ } (βE.symm a)
[PROOFSTEP]
rfl
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
a : Set Ξ±
β’ a β f β β b, CFilter.f F.F b β a
[PROOFSTEP]
cases F
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
a : Set Ξ±
Οβ : Type u_5
Fβ : CFilter (Set Ξ±) Οβ
eqβ : CFilter.toFilter Fβ = f
β’ a β f β β b, CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F b β a
[PROOFSTEP]
subst f
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
a : Set Ξ±
Οβ : Type u_5
Fβ : CFilter (Set Ξ±) Οβ
β’ a β CFilter.toFilter Fβ β
β b, CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F b β a
[PROOFSTEP]
rfl
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
xβ : Set Ξ±
β’ xβ β
(CFilter.toFilter
{ f := Subtype.val, pt := { val := univ, property := (_ : univ β f) },
inf := fun x x_1 =>
match x with
| { val := val, property := hβ } =>
match x_1 with
| { val := val_1, property := hβ } => { val := val β© val_1, property := (_ : val β© val_1 β f) },
inf_le_left :=
(_ :
β (x x_1 : βf.sets),
β((fun x x_2 =>
match x with
| { val := val, property := hβ } =>
match x_2 with
| { val := val_1, property := hβ } =>
{ val := val β© val_1, property := (_ : val β© val_1 β f) })
x x_1) β€
βx),
inf_le_right :=
(_ :
β (x x_1 : βf.sets),
β((fun x x_2 =>
match x with
| { val := val, property := hβ } =>
match x_2 with
| { val := val_1, property := hβ } =>
{ val := val β© val_1, property := (_ : val β© val_1 β f) })
x x_1) β€
βx_1) }).sets β
xβ β f.sets
[PROOFSTEP]
simp [exists_mem_subset_iff]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
E : F.Ο β Ο
β’ CFilter.toFilter (CFilter.ofEquiv E F.F) = f
[PROOFSTEP]
refine' Eq.trans _ F.eq
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
E : F.Ο β Ο
β’ CFilter.toFilter (CFilter.ofEquiv E F.F) = CFilter.toFilter F.F
[PROOFSTEP]
exact filter_eq (Set.ext fun _ β¦ β¨fun β¨s, hβ© β¦ β¨E.symm s, by simpa using hβ©, fun β¨t, hβ© β¦ β¨E t, by simp [h]β©β©)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
E : F.Ο β Ο
xβΒΉ : Set Ξ±
xβ : xβΒΉ β (CFilter.toFilter (CFilter.ofEquiv E F.F)).sets
s : Ο
h : CFilter.f (CFilter.ofEquiv E F.F) s β xβΒΉ
β’ CFilter.f F.F (βE.symm s) β xβΒΉ
[PROOFSTEP]
simpa using h
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
E : F.Ο β Ο
xβΒΉ : Set Ξ±
xβ : xβΒΉ β (CFilter.toFilter F.F).sets
t : F.Ο
h : CFilter.f F.F t β xβΒΉ
β’ CFilter.f (CFilter.ofEquiv E F.F) (βE t) β xβΒΉ
[PROOFSTEP]
simp [h]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
m : Ξ± β Ξ²
f : Filter Ξ±
F : Realizer f
xβ : Set Ξ²
β’ xβ β
(CFilter.toFilter
{ f := fun s => m '' CFilter.f F.F s, pt := F.F.pt, inf := F.F.inf,
inf_le_left := (_ : β (x x_1 : F.Ο), m '' CFilter.f F.F (CFilter.inf F.F x x_1) β m '' CFilter.f F.F x),
inf_le_right :=
(_ : β (x x_1 : F.Ο), m '' CFilter.f F.F (CFilter.inf F.F x x_1) β m '' CFilter.f F.F x_1) }).sets β
xβ β (map m f).sets
[PROOFSTEP]
simp only [CFilter.toFilter, image_subset_iff, mem_setOf_eq, Filter.mem_sets, mem_map]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
m : Ξ± β Ξ²
f : Filter Ξ±
F : Realizer f
xβ : Set Ξ²
β’ (β b, CFilter.f F.F b β m β»ΒΉ' xβ) β m β»ΒΉ' xβ β f
[PROOFSTEP]
rw [F.mem_sets]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
m : Ξ± β Ξ²
f : Filter Ξ²
F : Realizer f
xβ : Set Ξ±
β’ xβ β
(CFilter.toFilter
{ f := fun s => m β»ΒΉ' CFilter.f F.F s, pt := F.F.pt, inf := F.F.inf,
inf_le_left := (_ : β (x x_1 : F.Ο), m β»ΒΉ' CFilter.f F.F (CFilter.inf F.F x x_1) β m β»ΒΉ' CFilter.f F.F x),
inf_le_right :=
(_ : β (x x_1 : F.Ο), m β»ΒΉ' CFilter.f F.F (CFilter.inf F.F x x_1) β m β»ΒΉ' CFilter.f F.F x_1) }).sets β
xβ β (comap m f).sets
[PROOFSTEP]
cases F
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
m : Ξ± β Ξ²
f : Filter Ξ²
xβ : Set Ξ±
Οβ : Type ?u.20076
Fβ : CFilter (Set Ξ²) Οβ
eqβ : CFilter.toFilter Fβ = f
β’ xβ β
(CFilter.toFilter
{ f := fun s => m β»ΒΉ' CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F s,
pt := { Ο := Οβ, F := Fβ, eq := eqβ }.F.pt, inf := { Ο := Οβ, F := Fβ, eq := eqβ }.F.inf,
inf_le_left :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := eqβ }.Ο),
m β»ΒΉ'
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x x_1) β
m β»ΒΉ' CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x),
inf_le_right :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := eqβ }.Ο),
m β»ΒΉ'
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x x_1) β
m β»ΒΉ' CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x_1) }).sets β
xβ β (comap m f).sets
[PROOFSTEP]
subst f
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
m : Ξ± β Ξ²
xβ : Set Ξ±
Οβ : Type ?u.20076
Fβ : CFilter (Set Ξ²) Οβ
β’ xβ β
(CFilter.toFilter
{
f := fun s =>
m β»ΒΉ' CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F s,
pt := { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F.pt,
inf := { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F.inf,
inf_le_left :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.Ο),
m β»ΒΉ'
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x
x_1) β
m β»ΒΉ' CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x),
inf_le_right :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.Ο),
m β»ΒΉ'
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x
x_1) β
m β»ΒΉ'
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
x_1) }).sets β
xβ β (comap m (CFilter.toFilter Fβ)).sets
[PROOFSTEP]
exact β¨fun β¨s, hβ© β¦ β¨_, β¨s, Subset.refl _β©, hβ©, fun β¨_, β¨s, hβ©, hββ© β¦ β¨s, Subset.trans (preimage_mono h) hββ©β©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f g : Filter Ξ±
F : Realizer f
G : Realizer g
xβ : Set Ξ±
β’ xβ β
(CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) => CFilter.f F.F s βͺ CFilter.f G.F t,
pt := (F.F.pt, G.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') => (CFilter.inf F.F a b, CFilter.inf G.F a' b'),
inf_le_left :=
(_ :
β (x x_1 : F.Ο Γ G.Ο),
CFilter.f F.F (CFilter.inf F.F x.fst x_1.fst) βͺ CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f F.F x.fst βͺ CFilter.f G.F x.snd),
inf_le_right :=
(_ :
β (x x_1 : F.Ο Γ G.Ο),
CFilter.f F.F (CFilter.inf F.F x.fst x_1.fst) βͺ CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f F.F x_1.fst βͺ CFilter.f G.F x_1.snd) }).sets β
xβ β (f β g).sets
[PROOFSTEP]
cases F
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f g : Filter Ξ±
G : Realizer g
xβ : Set Ξ±
Οβ : Type ?u.22357
Fβ : CFilter (Set Ξ±) Οβ
eqβ : CFilter.toFilter Fβ = f
β’ xβ β
(CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) => CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F s βͺ CFilter.f G.F t,
pt := ({ Ο := Οβ, F := Fβ, eq := eqβ }.F.pt, G.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') => (CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F a b, CFilter.inf G.F a' b'),
inf_le_left :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := eqβ }.Ο Γ G.Ο),
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.fst x_1.fst) βͺ
CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x.fst βͺ CFilter.f G.F x.snd),
inf_le_right :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := eqβ }.Ο Γ G.Ο),
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.fst x_1.fst) βͺ
CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x_1.fst βͺ CFilter.f G.F x_1.snd) }).sets β
xβ β (f β g).sets
[PROOFSTEP]
cases G
[GOAL]
case mk.mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f g : Filter Ξ±
xβ : Set Ξ±
ΟβΒΉ : Type ?u.22357
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
eqβΒΉ : CFilter.toFilter FβΒΉ = f
Οβ : Type ?u.22412
Fβ : CFilter (Set Ξ±) Οβ
eqβ : CFilter.toFilter Fβ = g
β’ xβ β
(CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) =>
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F s βͺ CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F t,
pt := ({ Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F.pt, { Ο := Οβ, F := Fβ, eq := eqβ }.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') =>
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F a b,
CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F a' b'),
inf_le_left :=
(_ :
β (x x_1 : { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.Ο Γ { Ο := Οβ, F := Fβ, eq := eqβ }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x.fst x_1.fst) βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.snd x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x.fst βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x.snd),
inf_le_right :=
(_ :
β (x x_1 : { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.Ο Γ { Ο := Οβ, F := Fβ, eq := eqβ }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x.fst x_1.fst) βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.snd x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x_1.fst βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x_1.snd) }).sets β
xβ β (f β g).sets
[PROOFSTEP]
substs f g
[GOAL]
case mk.mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
xβ : Set Ξ±
ΟβΒΉ : Type ?u.22357
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.22412
Fβ : CFilter (Set Ξ±) Οβ
β’ xβ β
(CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) =>
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F s βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F t,
pt :=
({ Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F.pt,
{ Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') =>
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F a b,
CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F a' b'),
inf_le_left :=
(_ :
β
(x x_1 :
{ Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.Ο Γ
{ Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F
x.fst x_1.fst) βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x.snd
x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F x.fst βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x.snd),
inf_le_right :=
(_ :
β
(x x_1 :
{ Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.Ο Γ
{ Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F
x.fst x_1.fst) βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x.snd
x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F
x_1.fst βͺ
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
x_1.snd) }).sets β
xβ β (CFilter.toFilter FβΒΉ β CFilter.toFilter Fβ).sets
[PROOFSTEP]
simp [CFilter.toFilter]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f g : Filter Ξ±
F : Realizer f
G : Realizer g
β’ CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) => CFilter.f F.F s β© CFilter.f G.F t,
pt := (F.F.pt, G.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') => (CFilter.inf F.F a b, CFilter.inf G.F a' b'),
inf_le_left :=
(_ :
β (x x_1 : F.Ο Γ G.Ο),
CFilter.f F.F (CFilter.inf F.F x.fst x_1.fst) β© CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f F.F x.fst β© CFilter.f G.F x.snd),
inf_le_right :=
(_ :
β (x x_1 : F.Ο Γ G.Ο),
CFilter.f F.F (CFilter.inf F.F x.fst x_1.fst) β© CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f F.F x_1.fst β© CFilter.f G.F x_1.snd) } =
f β g
[PROOFSTEP]
cases F
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f g : Filter Ξ±
G : Realizer g
Οβ : Type ?u.34651
Fβ : CFilter (Set Ξ±) Οβ
eqβ : CFilter.toFilter Fβ = f
β’ CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) => CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F s β© CFilter.f G.F t,
pt := ({ Ο := Οβ, F := Fβ, eq := eqβ }.F.pt, G.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') => (CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F a b, CFilter.inf G.F a' b'),
inf_le_left :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := eqβ }.Ο Γ G.Ο),
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.fst x_1.fst) β©
CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x.fst β© CFilter.f G.F x.snd),
inf_le_right :=
(_ :
β (x x_1 : { Ο := Οβ, F := Fβ, eq := eqβ }.Ο Γ G.Ο),
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.fst x_1.fst) β©
CFilter.f G.F (CFilter.inf G.F x.snd x_1.snd) β
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x_1.fst β© CFilter.f G.F x_1.snd) } =
f β g
[PROOFSTEP]
cases G
[GOAL]
case mk.mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f g : Filter Ξ±
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
eqβΒΉ : CFilter.toFilter FβΒΉ = f
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
eqβ : CFilter.toFilter Fβ = g
β’ CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) => CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F s β© CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F t,
pt := ({ Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F.pt, { Ο := Οβ, F := Fβ, eq := eqβ }.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') =>
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F a b,
CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F a' b'),
inf_le_left :=
(_ :
β (x x_1 : { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.Ο Γ { Ο := Οβ, F := Fβ, eq := eqβ }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x.fst x_1.fst) β©
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.snd x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x.fst β©
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x.snd),
inf_le_right :=
(_ :
β (x x_1 : { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.Ο Γ { Ο := Οβ, F := Fβ, eq := eqβ }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x.fst x_1.fst) β©
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := eqβ }.F x.snd x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := eqβΒΉ }.F x_1.fst β©
CFilter.f { Ο := Οβ, F := Fβ, eq := eqβ }.F x_1.snd) } =
f β g
[PROOFSTEP]
substs f g
[GOAL]
case mk.mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
β’ CFilter.toFilter
{
f := fun x =>
match x with
| (s, t) =>
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F s β©
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F t,
pt :=
({ Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F.pt,
{ Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F.pt),
inf := fun x x_1 =>
match x with
| (a, a') =>
match x_1 with
| (b, b') =>
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F a b,
CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F a' b'),
inf_le_left :=
(_ :
β
(x x_1 :
{ Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.Ο Γ
{ Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F x.fst
x_1.fst) β©
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x.snd
x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F x.fst β©
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x.snd),
inf_le_right :=
(_ :
β
(x x_1 :
{ Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.Ο Γ
{ Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.Ο),
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F
(CFilter.inf { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F x.fst
x_1.fst) β©
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F
(CFilter.inf { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x.snd
x_1.snd) β
CFilter.f { Ο := ΟβΒΉ, F := FβΒΉ, eq := (_ : CFilter.toFilter FβΒΉ = CFilter.toFilter FβΒΉ) }.F x_1.fst β©
CFilter.f { Ο := Οβ, F := Fβ, eq := (_ : CFilter.toFilter Fβ = CFilter.toFilter Fβ) }.F x_1.snd) } =
CFilter.toFilter FβΒΉ β CFilter.toFilter Fβ
[PROOFSTEP]
simp only [CFilter.toFilter, Prod.exists]
[GOAL]
case mk.mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
β’ { sets := {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a},
univ_sets := (_ : univ β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
sets_of_superset :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β y β y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β© y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}) } =
{ sets := {a | β b, CFilter.f FβΒΉ b β a}, univ_sets := (_ : β b, CFilter.f FβΒΉ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f FβΒΉ b β a} β x β y β y β {a | β b, CFilter.f FβΒΉ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f FβΒΉ b β a} β
y β {a | β b, CFilter.f FβΒΉ b β a} β x β© y β {a | β b, CFilter.f FβΒΉ b β a}) } β
{ sets := {a | β b, CFilter.f Fβ b β a}, univ_sets := (_ : β b, CFilter.f Fβ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f Fβ b β a} β x β y β y β {a | β b, CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f Fβ b β a} β
y β {a | β b, CFilter.f Fβ b β a} β x β© y β {a | β b, CFilter.f Fβ b β a}) }
[PROOFSTEP]
ext
[GOAL]
case mk.mk.a
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
sβ : Set Ξ±
β’ sβ β
{ sets := {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a},
univ_sets := (_ : univ β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
sets_of_superset :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β y β y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β© y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}) } β
sβ β
{ sets := {a | β b, CFilter.f FβΒΉ b β a}, univ_sets := (_ : β b, CFilter.f FβΒΉ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f FβΒΉ b β a} β x β y β y β {a | β b, CFilter.f FβΒΉ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f FβΒΉ b β a} β
y β {a | β b, CFilter.f FβΒΉ b β a} β x β© y β {a | β b, CFilter.f FβΒΉ b β a}) } β
{ sets := {a | β b, CFilter.f Fβ b β a}, univ_sets := (_ : β b, CFilter.f Fβ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f Fβ b β a} β x β y β y β {a | β b, CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f Fβ b β a} β
y β {a | β b, CFilter.f Fβ b β a} β x β© y β {a | β b, CFilter.f Fβ b β a}) }
[PROOFSTEP]
constructor
[GOAL]
case mk.mk.a.mp
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
sβ : Set Ξ±
β’ sβ β
{ sets := {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a},
univ_sets := (_ : univ β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
sets_of_superset :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β y β y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β© y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}) } β
sβ β
{ sets := {a | β b, CFilter.f FβΒΉ b β a}, univ_sets := (_ : β b, CFilter.f FβΒΉ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f FβΒΉ b β a} β x β y β y β {a | β b, CFilter.f FβΒΉ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f FβΒΉ b β a} β
y β {a | β b, CFilter.f FβΒΉ b β a} β x β© y β {a | β b, CFilter.f FβΒΉ b β a}) } β
{ sets := {a | β b, CFilter.f Fβ b β a}, univ_sets := (_ : β b, CFilter.f Fβ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f Fβ b β a} β x β y β y β {a | β b, CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f Fβ b β a} β
y β {a | β b, CFilter.f Fβ b β a} β x β© y β {a | β b, CFilter.f Fβ b β a}) }
[PROOFSTEP]
rintro β¨s, t, hβ©
[GOAL]
case mk.mk.a.mp.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
sβ : Set Ξ±
s : ΟβΒΉ
t : Οβ
h : CFilter.f FβΒΉ s β© CFilter.f Fβ t β sβ
β’ sβ β
{ sets := {a | β b, CFilter.f FβΒΉ b β a}, univ_sets := (_ : β b, CFilter.f FβΒΉ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f FβΒΉ b β a} β x β y β y β {a | β b, CFilter.f FβΒΉ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f FβΒΉ b β a} β
y β {a | β b, CFilter.f FβΒΉ b β a} β x β© y β {a | β b, CFilter.f FβΒΉ b β a}) } β
{ sets := {a | β b, CFilter.f Fβ b β a}, univ_sets := (_ : β b, CFilter.f Fβ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f Fβ b β a} β x β y β y β {a | β b, CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f Fβ b β a} β
y β {a | β b, CFilter.f Fβ b β a} β x β© y β {a | β b, CFilter.f Fβ b β a}) }
[PROOFSTEP]
apply mem_inf_of_inter _ _ h
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
sβ : Set Ξ±
s : ΟβΒΉ
t : Οβ
h : CFilter.f FβΒΉ s β© CFilter.f Fβ t β sβ
β’ CFilter.f FβΒΉ s β
{ sets := {a | β b, CFilter.f FβΒΉ b β a}, univ_sets := (_ : β b, CFilter.f FβΒΉ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f FβΒΉ b β a} β x β y β y β {a | β b, CFilter.f FβΒΉ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f FβΒΉ b β a} β
y β {a | β b, CFilter.f FβΒΉ b β a} β x β© y β {a | β b, CFilter.f FβΒΉ b β a}) }
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
sβ : Set Ξ±
s : ΟβΒΉ
t : Οβ
h : CFilter.f FβΒΉ s β© CFilter.f Fβ t β sβ
β’ CFilter.f Fβ t β
{ sets := {a | β b, CFilter.f Fβ b β a}, univ_sets := (_ : β b, CFilter.f Fβ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f Fβ b β a} β x β y β y β {a | β b, CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f Fβ b β a} β
y β {a | β b, CFilter.f Fβ b β a} β x β© y β {a | β b, CFilter.f Fβ b β a}) }
[PROOFSTEP]
use s
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
sβ : Set Ξ±
s : ΟβΒΉ
t : Οβ
h : CFilter.f FβΒΉ s β© CFilter.f Fβ t β sβ
β’ CFilter.f Fβ t β
{ sets := {a | β b, CFilter.f Fβ b β a}, univ_sets := (_ : β b, CFilter.f Fβ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f Fβ b β a} β x β y β y β {a | β b, CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f Fβ b β a} β
y β {a | β b, CFilter.f Fβ b β a} β x β© y β {a | β b, CFilter.f Fβ b β a}) }
[PROOFSTEP]
use t
[GOAL]
case mk.mk.a.mpr
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
sβ : Set Ξ±
β’ sβ β
{ sets := {a | β b, CFilter.f FβΒΉ b β a}, univ_sets := (_ : β b, CFilter.f FβΒΉ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f FβΒΉ b β a} β x β y β y β {a | β b, CFilter.f FβΒΉ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f FβΒΉ b β a} β
y β {a | β b, CFilter.f FβΒΉ b β a} β x β© y β {a | β b, CFilter.f FβΒΉ b β a}) } β
{ sets := {a | β b, CFilter.f Fβ b β a}, univ_sets := (_ : β b, CFilter.f Fβ b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f Fβ b β a} β x β y β y β {a | β b, CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f Fβ b β a} β
y β {a | β b, CFilter.f Fβ b β a} β x β© y β {a | β b, CFilter.f Fβ b β a}) } β
sβ β
{ sets := {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a},
univ_sets := (_ : univ β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
sets_of_superset :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β y β y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β© y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}) }
[PROOFSTEP]
rintro β¨_, β¨a, haβ©, _, β¨b, hbβ©, rflβ©
[GOAL]
case mk.mk.a.mpr.intro.intro.intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
ΟβΒΉ : Type ?u.34651
FβΒΉ : CFilter (Set Ξ±) ΟβΒΉ
Οβ : Type ?u.34706
Fβ : CFilter (Set Ξ±) Οβ
wβΒΉ : Set Ξ±
a : ΟβΒΉ
ha : CFilter.f FβΒΉ a β wβΒΉ
wβ : Set Ξ±
b : Οβ
hb : CFilter.f Fβ b β wβ
β’ wβΒΉ β© wβ β
{ sets := {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a},
univ_sets := (_ : univ β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
sets_of_superset :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β y β y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a} β
x β© y β {a | β a_1 b, CFilter.f FβΒΉ a_1 β© CFilter.f Fβ b β a}) }
[PROOFSTEP]
exact β¨a, b, inter_subset_inter ha hbβ©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
instβ : DecidableEq Ξ±
xβ : Set Ξ±
h : xβ β cofinite.sets
β’ CFilter.f
{ f := fun s => {a | Β¬a β s}, pt := β
, inf := fun x x_1 => x βͺ x_1,
inf_le_left := (_ : β (x x_1 : Finset Ξ±) (x_2 : Ξ±), Β¬x_2 β (fun x x_3 => x βͺ x_3) x x_1 β Β¬x_2 β x),
inf_le_right := (_ : β (x x_1 : Finset Ξ±) (x_2 : Ξ±), Β¬x_2 β (fun x x_3 => x βͺ x_3) x x_1 β Β¬x_2 β x_1) }
(Finite.toFinset h) β
xβ
[PROOFSTEP]
simp [Subset.rfl]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
fβ : Filter Ξ±
m : Ξ± β Filter Ξ²
F : Realizer fβ
G : (i : Ξ±) β Realizer (m i)
xβ : (s : F.Ο) Γ ((i : Ξ±) β i β CFilter.f F.F s β (G i).Ο)
s : F.Ο
f : (i : Ξ±) β i β CFilter.f F.F s β (G i).Ο
i : Ξ±
hβ : i β CFilter.f F.F s
β’ i β CFilter.f F.F s
[PROOFSTEP]
assumption
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
m : Ξ± β Filter Ξ²
F : Realizer f
G : (i : Ξ±) β Realizer (m i)
xβΒ² xβΒΉ : (s : F.Ο) Γ ((i : Ξ±) β i β CFilter.f F.F s β (G i).Ο)
xβ : Ξ²
β’ xβ β
(fun x =>
match x with
| { fst := s, snd := f_1 } => β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
((fun x x_1 =>
match x with
| { fst := a, snd := f_1 } =>
match x_1 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf F.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f F.F a)) (f' i (_ : i β CFilter.f F.F b)) })
xβΒ² xβΒΉ) β
xβ β
(fun x =>
match x with
| { fst := s, snd := f_1 } => β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
xβΒ²
[PROOFSTEP]
simp only [mem_iUnion, forall_exists_index]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
m : Ξ± β Filter Ξ²
F : Realizer f
G : (i : Ξ±) β Realizer (m i)
xβΒ² xβΒΉ : (s : F.Ο) Γ ((i : Ξ±) β i β CFilter.f F.F s β (G i).Ο)
xβ : Ξ²
β’ β (x : Ξ±) (x_1 : x β CFilter.f F.F (CFilter.inf F.F xβΒ².fst xβΒΉ.fst)),
xβ β
CFilter.f (G x).F
(CFilter.inf (G x).F (Sigma.snd xβΒ² x (_ : x β CFilter.f F.F xβΒ².fst))
(Sigma.snd xβΒΉ x (_ : x β CFilter.f F.F xβΒΉ.fst))) β
β i i_1, xβ β CFilter.f (G i).F (Sigma.snd xβΒ² i i_1)
[PROOFSTEP]
exact fun i hβ hβ β¦ β¨i, F.F.inf_le_left _ _ hβ, (G i).F.inf_le_left _ _ hββ©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
m : Ξ± β Filter Ξ²
F : Realizer f
G : (i : Ξ±) β Realizer (m i)
xβΒ² xβΒΉ : (s : F.Ο) Γ ((i : Ξ±) β i β CFilter.f F.F s β (G i).Ο)
xβ : Ξ²
β’ xβ β
(fun x =>
match x with
| { fst := s, snd := f_1 } => β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
((fun x x_1 =>
match x with
| { fst := a, snd := f_1 } =>
match x_1 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf F.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f F.F a)) (f' i (_ : i β CFilter.f F.F b)) })
xβΒ² xβΒΉ) β
xβ β
(fun x =>
match x with
| { fst := s, snd := f_1 } => β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
xβΒΉ
[PROOFSTEP]
simp only [mem_iUnion, forall_exists_index]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
m : Ξ± β Filter Ξ²
F : Realizer f
G : (i : Ξ±) β Realizer (m i)
xβΒ² xβΒΉ : (s : F.Ο) Γ ((i : Ξ±) β i β CFilter.f F.F s β (G i).Ο)
xβ : Ξ²
β’ β (x : Ξ±) (x_1 : x β CFilter.f F.F (CFilter.inf F.F xβΒ².fst xβΒΉ.fst)),
xβ β
CFilter.f (G x).F
(CFilter.inf (G x).F (Sigma.snd xβΒ² x (_ : x β CFilter.f F.F xβΒ².fst))
(Sigma.snd xβΒΉ x (_ : x β CFilter.f F.F xβΒΉ.fst))) β
β i i_1, xβ β CFilter.f (G i).F (Sigma.snd xβΒΉ i i_1)
[PROOFSTEP]
exact fun i hβ hβ β¦ β¨i, F.F.inf_le_right _ _ hβ, (G i).F.inf_le_right _ _ hββ©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
m : Ξ± β Filter Ξ²
F : Realizer f
G : (i : Ξ±) β Realizer (m i)
xβ : Set Ξ²
β’ xβ β
(CFilter.toFilter
{
f := fun x =>
match x with
| { fst := s, snd := f_1 } => β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h),
pt := { fst := F.F.pt, snd := fun i x => (G i).F.pt },
inf := fun x x_1 =>
match x with
| { fst := a, snd := f_1 } =>
match x_1 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf F.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f F.F a)) (f' i (_ : i β CFilter.f F.F b)) },
inf_le_left :=
(_ :
β (x x_1 : (s : F.Ο) Γ ((i : Ξ±) β i β CFilter.f F.F s β (G i).Ο)) (x_2 : Ξ²),
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
((fun x x_3 =>
match x with
| { fst := a, snd := f_1 } =>
match x_3 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf F.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f F.F a))
(f' i (_ : i β CFilter.f F.F b)) })
x x_1) β
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
x),
inf_le_right :=
(_ :
β (x x_1 : (s : F.Ο) Γ ((i : Ξ±) β i β CFilter.f F.F s β (G i).Ο)) (x_2 : Ξ²),
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
((fun x x_3 =>
match x with
| { fst := a, snd := f_1 } =>
match x_3 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf F.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f F.F a))
(f' i (_ : i β CFilter.f F.F b)) })
x x_1) β
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f F.F s), CFilter.f (G i).F (f_1 i h))
x_1) }).sets β
xβ β (bind f m).sets
[PROOFSTEP]
cases' F with _ F _
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
m : Ξ± β Filter Ξ²
G : (i : Ξ±) β Realizer (m i)
xβ : Set Ξ²
Οβ : Type ?u.44096
F : CFilter (Set Ξ±) Οβ
eqβ : CFilter.toFilter F = f
β’ xβ β
(CFilter.toFilter
{
f := fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F s), CFilter.f (G i).F (f_1 i h),
pt := { fst := { Ο := Οβ, F := F, eq := eqβ }.F.pt, snd := fun i x => (G i).F.pt },
inf := fun x x_1 =>
match x with
| { fst := a, snd := f_1 } =>
match x_1 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf { Ο := Οβ, F := F, eq := eqβ }.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F a))
(f' i (_ : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F b)) },
inf_le_left :=
(_ :
β
(x x_1 :
(s : { Ο := Οβ, F := F, eq := eqβ }.Ο) Γ
((i : Ξ±) β i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F s β (G i).Ο))
(x_2 : Ξ²),
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F s),
CFilter.f (G i).F (f_1 i h))
((fun x x_3 =>
match x with
| { fst := a, snd := f_1 } =>
match x_3 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf { Ο := Οβ, F := F, eq := eqβ }.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F a))
(f' i (_ : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F b)) })
x x_1) β
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F s),
CFilter.f (G i).F (f_1 i h))
x),
inf_le_right :=
(_ :
β
(x x_1 :
(s : { Ο := Οβ, F := F, eq := eqβ }.Ο) Γ
((i : Ξ±) β i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F s β (G i).Ο))
(x_2 : Ξ²),
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F s),
CFilter.f (G i).F (f_1 i h))
((fun x x_3 =>
match x with
| { fst := a, snd := f_1 } =>
match x_3 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf { Ο := Οβ, F := F, eq := eqβ }.F a b,
snd := fun i h =>
CFilter.inf (G i).F (f_1 i (_ : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F a))
(f' i (_ : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F b)) })
x x_1) β
x_2 β
(fun x =>
match x with
| { fst := s, snd := f_1 } =>
β (i : Ξ±) (h : i β CFilter.f { Ο := Οβ, F := F, eq := eqβ }.F s),
CFilter.f (G i).F (f_1 i h))
x_1) }).sets β
xβ β (bind f m).sets
[PROOFSTEP]
subst f
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
m : Ξ± β Filter Ξ²
G : (i : Ξ±) β Realizer (m i)
xβ : Set Ξ²
Οβ : Type ?u.44096
F : CFilter (Set Ξ±) Οβ
β’ xβ β
(CFilter.toFilter
{
f := fun x =>
match x with
| { fst := s, snd := f } =>
β (i : Ξ±) (h :
i β CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F s),
CFilter.f (G i).F (f i h),
pt :=
{ fst := { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F.pt,
snd := fun i x => (G i).F.pt },
inf := fun x x_1 =>
match x with
| { fst := a, snd := f } =>
match x_1 with
| { fst := b, snd := f' } =>
{ fst := CFilter.inf { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F a b,
snd := fun i h =>
CFilter.inf (G i).F
(f i
(_ :
i β CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F a))
(f' i
(_ :
i β
CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F
b)) },
inf_le_left :=
(_ :
β
(x x_1 :
(s : { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.Ο) Γ
((i : Ξ±) β
i β CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F s β
(G i).Ο))
(x_2 : Ξ²),
x_2 β
(fun x =>
match x with
| { fst := s, snd := f } =>
β (i : Ξ±) (h :
i β
CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F s),
CFilter.f (G i).F (f i h))
((fun x x_3 =>
match x with
| { fst := a, snd := f } =>
match x_3 with
| { fst := b, snd := f' } =>
{
fst :=
CFilter.inf
{ Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F a b,
snd := fun i h =>
CFilter.inf (G i).F
(f i
(_ :
i β
CFilter.f
{ Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F
a))
(f' i
(_ :
i β
CFilter.f
{ Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F
b)) })
x x_1) β
x_2 β
(fun x =>
match x with
| { fst := s, snd := f } =>
β (i : Ξ±) (h :
i β
CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F s),
CFilter.f (G i).F (f i h))
x),
inf_le_right :=
(_ :
β
(x x_1 :
(s : { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.Ο) Γ
((i : Ξ±) β
i β CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F s β
(G i).Ο))
(x_2 : Ξ²),
x_2 β
(fun x =>
match x with
| { fst := s, snd := f } =>
β (i : Ξ±) (h :
i β
CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F s),
CFilter.f (G i).F (f i h))
((fun x x_3 =>
match x with
| { fst := a, snd := f } =>
match x_3 with
| { fst := b, snd := f' } =>
{
fst :=
CFilter.inf
{ Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F a b,
snd := fun i h =>
CFilter.inf (G i).F
(f i
(_ :
i β
CFilter.f
{ Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F
a))
(f' i
(_ :
i β
CFilter.f
{ Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F
b)) })
x x_1) β
x_2 β
(fun x =>
match x with
| { fst := s, snd := f } =>
β (i : Ξ±) (h :
i β
CFilter.f { Ο := Οβ, F := F, eq := (_ : CFilter.toFilter F = CFilter.toFilter F) }.F s),
CFilter.f (G i).F (f i h))
x_1) }).sets β
xβ β (bind (CFilter.toFilter F) m).sets
[PROOFSTEP]
simp only [CFilter.toFilter, iUnion_subset_iff, Sigma.exists, Filter.mem_sets, mem_bind]
[GOAL]
case mk
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
m : Ξ± β Filter Ξ²
G : (i : Ξ±) β Realizer (m i)
xβ : Set Ξ²
Οβ : Type ?u.44096
F : CFilter (Set Ξ±) Οβ
β’ xβ β {a | β a_1 b, β (i : Ξ±) (i_1 : i β CFilter.f F { fst := a_1, snd := b }.fst), CFilter.f (G i).F (b i i_1) β a} β
β t,
t β
{ sets := {a | β b, CFilter.f F b β a}, univ_sets := (_ : β b, CFilter.f F b β univ),
sets_of_superset :=
(_ : β {x y : Set Ξ±}, x β {a | β b, CFilter.f F b β a} β x β y β y β {a | β b, CFilter.f F b β a}),
inter_sets :=
(_ :
β {x y : Set Ξ±},
x β {a | β b, CFilter.f F b β a} β
y β {a | β b, CFilter.f F b β a} β x β© y β {a | β b, CFilter.f F b β a}) } β§
β (x : Ξ±), x β t β xβ β m x
[PROOFSTEP]
exact
β¨fun β¨s, f, hβ© β¦ β¨F s, β¨s, Subset.refl _β©, fun i H β¦ (G i).mem_sets.2 β¨f i H, fun _ h' β¦ h i H h'β©β©,
fun β¨_, β¨s, hβ©, fβ© β¦
let β¨f', h'β© := Classical.axiom_of_choice fun i : F s β¦ (G i).mem_sets.1 (f i (h i.2))
β¨s, fun i h β¦ f' β¨i, hβ©, fun _ H _ m β¦ h' β¨_, Hβ© mβ©β©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Ξ± β Filter Ξ²
F : (i : Ξ±) β Realizer (f i)
β’ β (x : Set Ξ²), x β (bind β€ fun i => f i).sets β x β (β¨ (i : Ξ±), f i).sets
[PROOFSTEP]
simp [Filter.bind, eq_univ_iff_forall, iSup_sets_eq]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
β’ f β β₯ β β (a : F.Ο), Set.Nonempty (CFilter.f F.F a)
[PROOFSTEP]
rw [not_iff_comm, β le_bot_iff, F.le_iff Realizer.bot, not_forall]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
β’ (β x, Β¬Set.Nonempty (CFilter.f F.F x)) β β (b : Realizer.bot.Ο), β a, CFilter.f F.F a β€ CFilter.f Realizer.bot.F b
[PROOFSTEP]
simp only [Set.not_nonempty_iff_eq_empty]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
Ο : Type u_3
Ο : Type u_4
f : Filter Ξ±
F : Realizer f
β’ (β x, CFilter.f F.F x = β
) β β (b : Realizer.bot.Ο), β a, CFilter.f F.F a β€ CFilter.f Realizer.bot.F b
[PROOFSTEP]
exact
β¨fun β¨x, eβ© _ β¦ β¨x, le_of_eq eβ©, fun h β¦
let β¨x, hβ© := h ()
β¨x, le_bot_iff.1 hβ©β©
|
------------------------------------------------------------------------------
-- Well-founded induction on natural numbers
------------------------------------------------------------------------------
{-# OPTIONS --exact-split #-}
{-# OPTIONS --no-sized-types #-}
{-# OPTIONS --no-universe-polymorphism #-}
{-# OPTIONS --without-K #-}
-- Adapted from
-- http://www.iis.sinica.edu.tw/~scm/2008/well-founded-recursion-and-accessibility/
-- and the Agda standard libraryΒ 0.8.1.
module FOTC.Induction.WF where
open import Common.Relation.Unary
open import FOTC.Base
------------------------------------------------------------------------------
-- The accessibility predicate: x is accessible if everything which is
-- smaller than x is also accessible (inductively).
data Acc (P : D β Set)(_<_ : D β D β Set)(x : D) : Set where
acc : (β {y} β P y β y < x β Acc P _<_ y) β Acc P _<_ x
accFold : {P Q : D β Set}(_<_ : D β D β Set) β
(β {x} β Q x β (β {y} β Q y β y < x β P y) β P x) β
β {x} β Q x β Acc Q _<_ x β P x
accFold _<_ f Qx (acc h) = f Qx (Ξ» Qy y<x β accFold _<_ f Qy (h Qy y<x))
-- The accessibility predicate encodes what it means to be
-- well-founded; if all elements are accessible, then _<_ is
-- well-founded.
WellFounded : {P : D β Set} β (D β D β Set) β Set
WellFounded {P} _<_ = β {x} β P x β Acc P _<_ x
WellFoundedInduction : {P Q : D β Set}
{_<_ : D β D β Set} β
WellFounded _<_ β
(β {x} β Q x β (β {y} β Q y β y < x β P y) β P x) β
β {x} β Q x β P x
WellFoundedInduction {_<_ = _<_} wf f Qx = accFold _<_ f Qx (wf Qx)
module Subrelation {P : D β Set}
{_<_ _<'_ : D β D β Set}
(<β<' : β {x y} β P x β x < y β x <' y)
where
accessible : Acc P _<'_ β Acc P _<_
accessible (acc h) = acc (Ξ» Py y<x β accessible (h Py (<β<' Py y<x)))
well-founded : WellFounded _<'_ β WellFounded _<_
well-founded wf = Ξ» Px β accessible (wf Px)
module InverseImage {P Q : D β Set}
{_<_ : D β D β Set}
{f : D β D}
(f-Q : β {x} β P x β Q (f x))
where
accessible : β {x} β P x β
Acc Q _<_ (f x) β Acc P (Ξ» x' y' β f x' < f y') x
accessible Px (acc h) =
acc (Ξ» {y} Py fy<fx β accessible Py (h (f-Q Py) fy<fx))
wellFounded : WellFounded _<_ β WellFounded (Ξ» x y β f x < f y)
wellFounded wf = Ξ» Px β accessible Px (wf (f-Q Px))
|
#' Scales for shapes, aka glyphs
#'
#' `scale_shape()` maps discrete variables to six easily discernible shapes.
#' If you have more than six levels, you will get a warning message, and the
#' seventh and subsequent levels will not appear on the plot. Use
#' [scale_shape_manual()] to supply your own values. You can not map
#' a continuous variable to shape unless `scale_shape_binned()` is used. Still,
#' as shape has no inherent order, this use is not advised.
#'
#' @param solid Should the shapes be solid, `TRUE`, or hollow,
#' `FALSE`?
#' @inheritParams scale_x_discrete
#' @inheritDotParams discrete_scale -expand -position
#' @rdname scale_shape
#' @export
#' @examples
#' set.seed(596)
#' dsmall <- diamonds[sample(nrow(diamonds), 100), ]
#'
#' (d <- ggplot(dsmall, aes(carat, price)) + geom_point(aes(shape = cut)))
#' d + scale_shape(solid = TRUE) # the default
#' d + scale_shape(solid = FALSE)
#' d + scale_shape(name = "Cut of diamond")
#'
#' # To change order of levels, change order of
#' # underlying factor
#' levels(dsmall$cut) <- c("Fair", "Good", "Very Good", "Premium", "Ideal")
#'
#' # Need to recreate plot to pick up new data
#' ggplot(dsmall, aes(price, carat)) + geom_point(aes(shape = cut))
#'
#' # Show a list of available shapes
#' df_shapes <- data.frame(shape = 0:24)
#' ggplot(df_shapes, aes(0, 0, shape = shape)) +
#' geom_point(aes(shape = shape), size = 5, fill = 'red') +
#' scale_shape_identity() +
#' facet_wrap(~shape) +
#' theme_void()
scale_shape <- function(..., solid = TRUE) {
discrete_scale("shape", "shape_d", shape_pal(solid), ...)
}
#' @rdname scale_shape
#' @export
scale_shape_binned <- function(..., solid = TRUE) {
binned_scale("shape", "shape_b", binned_pal(shape_pal(solid)), ...)
}
#' @rdname scale_shape
#' @export
#' @usage NULL
scale_shape_discrete <- scale_shape
#' @rdname scale_shape
#' @export
#' @usage NULL
scale_shape_ordinal <- function(...) {
cli::cli_warn("Using shapes for an ordinal variable is not advised")
scale_shape(...)
}
#' @rdname scale_shape
#' @export
#' @usage NULL
scale_shape_continuous <- function(...) {
cli::cli_abort(c(
"A continuous variable cannot be mapped to the {.field shape} aesthetic",
"i" = "choose a different aesthetic or use {.fn scale_shape_binned}"
))
}
|
module Issue395 where
foo : Set β Setβ
foo foo with Set
... | _ = Set
|
using JLD2
using FileIO
function test_merge(fname_base="output/simpleDemoCompareCost_results_", files=100)
if files < 1
return
end
o = load(string(fname_base, 1, ".jld2"))
AS_cost_ = o["AS_cost"]
BS_cost_ = o["BS_cost"]
ts_ = o["ts"]
Ns_ = o["Ns"]
maxIter_ = o["maxIter"]
for i in 2:files
o = load(string(fname_base, i, ".jld2"))
AS_cost_ = cat(AS_cost_,o["AS_cost"]; dims=3)
BS_cost_ = cat(BS_cost_,o["BS_cost"]; dims=3)
end
ts_, AS_cost_, BS_cost_, Ns_, maxIter_
end
ts, AS_iter, BS_iter, Ns, maxIter = test_merge()
@save "simpleDemoCompareCostAll_results.jld2" ts AS_iter BS_iter Ns maxIter
|
#pragma once
#include <iostream>
#include <string>
#include <utility>
#include <boost/foreach.hpp>
#if defined(USE_YAML)
#include <yaml-cpp/yaml.h>
#elif defined(USE_JSON)
#include "json.hpp"
using json = nlohmann::json;
#endif
class Messages
{
public:
static std::ostream& debug()
{
std::cerr << "#=debug ";
return std::cerr;
}
static void respondSucceed(const std::string& p_message)
{
#if defined(USE_YAML)
YAML::Node node;
#elif defined(USE_JSON)
json node;
#endif
node["status"] = "ok";
node["message"] = p_message;
message(node);
}
static void respondSucceed(
#if defined(USE_YAML)
const YAML::Node& p_node
#elif defined(USE_JSON)
const json& p_node
#endif
)
{
#if defined(USE_YAML)
YAML::Node rootNode;
#elif defined(USE_JSON)
json rootNode;
#endif
rootNode["status"] = "ok";
rootNode["data"] = p_node;
message(rootNode);
}
static void respondFailed(int code, const std::string& p_message)
{
#if defined(USE_YAML)
YAML::Node rootNode;
#elif defined(USE_JSON)
json rootNode;
#endif
rootNode["status"] = "error";
rootNode["code"] = code;
rootNode["message"] = p_message;
message(rootNode);
}
private:
static void message(
#if defined(USE_YAML)
const YAML::Node& p_node
#elif defined(USE_JSON)
const json& p_node
#endif
)
{
using namespace std;
cout << p_node << endl << "#=end" << endl;
}
}; |
[STATEMENT]
lemma composable_implies_arr:
assumes "\<nu> \<star> \<mu> \<noteq> null"
shows "arr \<mu>" and "arr \<nu>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. arr \<mu> &&& arr \<nu>
[PROOF STEP]
using assms is_extensional VoV.arr_char\<^sub>S\<^sub>b\<^sub>C VoV.inclusion
[PROOF STATE]
proof (prove)
using this:
\<nu> \<star> \<mu> \<noteq> null
\<not> VoV.arr ?f \<Longrightarrow> fst ?f \<star> snd ?f = null
VoV.arr ?f = (fst ?f \<star> snd ?f \<noteq> null)
fst ?f \<star> snd ?f \<noteq> null \<Longrightarrow> VxV.arr ?f
goal (1 subgoal):
1. arr \<mu> &&& arr \<nu>
[PROOF STEP]
by auto |
module PatternSynonymAmbiguousParse where
data X : Set where
if_then_else_ : X -> X -> X -> X
if_then_ : X -> X -> X
x : X
pattern bad x = if x then if x then x else x
|
theory Interpretation_in_nested_targets
imports MainRLT
begin
locale injection =
fixes f :: \<open>'a \<Rightarrow> 'b\<close>
assumes eqI: \<open>f x = f y \<Longrightarrow> x = y\<close>
begin
lemma eq_iff:
\<open>x = y \<longleftrightarrow> f x = f y\<close>
by (auto intro: eqI)
lemma inv_apply:
\<open>inv f (f x) = x\<close>
by (rule inv_f_f) (simp add: eqI injI)
end
context
fixes f :: \<open>'a::linorder \<Rightarrow> 'b::linorder\<close>
assumes \<open>strict_mono f\<close>
begin
global_interpretation strict_mono: injection f
by standard (simp add: \<open>strict_mono f\<close> strict_mono_eq)
thm strict_mono.eq_iff
thm strict_mono.inv_apply
end
thm strict_mono.eq_iff
thm strict_mono.inv_apply
end
|
function ihs_test03 ( )
%*****************************************************************************80
%
%% IHS_TEST03 tests the improved distributed hypercube sampling algorithm.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 27 February 2014
%
% Author:
%
% John Burkardt
%
dim_num = 2;
duplication = 5;
fprintf ( 1, '\n' );
fprintf ( 1, 'IHS_TEST03' );
fprintf ( 1, ' IHS implements the IHS Algorithm\n' );
fprintf ( 1, ' (Improved Distributed Hypercube Sampling)\n' );
fprintf ( 1, '\n' );
fprintf ( 1, ' Demonstrate the code for a fixed dimension\n' );
fprintf ( 1, ' and duplication value, and increasing number of points.\n' );
fprintf ( 1, '\n' );
fprintf ( 1, ' Spatial dimension = %d\n', dim_num );
fprintf ( 1, ' Duplication factor = %d\n', duplication );
for i = 1 : 5
point_num = 10 * 2^(i-1);
opt = point_num / point_num^( 1.0 / dim_num );
fprintf ( 1, '\n' );
fprintf ( 1, ' Number of points = %d\n', point_num );
fprintf ( 1, ' Desired minimum distance = %f\n', opt );
%
% Get the points.
%
x = ihs ( dim_num, point_num, duplication );
%
% Compute the covariance.
%
[ average, sd, covc ] = covariance ( dim_num, point_num, x );
fprintf ( 1, '\n' );
fprintf ( 1, ' Average minimum distance %f\n', average );
fprintf ( 1, ' Standard deviation: %f\n', sd );
fprintf ( 1, ' Covariance: %f\n', covc );
fprintf ( 1, '\n' );
for j = 1 : point_num
if ( j <= 10 | point_num - 10 <= j )
fprintf ( 1, '%4d ', j );
for i = 1 : dim_num
fprintf ( 1, '%4d ', x(i,j) );
end
fprintf ( 1, '\n');
elseif ( j == 11 )
fprintf ( 1, '.... ........\n' );
end
end
end
return
end
|
theory FSM_Product
imports FSM
begin
section \<open> Product machines with an additional fail state \<close>
text \<open>
We extend the product machine for language intersection presented in theory FSM by an additional
state that is reached only by sequences such that any proper prefix of the sequence is in the
language intersection, whereas the full sequence is only contained in the language of the machine
@{verbatim B} for which we want to check whether it is a reduction of some machine @{verbatim A}.
To allow for free choice of the FAIL state, we define the following property that holds iff
@{verbatim AB} is the product machine of @{verbatim A} and @{verbatim B} extended with fail state
@{verbatim FAIL}.
\<close>
fun productF :: "('in, 'out, 'state1) FSM \<Rightarrow> ('in, 'out, 'state2) FSM \<Rightarrow> ('state1 \<times> 'state2)
\<Rightarrow> ('in, 'out, 'state1 \<times>'state2) FSM \<Rightarrow> bool" where
"productF A B FAIL AB = (
(inputs A = inputs B)
\<and> (fst FAIL \<notin> nodes A)
\<and> (snd FAIL \<notin> nodes B)
\<and> AB = \<lparr>
succ = (\<lambda> a (p1,p2) . (if (p1 \<in> nodes A \<and> p2 \<in> nodes B \<and> (fst a \<in> inputs A)
\<and> (snd a \<in> outputs A \<union> outputs B))
then (if (succ A a p1 = {} \<and> succ B a p2 \<noteq> {})
then {FAIL}
else (succ A a p1 \<times> succ B a p2))
else {})),
inputs = inputs A,
outputs = outputs A \<union> outputs B,
initial = (initial A, initial B)
\<rparr> )"
lemma productF_simps[simp]:
"productF A B FAIL AB \<Longrightarrow> succ AB a (p1,p2) = (if (p1 \<in> nodes A \<and> p2 \<in> nodes B
\<and> (fst a \<in> inputs A) \<and> (snd a \<in> outputs A \<union> outputs B))
then (if (succ A a p1 = {} \<and> succ B a p2 \<noteq> {})
then {FAIL}
else (succ A a p1 \<times> succ B a p2))
else {})"
"productF A B FAIL AB \<Longrightarrow> inputs AB = inputs A"
"productF A B FAIL AB \<Longrightarrow> outputs AB = outputs A \<union> outputs B"
"productF A B FAIL AB \<Longrightarrow> initial AB = (initial A, initial B)"
unfolding productF.simps by simp+
lemma fail_next_productF :
assumes "well_formed M1"
and "well_formed M2"
and "productF M2 M1 FAIL PM"
shows "succ PM a FAIL = {}"
proof (cases "((fst FAIL) \<in> nodes M2 \<and> (snd FAIL) \<in> nodes M1)")
case True
then show ?thesis
using assms by auto
next
case False
then show ?thesis
using assms by (cases "(succ M2 a (fst FAIL) = {} \<and> (fst a \<in> inputs M2)
\<and> (snd a \<in> outputs M2))"; auto)
qed
lemma nodes_productF :
assumes "well_formed M1"
and "well_formed M2"
and "productF M2 M1 FAIL PM"
shows "nodes PM \<subseteq> insert FAIL (nodes M2 \<times> nodes M1)"
proof
fix q assume q_assm : "q \<in> nodes PM"
then show "q \<in> insert FAIL (nodes M2 \<times> nodes M1)"
using assms proof (cases)
case initial
then show ?thesis using assms by auto
next
case (execute p a)
then obtain p1 p2 x y q1 q2 where p_a_split[simp] : "p = (p1,p2)"
"a = ((x,y),q)"
"q = (q1,q2)"
by (metis eq_snd_iff)
have subnodes : "p1 \<in> nodes M2 \<and> p2 \<in> nodes M1 \<and> x \<in> inputs M2 \<and> y \<in> outputs M2 \<union> outputs M1"
proof (rule ccontr)
assume "\<not> (p1 \<in> nodes M2 \<and> p2 \<in> nodes M1 \<and> x \<in> inputs M2 \<and> y \<in> outputs M2 \<union> outputs M1)"
then have "succ PM (x,y) (p1,p2) = {}"
using assms(3) by auto
then show "False"
using execute by auto
qed
show ?thesis proof (cases "(succ M2 (x,y) p1 = {} \<and> succ M1 (x,y) p2 \<noteq> {})")
case True
then have "q = FAIL"
using subnodes assms(3) execute by auto
then show ?thesis
by auto
next
case False
then have "succ PM (fst a) p = succ M2 (x,y) p1 \<times> succ M1 (x,y) p2"
using subnodes assms(3) execute by auto
then have "q \<in> (succ M2 (x,y) p1 \<times> succ M1 (x,y) p2)"
using execute by blast
then have q_succ : "(q1,q2) \<in> (succ M2 (x,y) p1 \<times> succ M1 (x,y) p2)"
by simp
have "q1 \<in> succ M2 (x,y) p1"
using q_succ by simp
then have "q1 \<in> successors M2 p1"
by auto
then have "q1 \<in> reachable M2 p1"
by blast
then have "q1 \<in> reachable M2 (initial M2)"
using subnodes by blast
then have nodes1 : "q1 \<in> nodes M2"
by blast
have "q2 \<in> succ M1 (x,y) p2"
using q_succ by simp
then have "q2 \<in> successors M1 p2"
by auto
then have "q2 \<in> reachable M1 p2"
by blast
then have "q2 \<in> reachable M1 (initial M1)"
using subnodes by blast
then have nodes2 : "q2 \<in> nodes M1"
by blast
show ?thesis
using nodes1 nodes2 by auto
qed
qed
qed
lemma well_formed_productF[simp] :
assumes "well_formed M1"
and "well_formed M2"
and "productF M2 M1 FAIL PM"
shows "well_formed PM"
unfolding well_formed.simps proof
have "finite (nodes M1)" "finite (nodes M2)"
using assms by auto
then have "finite (insert FAIL (nodes M2 \<times> nodes M1))"
by simp
moreover have "nodes PM \<subseteq> insert FAIL (nodes M2 \<times> nodes M1)"
using nodes_productF assms by blast
moreover have "inputs PM = inputs M2" "outputs PM = outputs M2 \<union> outputs M1"
using assms by auto
ultimately show "finite_FSM PM"
using infinite_subset assms by auto
next
have "inputs PM = inputs M2" "outputs PM = outputs M2 \<union> outputs M1"
using assms by auto
then show "(\<forall>s1 x y. x \<notin> inputs PM \<or> y \<notin> outputs PM \<longrightarrow> succ PM (x, y) s1 = {})
\<and> inputs PM \<noteq> {} \<and> outputs PM \<noteq> {}"
using assms by auto
qed
lemma observable_productF[simp] :
assumes "observable M1"
and "observable M2"
and "productF M2 M1 FAIL PM"
shows "observable PM"
unfolding observable.simps
proof -
have "\<forall> t s . succ M1 t (fst s) = {} \<or> (\<exists>s2. succ M1 t (fst s) = {s2})"
using assms by auto
moreover have "\<forall> t s . succ M2 t (snd s) = {} \<or> (\<exists>s2. succ M2 t (snd s) = {s2})"
using assms by auto
ultimately have sub_succs : "\<forall> t s . succ M2 t (fst s) \<times> succ M1 t (snd s) = {}
\<or> (\<exists> s2 . succ M2 t (fst s) \<times> succ M1 t (snd s) = {s2})"
by fastforce
moreover have succ_split : "\<forall> t s . succ PM t s = {}
\<or> succ PM t s = {FAIL}
\<or> succ PM t s = succ M2 t (fst s) \<times> succ M1 t (snd s)"
using assms by auto
ultimately show "\<forall>t s. succ PM t s = {} \<or> (\<exists>s2. succ PM t s = {s2})"
by metis
qed
lemma no_transition_after_FAIL :
assumes "productF A B FAIL AB"
shows "succ AB io FAIL = {}"
using assms by auto
lemma no_prefix_targets_FAIL :
assumes "productF M2 M1 FAIL PM"
and "path PM p q"
and "k < length p"
shows "target (take k p) q \<noteq> FAIL"
proof
assume assm : "target (take k p) q = FAIL"
have "path PM (take k p @ drop k p) q"
using assms by auto
then have "path PM (drop k p) (target (take k p) q)"
by blast
then have path_from_FAIL : "path PM (drop k p) FAIL"
using assm by auto
have "length (drop k p) \<noteq> 0"
using assms by auto
then obtain io q where "drop k p = (io,q) # (drop (Suc k) p)"
by (metis Cons_nth_drop_Suc assms(3) prod_cases3)
then have "succ PM io FAIL \<noteq> {}"
using path_from_FAIL by auto
then show "False"
using no_transition_after_FAIL assms by auto
qed
lemma productF_path_inclusion :
assumes "length w = length r1" "length r1 = length r2"
and "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "path A (w || r1) p1 \<and> path B (w || r2) p2"
and "p1 \<in> nodes A"
and "p2 \<in> nodes B"
shows "path (AB) (w || r1 || r2) (p1, p2)"
using assms proof (induction w r1 r2 arbitrary: p1 p2 rule: list_induct3)
case Nil
then show ?case by auto
next
case (Cons w ws r1 r1s r2 r2s)
then have "path A ([w] || [r1]) p1 \<and> path B ([w] || [r2]) p2"
by auto
then have succs : "r1 \<in> succ A w p1 \<and> r2 \<in> succ B w p2"
by auto
then have "succ A w p1 \<noteq> {}"
by force
then have w_elem : "fst w \<in> inputs A \<and> snd w \<in> outputs A "
using Cons by (metis assms(4) prod.collapse well_formed.elims(2))
then have "(r1,r2) \<in> succ AB w (p1,p2)"
using Cons succs by auto
then have path_head : "path AB ([w] || [(r1,r2)]) (p1,p2)"
by auto
have "path A (ws || r1s) r1 \<and> path B (ws || r2s) r2"
using Cons by auto
moreover have "r1 \<in> nodes A \<and> r2 \<in> nodes B"
using succs Cons.prems succ_nodes[of r1 A w p1] succ_nodes[of r2 B w p2] by auto
ultimately have "path AB (ws || r1s || r2s) (r1,r2)"
using Cons by blast
then show ?case
using path_head by auto
qed
lemma productF_path_forward :
assumes "length w = length r1" "length r1 = length r2"
and "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "(path A (w || r1) p1 \<and> path B (w || r2) p2)
\<or> (target (w || r1 || r2) (p1, p2) = FAIL
\<and> length w > 0
\<and> path A (butlast (w || r1)) p1
\<and> path B (butlast (w || r2)) p2
\<and> succ A (last w) (target (butlast (w || r1)) p1) = {}
\<and> succ B (last w) (target (butlast (w || r2)) p2) \<noteq> {})"
and "p1 \<in> nodes A"
and "p2 \<in> nodes B"
shows "path (AB) (w || r1 || r2) (p1, p2)"
using assms proof (induction w r1 r2 arbitrary: p1 p2 rule: list_induct3)
case Nil
then show ?case by auto
next
case (Cons w ws r1 r1s r2 r2s)
then show ?case
proof (cases "(path A (w # ws || r1 # r1s) p1 \<and> path B (w # ws || r2 # r2s) p2)")
case True
then show ?thesis
using Cons productF_path_inclusion[of "w # ws" "r1 # r1s" "r2 # r2s" A B FAIL AB p1 p2]
by auto
next
case False
then have fail_prop : "target (w # ws || r1 # r1s || r2 # r2s) (p1, p2) = FAIL \<and>
0 < length (w # ws) \<and>
path A (butlast (w # ws || r1 # r1s)) p1 \<and>
path B (butlast (w # ws || r2 # r2s)) p2 \<and>
succ A (last (w # ws)) (target (butlast (w # ws || r1 # r1s)) p1) = {} \<and>
succ B (last (w # ws)) (target (butlast (w # ws || r2 # r2s)) p2) \<noteq> {}"
using Cons.prems by fastforce
then show ?thesis
proof (cases "length ws")
case 0
then have empty[simp] : "ws = []" "r1s = []" "r2s = []"
using Cons.hyps by auto
then have fail_prop_0 : "target ( [w] || [r1] || [r2]) (p1, p2) = FAIL \<and>
0 < length ([w]) \<and>
path A [] p1 \<and>
path B [] p2 \<and>
succ A w p1 = {} \<and>
succ B w p2 \<noteq> {}"
using fail_prop by auto
then have "fst w \<in> inputs B \<and> snd w \<in> outputs B"
using Cons.prems by (metis prod.collapse well_formed.elims(2))
then have inputs_0 : "fst w \<in> inputs A \<and> snd w \<in> outputs B"
using Cons.prems by auto
moreover have fail_elems_0 : "(r1,r2) = FAIL"
using fail_prop by auto
ultimately have "succ AB w (p1,p2) = {FAIL}"
using fail_prop_0 Cons.prems by auto
then have "path AB ( [w] || [r1] || [r2]) (p1, p2)"
using Cons.prems fail_elems_0 by auto
then show ?thesis
by auto
next
case (Suc nat)
then have path_r1 : "path A ([w] || [r1]) p1"
using fail_prop
by (metis Cons.hyps(1) FSM.nil FSM.path.intros(2) FSM.path_cons_elim Suc_neq_Zero
butlast.simps(2) length_0_conv zip_Cons_Cons zip_Nil zip_eq)
then have path_r1s : "path A (butlast (ws || r1s)) r1"
using Suc
by (metis (no_types, lifting) Cons.hyps(1) FSM.path_cons_elim Suc_neq_Zero butlast.simps(2)
fail_prop length_0_conv snd_conv zip.simps(1) zip_Cons_Cons zip_eq)
have path_r2 : "path B ([w] || [r2]) p2"
using Suc fail_prop
by (metis Cons.hyps(1) Cons.hyps(2) FSM.nil FSM.path.intros(2) FSM.path_cons_elim
Suc_neq_Zero butlast.simps(2) length_0_conv zip_Cons_Cons zip_Nil zip_eq)
then have path_r2s : "path B (butlast (ws || r2s)) r2"
using Suc
by (metis (no_types, lifting) Cons.hyps(1) Cons.hyps(2) FSM.path_cons_elim Suc_neq_Zero
butlast.simps(2) fail_prop length_0_conv snd_conv zip.simps(1) zip_Cons_Cons zip_eq)
have "target (ws || r1s || r2s) (r1, r2) = FAIL"
using fail_prop by auto
moreover have "r1 \<in> nodes A"
using Cons.prems path_r1 by (metis FSM.path_cons_elim snd_conv succ_nodes zip_Cons_Cons)
moreover have "r2 \<in> nodes B"
using Cons.prems path_r2 by (metis FSM.path_cons_elim snd_conv succ_nodes zip_Cons_Cons)
moreover have "succ A (last ws) (target (butlast (ws || r1s)) r1) = {}"
by (metis (no_types, lifting) Cons.hyps(1) Suc Suc_neq_Zero butlast.simps(2) fail_prop
fold_simps(2) last_ConsR list.size(3) snd_conv zip_Cons_Cons zip_Nil zip_eq)
moreover have "succ B (last ws) (target (butlast (ws || r2s)) r2) \<noteq> {}"
by (metis (no_types, lifting) Cons.hyps(1) Cons.hyps(2) Suc Suc_neq_Zero butlast.simps(2)
fail_prop fold_simps(2) last_ConsR list.size(3) snd_conv zip_Cons_Cons zip_Nil zip_eq)
have "path AB (ws || r1s || r2s) (r1, r2)"
using Cons.IH Suc \<open>succ B (last ws) (target (butlast (ws || r2s)) r2) \<noteq> {}\<close>
assms(3) assms(4) assms(5) calculation(1-4) path_r1s path_r2s zero_less_Suc
by presburger
moreover have "path AB ([w] || [r1] || [r2]) (p1,p2)"
using path_r1 path_r2 productF_path_inclusion[of "[w]" "[r1]" "[r2]" A B FAIL AB p1 p2]
Cons.prems
by auto
ultimately show ?thesis
by auto
qed
qed
qed
lemma butlast_zip_cons : "length ws = length r1s \<Longrightarrow> ws \<noteq> []
\<Longrightarrow> butlast (w # ws || r1 # r1s) = ((w,r1) # (butlast (ws || r1s)))"
proof -
assume a1: "length ws = length r1s"
assume a2: "ws \<noteq> []"
have "length (w # ws) = length r1s + Suc 0"
using a1 by (metis list.size(4))
then have f3: "length (w # ws) = length (r1 # r1s)"
by (metis list.size(4))
have f4: "ws @ w # ws \<noteq> w # ws"
using a2 by (meson append_self_conv2)
have "length (ws @ w # ws) = length (r1s @ r1 # r1s)"
using a1 by auto
then have "ws @ w # ws || r1s @ r1 # r1s \<noteq> w # ws || r1 # r1s"
using f4 f3 by (meson zip_eq)
then show ?thesis
using a1 by simp
qed
lemma productF_succ_fail_imp :
assumes "productF A B FAIL AB"
and "FAIL \<in> succ AB w (p1,p2)"
and "well_formed A"
and "well_formed B"
shows "p1 \<in> nodes A \<and> p2 \<in> nodes B \<and> (fst w \<in> inputs A) \<and> (snd w \<in> outputs A \<union> outputs B)
\<and> succ AB w (p1,p2) = {FAIL} \<and> succ A w p1 = {} \<and> succ B w p2 \<noteq> {}"
proof -
have path_head : "path AB ([w] || [FAIL]) (p1,p2)"
using assms by auto
then have succ_nonempty : "succ AB w (p1,p2) \<noteq> {}"
by force
then have succ_if_1 : "p1 \<in> nodes A \<and> p2 \<in> nodes B \<and> (fst w \<in> inputs A)
\<and> (snd w \<in> outputs A \<union> outputs B)"
using assms by auto
then have "(p1,p2) \<noteq> FAIL"
using assms by auto
have "succ A w p1 \<subseteq> nodes A"
using assms succ_if_1 by (simp add: subsetI succ_nodes)
moreover have "succ B w p2 \<subseteq> nodes B"
using assms succ_if_1 by (simp add: subsetI succ_nodes)
ultimately have "FAIL \<notin> (succ A w p1 \<times> succ B w p2)"
using assms by auto
then have succ_no_inclusion : "succ AB w (p1,p2) \<noteq> (succ A w p1 \<times> succ B w p2)"
using assms succ_if_1 by blast
moreover have "succ AB w (p1,p2) = {} \<or> succ AB w (p1,p2) = {FAIL}
\<or> succ AB w (p1,p2) = (succ A w p1 \<times> succ B w p2)"
using assms by simp
ultimately have succ_fail : "succ AB w (p1,p2) = {FAIL}"
using succ_nonempty by simp
have "succ A w p1 = {} \<and> succ B w p2 \<noteq> {}"
proof (rule ccontr)
assume "\<not> (succ A w p1 = {} \<and> succ B w p2 \<noteq> {})"
then have "succ AB w (p1,p2) = (succ A w p1 \<times> succ B w p2)"
using assms by auto
then show "False"
using succ_no_inclusion by simp
qed
then show ?thesis
using succ_if_1 succ_fail by simp
qed
lemma productF_path_reverse :
assumes "length w = length r1" "length r1 = length r2"
and "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "path AB (w || r1 || r2) (p1, p2)"
and "p1 \<in> nodes A"
and "p2 \<in> nodes B"
shows "(path A (w || r1) p1 \<and> path B (w || r2) p2)
\<or> (target (w || r1 || r2) (p1, p2) = FAIL
\<and> length w > 0
\<and> path A (butlast (w || r1)) p1
\<and> path B (butlast (w || r2)) p2
\<and> succ A (last w) (target (butlast (w || r1)) p1) = {}
\<and> succ B (last w) (target (butlast (w || r2)) p2) \<noteq> {})"
using assms proof (induction w r1 r2 arbitrary: p1 p2 rule: list_induct3)
case Nil
then show ?case by auto
next
case (Cons w ws r1 r1s r2 r2s)
have path_head : "path AB ([w] || [(r1,r2)]) (p1,p2)" using Cons by auto
then have succ_nonempty : "succ AB w (p1,p2) \<noteq> {}" by force
then have succ_if_1 : "p1 \<in> nodes A \<and> p2 \<in> nodes B \<and> (fst w \<in> inputs A)
\<and> (snd w \<in> outputs A \<union> outputs B)"
using Cons by fastforce
then have "(p1,p2) \<noteq> FAIL"
using Cons by auto
have path_tail : "path AB (ws || r1s || r2s) (r1,r2)"
using path_head Cons by auto
show ?case
proof (cases "(r1,r2) = FAIL")
case True
have "r1s = []"
proof (rule ccontr)
assume "\<not> (r1s = [])"
then have "(\<not> (ws = [])) \<and> (\<not> (r1s = [])) \<and> (\<not> (r2s = []))"
using Cons.hyps by auto
moreover have "path AB (ws || r1s || r2s) FAIL"
using True path_tail by simp
ultimately have "path AB ([hd ws] @ tl ws || [hd r1s] @ tl r1s || [hd r2s] @ tl r2s) FAIL"
by simp
then have "path AB ([hd ws] || [hd r1s] || [hd r2s]) FAIL"
by auto
then have "succ AB (hd ws) FAIL \<noteq> {}"
by auto
then show "False" using no_transition_after_FAIL
using Cons.prems by auto
qed
then have tail_nil : "ws = [] \<and> r1s = [] \<and> r2s = []"
using Cons.hyps by simp
have succ_fail : "FAIL \<in> succ AB w (p1,p2)"
using path_head True by auto
then have succs : "succ A w p1 = {} \<and> succ B w p2 \<noteq> {}"
using Cons.prems by (meson productF_succ_fail_imp)
have "target (w # ws || r1 # r1s || r2 # r2s) (p1, p2) = FAIL"
using True tail_nil by simp
moreover have "0 < length (w # ws)"
by simp
moreover have "path A (butlast (w # ws || r1 # r1s)) p1"
using tail_nil by auto
moreover have "path B (butlast (w # ws || r2 # r2s)) p2"
using tail_nil by auto
moreover have "succ A (last (w # ws)) (target (butlast (w # ws || r1 # r1s)) p1) = {}"
using succs tail_nil by simp
moreover have "succ B (last (w # ws)) (target (butlast (w # ws || r2 # r2s)) p2) \<noteq> {}"
using succs tail_nil by simp
ultimately show ?thesis
by simp
next
case False
have "(r1,r2) \<in> succ AB w (p1,p2)"
using path_head by auto
then have succ_not_fail : "succ AB w (p1,p2) \<noteq> {FAIL}"
using succ_nonempty False by auto
have "\<not> (succ A w p1 = {} \<and> succ B w p2 \<noteq> {})"
proof (rule ccontr)
assume "\<not> \<not> (succ A w p1 = {} \<and> succ B w p2 \<noteq> {})"
then have "succ AB w (p1,p2) = {FAIL}"
using succ_if_1 Cons by auto
then show "False"
using succ_not_fail by simp
qed
then have "succ AB w (p1,p2) = (succ A w p1 \<times> succ B w p2)"
using succ_if_1 Cons by auto
then have "(r1,r2) \<in> (succ A w p1 \<times> succ B w p2)"
using Cons by auto
then have succs_next : "r1 \<in> succ A w p1 \<and> r2 \<in> succ B w p2"
by auto
then have nodes_next : "r1 \<in> nodes A \<and> r2 \<in> nodes B"
using Cons succ_nodes by metis
moreover have path_tail : "path AB (ws || r1s || r2s) (r1,r2)"
using Cons by auto
ultimately have prop_tail :
"path A (ws || r1s) r1 \<and> path B (ws || r2s) r2 \<or>
target (ws || r1s || r2s) (r1, r2) = FAIL \<and>
0 < length ws \<and>
path A (butlast (ws || r1s)) r1 \<and>
path B (butlast (ws || r2s)) r2 \<and>
succ A (last ws) (target (butlast (ws || r1s)) r1) = {} \<and>
succ B (last ws) (target (butlast (ws || r2s)) r2) \<noteq> {}"
using Cons.IH[of r1 r2] Cons.prems by auto
moreover have "path A ([w] || [r1]) p1 \<and> path B ([w] || [r2]) p2"
using succs_next by auto
then show ?thesis
proof (cases "path A (ws || r1s) r1 \<and> path B (ws || r2s) r2")
case True
moreover have paths_head : "path A ([w] || [r1]) p1 \<and> path B ([w] || [r2]) p2"
using succs_next by auto
ultimately show ?thesis
by (metis (no_types) FSM.path.simps FSM.path_cons_elim True eq_snd_iff
paths_head zip_Cons_Cons)
next
case False
then have fail_prop : "target (ws || r1s || r2s) (r1, r2) = FAIL \<and>
0 < length ws \<and>
path A (butlast (ws || r1s)) r1 \<and>
path B (butlast (ws || r2s)) r2 \<and>
succ A (last ws) (target (butlast (ws || r1s)) r1) = {} \<and>
succ B (last ws) (target (butlast (ws || r2s)) r2) \<noteq> {}"
using prop_tail by auto
then have paths_head : "path A ([w] || [r1]) p1 \<and> path B ([w] || [r2]) p2"
using succs_next by auto
have "(last (w # ws)) = last ws"
using fail_prop by simp
moreover have "(target (butlast (w # ws || r1 # r1s)) p1) = (target (butlast (ws || r1s)) r1)"
using fail_prop Cons.hyps(1) butlast_zip_cons by fastforce
moreover have "(target (butlast (w # ws || r2 # r2s)) p2) = (target (butlast (ws || r2s)) r2)"
using fail_prop Cons.hyps(1) Cons.hyps(2) butlast_zip_cons by fastforce
ultimately have "succ A (last (w # ws)) (target (butlast (w # ws || r1 # r1s)) p1) = {}
\<and> succ B (last (w # ws)) (target (butlast (w # ws || r2 # r2s)) p2) \<noteq> {}"
using fail_prop by auto
moreover have "path A (butlast (w # ws || r1 # r1s)) p1"
using fail_prop paths_head by auto
moreover have "path B (butlast (w # ws || r2 # r2s)) p2"
using fail_prop paths_head by auto
moreover have "target (w # ws || r1 # r1s || r2 # r2s) (p1, p2) = FAIL"
using fail_prop paths_head by auto
ultimately show ?thesis
by simp
qed
qed
qed
lemma butlast_zip[simp] :
assumes "length xs = length ys"
shows "butlast (xs || ys) = (butlast xs || butlast ys)"
using assms by (metis (no_types, lifting) map_butlast map_fst_zip map_snd_zip zip_map_fst_snd)
lemma productF_path_reverse_ob :
assumes "length w = length r1" "length r1 = length r2"
and "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "path AB (w || r1 || r2) (p1, p2)"
and "p1 \<in> nodes A"
and "p2 \<in> nodes B"
obtains r2'
where "path B (w || r2') p2 \<and> length w = length r2'"
proof -
have path_prop : "(path A (w || r1) p1 \<and> path B (w || r2) p2)
\<or> (target (w || r1 || r2) (p1, p2) = FAIL
\<and> length w > 0
\<and> path A (butlast (w || r1)) p1
\<and> path B (butlast (w || r2)) p2
\<and> succ A (last w) (target (butlast (w || r1)) p1) = {}
\<and> succ B (last w) (target (butlast (w || r2)) p2) \<noteq> {})"
using assms productF_path_reverse[of w r1 r2 A B FAIL AB p1 p2] by simp
have "\<exists> r1' . path B (w || r1') p2 \<and> length w = length r1'"
proof (cases "path A (w || r1) p1 \<and> path B (w || r2) p2")
case True
then show ?thesis
using assms by auto
next
case False
then have B_prop : "length w > 0
\<and> path B (butlast (w || r2)) p2
\<and> succ B (last w) (target (butlast (w || r2)) p2) \<noteq> {}"
using path_prop by auto
then obtain rx where "rx \<in> succ B (last w) (target (butlast (w || r2)) p2)"
by auto
then have "path B ([last w] || [rx]) (target (butlast (w || r2)) p2)"
using B_prop by auto
then have "path B ((butlast (w || r2)) @ ([last w] || [rx])) p2"
using B_prop by auto
moreover have "butlast (w || r2) = (butlast w || butlast r2)"
using assms by simp
ultimately have "path B ((butlast w) @ [last w] || (butlast r2) @ [rx]) p2"
using assms B_prop by auto
moreover have "(butlast w) @ [last w] = w"
using B_prop by simp
moreover have "length ((butlast r2) @ [rx]) = length w"
using assms B_prop by auto
ultimately show ?thesis
by auto
qed
then obtain r1' where "path B (w || r1') p2 \<and> length w = length r1'"
by blast
then show ?thesis
using that by blast
qed
text \<open>
The following lemma formalizes the property of paths of the product machine as described
in the section introduction.
\<close>
lemma productF_path[iff] :
assumes "length w = length r1" "length r1 = length r2"
and "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "p1 \<in> nodes A"
and "p2 \<in> nodes B"
shows "path AB (w || r1 || r2) (p1, p2) \<longleftrightarrow> ((path A (w || r1) p1 \<and> path B (w || r2) p2)
\<or> (target (w || r1 || r2) (p1, p2) = FAIL
\<and> length w > 0
\<and> path A (butlast (w || r1)) p1
\<and> path B (butlast (w || r2)) p2
\<and> succ A (last w) (target (butlast (w || r1)) p1) = {}
\<and> succ B (last w) (target (butlast (w || r2)) p2) \<noteq> {}))" (is "?path \<longleftrightarrow> ?paths")
proof
assume ?path
then show ?paths using assms productF_path_reverse[of w r1 r2 A B FAIL AB p1 p2] by simp
next
assume ?paths
then show ?path using assms productF_path_forward[of w r1 r2 A B FAIL AB p1 p2] by simp
qed
lemma path_last_succ :
assumes "path A (ws || r1s) p1"
and "length r1s = length ws"
and "length ws > 0"
shows "last r1s \<in> succ A (last ws) (target (butlast (ws || r1s)) p1)"
proof -
have "path A (butlast (ws || r1s)) p1
\<and> path A [last (ws || r1s)] (target (butlast (ws || r1s)) p1)"
by (metis FSM.path_append_elim append_butlast_last_id assms length_greater_0_conv
list.size(3) zip_Nil zip_eq)
then have "snd (last (ws || r1s)) \<in>
succ A (fst (last (ws || r1s))) (target (butlast (ws || r1s)) p1)"
by auto
moreover have "ws || r1s \<noteq> []"
using assms(3) assms(2) by (metis length_zip list.size(3) min.idem neq0_conv)
ultimately have "last r1s \<in> succ A (last ws) (target (butlast (ws || r1s)) p1)"
by (simp add: assms(2))
then show ?thesis
by auto
qed
lemma zip_last :
assumes "length r1 > 0"
and "length r1 = length r2"
shows "last (r1 || r2) = (last r1, last r2)"
by (metis (no_types) assms(1) assms(2) less_nat_zero_code list.size(3)
map_fst_zip zip_Nil zip_last)
lemma productF_path_reverse_ob_2 :
assumes "length w = length r1" "length r1 = length r2"
and "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "path AB (w || r1 || r2) (p1, p2)"
and "p1 \<in> nodes A"
and "p2 \<in> nodes B"
and "w \<in> language_state A p1"
and "observable A"
shows "path A (w || r1) p1 \<and> length w = length r1" "path B (w || r2) p2 \<and> length w = length r2"
"target (w || r1) p1 = fst (target (w || r1 || r2) (p1,p2))"
"target (w || r2) p2 = snd (target (w || r1 || r2) (p1,p2))"
proof -
have "(path A (w || r1) p1 \<and> path B (w || r2) p2)
\<or> (target (w || r1 || r2) (p1, p2) = FAIL
\<and> length w > 0
\<and> path A (butlast (w || r1)) p1
\<and> path B (butlast (w || r2)) p2
\<and> succ A (last w) (target (butlast (w || r1)) p1) = {}
\<and> succ B (last w) (target (butlast (w || r2)) p2) \<noteq> {})"
using productF_path[of w r1 r2 A B FAIL AB p1 p2] assms by blast
moreover have "path A (butlast (w || r1)) p1
\<and> succ A (last w) (target (butlast (w || r1)) p1) = {}
\<and> length w > 0 \<Longrightarrow> False"
proof -
assume assm : "path A (butlast (w || r1)) p1
\<and> succ A (last w) (target (butlast (w || r1)) p1) = {}
\<and> length w > 0"
obtain r1' where r1'_def : "path A (w || r1') p1 \<and> length r1' = length w"
using assms(9) by auto
then have "path A (butlast (w || r1')) p1 \<and> length (butlast r1') = length (butlast w)"
by (metis FSM.path_append_elim append_butlast_last_id butlast.simps(1) length_butlast)
moreover have "path A (butlast (w || r1)) p1 \<and> length (butlast r1) = length (butlast w)"
using assm assms(1) by auto
ultimately have "butlast r1 = butlast r1'"
by (metis assms(1) assms(10) butlast_zip language_state observable_path_unique r1'_def)
then have "butlast (w || r1) = butlast (w || r1')"
using assms(1) r1'_def by simp
moreover have "succ A (last w) (target (butlast (w || r1')) p1) \<noteq> {}"
by (metis (no_types) assm empty_iff path_last_succ r1'_def)
ultimately show "False"
using assm by auto
qed
ultimately have paths : "(path A (w || r1) p1 \<and> path B (w || r2) p2)"
by auto
show "path A (w || r1) p1 \<and> length w = length r1"
using assms(1) paths by simp
show "path B (w || r2) p2 \<and> length w = length r2"
using assms(1) assms(2) paths by simp
have "length w = 0 \<Longrightarrow> target (w || r1 || r2) (p1,p2) = (p1,p2)"
by simp
moreover have "length w > 0 \<Longrightarrow> target (w || r1 || r2) (p1,p2) = last (r1 || r2)"
proof -
assume "length w > 0"
moreover have "length w = length (r1 || r2)"
using assms(1) assms(2) by simp
ultimately show ?thesis
using target_alt_def(2)[of w "r1 || r2" "(p1,p2)"] by simp
qed
ultimately have "target (w || r1) p1 = fst (target (w || r1 || r2) (p1, p2))
\<and> target (w || r2) p2 = snd (target (w || r1 || r2) (p1, p2))"
proof (cases "length w")
case 0
then show ?thesis by simp
next
case (Suc nat)
then have "length w > 0" by simp
have "target (w || r1 || r2) (p1,p2) = last (r1 || r2)"
proof -
have "length w = length (r1 || r2)"
using assms(1) assms(2) by simp
then show ?thesis
using \<open>length w > 0\<close> target_alt_def(2)[of w "r1 || r2" "(p1,p2)"] by simp
qed
moreover have "target (w || r1) p1 = last r1"
using \<open>length w > 0\<close> target_alt_def(2)[of w r1 p1] assms(1) by simp
moreover have "target (w || r2) p2 = last r2"
using \<open>length w > 0\<close> target_alt_def(2)[of w r2 p2] assms(1) assms(2) by simp
moreover have "last (r1 || r2) = (last r1, last r2)"
using \<open>length w > 0\<close> assms(1) assms(2) zip_last[of r1 r2] by simp
ultimately show ?thesis
by simp
qed
then show "target (w || r1) p1 = fst (target (w || r1 || r2) (p1,p2))"
"target (w || r2) p2 = snd (target (w || r1 || r2) (p1,p2))"
by simp+
qed
lemma productF_path_unzip :
assumes "productF A B FAIL AB"
and "path AB (w || tr) q"
and "length tr = length w"
shows "path AB (w || (map fst tr || map snd tr)) q"
proof -
have "map fst tr || map snd tr = tr"
by auto
then show ?thesis
using assms by auto
qed
lemma productF_path_io_targets :
assumes "productF A B FAIL AB"
and "io_targets AB (qA,qB) w = {(pA,pB)}"
and "w \<in> language_state A qA"
and "w \<in> language_state B qB"
and "observable A"
and "observable B"
and "well_formed A"
and "well_formed B"
and "qA \<in> nodes A"
and "qB \<in> nodes B"
shows "pA \<in> io_targets A qA w" "pB \<in> io_targets B qB w"
proof -
obtain tr where tr_def : "target (w || tr) (qA,qB) = (pA,pB)
\<and> path AB (w || tr) (qA,qB)
\<and> length w = length tr" using assms(2)
by blast
have path_A : "path A (w || map fst tr) qA \<and> length w = length (map fst tr)"
using productF_path_reverse_ob_2[of w "map fst tr" "map snd tr" A B FAIL AB qA qB]
assms tr_def by auto
have path_B : "path B (w || map snd tr) qB \<and> length w = length (map snd tr)"
using productF_path_reverse_ob_2[of w "map fst tr" "map snd tr" A B FAIL AB qA qB]
assms tr_def by auto
have targets : "target (w || map fst tr) qA = pA \<and> target (w || map snd tr) qB = pB"
proof (cases tr)
case Nil
then have "qA = pA \<and> qB = pB"
using tr_def by auto
then show ?thesis
by (simp add: local.Nil)
next
case (Cons a list)
then have "last tr = (pA,pB)"
using tr_def by (simp add: tr_def FSM.target_alt_def states_alt_def)
moreover have "target (w || map fst tr) qA = last (map fst tr)"
using Cons by (simp add: FSM.target_alt_def states_alt_def tr_def)
moreover have "last (map fst tr) = fst (last tr)"
using last_map Cons by blast
moreover have "target (w || map snd tr) qB = last (map snd tr)"
using Cons by (simp add: FSM.target_alt_def states_alt_def tr_def)
moreover have "last (map snd tr) = snd (last tr)"
using last_map Cons by blast
ultimately show ?thesis
by simp
qed
show "pA \<in> io_targets A qA w"
using path_A targets by auto
show "pB \<in> io_targets B qB w"
using path_B targets by auto
qed
lemma productF_path_io_targets_reverse :
assumes "productF A B FAIL AB"
and "pA \<in> io_targets A qA w"
and "pB \<in> io_targets B qB w"
and "w \<in> language_state A qA"
and "w \<in> language_state B qB"
and "observable A"
and "observable B"
and "well_formed A"
and "well_formed B"
and "qA \<in> nodes A"
and "qB \<in> nodes B"
shows "io_targets AB (qA,qB) w = {(pA,pB)}"
proof -
obtain trA where "path A (w || trA) qA"
"length w = length trA"
"target (w || trA) qA = pA"
using assms(2) by auto
obtain trB where "path B (w || trB) qB"
"length trA = length trB"
"target (w || trB) qB = pB"
using \<open>length w = length trA\<close> assms(3) by auto
have "path AB (w || trA || trB) (qA,qB)"
"length (trA || trB) = length w"
using productF_path_inclusion
[OF \<open>length w = length trA\<close> \<open>length trA = length trB\<close> assms(1) assms(8,9) _ assms(10,11)]
by (simp add: \<open>length trA = length trB\<close> \<open>length w = length trA\<close> \<open>path A (w || trA) qA\<close>
\<open>path B (w || trB) qB\<close>)+
have "target (w || trA || trB) (qA,qB) = (pA,pB)"
by (simp add: \<open>length trA = length trB\<close> \<open>length w = length trA\<close> \<open>target (w || trA) qA = pA\<close>
\<open>target (w || trB) qB = pB\<close>)
have "(pA,pB) \<in> io_targets AB (qA,qB) w"
by (metis \<open>length (trA || trB) = length w\<close> \<open>path AB (w || trA || trB) (qA, qB)\<close>
\<open>target (w || trA || trB) (qA, qB) = (pA, pB)\<close> io_target_from_path)
have "observable AB"
by (metis (no_types) assms(1) assms(6) assms(7) observable_productF)
show ?thesis
by (meson \<open>(pA, pB) \<in> io_targets AB (qA, qB) w\<close> \<open>observable AB\<close>
observable_io_target_is_singleton)
qed
subsection \<open> Sequences to failure in the product machine \<close>
text \<open>
A sequence to a failure for @{verbatim A} and @{verbatim B} reaches the fail state of any product
machine of @{verbatim A} and @{verbatim B} with added fail state.
\<close>
lemma fail_reachable_by_sequence_to_failure :
assumes "sequence_to_failure M1 M2 io"
and "well_formed M1"
and "well_formed M2"
and "productF M2 M1 FAIL PM"
obtains p
where "path PM (io||p) (initial PM) \<and> length p = length io \<and> target (io||p) (initial PM) = FAIL"
proof -
have "io \<noteq> []"
using assms by auto
then obtain io_init io_last where io_split[simp] : "io = io_init @ [io_last]"
by (metis append_butlast_last_id)
have io_init_inclusion : "io_init \<in> language_state M1 (initial M1)
\<and> io_init \<in> language_state M2 (initial M2)"
using assms by auto
have "io_init @ [io_last] \<in> language_state M1 (initial M1)"
using assms by auto
then obtain tr1_init tr1_last where tr1_def :
"path M1 (io_init @ [io_last] || tr1_init @ [tr1_last]) (initial M1)
\<and> length (tr1_init @ [tr1_last]) = length (io_init @ [io_last])"
by (metis append_butlast_last_id language_state_elim length_0_conv length_append_singleton
nat.simps(3))
then have path_init_1 : "path M1 (io_init || tr1_init) (initial M1)
\<and> length tr1_init = length io_init"
by auto
then have "path M1 ([io_last] || [tr1_last]) (target (io_init || tr1_init) (initial M1))"
using tr1_def by auto
then have succ_1 : "succ M1 io_last (target (io_init || tr1_init) (initial M1)) \<noteq> {}"
by auto
obtain tr2 where tr2_def : "path M2 (io_init || tr2) (initial M2) \<and> length tr2 = length io_init"
using io_init_inclusion by auto
have succ_2 : "succ M2 io_last (target (io_init || tr2) (initial M2)) = {}"
proof (rule ccontr)
assume "succ M2 io_last (target (io_init || tr2) (initial M2)) \<noteq> {}"
then obtain tr2_last where "tr2_last \<in> succ M2 io_last (target (io_init || tr2) (initial M2))"
by auto
then have "path M2 ([io_last] || [tr2_last]) (target (io_init || tr2) (initial M2))"
by auto
then have "io_init @ [io_last] \<in> language_state M2 (initial M2)"
by (metis FSM.path_append language_state length_Cons length_append list.size(3) tr2_def
zip_append)
then show "False"
using assms io_split by simp
qed
have fail_lengths : "length (io_init @ [io_last]) = length (tr2 @ [fst FAIL])
\<and> length (tr2 @ [fst FAIL]) = length (tr1_init @ [snd FAIL])"
using assms tr2_def tr1_def by auto
then have fail_tgt : "target (io_init @ [io_last] || tr2 @ [fst FAIL] || tr1_init @ [snd FAIL])
(initial M2, initial M1) = FAIL"
by auto
have fail_butlast_simp[simp] :
"butlast (io_init @ [io_last] || tr2 @ [fst FAIL]) = io_init || tr2"
"butlast (io_init @ [io_last] || tr1_init @ [snd FAIL]) = io_init || tr1_init"
using fail_lengths by simp+
have "path M2 (butlast (io_init @ [io_last] || tr2 @ [fst FAIL])) (initial M2)
\<and> path M1 (butlast (io_init @ [io_last] || tr1_init @ [snd FAIL])) (initial M1)"
using tr1_def tr2_def by auto
moreover have "succ M2 (last (io_init @ [io_last]))
(target (butlast (io_init @ [io_last] || tr2 @ [fst FAIL])) (initial M2)) = {}"
using succ_2 by simp
moreover have "succ M1 (last (io_init @ [io_last]))
(target (butlast (io_init @ [io_last] || tr1_init @ [snd FAIL])) (initial M1))
\<noteq> {}"
using succ_1 by simp
moreover have "initial M2 \<in> nodes M2 \<and> initial M1 \<in> nodes M1"
by auto
ultimately have "path PM (io_init @ [io_last] || tr2 @ [fst FAIL] || tr1_init @ [snd FAIL])
(initial M2, initial M1)"
using fail_lengths fail_tgt assms path_init_1 tr2_def productF_path_forward
[of "io_init @ [io_last]" "tr2 @ [fst FAIL]" "tr1_init @ [snd FAIL]" M2 M1 FAIL PM
"initial M2" "initial M1" ]
by simp
moreover have "initial PM = (initial M2, initial M1)"
using assms(4) productF_simps(4) by blast
ultimately have
"path PM (io_init @ [io_last] || tr2 @ [fst FAIL] || tr1_init @ [snd FAIL]) (initial PM)
\<and> length (tr2 @ [fst FAIL] || tr1_init @ [snd FAIL]) = length (io_init @ [io_last])
\<and> target (io_init @ [io_last] || tr2 @ [fst FAIL] || tr1_init @ [snd FAIL]) (initial PM)= FAIL"
using fail_lengths fail_tgt by auto
then show ?thesis using that
using io_split by blast
qed
lemma fail_reachable :
assumes "\<not> M1 \<preceq> M2"
and "well_formed M1"
and "well_formed M2"
and "productF M2 M1 FAIL PM"
shows "FAIL \<in> reachable PM (initial PM)"
proof -
obtain io where "sequence_to_failure M1 M2 io"
using sequence_to_failure_ob assms by blast
then show ?thesis
using assms fail_reachable_by_sequence_to_failure[of M1 M2 io FAIL PM]
by (metis FSM.reachable.reflexive FSM.reachable_target)
qed
lemma fail_reachable_ob :
assumes "\<not> M1 \<preceq> M2"
and "well_formed M1"
and "well_formed M2"
and "observable M2"
and "productF M2 M1 FAIL PM"
obtains p
where "path PM p (initial PM)" "target p (initial PM) = FAIL"
using assms fail_reachable by (metis FSM.reachable_target_elim)
lemma fail_reachable_reverse :
assumes "well_formed M1"
and "well_formed M2"
and "productF M2 M1 FAIL PM"
and "FAIL \<in> reachable PM (initial PM)"
and "observable M2"
shows "\<not> M1 \<preceq> M2"
proof -
obtain pathF where pathF_def : "path PM pathF (initial PM) \<and> target pathF (initial PM) = FAIL"
using assms by auto
let ?io = "map fst pathF"
let ?tr2 = "map fst (map snd pathF)"
let ?tr1 = "map snd (map snd pathF)"
have "initial PM \<noteq> FAIL"
using assms by auto
then have "pathF \<noteq> []"
using pathF_def by auto
moreover have "initial PM = (initial M2, initial M1)"
using assms by simp
ultimately have "path M2 (?io || ?tr2) (initial M2) \<and> path M1 (?io || ?tr1) (initial M1) \<or>
target (?io || ?tr2 || ?tr1) (initial M2, initial M1) = FAIL \<and>
0 < length (?io) \<and>
path M2 (butlast (?io || ?tr2)) (initial M2) \<and>
path M1 (butlast (?io || ?tr1)) (initial M1) \<and>
succ M2 (last (?io)) (target (butlast (?io || ?tr2)) (initial M2)) = {} \<and>
succ M1 (last (?io)) (target (butlast (?io || ?tr1)) (initial M1)) \<noteq> {}"
using productF_path_reverse[of ?io ?tr2 ?tr1 M2 M1 FAIL PM "initial M2" "initial M1"]
using assms pathF_def
proof -
have f1: "path PM (?io || ?tr2 || ?tr1) (initial M2, initial M1)"
by (metis (no_types) \<open>initial PM = (initial M2, initial M1)\<close> pathF_def zip_map_fst_snd)
have f2: "length (?io) = length pathF \<longrightarrow> length (?io) = length (?tr2)"
by auto
have "length (?io) = length pathF \<and> length (?tr2) = length (?tr1)"
by auto
then show ?thesis
using f2 f1 \<open>productF M2 M1 FAIL PM\<close> \<open>well_formed M1\<close> \<open>well_formed M2\<close> by blast
qed
moreover have "\<not> (path M2 (?io || ?tr2) (initial M2) \<and> path M1 (?io || ?tr1) (initial M1))"
proof (rule ccontr)
assume " \<not> \<not> (path M2 (?io || ?tr2) (initial M2) \<and>
path M1 (?io || ?tr1) (initial M1))"
then have "path M2 (?io || ?tr2) (initial M2)"
by simp
then have "target (?io || ?tr2) (initial M2) \<in> nodes M2"
by auto
then have "target (?io || ?tr2) (initial M2) \<noteq> fst FAIL"
using assms by auto
then show "False"
using pathF_def
proof -
have "FAIL = target (map fst pathF || map fst (map snd pathF) || map snd (map snd pathF))
(initial M2, initial M1)"
by (metis (no_types) \<open>initial PM = (initial M2, initial M1)\<close>
\<open>path PM pathF (initial PM) \<and> target pathF (initial PM) = FAIL\<close> zip_map_fst_snd)
then show ?thesis
using \<open>target (map fst pathF || map fst (map snd pathF)) (initial M2) \<noteq> fst FAIL\<close> by auto
qed
qed
ultimately have fail_prop :
"target (?io || ?tr2 || ?tr1) (initial M2, initial M1) = FAIL \<and>
0 < length (?io) \<and>
path M2 (butlast (?io || ?tr2)) (initial M2) \<and>
path M1 (butlast (?io || ?tr1)) (initial M1) \<and>
succ M2 (last (?io)) (target (butlast (?io || ?tr2)) (initial M2)) = {} \<and>
succ M1 (last (?io)) (target (butlast (?io || ?tr1)) (initial M1)) \<noteq> {}"
by auto
then have "?io \<in> language_state M1 (initial M1)"
proof -
have f1: "path PM (map fst pathF || map fst (map snd pathF) || map snd (map snd pathF))
(initial M2, initial M1)"
by (metis (no_types) \<open>initial PM = (initial M2, initial M1)\<close> pathF_def zip_map_fst_snd)
have "\<forall>c f. c \<noteq> initial (f::('a, 'b, 'c) FSM) \<or> c \<in> nodes f"
by blast
then show ?thesis
using f1 by (metis (no_types) assms(1) assms(2) assms(3) language_state length_map
productF_path_reverse_ob)
qed
moreover have "?io \<notin> language_state M2 (initial M2)"
proof (rule ccontr)
assume "\<not> ?io \<notin> language_state M2 (initial M2)"
then have assm : "?io \<in> language_state M2 (initial M2)"
by simp
then obtain tr2' where tr2'_def : "path M2 (?io || tr2') (initial M2)
\<and> length ?io = length tr2'"
by auto
then obtain tr2'_init tr2'_last where tr2'_split : "tr2' = tr2'_init @ [tr2'_last]"
using fail_prop by (metis \<open>pathF \<noteq> []\<close> append_butlast_last_id length_0_conv map_is_Nil_conv)
have "butlast ?io \<in> language_state M2 (initial M2)"
using fail_prop by auto
then have "{t. path M2 (butlast ?io || t) (initial M2) \<and> length (butlast ?io) = length t}
= {butlast ?tr2}"
using assms(5) observable_path_unique[of "butlast ?io" M2 "initial M2" "butlast ?tr2"]
fail_prop by fastforce
then have "\<forall> t ts . path M2 ((butlast ?io) @ [last ?io] || ts @ [t]) (initial M2)
\<and> length ((butlast ?io) @ [last ?io]) = length (ts @ [t])
\<longrightarrow> ts = butlast ?tr2"
by (metis (no_types, lifting) FSM.path_append_elim
\<open>butlast (map fst pathF) \<in> language_state M2 (initial M2)\<close> assms(5) butlast_snoc
butlast_zip fail_prop length_butlast length_map observable_path_unique zip_append)
then have "tr2'_init = butlast ?tr2"
using tr2'_def tr2'_split \<open>pathF \<noteq> []\<close> by auto
then have "path M2 ((butlast ?io) @ [last ?io] || (butlast ?tr2) @ [tr2'_last]) (initial M2)
\<and> length ((butlast ?io) @ [last ?io]) = length ((butlast ?tr2) @ [tr2'_last])"
using tr2'_def fail_prop tr2'_split by auto
then have "path M2 ([last ?io] || [tr2'_last])
(target (butlast ?io || butlast ?tr2) (initial M2))
\<and> length [last ?io] = length [tr2'_last]"
by auto
then have "tr2'_last \<in> succ M2 (last (?io)) (target (butlast (?io || ?tr2)) (initial M2))"
by auto
then show "False"
using fail_prop by auto
qed
ultimately show ?thesis by auto
qed
lemma fail_reachable_iff[iff] :
assumes "well_formed M1"
and "well_formed M2"
and "productF M2 M1 FAIL PM"
and "observable M2"
shows "FAIL \<in> reachable PM (initial PM) \<longleftrightarrow> \<not> M1 \<preceq> M2"
proof
show "FAIL \<in> reachable PM (initial PM) \<Longrightarrow> \<not> M1 \<preceq> M2"
using assms fail_reachable_reverse by blast
show "\<not> M1 \<preceq> M2 \<Longrightarrow> FAIL \<in> reachable PM (initial PM)"
using assms fail_reachable by blast
qed
lemma reaching_path_length :
assumes "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "q2 \<in> reachable AB q1"
and "q2 \<noteq> FAIL"
and "q1 \<in> nodes AB"
shows "\<exists> p . path AB p q1 \<and> target p q1 = q2 \<and> length p < card (nodes A) * card (nodes B)"
proof -
obtain p where p_def : "path AB p q1 \<and> target p q1 = q2 \<and> distinct (q1 # states p q1)"
using assms reaching_path_without_repetition by (metis well_formed_productF)
have "FAIL \<notin> set (q1 # states p q1)"
proof(cases p)
case Nil
then have "q1 = q2"
using p_def by auto
then have "q1 \<noteq> FAIL"
using assms by auto
then show ?thesis
using Nil by auto
next
case (Cons a list)
have "FAIL \<notin> set (butlast (q1 # states p q1))"
proof (rule ccontr)
assume assm : "\<not> FAIL \<notin> set (butlast (q1 # states p q1))"
then obtain i where i_def : "i < length (butlast (q1 # states p q1))
\<and> butlast (q1 # states p q1) ! i = FAIL"
by (metis distinct_Ex1 distinct_butlast p_def)
then have "i < Suc (length (butlast p))"
using local.Cons by fastforce
then have "i < length p"
by (metis append_butlast_last_id length_append_singleton list.simps(3) local.Cons)
then have "butlast (q1 # states p q1) ! i = target (take i p) q1"
using i_def assm proof (induction i)
case 0
then show ?case by auto
next
case (Suc i)
then show ?case by (metis Suc_lessD nth_Cons_Suc nth_butlast states_target_index)
qed
then have "target (take i p) q1 = FAIL" using i_def by auto
moreover have "\<forall> k . k < length p \<longrightarrow> target (take k p) q1 \<noteq> FAIL"
using no_prefix_targets_FAIL[of A B FAIL AB p q1] assms p_def by auto
ultimately show "False"
by (metis assms(5) linorder_neqE_nat nat_less_le order_refl p_def take_all)
qed
moreover have "last (q1 # states p q1) \<noteq> FAIL"
using assms(5) local.Cons p_def transition_system_universal.target_alt_def by force
ultimately show ?thesis
by (metis (no_types, lifting) UnE append_butlast_last_id list.set(1) list.set(2)
list.simps(3) set_append singletonD)
qed
moreover have "set (q1 # states p q1) \<subseteq> nodes AB"
using assms by (metis FSM.nodes_states insert_subset list.simps(15) p_def)
ultimately have states_subset : "set (q1 # states p q1) \<subseteq> nodes A \<times> nodes B"
using nodes_productF assms by blast
have finite_nodes : "finite (nodes A \<times> nodes B)"
using assms(2) assms(3) by auto
have "length p \<le> length (states p q1)"
by simp
then have "length p < card (nodes A) * card (nodes B)"
by (metis (no_types) finite_nodes states_subset card_cartesian_product card_mono distinct_card
impossible_Cons less_le_trans not_less p_def)
then show ?thesis
using p_def by blast
qed
lemma reaching_path_fail_length :
assumes "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "q2 \<in> reachable AB q1"
and "q1 \<in> nodes AB"
shows "\<exists> p . path AB p q1 \<and> target p q1 = q2 \<and> length p \<le> card (nodes A) * card (nodes B)"
proof (cases "q2 = FAIL")
case True
then have q2_def : "q2 = FAIL"
by simp
then show ?thesis
proof (cases "q1 = q2")
case True
then show ?thesis by auto
next
case False
then obtain px where px_def : "path AB px q1 \<and> target px q1 = q2"
using assms by auto
then have px_nonempty : "px \<noteq> []"
using q2_def False by auto
let ?qx = "target (butlast px) q1"
have "?qx \<in> reachable AB q1"
using px_def px_nonempty
by (metis FSM.path_append_elim FSM.reachable.reflexive FSM.reachable_target
append_butlast_last_id)
moreover have "?qx \<noteq> FAIL"
using False q2_def assms
by (metis One_nat_def Suc_pred butlast_conv_take length_greater_0_conv lessI
no_prefix_targets_FAIL px_def px_nonempty)
ultimately obtain px' where px'_def : "path AB px' q1
\<and> target px' q1 = ?qx
\<and> length px' < card (nodes A) * card (nodes B)"
using assms reaching_path_length[of A B FAIL AB ?qx q1] by blast
have px_split : "path AB ((butlast px) @ [last px]) q1
\<and> target ((butlast px) @ [last px]) q1 = q2"
using px_def px_nonempty by auto
then have "path AB [last px] ?qx \<and> target [last px] ?qx = q2"
using px_nonempty
proof -
have "target [last px] (target (butlast px) q1) = q2"
using px_split by force
then show ?thesis
using px_split by blast
qed
then have "path AB (px' @ [last px]) q1 \<and> target (px' @ [last px]) q1 = q2"
using px'_def by auto
moreover have "length (px' @ [last px]) \<le> card (nodes A) * card (nodes B)"
using px'_def by auto
ultimately show ?thesis
by blast
qed
next
case False
then show ?thesis
using assms reaching_path_length by (metis less_imp_le)
qed
lemma productF_language :
assumes "productF A B FAIL AB"
and "well_formed A"
and "well_formed B"
and "io \<in> L A \<inter> L B"
shows "io \<in> L AB"
proof -
obtain trA trB where tr_def : "path A (io || trA) (initial A) \<and> length io = length trA"
"path B (io || trB) (initial B) \<and> length io = length trB"
using assms by blast
then have "path AB (io || trA || trB) (initial A, initial B)"
using assms by (metis FSM.nodes.initial productF_path_inclusion)
then show ?thesis
using tr_def by (metis assms(1) language_state length_zip min.idem productF_simps(4))
qed
lemma productF_language_state_intermediate :
assumes "vs @ xs \<in> L M2 \<inter> L M1"
and "productF M2 M1 FAIL PM"
and "observable M2"
and "well_formed M2"
and "observable M1"
and "well_formed M1"
obtains q2 q1 tr
where "io_targets PM (initial PM) vs = {(q2,q1)}"
"path PM (xs || tr) (q2,q1)"
"length xs = length tr"
proof -
have "vs @ xs \<in> L PM"
using productF_language[OF assms(2,4,6,1)] by simp
then obtain trVX where "path PM (vs@xs || trVX) (initial PM) \<and> length trVX = length (vs@xs)"
by auto
then have tgt_VX : "io_targets PM (initial PM) (vs@xs) = {target (vs@xs || trVX) (initial PM)}"
by (metis assms(2) assms(3) assms(5) obs_target_is_io_targets observable_productF)
have "vs \<in> L PM" using \<open>vs@xs \<in> L PM\<close>
by (meson language_state_prefix)
then obtain trV where "path PM (vs || trV) (initial PM) \<and> length trV = length vs"
by auto
then have tgt_V : "io_targets PM (initial PM) vs = {target (vs || trV) (initial PM)}"
by (metis assms(2) assms(3) assms(5) obs_target_is_io_targets observable_productF)
let ?q2 = "fst (target (vs || trV) (initial PM))"
let ?q1 = "snd (target (vs || trV) (initial PM))"
have "observable PM"
by (meson assms(2,3,5) observable_productF)
have "io_targets PM (?q2,?q1) xs = {target (vs @ xs || trVX) (initial PM)}"
using observable_io_targets_split[OF \<open>observable PM\<close> tgt_VX tgt_V] by simp
then have "xs \<in> language_state PM (?q2,?q1)"
by auto
then obtain tr where "path PM (xs || tr) (?q2,?q1)"
"length xs = length tr"
by auto
then show ?thesis
by (metis prod.collapse tgt_V that)
qed
lemma sequence_to_failure_reaches_FAIL :
assumes "sequence_to_failure M1 M2 io"
and "OFSM M1"
and "OFSM M2"
and "productF M2 M1 FAIL PM"
shows "FAIL \<in> io_targets PM (initial PM) io"
proof -
obtain p where "path PM (io || p) (initial PM)
\<and> length p = length io
\<and> target (io || p) (initial PM) = FAIL"
using fail_reachable_by_sequence_to_failure[OF assms(1)]
using assms(2) assms(3) assms(4) by blast
then show ?thesis
by auto
qed
lemma sequence_to_failure_alt_def :
assumes "io_targets PM (initial PM) io = {FAIL}"
and "OFSM M1"
and "OFSM M2"
and "productF M2 M1 FAIL PM"
shows "sequence_to_failure M1 M2 io"
proof -
obtain p where "path PM (io || p) (initial PM)"
"length p = length io"
"target (io || p) (initial PM) = FAIL"
using assms(1) by (metis io_targets_elim singletonI)
have "io \<noteq> []"
proof
assume "io = []"
then have "io_targets PM (initial PM) io = {initial PM}"
by auto
moreover have "initial PM \<noteq> FAIL"
proof -
have "initial PM = (initial M2, initial M1)"
using assms(4) by auto
then have "initial PM \<in> (nodes M2 \<times> nodes M1)"
by (simp add: FSM.nodes.initial)
moreover have "FAIL \<notin> (nodes M2 \<times> nodes M1)"
using assms(4) by auto
ultimately show ?thesis
by auto
qed
ultimately show "False"
using assms(1) by blast
qed
then have "0 < length io"
by blast
have "target (butlast (io||p)) (initial PM) \<noteq> FAIL"
using no_prefix_targets_FAIL[OF assms(4) \<open>path PM (io || p) (initial PM)\<close>, of "(length io) - 1"]
by (metis (no_types, lifting) \<open>0 < length io\<close> \<open>length p = length io\<close> butlast_conv_take
diff_less length_map less_numeral_extra(1) map_fst_zip)
have "target (butlast (io||p)) (initial PM) \<in> nodes PM"
by (metis FSM.nodes.initial FSM.nodes_target FSM.path_append_elim
\<open>path PM (io || p) (initial PM)\<close> append_butlast_last_id butlast.simps(1))
moreover have "nodes PM \<subseteq> insert FAIL (nodes M2 \<times> nodes M1)"
using nodes_productF[OF _ _ assms(4)] assms(2) assms(3) by linarith
ultimately have "target (butlast (io||p)) (initial PM) \<in> insert FAIL (nodes M2 \<times> nodes M1)"
by blast
have "target (butlast (io||p)) (initial PM) \<in> (nodes M2 \<times> nodes M1)"
using \<open>target (butlast (io || p)) (initial PM) \<in> insert FAIL (nodes M2 \<times> nodes M1)\<close>
\<open>target (butlast (io || p)) (initial PM) \<noteq> FAIL\<close>
by blast
then obtain s2 s1 where "target (butlast (io||p)) (initial PM) = (s2,s1)"
"s2 \<in> nodes M2" "s1 \<in> nodes M1"
by blast
have "length (butlast io) = length (map fst (butlast p))"
"length (map fst (butlast p)) = length (map snd (butlast p))"
by (simp add: \<open>length p = length io\<close>)+
have "path PM (butlast (io||p)) (initial PM)"
by (metis FSM.path_append_elim \<open>path PM (io || p) (initial PM)\<close> append_butlast_last_id
butlast.simps(1))
then have "path PM ((butlast io) || (map fst (butlast p)) || (map snd (butlast p)))
(initial M2, initial M1)"
using \<open>length p = length io\<close> assms(4) by auto
have "target (butlast io || map fst (butlast p) || map snd (butlast p)) (initial M2, initial M1)
\<noteq> FAIL"
using \<open>length p = length io\<close> \<open>target (butlast (io || p)) (initial PM) \<noteq> FAIL\<close> assms(4)
by auto
have "path M2 (butlast io || map fst (butlast p)) (initial M2) \<and>
path M1 (butlast io || map snd (butlast p)) (initial M1) \<or>
target (butlast io || map fst (butlast p) || map snd (butlast p)) (initial M2, initial M1)
= FAIL"
using productF_path_reverse
[OF \<open>length (butlast io) = length (map fst (butlast p))\<close>
\<open>length (map fst (butlast p)) = length (map snd (butlast p))\<close>
assms(4) _ _
\<open>path PM ((butlast io) || (map fst (butlast p)) || (map snd (butlast p)))
(initial M2, initial M1)\<close> _ _]
using assms(2) assms(3) by auto
then have "path M2 (butlast io || map fst (butlast p)) (initial M2)"
"path M1 (butlast io || map snd (butlast p)) (initial M1)"
using \<open>target (butlast io || map fst (butlast p) || map snd (butlast p))
(initial M2, initial M1) \<noteq> FAIL\<close>
by auto
then have "butlast io \<in> L M2 \<inter> L M1"
using \<open>length (butlast io) = length (map fst (butlast p))\<close> by auto
have "path PM (io || map fst p || map snd p) (initial M2, initial M1)"
using \<open>path PM (io || p) (initial PM)\<close> assms(4) by auto
have "length io = length (map fst p)"
"length (map fst p) = length (map snd p)"
by (simp add: \<open>length p = length io\<close>)+
obtain p1' where "path M1 (io || p1') (initial M1) \<and> length io = length p1'"
using productF_path_reverse_ob
[OF \<open>length io = length (map fst p)\<close>
\<open>length (map fst p) = length (map snd p)\<close> assms(4) _ _
\<open>path PM (io || map fst p || map snd p) (initial M2, initial M1)\<close>]
using assms(2) assms(3) by blast
then have "io \<in> L M1"
by auto
moreover have "io \<notin> L M2"
proof
assume "io \<in> L M2" \<comment> \<open> only possible if io does not target FAIL \<close>
then obtain p2' where "path M2 (io || p2') (initial M2)" "length io = length p2'"
by auto
then have "length p2' = length p1'"
using \<open>path M1 (io || p1') (initial M1) \<and> length io = length p1'\<close>
by auto
have "path PM (io || p2' || p1') (initial M2, initial M1)"
using productF_path_inclusion[OF \<open>length io = length p2'\<close> \<open>length p2' = length p1'\<close> assms(4),
of "initial M2" "initial M1"]
\<open>path M1 (io || p1') (initial M1) \<and> length io = length p1'\<close>
\<open>path M2 (io || p2') (initial M2)\<close> assms(2) assms(3)
by blast
have "target (io || p2' || p1') (initial M2, initial M1) \<in> (nodes M2 \<times> nodes M1)"
using \<open>length io = length p2'\<close> \<open>path M1 (io || p1') (initial M1) \<and> length io = length p1'\<close>
\<open>path M2 (io || p2') (initial M2)\<close>
by auto
moreover have "FAIL \<notin> (nodes M2 \<times> nodes M1)"
using assms(4) by auto
ultimately have "target (io || p2' || p1') (initial M2, initial M1) \<noteq> FAIL"
by blast
have "length io = length (p2' || p1')"
by (simp add: \<open>length io = length p2'\<close> \<open>length p2' = length p1'\<close>)
have "target (io || p2' || p1') (initial M2, initial M1)
\<in> io_targets PM (initial M2, initial M1) io"
using \<open>path PM (io || p2' || p1') (initial M2, initial M1)\<close> \<open>length io = length (p2' || p1')\<close>
unfolding io_targets.simps by blast
have "io_targets PM (initial PM) io \<noteq> {FAIL}"
using \<open>target (io || p2' || p1') (initial M2, initial M1)
\<in> io_targets PM (initial M2, initial M1) io\<close>
\<open>target (io || p2' || p1') (initial M2, initial M1) \<noteq> FAIL\<close> assms(4)
by auto
then show "False"
using assms(1) by blast
qed
ultimately have "io \<in> L M1 - L M2"
by blast
show "sequence_to_failure M1 M2 io"
using \<open>butlast io \<in> L M2 \<inter> L M1\<close> \<open>io \<in> L M1 - L M2\<close> by auto
qed
end |
function rs = amutual2(s, len)
%tstoolbox/@signal/amutual2
% Syntax:
% * amutual2(s, len)
%
% Input arguments:
% * len - maximal lag
%
% Auto mutual information (average) function for real scalar signals
% using 128 equidistant partitions.
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt
narginchk(2,2);
if (ndim(s) > 1) | (~isreal(data(s)))
help(mfilename)
return
end
c = amutual2(s.core, len);
rs = signal(c, s); % special constructor calling syntax for working routines
a = getaxis(s, 1);
dl = delta(a);
a = setfirst(a, 0);
rs = setaxis(rs, 1, a);
rs = setyunit(rs, unit('Bit')); % acf values are scalars without unit
rs = addhistory(rs, ['Auto mutual information of length ' num2str(len)]);
rs = addcommandlines(rs, 's = amutual(s', len);
|
[STATEMENT]
theorem M0: "\<turnstile> \<box>F \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<turnstile> \<box>F \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
[PROOF STEP]
proof -
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<turnstile> \<box>F \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
[PROOF STEP]
from P1
[PROOF STATE]
proof (chain)
picking this:
|~ \<box>?F \<longrightarrow> \<circle>?F
[PROOF STEP]
have "|~ \<box>F \<longrightarrow> F \<longrightarrow> \<circle>F"
[PROOF STATE]
proof (prove)
using this:
|~ \<box>?F \<longrightarrow> \<circle>?F
goal (1 subgoal):
1. |~ \<box>F \<longrightarrow> F \<longrightarrow> \<circle>F
[PROOF STEP]
by force
[PROOF STATE]
proof (state)
this:
|~ \<box>F \<longrightarrow> F \<longrightarrow> \<circle>F
goal (1 subgoal):
1. \<turnstile> \<box>F \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
[PROOF STEP]
hence "\<turnstile> \<box>[\<box>F]_v \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v"
[PROOF STATE]
proof (prove)
using this:
|~ \<box>F \<longrightarrow> F \<longrightarrow> \<circle>F
goal (1 subgoal):
1. \<turnstile> \<box>[\<box>F]_v \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
[PROOF STEP]
by (rule M2)
[PROOF STATE]
proof (state)
this:
\<turnstile> \<box>[\<box>F]_v \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
goal (1 subgoal):
1. \<turnstile> \<box>F \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
[PROOF STEP]
with ax2
[PROOF STATE]
proof (chain)
picking this:
\<turnstile> \<box>?F \<longrightarrow> \<box>[\<box>?F]_?v
\<turnstile> \<box>[\<box>F]_v \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
[PROOF STEP]
show ?thesis
[PROOF STATE]
proof (prove)
using this:
\<turnstile> \<box>?F \<longrightarrow> \<box>[\<box>?F]_?v
\<turnstile> \<box>[\<box>F]_v \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
goal (1 subgoal):
1. \<turnstile> \<box>F \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
[PROOF STEP]
by (rule lift_imp_trans)
[PROOF STATE]
proof (state)
this:
\<turnstile> \<box>F \<longrightarrow> \<box>[F \<longrightarrow> \<circle>F]_v
goal:
No subgoals!
[PROOF STEP]
qed |
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
β’ MeasureTheory.SignedMeasure.ExistsOneDivLT s i (MeasureTheory.SignedMeasure.findExistsOneDivLT s i)
[PROOFSTEP]
rw [findExistsOneDivLT, dif_pos hi]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
β’ MeasureTheory.SignedMeasure.ExistsOneDivLT s i (Nat.find (_ : β n, MeasureTheory.SignedMeasure.ExistsOneDivLT s i n))
[PROOFSTEP]
convert Nat.find_spec (existsNatOneDivLTMeasure_of_not_negative hi)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
m : β
hm : m < MeasureTheory.SignedMeasure.findExistsOneDivLT s i
β’ Β¬MeasureTheory.SignedMeasure.ExistsOneDivLT s i m
[PROOFSTEP]
rw [findExistsOneDivLT, dif_pos hi] at hm
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
m : β
hm : m < Nat.find (_ : β n, MeasureTheory.SignedMeasure.ExistsOneDivLT s i n)
β’ Β¬MeasureTheory.SignedMeasure.ExistsOneDivLT s i m
[PROOFSTEP]
exact Nat.find_min _ hm
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
β’ MeasureTheory.SignedMeasure.someExistsOneDivLT s i β i β§
MeasurableSet (MeasureTheory.SignedMeasure.someExistsOneDivLT s i) β§
1 / (β(MeasureTheory.SignedMeasure.findExistsOneDivLT s i) + 1) <
βs (MeasureTheory.SignedMeasure.someExistsOneDivLT s i)
[PROOFSTEP]
rw [someExistsOneDivLT, dif_pos hi]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
β’ Classical.choose
(_ : MeasureTheory.SignedMeasure.ExistsOneDivLT s i (MeasureTheory.SignedMeasure.findExistsOneDivLT s i)) β
i β§
MeasurableSet
(Classical.choose
(_ : MeasureTheory.SignedMeasure.ExistsOneDivLT s i (MeasureTheory.SignedMeasure.findExistsOneDivLT s i))) β§
1 / (β(MeasureTheory.SignedMeasure.findExistsOneDivLT s i) + 1) <
βs
(Classical.choose
(_ : MeasureTheory.SignedMeasure.ExistsOneDivLT s i (MeasureTheory.SignedMeasure.findExistsOneDivLT s i)))
[PROOFSTEP]
exact Classical.choose_spec (findExistsOneDivLT_spec hi)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ MeasureTheory.SignedMeasure.someExistsOneDivLT s i β i
[PROOFSTEP]
by_cases hi : Β¬s β€[i] 0
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
β’ MeasureTheory.SignedMeasure.someExistsOneDivLT s i β i
[PROOFSTEP]
exact
let β¨h, _β© := someExistsOneDivLT_spec hi
h
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : ¬¬restrict s i †restrict 0 i
β’ MeasureTheory.SignedMeasure.someExistsOneDivLT s i β i
[PROOFSTEP]
rw [someExistsOneDivLT, dif_neg hi]
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : ¬¬restrict s i †restrict 0 i
β’ β
β i
[PROOFSTEP]
exact Set.empty_subset _
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ MeasurableSet (MeasureTheory.SignedMeasure.someExistsOneDivLT s i)
[PROOFSTEP]
by_cases hi : Β¬s β€[i] 0
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : Β¬restrict s i β€ restrict 0 i
β’ MeasurableSet (MeasureTheory.SignedMeasure.someExistsOneDivLT s i)
[PROOFSTEP]
exact
let β¨_, h, _β© := someExistsOneDivLT_spec hi
h
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : ¬¬restrict s i †restrict 0 i
β’ MeasurableSet (MeasureTheory.SignedMeasure.someExistsOneDivLT s i)
[PROOFSTEP]
rw [someExistsOneDivLT, dif_neg hi]
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : ¬¬restrict s i †restrict 0 i
β’ MeasurableSet β
[PROOFSTEP]
exact MeasurableSet.empty
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i (Nat.succ n) =
MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
[PROOFSTEP]
rw [restrictNonposSeq]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i n β i
[PROOFSTEP]
cases n
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i Nat.zero β i
[PROOFSTEP]
rw [restrictNonposSeq]
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
) β i
[PROOFSTEP]
exact someExistsOneDivLT_subset'
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
nβ : β
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i (Nat.succ nβ) β i
[PROOFSTEP]
rw [restrictNonposSeq]
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
nβ : β
β’ MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \
β (k : β) (H : k β€ nβ),
let_fun this := (_ : k < Nat.succ nβ);
MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β
i
[PROOFSTEP]
exact someExistsOneDivLT_subset'
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 1 /
(β(MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)) +
1) <
βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i (Nat.succ n))
[PROOFSTEP]
rw [restrictNonposSeq_succ]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 1 /
(β(MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)) +
1) <
βs
(MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k))
[PROOFSTEP]
apply someExistsOneDivLT_lt hn
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i n)
[PROOFSTEP]
cases n with
| zero =>
rw [restrictNonposSeq]; rw [β @Set.diff_empty _ i] at hiβ
rcases someExistsOneDivLT_spec hiβ with β¨_, _, hβ©
exact lt_trans Nat.one_div_pos_of_nat h
| succ n =>
rw [restrictNonposSeq_succ]
have hβ : Β¬s β€[i \ β (k : β) (_ : k β€ n), restrictNonposSeq s i k] 0 :=
by
refine' mt (restrict_le_zero_subset _ _ (by simp [Nat.lt_succ_iff]; rfl)) hn
convert measurable_of_not_restrict_le_zero _ hn using 3
exact funext fun x => by rw [Nat.lt_succ_iff]
rcases someExistsOneDivLT_spec hβ with β¨_, _, hβ©
exact lt_trans Nat.one_div_pos_of_nat h
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i n)
[PROOFSTEP]
cases n with
| zero =>
rw [restrictNonposSeq]; rw [β @Set.diff_empty _ i] at hiβ
rcases someExistsOneDivLT_spec hiβ with β¨_, _, hβ©
exact lt_trans Nat.one_div_pos_of_nat h
| succ n =>
rw [restrictNonposSeq_succ]
have hβ : Β¬s β€[i \ β (k : β) (_ : k β€ n), restrictNonposSeq s i k] 0 :=
by
refine' mt (restrict_le_zero_subset _ _ (by simp [Nat.lt_succ_iff]; rfl)) hn
convert measurable_of_not_restrict_le_zero _ hn using 3
exact funext fun x => by rw [Nat.lt_succ_iff]
rcases someExistsOneDivLT_spec hβ with β¨_, _, hβ©
exact lt_trans Nat.one_div_pos_of_nat h
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i Nat.zero)
[PROOFSTEP]
| zero =>
rw [restrictNonposSeq]; rw [β @Set.diff_empty _ i] at hiβ
rcases someExistsOneDivLT_spec hiβ with β¨_, _, hβ©
exact lt_trans Nat.one_div_pos_of_nat h
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i Nat.zero)
[PROOFSTEP]
rw [restrictNonposSeq]
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
))
[PROOFSTEP]
rw [β @Set.diff_empty _ i] at hiβ
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s (i \ β
) β€ restrict 0 (i \ β
)
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
))
[PROOFSTEP]
rcases someExistsOneDivLT_spec hiβ with β¨_, _, hβ©
[GOAL]
case zero.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s (i \ β
) β€ restrict 0 (i \ β
)
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.zero), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
leftβΒΉ : MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
) β i \ β
leftβ : MeasurableSet (MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
))
h :
1 / (β(MeasureTheory.SignedMeasure.findExistsOneDivLT s (i \ β
)) + 1) <
βs (MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
))
β’ 0 < βs (MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
))
[PROOFSTEP]
exact lt_trans Nat.one_div_pos_of_nat h
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i (Nat.succ n))
[PROOFSTEP]
| succ n =>
rw [restrictNonposSeq_succ]
have hβ : Β¬s β€[i \ β (k : β) (_ : k β€ n), restrictNonposSeq s i k] 0 :=
by
refine' mt (restrict_le_zero_subset _ _ (by simp [Nat.lt_succ_iff]; rfl)) hn
convert measurable_of_not_restrict_le_zero _ hn using 3
exact funext fun x => by rw [Nat.lt_succ_iff]
rcases someExistsOneDivLT_spec hβ with β¨_, _, hβ©
exact lt_trans Nat.one_div_pos_of_nat h
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 < βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i (Nat.succ n))
[PROOFSTEP]
rw [restrictNonposSeq_succ]
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 <
βs
(MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k))
[PROOFSTEP]
have hβ : Β¬s β€[i \ β (k : β) (_ : k β€ n), restrictNonposSeq s i k] 0 :=
by
refine' mt (restrict_le_zero_subset _ _ (by simp [Nat.lt_succ_iff]; rfl)) hn
convert measurable_of_not_restrict_le_zero _ hn using 3
exact funext fun x => by rw [Nat.lt_succ_iff]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ Β¬restrict s (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
[PROOFSTEP]
refine' mt (restrict_le_zero_subset _ _ (by simp [Nat.lt_succ_iff]; rfl)) hn
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k β
i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k
[PROOFSTEP]
simp [Nat.lt_succ_iff]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k β
i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k
[PROOFSTEP]
rfl
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ MeasurableSet (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
[PROOFSTEP]
convert measurable_of_not_restrict_le_zero _ hn using 3
[GOAL]
case h.e'_3.h.e'_4.h.e'_3
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ (fun k => β (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) = fun k =>
β (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k
[PROOFSTEP]
exact funext fun x => by rw [Nat.lt_succ_iff]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
x : β
β’ β (_ : x β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i x =
β (_ : x < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i x
[PROOFSTEP]
rw [Nat.lt_succ_iff]
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hβ :
Β¬restrict s (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ 0 <
βs
(MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k))
[PROOFSTEP]
rcases someExistsOneDivLT_spec hβ with β¨_, _, hβ©
[GOAL]
case succ.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : Β¬restrict s i β€ restrict 0 i
n : β
hn :
Β¬restrict s (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < Nat.succ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hβ :
Β¬restrict s (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
leftβΒΉ :
MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β
i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k
leftβ :
MeasurableSet
(MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k))
h :
1 /
(β(MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)) +
1) <
βs
(MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k))
β’ 0 <
βs
(MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k))
[PROOFSTEP]
exact lt_trans Nat.one_div_pos_of_nat h
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
β’ MeasurableSet (MeasureTheory.SignedMeasure.restrictNonposSeq s i n)
[PROOFSTEP]
cases n
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ MeasurableSet (MeasureTheory.SignedMeasure.restrictNonposSeq s i Nat.zero)
[PROOFSTEP]
rw [restrictNonposSeq]
[GOAL]
case zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ MeasurableSet (MeasureTheory.SignedMeasure.someExistsOneDivLT s (i \ β
))
[PROOFSTEP]
exact someExistsOneDivLT_measurableSet
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
nβ : β
β’ MeasurableSet (MeasureTheory.SignedMeasure.restrictNonposSeq s i (Nat.succ nβ))
[PROOFSTEP]
rw [restrictNonposSeq]
[GOAL]
case succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
nβ : β
β’ MeasurableSet
(MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \
β (k : β) (H : k β€ nβ),
let_fun this := (_ : k < Nat.succ nβ);
MeasureTheory.SignedMeasure.restrictNonposSeq s i k))
[PROOFSTEP]
exact someExistsOneDivLT_measurableSet
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n m : β
h : n < m
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i n β© MeasureTheory.SignedMeasure.restrictNonposSeq s i m = β
[PROOFSTEP]
rw [Set.eq_empty_iff_forall_not_mem]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n m : β
h : n < m
β’ β (x : Ξ±),
Β¬x β MeasureTheory.SignedMeasure.restrictNonposSeq s i n β© MeasureTheory.SignedMeasure.restrictNonposSeq s i m
[PROOFSTEP]
rintro x β¨hxβ, hxββ©
[GOAL]
case intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n m : β
h : n < m
x : Ξ±
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i n
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i m
β’ False
[PROOFSTEP]
cases m
[GOAL]
case intro.zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
x : Ξ±
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i n
h : n < Nat.zero
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i Nat.zero
β’ False
[PROOFSTEP]
rw [Nat.zero_eq] at h
[GOAL]
case intro.zero
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
x : Ξ±
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i n
h : n < 0
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i Nat.zero
β’ False
[PROOFSTEP]
linarith
[GOAL]
case intro.succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
x : Ξ±
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i n
nβ : β
h : n < Nat.succ nβ
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i (Nat.succ nβ)
β’ False
[PROOFSTEP]
rw [restrictNonposSeq] at hxβ
[GOAL]
case intro.succ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n : β
x : Ξ±
hxβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i n
nβ : β
h : n < Nat.succ nβ
hxβ :
x β
MeasureTheory.SignedMeasure.someExistsOneDivLT s
(i \
β (k : β) (H : k β€ nβ),
let_fun this := (_ : k < Nat.succ nβ);
MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ False
[PROOFSTEP]
exact (someExistsOneDivLT_subset hxβ).2 (Set.mem_iUnion.2 β¨n, Set.mem_iUnion.2 β¨Nat.lt_succ_iff.mp h, hxββ©β©)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ Pairwise (Disjoint on MeasureTheory.SignedMeasure.restrictNonposSeq s i)
[PROOFSTEP]
intro n m h
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n m : β
h : n β m
β’ (Disjoint on MeasureTheory.SignedMeasure.restrictNonposSeq s i) n m
[PROOFSTEP]
rw [Function.onFun, Set.disjoint_iff_inter_eq_empty]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n m : β
h : n β m
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i n β© MeasureTheory.SignedMeasure.restrictNonposSeq s i m = β
[PROOFSTEP]
rcases lt_or_gt_of_ne h with (h | h)
[GOAL]
case inl
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n m : β
hβ : n β m
h : n < m
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i n β© MeasureTheory.SignedMeasure.restrictNonposSeq s i m = β
[PROOFSTEP]
rw [restrictNonposSeq_disjoint' h]
[GOAL]
case inr
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
n m : β
hβ : n β m
h : n > m
β’ MeasureTheory.SignedMeasure.restrictNonposSeq s i n β© MeasureTheory.SignedMeasure.restrictNonposSeq s i m = β
[PROOFSTEP]
rw [Set.inter_comm, restrictNonposSeq_disjoint' h]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hn :
Β¬β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
by_cases s β€[i] 0
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hn :
Β¬β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
by_cases s β€[i] 0
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hn :
Β¬β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
h : restrict s i β€ restrict 0 i
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
exact β¨i, hiβ, Set.Subset.refl _, h, hiββ©
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hn :
Β¬β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
h : Β¬restrict s i β€ restrict 0 i
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
push_neg at hn
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
set k := Nat.find hn
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hkβ : s β€[i \ β l < k, restrictNonposSeq s i l] 0 := Nat.find_spec hn
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hmeas : MeasurableSet (β (l : β) (_ : l < k), restrictNonposSeq s i l) :=
MeasurableSet.iUnion fun _ => MeasurableSet.iUnion fun _ => restrictNonposSeq_measurableSet _
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
refine' β¨i \ β l < k, restrictNonposSeq s i l, hiβ.diff hmeas, Set.diff_subset _ _, hkβ, _β©
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) < 0
[PROOFSTEP]
rw [of_diff hmeas hiβ, s.of_disjoint_iUnion_nat]
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs i - β' (i_1 : β), βs (β (_ : i_1 < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1) < 0
[PROOFSTEP]
have hβ : β l < k, 0 β€ s (restrictNonposSeq s i l) := by
intro l hl
refine' le_of_lt (measure_of_restrictNonposSeq h _ _)
refine' mt (restrict_le_zero_subset _ (hiβ.diff _) (Set.Subset.refl _)) (Nat.find_min hn hl)
exact MeasurableSet.iUnion fun _ => MeasurableSet.iUnion fun _ => restrictNonposSeq_measurableSet _
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
intro l hl
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
hl : l < k
β’ 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
refine' le_of_lt (measure_of_restrictNonposSeq h _ _)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
hl : l < k
β’ Β¬restrict s (i \ β (k : β) (_ : k < l), MeasureTheory.SignedMeasure.restrictNonposSeq s i k) β€
restrict 0 (i \ β (k : β) (_ : k < l), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
[PROOFSTEP]
refine' mt (restrict_le_zero_subset _ (hiβ.diff _) (Set.Subset.refl _)) (Nat.find_min hn hl)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
hl : l < k
β’ MeasurableSet (β (k : β) (_ : k < l), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
[PROOFSTEP]
exact MeasurableSet.iUnion fun _ => MeasurableSet.iUnion fun _ => restrictNonposSeq_measurableSet _
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs i - β' (i_1 : β), βs (β (_ : i_1 < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1) < 0
[PROOFSTEP]
suffices 0 β€ β' l : β, s (β _ : l < k, restrictNonposSeq s i l)
by
rw [sub_neg]
exact lt_of_lt_of_le hiβ this
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
this : 0 β€ β' (l : β), βs (β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs i - β' (i_1 : β), βs (β (_ : i_1 < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1) < 0
[PROOFSTEP]
rw [sub_neg]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
this : 0 β€ β' (l : β), βs (β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs i < β' (i_1 : β), βs (β (_ : i_1 < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1)
[PROOFSTEP]
exact lt_of_lt_of_le hiβ this
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ 0 β€ β' (l : β), βs (β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
refine' tsum_nonneg _
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (i_1 : β), 0 β€ βs (β (_ : i_1 < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1)
[PROOFSTEP]
intro l
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
β’ 0 β€ βs (β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
by_cases l < k
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
β’ 0 β€ βs (β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
by_cases l < k
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : l < k
β’ 0 β€ βs (β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
convert hβ _ h
[GOAL]
case h.e'_4.h.e'_7
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : l < k
β’ β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l =
MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
ext x
[GOAL]
case h.e'_4.h.e'_7.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : l < k
x : Ξ±
β’ x β β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β
x β MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
rw [Set.mem_iUnion, exists_prop, and_iff_right_iff_imp]
[GOAL]
case h.e'_4.h.e'_7.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : l < k
x : Ξ±
β’ x β MeasureTheory.SignedMeasure.restrictNonposSeq s i l β l < k
[PROOFSTEP]
exact fun _ => h
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : Β¬l < k
β’ 0 β€ βs (β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
convert le_of_eq s.empty.symm
[GOAL]
case h.e'_4.h.e'_7
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : Β¬l < k
β’ β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l = β
[PROOFSTEP]
ext
[GOAL]
case h.e'_4.h.e'_7.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : Β¬l < k
xβ : Ξ±
β’ xβ β β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β xβ β β
[PROOFSTEP]
simp only [exists_prop, Set.mem_empty_iff_false, Set.mem_iUnion, not_and, iff_false_iff]
[GOAL]
case h.e'_4.h.e'_7.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
hβ : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : β (l : β), l < k β 0 β€ βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
l : β
h : Β¬l < k
xβ : Ξ±
β’ l < Nat.find hn β Β¬xβ β MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
exact fun h' => False.elim (h h')
[GOAL]
case neg.hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (i_1 : β), MeasurableSet (β (_ : i_1 < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1)
[PROOFSTEP]
intro
[GOAL]
case neg.hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
iβ : β
β’ MeasurableSet (β (_ : iβ < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i iβ)
[PROOFSTEP]
exact MeasurableSet.iUnion fun _ => restrictNonposSeq_measurableSet _
[GOAL]
case neg.hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ Pairwise (Disjoint on fun l => β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
intro a b hab
[GOAL]
case neg.hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
a b : β
hab : a β b
β’ (Disjoint on fun l => β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) a b
[PROOFSTEP]
refine' Set.disjoint_iUnion_left.mpr fun _ => _
[GOAL]
case neg.hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
a b : β
hab : a β b
xβ : a < k
β’ Disjoint (MeasureTheory.SignedMeasure.restrictNonposSeq s i a)
((fun l => β (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) b)
[PROOFSTEP]
refine' Set.disjoint_iUnion_right.mpr fun _ => _
[GOAL]
case neg.hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
a b : β
hab : a β b
xβΒΉ : a < k
xβ : b < k
β’ Disjoint (MeasureTheory.SignedMeasure.restrictNonposSeq s i a) (MeasureTheory.SignedMeasure.restrictNonposSeq s i b)
[PROOFSTEP]
exact restrictNonposSeq_disjoint hab
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β i
[PROOFSTEP]
apply Set.iUnion_subset
[GOAL]
case neg.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (i_1 : β), β (_ : i_1 < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1 β i
[PROOFSTEP]
intro a x
[GOAL]
case neg.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
a : β
x : Ξ±
β’ x β β (_ : a < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i a β x β i
[PROOFSTEP]
simp only [and_imp, exists_prop, Set.mem_iUnion]
[GOAL]
case neg.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
a : β
x : Ξ±
β’ a < Nat.find hn β x β MeasureTheory.SignedMeasure.restrictNonposSeq s i a β x β i
[PROOFSTEP]
intro _ hx
[GOAL]
case neg.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hiβ : MeasurableSet i
hiβ : βs i < 0
h : Β¬restrict s i β€ restrict 0 i
hn :
β n,
restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
k : β := Nat.find hn
hkβ :
restrict s (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hmeas : MeasurableSet (β (l : β) (_ : l < k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
a : β
x : Ξ±
aβ : a < Nat.find hn
hx : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i a
β’ x β i
[PROOFSTEP]
exact restrictNonposSeq_subset _ hx
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hiβ : MeasurableSet i := by_contradiction fun h => ne_of_lt hi <| s.not_measurable h
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
by_cases s β€[i] 0
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
by_cases s β€[i] 0
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : restrict s i β€ restrict 0 i
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
exact β¨i, hiβ, Set.Subset.refl _, h, hiβ©
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
by_cases hn : β n : β, Β¬s β€[i \ β l < n, restrictNonposSeq s i l] 0
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
Β¬β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
swap
[GOAL]
case neg
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
Β¬β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
exact exists_subset_restrict_nonpos' hiβ hi hn
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
set A := i \ β l, restrictNonposSeq s i l with hA
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
set bdd : β β β := fun n => findExistsOneDivLT s (i \ β k β€ n, restrictNonposSeq s i k)
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hn' : β n : β, Β¬s β€[i \ β l β€ n, restrictNonposSeq s i l] 0 :=
by
intro n
convert hn (n + 1) using 5 <;>
Β· ext l
simp only [exists_prop, Set.mem_iUnion, and_congr_left_iff]
exact fun _ => Nat.lt_succ_iff.symm
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
β’ β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
intro n
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
n : β
β’ Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
convert hn (n + 1) using 5
[GOAL]
case h.e'_1.h.e'_3.h.e'_7.h.e'_4.h.e'_3
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
n : β
β’ (fun l => β (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) = fun l =>
β (_ : l < n + 1), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
ext l
[GOAL]
case h.e'_1.h.e'_3.h.e'_7.h.e'_4.h.e'_3.h.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
n l : β
xβ : Ξ±
β’ xβ β β (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β
xβ β β (_ : l < n + 1), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
simp only [exists_prop, Set.mem_iUnion, and_congr_left_iff]
[GOAL]
case h.e'_1.h.e'_3.h.e'_7.h.e'_4.h.e'_3.h.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
n l : β
xβ : Ξ±
β’ xβ β MeasureTheory.SignedMeasure.restrictNonposSeq s i l β (l β€ n β l < n + 1)
[PROOFSTEP]
exact fun _ => Nat.lt_succ_iff.symm
[GOAL]
case h.e'_1.h.e'_4.h.e'_7.h.e'_4.h.e'_3
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
n : β
β’ (fun l => β (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) = fun l =>
β (_ : l < n + 1), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
ext l
[GOAL]
case h.e'_1.h.e'_4.h.e'_7.h.e'_4.h.e'_3.h.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
n l : β
xβ : Ξ±
β’ xβ β β (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β
xβ β β (_ : l < n + 1), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
simp only [exists_prop, Set.mem_iUnion, and_congr_left_iff]
[GOAL]
case h.e'_1.h.e'_4.h.e'_7.h.e'_4.h.e'_3.h.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
n l : β
xβ : Ξ±
β’ xβ β MeasureTheory.SignedMeasure.restrictNonposSeq s i l β (l β€ n β l < n + 1)
[PROOFSTEP]
exact fun _ => Nat.lt_succ_iff.symm
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hβ : s i = s A + β' l, s (restrictNonposSeq s i l) :=
by
rw [hA, β s.of_disjoint_iUnion_nat, add_comm, of_add_of_diff]
exact MeasurableSet.iUnion fun _ => restrictNonposSeq_measurableSet _
exacts [hiβ, Set.iUnion_subset fun _ => restrictNonposSeq_subset _, fun _ => restrictNonposSeq_measurableSet _,
restrictNonposSeq_disjoint]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
rw [hA, β s.of_disjoint_iUnion_nat, add_comm, of_add_of_diff]
[GOAL]
case hA
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ MeasurableSet (β (i_1 : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1)
case hB
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ MeasurableSet i
case h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (i_1 : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1 β i
case hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (i_1 : β), MeasurableSet (MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1)
case hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ Pairwise (Disjoint on fun l => MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
exact MeasurableSet.iUnion fun _ => restrictNonposSeq_measurableSet _
[GOAL]
case hB
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ MeasurableSet i
case h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (i_1 : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1 β i
case hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β (i_1 : β), MeasurableSet (MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1)
case hfβ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ Pairwise (Disjoint on fun l => MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
exacts [hiβ, Set.iUnion_subset fun _ => restrictNonposSeq_subset _, fun _ => restrictNonposSeq_measurableSet _,
restrictNonposSeq_disjoint]
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hβ : s A β€ s i := by
rw [hβ]
apply le_add_of_nonneg_right
exact tsum_nonneg fun n => le_of_lt (measure_of_restrictNonposSeq h _ (hn n))
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs A β€ βs i
[PROOFSTEP]
rw [hβ]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ βs A β€ βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
apply le_add_of_nonneg_right
[GOAL]
case h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ 0 β€ β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
[PROOFSTEP]
exact tsum_nonneg fun n => le_of_lt (measure_of_restrictNonposSeq h _ (hn n))
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hβ' : Summable fun n => (1 / (bdd n + 1) : β) :=
by
have : Summable fun l => s (restrictNonposSeq s i l) :=
HasSum.summable (s.m_iUnion (fun _ => restrictNonposSeq_measurableSet _) restrictNonposSeq_disjoint)
refine' summable_of_nonneg_of_le (fun n => _) (fun n => _) (Summable.comp_injective this Nat.succ_injective)
Β· exact le_of_lt Nat.one_div_pos_of_nat
Β· exact le_of_lt (restrictNonposSeq_lt n (hn' n))
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
β’ Summable fun n => 1 / (β(bdd n) + 1)
[PROOFSTEP]
have : Summable fun l => s (restrictNonposSeq s i l) :=
HasSum.summable (s.m_iUnion (fun _ => restrictNonposSeq_measurableSet _) restrictNonposSeq_disjoint)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
this : Summable fun l => βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
β’ Summable fun n => 1 / (β(bdd n) + 1)
[PROOFSTEP]
refine' summable_of_nonneg_of_le (fun n => _) (fun n => _) (Summable.comp_injective this Nat.succ_injective)
[GOAL]
case refine'_1
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
this : Summable fun l => βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
n : β
β’ 0 β€ 1 / (β(bdd n) + 1)
[PROOFSTEP]
exact le_of_lt Nat.one_div_pos_of_nat
[GOAL]
case refine'_2
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
this : Summable fun l => βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
n : β
β’ 1 / (β(bdd n) + 1) β€ ((fun l => βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)) β Nat.succ) n
[PROOFSTEP]
exact le_of_lt (restrictNonposSeq_lt n (hn' n))
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hβ : Tendsto (fun n => (bdd n : β) + 1) atTop atTop :=
by
simp only [one_div] at hβ'
exact Summable.tendsto_atTop_of_pos hβ' fun n => Nat.cast_add_one_pos (bdd n)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
β’ Tendsto (fun n => β(bdd n) + 1) atTop atTop
[PROOFSTEP]
simp only [one_div] at hβ'
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' :
Summable fun n =>
(β(MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)) +
1)β»ΒΉ
β’ Tendsto (fun n => β(bdd n) + 1) atTop atTop
[PROOFSTEP]
exact Summable.tendsto_atTop_of_pos hβ' fun n => Nat.cast_add_one_pos (bdd n)
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have hβ : Tendsto (fun n => (bdd n : β)) atTop atTop := by convert atTop.tendsto_atTop_add_const_right (-1) hβ; simp
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
β’ Tendsto (fun n => β(bdd n)) atTop atTop
[PROOFSTEP]
convert atTop.tendsto_atTop_add_const_right (-1) hβ
[GOAL]
case h.e'_3.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
xβ : β
β’ β(bdd xβ) = β(bdd xβ) + 1 + -1
[PROOFSTEP]
simp
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
have A_meas : MeasurableSet A := hiβ.diff (MeasurableSet.iUnion fun _ => restrictNonposSeq_measurableSet _)
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
β’ β j, MeasurableSet j β§ j β i β§ restrict s j β€ restrict 0 j β§ βs j < 0
[PROOFSTEP]
refine' β¨A, A_meas, Set.diff_subset _ _, _, hβ.trans_lt hiβ©
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
β’ restrict s A β€ restrict 0 A
[PROOFSTEP]
by_contra hnn
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
hnn : Β¬restrict s A β€ restrict 0 A
β’ False
[PROOFSTEP]
rw [restrict_le_restrict_iff _ _ A_meas] at hnn
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
hnn : Β¬β β¦j : Set Ξ±β¦, MeasurableSet j β j β A β βs j β€ β0 j
β’ False
[PROOFSTEP]
push_neg at hnn
[GOAL]
case pos
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
hnn :
Exists fun β¦jβ¦ =>
MeasurableSet j β§ j β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β§ β0 j < βs j
β’ False
[PROOFSTEP]
obtain β¨E, hEβ, hEβ, hEββ© := hnn
[GOAL]
case pos.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
β’ False
[PROOFSTEP]
have : β k, 1 β€ bdd k β§ 1 / (bdd k : β) < s E :=
by
rw [tendsto_atTop_atTop] at hβ
obtain β¨k, hkβ© := hβ (max (1 / s E + 1) 1)
refine' β¨k, _, _β©
Β· have hle := le_of_max_le_right (hk k le_rfl)
norm_cast at hle
Β· have : 1 / s E < bdd k := by linarith only [le_of_max_le_left (hk k le_rfl)]
rw [one_div] at this β’
rwa [inv_lt (lt_trans (inv_pos.2 hEβ) this) hEβ]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
β’ β k, 1 β€ bdd k β§ 1 / β(bdd k) < βs E
[PROOFSTEP]
rw [tendsto_atTop_atTop] at hβ
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
β’ β k, 1 β€ bdd k β§ 1 / β(bdd k) < βs E
[PROOFSTEP]
obtain β¨k, hkβ© := hβ (max (1 / s E + 1) 1)
[GOAL]
case intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hk : β (a : β), k β€ a β max (1 / βs E + 1) 1 β€ β(bdd a)
β’ β k, 1 β€ bdd k β§ 1 / β(bdd k) < βs E
[PROOFSTEP]
refine' β¨k, _, _β©
[GOAL]
case intro.refine'_1
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hk : β (a : β), k β€ a β max (1 / βs E + 1) 1 β€ β(bdd a)
β’ 1 β€ bdd k
[PROOFSTEP]
have hle := le_of_max_le_right (hk k le_rfl)
[GOAL]
case intro.refine'_1
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hk : β (a : β), k β€ a β max (1 / βs E + 1) 1 β€ β(bdd a)
hle : 1 β€ β(bdd k)
β’ 1 β€ bdd k
[PROOFSTEP]
norm_cast at hle
[GOAL]
case intro.refine'_2
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hk : β (a : β), k β€ a β max (1 / βs E + 1) 1 β€ β(bdd a)
β’ 1 / β(bdd k) < βs E
[PROOFSTEP]
have : 1 / s E < bdd k := by linarith only [le_of_max_le_left (hk k le_rfl)]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hk : β (a : β), k β€ a β max (1 / βs E + 1) 1 β€ β(bdd a)
β’ 1 / βs E < β(bdd k)
[PROOFSTEP]
linarith only [le_of_max_le_left (hk k le_rfl)]
[GOAL]
case intro.refine'_2
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hk : β (a : β), k β€ a β max (1 / βs E + 1) 1 β€ β(bdd a)
this : 1 / βs E < β(bdd k)
β’ 1 / β(bdd k) < βs E
[PROOFSTEP]
rw [one_div] at this β’
[GOAL]
case intro.refine'_2
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : β (b : β), β i, β (a : β), i β€ a β b β€ β(bdd a)
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hk : β (a : β), k β€ a β max (1 / βs E + 1) 1 β€ β(bdd a)
this : (βs E)β»ΒΉ < β(bdd k)
β’ (β(bdd k))β»ΒΉ < βs E
[PROOFSTEP]
rwa [inv_lt (lt_trans (inv_pos.2 hEβ) this) hEβ]
[GOAL]
case pos.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
this : β k, 1 β€ bdd k β§ 1 / β(bdd k) < βs E
β’ False
[PROOFSTEP]
obtain β¨k, hkβ, hkββ© := this
[GOAL]
case pos.intro.intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
β’ False
[PROOFSTEP]
have hA' : A β i \ β l β€ k, restrictNonposSeq s i l :=
by
apply Set.diff_subset_diff_right
intro x; simp only [Set.mem_iUnion]
rintro β¨n, _, hnββ©
exact β¨n, hnββ©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
β’ A β i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
apply Set.diff_subset_diff_right
[GOAL]
case h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
β’ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β
β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
intro x
[GOAL]
case h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
x : Ξ±
β’ x β β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l β
x β β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
[PROOFSTEP]
simp only [Set.mem_iUnion]
[GOAL]
case h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
x : Ξ±
β’ (β i_1 i_2, x β MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1) β
β i_1, x β MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1
[PROOFSTEP]
rintro β¨n, _, hnββ©
[GOAL]
case h.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
x : Ξ±
n : β
wβ : n β€ k
hnβ : x β MeasureTheory.SignedMeasure.restrictNonposSeq s i n
β’ β i_1, x β MeasureTheory.SignedMeasure.restrictNonposSeq s i i_1
[PROOFSTEP]
exact β¨n, hnββ©
[GOAL]
case pos.intro.intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
hA' : A β i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
β’ False
[PROOFSTEP]
refine' findExistsOneDivLT_min (hn' k) (Nat.sub_lt hkβ Nat.zero_lt_one) β¨E, Set.Subset.trans hEβ hA', hEβ, _β©
[GOAL]
case pos.intro.intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
hA' : A β i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
β’ 1 /
(β(MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) -
1) +
1) <
βs E
[PROOFSTEP]
convert hkβ
[GOAL]
case h.e'_3.h.e'_6
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
hA' : A β i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
β’ β(MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) -
1) +
1 =
β(bdd k)
[PROOFSTEP]
norm_cast
[GOAL]
case h.e'_3.h.e'_6
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : βs i < 0
hiβ : MeasurableSet i
h : Β¬restrict s i β€ restrict 0 i
hn :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l < n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
A : Set Ξ± := i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hA : A = i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
bdd : β β β :=
fun n =>
MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (k : β) (_ : k β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i k)
hn' :
β (n : β),
Β¬restrict s (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) β€
restrict 0 (i \ β (l : β) (_ : l β€ n), MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs i = βs A + β' (l : β), βs (MeasureTheory.SignedMeasure.restrictNonposSeq s i l)
hβ : βs A β€ βs i
hβ' : Summable fun n => 1 / (β(bdd n) + 1)
hβ : Tendsto (fun n => β(bdd n) + 1) atTop atTop
hβ : Tendsto (fun n => β(bdd n)) atTop atTop
A_meas : MeasurableSet A
E : Set Ξ±
hEβ : MeasurableSet E
hEβ : E β i \ β (l : β), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
hEβ : β0 E < βs E
k : β
hkβ : 1 β€ bdd k
hkβ : 1 / β(bdd k) < βs E
hA' : A β i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l
β’ MeasureTheory.SignedMeasure.findExistsOneDivLT s
(i \ β (l : β) (_ : l β€ k), MeasureTheory.SignedMeasure.restrictNonposSeq s i l) -
1 +
1 =
bdd k
[PROOFSTEP]
exact tsub_add_cancel_of_le hkβ
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ BddBelow (measureOfNegatives s)
[PROOFSTEP]
simp_rw [BddBelow, Set.Nonempty, mem_lowerBounds]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
β’ β x, β (x_1 : β), x_1 β measureOfNegatives s β x β€ x_1
[PROOFSTEP]
by_contra' h
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
β’ False
[PROOFSTEP]
have h' : β n : β, β y : β, y β s.measureOfNegatives β§ y < -n := fun n => h (-n)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
h' : β (n : β), β y, y β measureOfNegatives s β§ y < -βn
β’ False
[PROOFSTEP]
choose f hf using h'
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
β’ False
[PROOFSTEP]
have hf' : β n : β, β B, MeasurableSet B β§ s β€[B] 0 β§ s B < -n :=
by
intro n
rcases hf n with β¨β¨B, β¨hBβ, hBrβ©, hBββ©, hltβ©
exact β¨B, hBβ, hBr, hBβ.symm βΈ hltβ©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
β’ β (n : β), β B, MeasurableSet B β§ restrict s B β€ restrict 0 B β§ βs B < -βn
[PROOFSTEP]
intro n
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
n : β
β’ β B, MeasurableSet B β§ restrict s B β€ restrict 0 B β§ βs B < -βn
[PROOFSTEP]
rcases hf n with β¨β¨B, β¨hBβ, hBrβ©, hBββ©, hltβ©
[GOAL]
case intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
n : β
hlt : f n < -βn
B : Set Ξ±
hBβ : βs B = f n
hBβ : MeasurableSet B
hBr : restrict s B β€ restrict 0 B
β’ β B, MeasurableSet B β§ restrict s B β€ restrict 0 B β§ βs B < -βn
[PROOFSTEP]
exact β¨B, hBβ, hBr, hBβ.symm βΈ hltβ©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
hf' : β (n : β), β B, MeasurableSet B β§ restrict s B β€ restrict 0 B β§ βs B < -βn
β’ False
[PROOFSTEP]
choose B hmeas hr h_lt using hf'
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
β’ False
[PROOFSTEP]
set A := β n, B n with hA
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
β’ False
[PROOFSTEP]
have hfalse : β n : β, s A β€ -n := by
intro n
refine' le_trans _ (le_of_lt (h_lt _))
rw [hA, β Set.diff_union_of_subset (Set.subset_iUnion _ n), of_union Set.disjoint_sdiff_left _ (hmeas n)]
Β· refine' add_le_of_nonpos_left _
have : s β€[A] 0 := restrict_le_restrict_iUnion _ _ hmeas hr
refine' nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (Set.diff_subset _ _) this)
exact MeasurableSet.iUnion hmeas
Β· exact (MeasurableSet.iUnion hmeas).diff (hmeas n)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
β’ β (n : β), βs A β€ -βn
[PROOFSTEP]
intro n
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
n : β
β’ βs A β€ -βn
[PROOFSTEP]
refine' le_trans _ (le_of_lt (h_lt _))
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
n : β
β’ βs A β€ βs (B n)
[PROOFSTEP]
rw [hA, β Set.diff_union_of_subset (Set.subset_iUnion _ n), of_union Set.disjoint_sdiff_left _ (hmeas n)]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
n : β
β’ βs ((β (i : β), B i) \ B n) + βs (B n) β€ βs (B n)
[PROOFSTEP]
refine' add_le_of_nonpos_left _
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
n : β
β’ βs ((β (i : β), B i) \ B n) β€ 0
[PROOFSTEP]
have : s β€[A] 0 := restrict_le_restrict_iUnion _ _ hmeas hr
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
n : β
this : restrict s A β€ restrict 0 A
β’ βs ((β (i : β), B i) \ B n) β€ 0
[PROOFSTEP]
refine' nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (Set.diff_subset _ _) this)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
n : β
this : restrict s A β€ restrict 0 A
β’ MeasurableSet (β (i : β), B i)
[PROOFSTEP]
exact MeasurableSet.iUnion hmeas
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
n : β
β’ MeasurableSet ((β (i : β), B i) \ B n)
[PROOFSTEP]
exact (MeasurableSet.iUnion hmeas).diff (hmeas n)
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hfalse : β (n : β), βs A β€ -βn
β’ False
[PROOFSTEP]
rcases exists_nat_gt (-s A) with β¨n, hnβ©
[GOAL]
case intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
s : SignedMeasure Ξ±
i j : Set Ξ±
h : β (x : β), β x_1, x_1 β measureOfNegatives s β§ x_1 < x
f : β β β
hf : β (n : β), f n β measureOfNegatives s β§ f n < -βn
B : β β Set Ξ±
hmeas : β (n : β), MeasurableSet (B n)
hr : β (n : β), restrict s (B n) β€ restrict 0 (B n)
h_lt : β (n : β), βs (B n) < -βn
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hfalse : β (n : β), βs A β€ -βn
n : β
hn : -βs A < βn
β’ False
[PROOFSTEP]
exact lt_irrefl _ ((neg_lt.1 hn).trans_le (hfalse n))
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
obtain β¨f, _, hfβ, hfββ© := exists_seq_tendsto_sInf β¨0, @zero_mem_measureOfNegatives _ _ sβ© bddBelow_measureOfNegatives
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
hfβ : β (n : β), f n β measureOfNegatives s
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
choose B hB using hfβ
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
have hBβ : β n, MeasurableSet (B n) := fun n => (hB n).1.1
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
have hBβ : β n, s β€[B n] 0 := fun n => (hB n).1.2
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
set A := β n, B n with hA
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
have hAβ : MeasurableSet A := MeasurableSet.iUnion hBβ
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
have hAβ : s β€[A] 0 := restrict_le_restrict_iUnion _ _ hBβ hBβ
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
have hAβ : s A = sInf s.measureOfNegatives := by
apply le_antisymm
Β· refine' le_of_tendsto_of_tendsto tendsto_const_nhds hfβ (eventually_of_forall fun n => _)
rw [β (hB n).2, hA, β Set.diff_union_of_subset (Set.subset_iUnion _ n), of_union Set.disjoint_sdiff_left _ (hBβ n)]
Β· refine' add_le_of_nonpos_left _
have : s β€[A] 0 :=
restrict_le_restrict_iUnion _ _ hBβ fun m =>
let β¨_, hβ© := (hB m).1
h
refine' nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (Set.diff_subset _ _) this)
exact MeasurableSet.iUnion hBβ
Β· exact (MeasurableSet.iUnion hBβ).diff (hBβ n)
Β· exact csInf_le bddBelow_measureOfNegatives β¨A, β¨hAβ, hAββ©, rflβ©
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
β’ βs A = sInf (measureOfNegatives s)
[PROOFSTEP]
apply le_antisymm
[GOAL]
case a
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
β’ βs A β€ sInf (measureOfNegatives s)
[PROOFSTEP]
refine' le_of_tendsto_of_tendsto tendsto_const_nhds hfβ (eventually_of_forall fun n => _)
[GOAL]
case a
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
n : β
β’ (fun x => βs A) n β€ f n
[PROOFSTEP]
rw [β (hB n).2, hA, β Set.diff_union_of_subset (Set.subset_iUnion _ n), of_union Set.disjoint_sdiff_left _ (hBβ n)]
[GOAL]
case a
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
n : β
β’ (fun x => βs ((β (i : β), B i) \ B n) + βs (B n)) n β€ βs (B n)
[PROOFSTEP]
refine' add_le_of_nonpos_left _
[GOAL]
case a
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
n : β
β’ βs ((β (i : β), B i) \ B n) β€ 0
[PROOFSTEP]
have : s β€[A] 0 :=
restrict_le_restrict_iUnion _ _ hBβ fun m =>
let β¨_, hβ© := (hB m).1
h
[GOAL]
case a
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
n : β
this : restrict s A β€ restrict 0 A
β’ βs ((β (i : β), B i) \ B n) β€ 0
[PROOFSTEP]
refine' nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (Set.diff_subset _ _) this)
[GOAL]
case a
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
n : β
this : restrict s A β€ restrict 0 A
β’ MeasurableSet (β (i : β), B i)
[PROOFSTEP]
exact MeasurableSet.iUnion hBβ
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
n : β
β’ MeasurableSet ((β (i : β), B i) \ B n)
[PROOFSTEP]
exact (MeasurableSet.iUnion hBβ).diff (hBβ n)
[GOAL]
case a
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
β’ sInf (measureOfNegatives s) β€ βs A
[PROOFSTEP]
exact csInf_le bddBelow_measureOfNegatives β¨A, β¨hAβ, hAββ©, rflβ©
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
β’ β i, MeasurableSet i β§ restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
[PROOFSTEP]
refine' β¨AαΆ, hAβ.compl, _, (compl_compl A).symm βΈ hAββ©
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
β’ restrict 0 AαΆ β€ restrict s AαΆ
[PROOFSTEP]
rw [restrict_le_restrict_iff _ _ hAβ.compl]
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
β’ β β¦j : Set Ξ±β¦, MeasurableSet j β j β AαΆ β β0 j β€ βs j
[PROOFSTEP]
intro C _ hCβ
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
β’ β0 C β€ βs C
[PROOFSTEP]
by_contra' hCβ
[GOAL]
case intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
β’ False
[PROOFSTEP]
rcases exists_subset_restrict_nonpos hCβ with β¨D, hDβ, hD, hDβ, hDββ©
[GOAL]
case intro.intro.intro.intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
D : Set Ξ±
hDβ : MeasurableSet D
hD : D β C
hDβ : restrict s D β€ restrict 0 D
hDβ : βs D < 0
β’ False
[PROOFSTEP]
have : s (A βͺ D) < sInf s.measureOfNegatives :=
by
rw [β hAβ, of_union (Set.disjoint_of_subset_right (Set.Subset.trans hD hCβ) disjoint_compl_right) hAβ hDβ]
linarith
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
D : Set Ξ±
hDβ : MeasurableSet D
hD : D β C
hDβ : restrict s D β€ restrict 0 D
hDβ : βs D < 0
β’ βs (A βͺ D) < sInf (measureOfNegatives s)
[PROOFSTEP]
rw [β hAβ, of_union (Set.disjoint_of_subset_right (Set.Subset.trans hD hCβ) disjoint_compl_right) hAβ hDβ]
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
D : Set Ξ±
hDβ : MeasurableSet D
hD : D β C
hDβ : restrict s D β€ restrict 0 D
hDβ : βs D < 0
β’ βs A + βs D < βs A
[PROOFSTEP]
linarith
[GOAL]
case intro.intro.intro.intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
D : Set Ξ±
hDβ : MeasurableSet D
hD : D β C
hDβ : restrict s D β€ restrict 0 D
hDβ : βs D < 0
this : βs (A βͺ D) < sInf (measureOfNegatives s)
β’ False
[PROOFSTEP]
refine' not_le.2 this _
[GOAL]
case intro.intro.intro.intro.intro.intro.intro
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
D : Set Ξ±
hDβ : MeasurableSet D
hD : D β C
hDβ : restrict s D β€ restrict 0 D
hDβ : βs D < 0
this : βs (A βͺ D) < sInf (measureOfNegatives s)
β’ sInf (measureOfNegatives s) β€ βs (A βͺ D)
[PROOFSTEP]
refine' csInf_le bddBelow_measureOfNegatives β¨A βͺ D, β¨_, _β©, rflβ©
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.refine'_1
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
D : Set Ξ±
hDβ : MeasurableSet D
hD : D β C
hDβ : restrict s D β€ restrict 0 D
hDβ : βs D < 0
this : βs (A βͺ D) < sInf (measureOfNegatives s)
β’ MeasurableSet (A βͺ D)
[PROOFSTEP]
exact hAβ.union hDβ
[GOAL]
case intro.intro.intro.intro.intro.intro.intro.refine'_2
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
i j : Set Ξ±
s : SignedMeasure Ξ±
f : β β β
leftβ : Antitone f
hfβ : Tendsto f atTop (nhds (sInf (measureOfNegatives s)))
B : β β Set Ξ±
hB : β (n : β), B n β {B | MeasurableSet B β§ restrict s B β€ restrict 0 B} β§ βs (B n) = f n
hBβ : β (n : β), MeasurableSet (B n)
hBβ : β (n : β), restrict s (B n) β€ restrict 0 (B n)
A : Set Ξ± := β (n : β), B n
hA : A = β (n : β), B n
hAβ : MeasurableSet A
hAβ : restrict s A β€ restrict 0 A
hAβ : βs A = sInf (measureOfNegatives s)
C : Set Ξ±
aβ : MeasurableSet C
hCβ : C β AαΆ
hCβ : βs C < β0 C
D : Set Ξ±
hDβ : MeasurableSet D
hD : D β C
hDβ : restrict s D β€ restrict 0 D
hDβ : βs D < 0
this : βs (A βͺ D) < sInf (measureOfNegatives s)
β’ restrict s (A βͺ D) β€ restrict 0 (A βͺ D)
[PROOFSTEP]
exact restrict_le_restrict_union _ _ hAβ hAβ hDβ hDβ
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
hj' : restrict 0 j β€ restrict s j β§ restrict s jαΆ β€ restrict 0 jαΆ
β’ βs (i β j) = 0 β§ βs (iαΆ β jαΆ) = 0
[PROOFSTEP]
rw [restrict_le_restrict_iff s 0, restrict_le_restrict_iff 0 s] at hi' hj'
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ βs (i β j) = 0 β§ βs (iαΆ β jαΆ) = 0
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet j
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet i
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ restrict s jαΆ β€ restrict 0 jαΆ
β’ MeasurableSet jαΆ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
hj' : restrict 0 j β€ restrict s j β§ restrict s jαΆ β€ restrict 0 jαΆ
β’ MeasurableSet iαΆ
[PROOFSTEP]
constructor
[GOAL]
case left
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ βs (i β j) = 0
[PROOFSTEP]
rw [Set.symmDiff_def, Set.diff_eq_compl_inter, Set.diff_eq_compl_inter, of_union,
le_antisymm (hi'.2 (hi.compl.inter hj) (Set.inter_subset_left _ _))
(hj'.1 (hi.compl.inter hj) (Set.inter_subset_right _ _)),
le_antisymm (hj'.2 (hj.compl.inter hi) (Set.inter_subset_left _ _))
(hi'.1 (hj.compl.inter hi) (Set.inter_subset_right _ _)),
zero_apply, zero_apply, zero_add]
[GOAL]
case left.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ Disjoint (jαΆ β© i) (iαΆ β© j)
[PROOFSTEP]
exact
Set.disjoint_of_subset_left (Set.inter_subset_left _ _)
(Set.disjoint_of_subset_right (Set.inter_subset_right _ _) (disjoint_comm.1 (IsCompl.disjoint isCompl_compl)))
[GOAL]
case left.hA
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet (jαΆ β© i)
[PROOFSTEP]
exact hj.compl.inter hi
[GOAL]
case left.hB
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet (iαΆ β© j)
[PROOFSTEP]
exact hi.compl.inter hj
[GOAL]
case right
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ βs (iαΆ β jαΆ) = 0
[PROOFSTEP]
rw [Set.symmDiff_def, Set.diff_eq_compl_inter, Set.diff_eq_compl_inter, compl_compl, compl_compl, of_union,
le_antisymm (hi'.2 (hj.inter hi.compl) (Set.inter_subset_right _ _))
(hj'.1 (hj.inter hi.compl) (Set.inter_subset_left _ _)),
le_antisymm (hj'.2 (hi.inter hj.compl) (Set.inter_subset_right _ _))
(hi'.1 (hi.inter hj.compl) (Set.inter_subset_left _ _)),
zero_apply, zero_apply, zero_add]
[GOAL]
case right.h
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ Disjoint (j β© iαΆ) (i β© jαΆ)
[PROOFSTEP]
exact
Set.disjoint_of_subset_left (Set.inter_subset_left _ _)
(Set.disjoint_of_subset_right (Set.inter_subset_right _ _) (IsCompl.disjoint isCompl_compl))
[GOAL]
case right.hA
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet (j β© iαΆ)
[PROOFSTEP]
exact hj.inter hi.compl
[GOAL]
case right.hB
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' :
(β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β j β β0 j_1 β€ βs j_1) β§
β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet (i β© jαΆ)
[PROOFSTEP]
exact hi.inter hj.compl
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet j
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet i
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ restrict s jαΆ β€ restrict 0 jαΆ
β’ MeasurableSet jαΆ
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
hj' : restrict 0 j β€ restrict s j β§ restrict s jαΆ β€ restrict 0 jαΆ
β’ MeasurableSet iαΆ
[PROOFSTEP]
all_goals measurability
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : (β β¦j : Set Ξ±β¦, MeasurableSet j β j β i β β0 j β€ βs j) β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet j
[PROOFSTEP]
measurability
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ β β¦j_1 : Set Ξ±β¦, MeasurableSet j_1 β j_1 β jαΆ β βs j_1 β€ β0 j_1
β’ MeasurableSet i
[PROOFSTEP]
measurability
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ β β¦j : Set Ξ±β¦, MeasurableSet j β j β iαΆ β βs j β€ β0 j
hj' : restrict 0 j β€ restrict s j β§ restrict s jαΆ β€ restrict 0 jαΆ
β’ MeasurableSet jαΆ
[PROOFSTEP]
measurability
[GOAL]
Ξ± : Type u_1
Ξ² : Type u_2
instβΒ³ : MeasurableSpace Ξ±
M : Type u_3
instβΒ² : AddCommMonoid M
instβΒΉ : TopologicalSpace M
instβ : OrderedAddCommMonoid M
sβ : SignedMeasure Ξ±
iβ jβ : Set Ξ±
s : SignedMeasure Ξ±
i j : Set Ξ±
hi : MeasurableSet i
hj : MeasurableSet j
hi' : restrict 0 i β€ restrict s i β§ restrict s iαΆ β€ restrict 0 iαΆ
hj' : restrict 0 j β€ restrict s j β§ restrict s jαΆ β€ restrict 0 jαΆ
β’ MeasurableSet iαΆ
[PROOFSTEP]
measurability
|
module Control.Optics.Prism
import public Control.Optics.Types
export
prism : (b -> t) -> (s -> Either t a) -> Prism s t a b
prism inj prj = dimap prj (either pure (map inj)) . right'
|
------------------------------------------------------------------------
-- Some auxiliary operations and lemmas
------------------------------------------------------------------------
module BreadthFirst.Lemmas where
open import Codata.Musical.Notation
open import Codata.Musical.Colist as Colist
using (Colist; []; _β·_; concat; _++_)
open import Function
open import Data.List using ([]; _β·_)
open import Data.List.NonEmpty as ListβΊ using (ListβΊ; [_]; _β·_; _βΊ++βΊ_)
import Data.Vec as Vec
open import Data.Product using (_,_)
open import Relation.Binary.PropositionalEquality as PropEq
using (_β‘_) renaming (refl to β‘-refl)
open import BreadthFirst.Universe
open import BreadthFirst.Programs
open import Tree using (leaf; node; map)
open import Stream using (Stream; _βΊ_) renaming (_++_ to _++β_)
------------------------------------------------------------------------
-- Some operations
zipWith : {A B : Set} (f : A β B β B) β Colist A β Stream B β Stream B
zipWith f [] ys = ys
zipWith f (x β· xs) (y βΊ ys) = f x y βΊ β― zipWith f (β xs) (β ys)
infixr 5 _βΊ++_ _βΊ++β_
_βΊ++β_ : {A : Set} β ListβΊ A β Stream A β Stream A
xs βΊ++β ys = Colist.fromList (Vec.toList $ ListβΊ.toVec xs) ++β ys
_βΊ++_ : {A : Set} β ListβΊ A β Colist A β Colist A
xs βΊ++ ys = Colist.fromList (Vec.toList $ ListβΊ.toVec xs) ++ ys
------------------------------------------------------------------------
-- Eq is an equivalence relation
refl : β {a} x β Eq a x x
refl {a = tree a} leaf = leaf
refl {a = tree a} (node l x r) = node (β― refl (β l)) (refl x) (β― refl (β r))
refl {a = stream a} (x βΊ xs) = refl x βΊ β― refl (β xs)
refl {a = colist a} [] = []
refl {a = colist a} (x β· xs) = refl x β· β― refl (β xs)
refl {a = a β b} (x , y) = (refl x , refl y)
refl {a = β A β} x = β PropEq.refl β
sym : β {a x y} β Eq a x y β Eq a y x
sym {a = tree a} leaf = leaf
sym {a = tree a} (node lβlβ² xβxβ² rβrβ²) = node (β― sym (β lβlβ²)) (sym xβxβ²) (β― sym (β rβrβ²))
sym {a = stream a} (xβxβ² βΊ xsβxsβ²) = sym xβxβ² βΊ β― sym (β xsβxsβ²)
sym {a = colist a} [] = []
sym {a = colist a} (xβxβ² β· xsβxsβ²) = sym xβxβ² β· β― sym (β xsβxsβ²)
sym {a = a β b} (xβxβ² , yβyβ²) = (sym xβxβ² , sym yβyβ²)
sym {a = β A β} β xβ‘xβ² β = β PropEq.sym xβ‘xβ² β
trans : β {a x y z} β Eq a x y β Eq a y z β Eq a x z
trans {a = tree a} leaf leaf = leaf
trans {a = tree a} (node lβlβ² xβxβ² rβrβ²)
(node lβ²βlβ³ xβ²βxβ³ rβ²βrβ³) = node (β― trans (β lβlβ²) (β lβ²βlβ³))
(trans xβxβ² xβ²βxβ³)
(β― trans (β rβrβ²) (β rβ²βrβ³))
trans {a = stream a} (xβxβ² βΊ xsβxsβ²)
(xβ²βxβ³ βΊ xsβ²βxsβ³) = trans xβxβ² xβ²βxβ³ βΊ β― trans (β xsβxsβ²) (β xsβ²βxsβ³)
trans {a = colist a} [] [] = []
trans {a = colist a} (xβxβ² β· xsβxsβ²)
(xβ²βxβ³ β· xsβ²βxsβ³) = trans xβxβ² xβ²βxβ³ β· β― trans (β xsβxsβ²) (β xsβ²βxsβ³)
trans {a = a β b} (xβxβ² , yβyβ²)
(xβ²βxβ³ , yβ²βyβ³) = (trans xβxβ² xβ²βxβ³ , trans yβyβ² yβ²βyβ³)
trans {a = β A β} β xβ‘xβ² β β xβ²β‘xβ³ β = β PropEq.trans xβ‘xβ² xβ²β‘xβ³ β
------------------------------------------------------------------------
-- Productivity checker workaround for Eq
infixr 5 _βΊ_ _β·_
infixr 4 _,_
infix 3 _β
infixr 2 _ββ¨_β©_ _ββ¨_β©_
data EqP : β a β El a β El a β Setβ where
leaf : β {a} β EqP (tree a) leaf leaf
node : β {a x xβ² l lβ² r rβ²}
(lβlβ² : β (EqP (tree a) (β l) (β lβ²)))
(xβxβ² : Eq a x xβ² )
(rβrβ² : β (EqP (tree a) (β r) (β rβ²))) β
EqP (tree a) (node l x r) (node lβ² xβ² rβ²)
_βΊ_ : β {a x xβ² xs xsβ²}
(xβxβ² : Eq a x xβ² )
(xsβxsβ² : β (EqP (stream a) (β xs) (β xsβ²))) β
EqP (stream a) (x βΊ xs) (xβ² βΊ xsβ²)
[] : β {a} β EqP (colist a) [] []
_β·_ : β {a x xβ² xs xsβ²}
(xβxβ² : Eq a x xβ² )
(xsβxsβ² : β (EqP (colist a) (β xs) (β xsβ²))) β
EqP (colist a) (x β· xs) (xβ² β· xsβ²)
_,_ : β {a b x xβ² y yβ²}
(xβxβ² : Eq a x xβ²) (yβyβ² : Eq b y yβ²) β
EqP (a β b) (x , y) (xβ² , yβ²)
β_β : β {A x xβ²} (xβ‘xβ² : x β‘ xβ²) β EqP β A β x xβ²
_ββ¨_β©_ : β {a} x {y z}
(xβy : EqP a x y) (yβz : EqP a y z) β EqP a x z
zipWith-cong :
β {a b} {f : El a β El b β El b}
(cong : β {x xβ² y yβ²} β
Eq a x xβ² β Eq b y yβ² β Eq b (f x y) (f xβ² yβ²))
{xs xsβ² ys ysβ²}
(xsβxsβ² : EqP (colist a) xs xsβ²)
(ysβysβ² : EqP (stream b) ys ysβ²) β
EqP (stream b) (zipWith f xs ys) (zipWith f xsβ² ysβ²)
data EqW : β a β El a β El a β Setβ where
leaf : β {a} β EqW (tree a) leaf leaf
node : β {a x xβ² l lβ² r rβ²}
(lβlβ² : EqP (tree a) (β l) (β lβ²))
(xβxβ² : Eq a x xβ² )
(rβrβ² : EqP (tree a) (β r) (β rβ²)) β
EqW (tree a) (node l x r) (node lβ² xβ² rβ²)
_βΊ_ : β {a x xβ² xs xsβ²}
(xβxβ² : Eq a x xβ² )
(xsβxsβ² : EqP (stream a) (β xs) (β xsβ²)) β
EqW (stream a) (x βΊ xs) (xβ² βΊ xsβ²)
[] : β {a} β EqW (colist a) [] []
_β·_ : β {a x xβ² xs xsβ²}
(xβxβ² : Eq a x xβ² )
(xsβxsβ² : EqP (colist a) (β xs) (β xsβ²)) β
EqW (colist a) (x β· xs) (xβ² β· xsβ²)
_,_ : β {a b x xβ² y yβ²}
(xβxβ² : Eq a x xβ²) (yβyβ² : Eq b y yβ²) β
EqW (a β b) (x , y) (xβ² , yβ²)
β_β : β {A x xβ²} (xβ‘xβ² : x β‘ xβ²) β EqW β A β x xβ²
β¦_β§ββ»ΒΉ : β {a} {x y : El a} β Eq a x y β EqP a x y
β¦ leaf β§ββ»ΒΉ = leaf
β¦ node lβlβ² xβxβ² rβrβ² β§ββ»ΒΉ = node (β― β¦ β lβlβ² β§ββ»ΒΉ) xβxβ² (β― β¦ β rβrβ² β§ββ»ΒΉ)
β¦ xβxβ² βΊ xsβxsβ² β§ββ»ΒΉ = xβxβ² βΊ β― β¦ β xsβxsβ² β§ββ»ΒΉ
β¦ [] β§ββ»ΒΉ = []
β¦ xβxβ² β· xsβxsβ² β§ββ»ΒΉ = xβxβ² β· β― β¦ β xsβxsβ² β§ββ»ΒΉ
β¦ (xβxβ² , yβyβ²) β§ββ»ΒΉ = (xβxβ² , yβyβ²)
β¦ β xβ‘xβ² β β§ββ»ΒΉ = β xβ‘xβ² β
whnfβ : β {a xs ys} β EqP a xs ys β EqW a xs ys
whnfβ leaf = leaf
whnfβ (node lβlβ² xβxβ² rβrβ²) = node (β lβlβ²) xβxβ² (β rβrβ²)
whnfβ (xβxβ² βΊ xsβxsβ²) = xβxβ² βΊ β xsβxsβ²
whnfβ [] = []
whnfβ (xβxβ² β· xsβxsβ²) = xβxβ² β· β xsβxsβ²
whnfβ (xβxβ² , yβyβ²) = (xβxβ² , yβyβ²)
whnfβ β xβ‘xβ² β = β xβ‘xβ² β
whnfβ ( _ ββ¨ xβy β© yβz) with whnfβ xβy | whnfβ yβz
whnfβ (._ ββ¨ xβy β© yβz) | leaf | leaf = leaf
whnfβ (._ ββ¨ xβy β© yβz) | node lβlβ² xβxβ² rβrβ²
| node lβ²βlβ³ xβ²βxβ³ rβ²βrβ³ = node (_ ββ¨ lβlβ² β© lβ²βlβ³) (trans xβxβ² xβ²βxβ³) (_ ββ¨ rβrβ² β© rβ²βrβ³)
whnfβ (._ ββ¨ xβy β© yβz) | [] | [] = []
whnfβ (._ ββ¨ xβy β© yβz) | xβyβ² β· xsβysβ² | yβzβ² β· ysβzsβ² = trans xβyβ² yβzβ² β· (_ ββ¨ xsβysβ² β© ysβzsβ²)
whnfβ (._ ββ¨ xβy β© yβz) | xβyβ² βΊ xsβysβ² | yβzβ² βΊ ysβzsβ² = trans xβyβ² yβzβ² βΊ (_ ββ¨ xsβysβ² β© ysβzsβ²)
whnfβ (._ ββ¨ xβy β© yβz) | (xβxβ² , yβyβ²) | (xβ²βxβ³ , yβ²βyβ³) = (trans xβxβ² xβ²βxβ³ , trans yβyβ² yβ²βyβ³)
whnfβ ( _ ββ¨ xβy β© yβz) | β xβ‘xβ² β | β xβ²β‘xβ³ β = β PropEq.trans xβ‘xβ² xβ²β‘xβ³ β
whnfβ (zipWith-cong cong xsβxsβ² ysβysβ²) with whnfβ xsβxsβ² | whnfβ ysβysβ²
... | [] | ysβysβ³ = ysβysβ³
... | xβxβ² β· xsβxsβ³ | yβyβ² βΊ ysβysβ³ =
cong xβxβ² yβyβ² βΊ zipWith-cong cong xsβxsβ³ ysβysβ³
mutual
valueβ : β {a xs ys} β EqW a xs ys β Eq a xs ys
valueβ leaf = leaf
valueβ (node lβlβ² xβxβ² rβrβ²) = node (β― β¦ lβlβ² β§β) xβxβ² (β― β¦ rβrβ² β§β)
valueβ (xβxβ² βΊ xsβxsβ²) = xβxβ² βΊ β― β¦ xsβxsβ² β§β
valueβ [] = []
valueβ (xβxβ² β· xsβxsβ²) = xβxβ² β· β― β¦ xsβxsβ² β§β
valueβ (xβxβ² , yβyβ²) = (xβxβ² , yβyβ²)
valueβ β xβ‘xβ² β = β xβ‘xβ² β
β¦_β§β : β {a xs ys} β EqP a xs ys β Eq a xs ys
β¦ xsβys β§β = valueβ (whnfβ xsβys)
_ββ¨_β©_ : β {a} x {y z}
(xβy : Eq a x y) (yβz : EqP a y z) β EqP a x z
x ββ¨ xβy β© yβz = x ββ¨ β¦ xβy β§ββ»ΒΉ β© yβz
_β : β {a} x β EqP a x x
x β = β¦ refl x β§ββ»ΒΉ
------------------------------------------------------------------------
-- Productivity checker workaround for PrefixOf
infixr 2 _ββ¨_β©_ _ββ¨_β©_
data PrefixOfP (a : U) :
Colist (El a) β Stream (El a) β Setβ where
[] : β {ys} β PrefixOfP a [] ys
βΊ++-mono : β xs {ys ysβ²} (ysβysβ² : β (PrefixOfP a ys ysβ²)) β
PrefixOfP a (xs βΊ++ ys) (xs βΊ++β ysβ²)
_ββ¨_β©_ : β xs {ys zs} (xsβys : Eq (colist a) xs ys)
(ysβzs : PrefixOfP a ys zs) β PrefixOfP a xs zs
_ββ¨_β©_ : β xs {ys zs} (xsβys : PrefixOfP a xs ys)
(ysβzs : EqP (stream a) ys zs) β PrefixOfP a xs zs
data PrefixOfW (a : U) :
Colist (El a) β Stream (El a) β Setβ where
[] : β {ys} β PrefixOfW a [] ys
_β·_ : β {x y xs ys}
(xβy : Eq a x y) (p : PrefixOfP a (β xs) (β ys)) β
PrefixOfW a (x β· xs) (y βΊ ys)
whnfβ : β {a xs ys} β
PrefixOfP a xs ys β PrefixOfW a xs ys
whnfβ [] = []
whnfβ (βΊ++-mono (x β· []) ysβysβ²) = refl x β· β ysβysβ²
whnfβ (βΊ++-mono (x β· (xβ² β· xs)) ysβysβ²) =
refl x β· βΊ++-mono (xβ² β· xs) ysβysβ²
whnfβ (._ ββ¨ [] β© _ ) = []
whnfβ (._ ββ¨ xβy β· xsβys β© ysβzs) with whnfβ ysβzs
... | yβz β· ysβzsβ² = trans xβy yβz β· (_ ββ¨ β xsβys β© ysβzsβ²)
whnfβ (._ ββ¨ xsβys β© ysβzs) with whnfβ xsβys | whnfβ ysβzs
... | [] | _ = []
... | xβy β· xsβysβ² | yβz βΊ ysβzsβ² = trans xβy yβz β· (_ ββ¨ xsβysβ² β© ysβzsβ²)
mutual
valueβ : β {a xs ys} β PrefixOfW a xs ys β PrefixOf a xs ys
valueβ [] = []
valueβ (xβy β· xsβys) = xβy β· β― β¦ xsβys β§β
β¦_β§β : β {a xs ys} β PrefixOfP a xs ys β PrefixOf a xs ys
β¦ xsβys β§β = valueβ (whnfβ xsβys)
------------------------------------------------------------------------
-- More lemmas
βΊ++β-cong : β {a xs xsβ² ys ysβ²} β
Eq β ListβΊ (El a) β xs xsβ² β
Eq (stream a) ys ysβ² β
Eq (stream a) (xs βΊ++β ys) (xsβ² βΊ++β ysβ²)
βΊ++β-cong {xs = x β· []} β β‘-refl β ysβysβ² = refl x βΊ β― ysβysβ²
βΊ++β-cong {xs = x β· (xβ² β· xs)} β β‘-refl β ysβysβ² =
refl x βΊ β― βΊ++β-cong {xs = xβ² β· xs} β β‘-refl β ysβysβ²
++-assoc : β {a} xs ys zs β
Eq (stream a) (xs βΊ++β (ys βΊ++β zs)) ((xs βΊ++βΊ ys) βΊ++β zs)
++-assoc (x β· []) ys zs = refl x βΊ β― refl (ys βΊ++β zs)
++-assoc (x β· (xβ² β· xs)) ys zs = refl x βΊ β― ++-assoc (xβ² β· xs) ys zs
zip-++-assoc : β {a} xss yss (zss : Stream (Stream (El a))) β
Eq (stream (stream a))
(zipWith _βΊ++β_ β¦ xss β§ (zipWith _βΊ++β_ β¦ yss β§ zss))
(zipWith _βΊ++β_ β¦ longZipWith _βΊ++βΊ_ xss yss β§ zss)
zip-++-assoc xss yss (zs βΊ zss) with whnf xss | whnf yss
... | [] | [] = refl _
... | [] | ys β· yssβ² = refl _
... | xs β· xssβ² | [] = refl _
... | β xs β β· xssβ² | β ys β β· yssβ² =
++-assoc xs ys zs βΊ β― zip-++-assoc (β xssβ²) (β yssβ²) (β zss)
concat-lemma : β {a} xs xss β
Eq (colist a) (concat (xs β· xss))
(xs βΊ++ concat (β xss))
concat-lemma (x β· []) xss = refl x β· β― refl (concat (β xss))
concat-lemma (x β· (xβ² β· xs)) xss = refl x β· β― concat-lemma (xβ² β· xs) xss
|
> module Unique.Predicates -- from an idea by Tim Richter
> %default total
> %access public export
> %auto_implicits off
> Unique : Type -> Type
> Unique t = (p : t) -> (q : t) -> p = q
> Unique0 : Type -> Type
> Unique0 = Unique
> Unique1 : {A : Type} -> (A -> Type) -> Type
> Unique1 {A} P = (a : A) -> Unique0 (P a)
> UniqueEq0 : Type -> Type
> UniqueEq0 A = (a1 : A) -> (a2 : A) -> Unique (a1 = a2)
> UniqueEq1 : {A : Type} -> (P : A -> Type) -> Type
> UniqueEq1 {A} P = (a : A) -> UniqueEq0 (P a)
> {- Maybe implement via a type class ?
> class Unique t where
> unique : (p : t) -> (q : t) -> p = q
> -}
|
module Algoritmo where
import Prelude as P
import Data.Complex
import Control.Monad.State
import Numeric.Statistics (percentile)
import Numeric.LinearAlgebra
import Data.Vector.Storable as VS hiding (modify, null)
import FFT
import ArrayPoking
import Bases
type L2 = Vector (Complex Double)
type Dim = Int
type Niveles = Int
secAnalitica :: Niveles -> L2 -> State [L2] ()
secAnalitica n zF =
do let dim = VS.length zF
uF = conj . fft $ haarU dim
vF = conj . fft $ haarV dim
x1 = downSampF (zF * vF) dim
y1 = downSampF (zF * uF) dim
-- [y3, x3, x2, x1]
-- modify (x1 :)
if n <= 1
-- Haz nada, este es el ultimo nivel
then modify (zF :)
--
else modify (x1 :) >> secAnalitica (n - 1) y1
secSintetica :: Niveles -> State [L2] L2
secSintetica n =
do y2 : x2 : rest <- get
let dim = VS.length y2
dim_n = dim * 2
x2' = upSampF x2 dim
y2' = upSampF y2 dim
y1 = x2' * (fft (haarV dim_n)) +
y2' * (fft (haarU dim_n))
put (y1 : rest)
if null rest || n <= 1
then return y1
else secSintetica (n - 1)
{-
Idea: Mantener los @k terminos mayores y lo demas setearlos a 0. Es
molesto contar, asi que veremos un porcentaje.
rate = 90.0, es decir 90% de calidad, debo de matar 10% de los
candidatos.
-}
compresion :: Double -> State [L2] ()
compresion rate =
do vec <- get
let cut = percentile (100 - rate) . sortIP
. cmap magnitude $ VS.concat vec
go c = if magnitude c < cut then 0 else c
put $ P.map (VS.map go) vec
waveletAlgo :: Double -> Niveles -> Niveles -> L2 -> L2
waveletAlgo calidad div recon color = evalState go []
where
go :: State [L2] L2
go = return (fft color)
>>= secAnalitica div
-- >> modify (P.map ifft)
>> compresion calidad
-- >> modify (P.map fft)
>> secSintetica recon
>>= return . ifft
|
\section{MODULE DESIGN}
\subsection{DATA PREPROCESSING}
JPEG uses a lossy image compression. Each re-encoding process (new saving) performed on the image leads to further loss of quality. The JPEG algorithm is based on a 8x8 pixel grid. Each 8x8 square grid is thereby treated and compressed separately. If the image is untouched, then all these 8x8 squares will show the same error level potential.
\subsubsection{Algorithm:}
\begin{enumerate}
\item The image is resaved with 95\%(or 90\%)JPEG quality.
\item Compare each(8*8) blocks of corresponding original and new resaved image.
\item If image is unmodified, then all 8 x8 squares should have similar error potentials.
\item Else modified areas will appear with a higher potential error level.
\end{enumerate}
INPUT \ \ \ \ : Tampered image
OUTPUT : The output of ELA is image with higher error potential.
\subsection{TRAINING THE CNN}
\begin{figure}[htp]
\centering
\includegraphics[scale=0.5,width=17cm]{Figures/cnn.PNG}
\caption{Training the model}
\label{fig:universe}
\end{figure}
The training process of a CNN is done through an iterative algorithm that alternates between feedforward and back propagation passes of the data. The weights of the convolutional filters and fully-connected layers are updated at each iteration of the backpropagation passes. CNN is capable of learning classification features directly from the data. The ReLU activation function is applied to each value in the feature maps of every convolutional layer. The convolutional layers are followed by the max pooling layers. We use a batch normalization layer after each regular convolutional layer. However, the prediction error convolutional filters outputs are directly convolved with the next convolutional layer without using the batch normalization layer. We consider the RMSProp optimizer to train our model. This module is proposed to extract features related to the traces left by different editing operations, and which are utilized to check the authenticity of images.
INPUT \ \ \ \ : The pre-processed images.
OUTPUT : The trained classifier to detect the tampered images.
\subsubsection{Algorithm:}
1. Initialize w_k 's\ using \ randomly\ drawn\ weights.
2. Assign i=1
3. While i \leq maximum\_iteration \ do
4. Feedforward pass.
5. Update filter weights and backpropagate errors.
6. Set w_k(0, 0)^(^1^) = 0 for \ all \ K \ filters
7. Normalize w_k^(^1^) βs \ such \ that \ \Sigma_l_,_m_ \neq _0 w_k^(^1^) (l, m) = 1
8. Set w_k(0, 0)^(^1^) = - 1 \ for \ all \ K \ filters
9. i = i + 1
10. If training accuracy converges then
11. exit
12. end
\newpage
\subsubsection{RMSPROP OPTIMISER }
The RMSprop optimizer is similar to the gradient descent algorithm with momentum. The RMSprop optimizer restricts the oscillations in the vertical direction. Therefore, we can increase our learning rate and our algorithm could take larger steps in the horizontal direction converging faster.
vdw =\beta. vdw + (1- \beta).dw2
where \beta \ is \ a \ momentum \ in \ learning \ rate
vdb = \beta. vdw + (1- \beta).db2
W = W -\alpha dw/(\sqrt(v\_db )+β)
where W are weights to be updated during the back propagation and \alpha \ is \ a \ value \ always \textless 1.
b = b - \alpha dw/(\sqrt(v\_db )+\epsilon)
where b is the calculated gradient of the system while learning and \epsilon \ is\ a \ small \ value \ added \ to \ prevent \ gradient \ from \ blowing \ up.
\subsubsection{CROSS ENTROPY LOSS FUNCTION}
Cross Entropy is commonly-used in binary classification (labels are assumed to take values 0 or 1) as a loss function (For multi-classification, use Multiclass Cross Entropy), which is computed by
L=-1/n \Sigma_(i_=_1)^n [\ (\ y^(^i^) log(\ \^y^i)\ +(\ 1-y^i)log(\ 1-\^y^i) ]\
Where L is a loss calculated which is the difference between the actual and the predicted output.
Cross entropy measures the divergence between two probability distribution, if the cross entropy is large, which means that the difference between two distribution is large, while if the cross entropy is small, which means that two distribution is similar to each other. When the difference between predicted value and actual value is large, the learning speed, i.e., convergence speed, is fast, otherwise, the difference is small, the learning speed is small. Cross entropy cost function has the advantages of fast convergence and is more likely to reach the global optimization.
\subsection{CLASSIFICATION BLOCK}
\begin{figure}[htp]
\centering
\includegraphics[scale=0.5,width=10cm]{Figures/soft.PNG}
\caption{Classification}
\label{fig:universe}
\end{figure}
This first layer of the classification block contains about 256 nodes and accepts input as vectors. This layer uses ReLU activation function where negative values will not be considered significant hence makes it more efficient. To give the accurate result the last layer in the classification block of the neural network uses the softmax activation function which gives the highest activation level. The CNN model extracts the feature and classifies the pre-processed forged image to detect whether the given image is spiced or not.
\subsection{COPY MOVE TYPE DETECTION}
A copy move attack is commonly used to conceal parts of an image or to remove unwanted portions in an image. A portion from the picture is copied and pasted over any unwanted portion in the same image.
This block is where the image that is not detected to be spliced is checked for copy move forgery using the following steps:
\begin{enumerate}
\item Blur image for eliminating image details.
\item Convert image to degraded palette.
\item Decompose the image into small NxN pixel blocks.
\item Alphabetically order these blocks by their pixel values.
\item Extract only these adjacent blocks which have small absolute color difference.
\item Cluster these blocks into clusters by intersection area among blocks.
\item Extract only these clusters which are bigger than block size.
\item Extract only these clusters which have similar cluster, by using some sort of similarity function (in this case Hausdorff distance between clusters).
\item Draw discovered similar clusters on image.
\end{enumerate}
\section{COMPLEXITY ANALYSIS}
\subsection{COMPLEXITY OF THE PROJECT}
\begin{itemize}
\item The complexity of the project lies in determining the passive type of forgery the image has undergone rather than just determining if the image is only forged or not. The neural network is used to detect the spliced images.
\item The accuracy of the neural network also affects the efο¬ciency of the output. Hence efficient loss function and optimiser with the appropriate parameters needs to be chosen.
\item Certain additional hints need to be added to the images in order to efficiently detect the tampered regions in the images. Error Level Analysis is used for this purpose. This analysis is made to all images irrespective of their formats and error potential.
\item Determining the identical regions in a copy move image is done by the extraction of similar properties between those regions for which efficient similarity functions has to be used.
\item The identification of copy move image is done without any comparison with the original image but rather the input image itself which makes it a tedious task to implement.
\end{itemize} |
# Algorith for Titanic Challenge |
When a tractor doesnβt start, troubleshooting should begin with an examination of the Kubota safety switches. Owners sometimes report intermittent starting issues that are traced back to one of the switches.
Although a Kubota safety switch is an integral part of the tractorβs design, it is suddenly an issue when it prevents a tractor from operating. Every manufacturer faces the dilemma of how to keep riders safe while not inconveniencing them with excessive switch activations.
An efficient diagnosis of the problem saves time and helps get your machine back to being productive.
Learn more about Kubota tractor safety switch locations from your authorized Kubota dealer in Houston, Bobby Ford Tractor & Equipment.
On most Kubota tractors, making an adjustment or replacing a defective safety switch is quite manageable.
When a tractor doesnβt start because of unwanted switch activation, it may be necessary to eliminate each switch as the possible culprit systematically. Sometimes the switch and its wiring are okay. On several Kubota tractors, merely adjusting seat tension will minimize unwanted switch activations.
Here are a few examples of Kubota safety switch issues that could be slowing you down.
There are multiple switches on the Kubota B7800, including seat, PTO, rocker pedal and transmission switches. If a single safety switch is not in neutral, the tractor will not start.
Sometimes, a switch is very close to moving in and out of neutral β so much so that you will experience intermittent starts. To identify which switch is the problem, clean them by blowing them out with compressed air. First, jump the seat switch to remove it from the circuit, then proceed through a process of elimination.
Locations of safety switches vary from model to model. For example, on the Kubota B7800, the clutch safety switch is under the left floorboard. A tab of the clutch pedal operates it.
The most prominent safety switch on many Kubota tractors is located right under the seat. To troubleshoot Kubota safety switch issues, it is often necessary to check both the switches and the wiring.
For example, on an L3940, two wires run from the seat frame to the exposed switch. Also, another set of wires run into the seat bottom.
On an L3200 HST, one owner with a starting issue rocked the foot pedal back and forth. When it would just not start, he used an ohm meter to confirm the safety switch on the clutch was functional. He then went on to troubleshoot other safety switches on the tractor.
With this and other models, you want to confirm that the interlock switches for the PTO, seat and cruise control are all cleaned, adjusted and operational.
Sometimes, sensitivity issues require adjustments to improve switch engagement. For example, on a BX2360, the sensitivity of the safety switch on the PTO lever is addressed by bending the tab for better contact.
On sidehill jobs, it is essential to use the seatbelt to avoid lifting from the seat long enough to activate the safety switch.
Finally, there have been reports of other brands switching off when a relatively light individual hits a big bump that momentarily lifts the rider off the seat. However, lighter-weight Kubota operators have weighed in on this issue (pardon the pun) without reporting unwanted switch-off problems.
If you suspect you have a safety switch problem, or your Kubota tractor will not start for any reason, the Kubota tractor mechanics at Bobby Ford Tractor and Equipment can help.
When you are looking for Kubota Tractors in Houston, look to Bobby Ford Tractor and Equipment for prompt, professional and knowledgeable assistance. Contact us today! |
module Scene.Material.Skylike where
import Numeric.LinearAlgebra
import Scene.Base
import Math.Color
import Math.Ray
import Scene.Monad
import Control.Applicative
import Control.Monad.Random
skylike :: Color -> Color -> Material
skylike near far (Ray p normal) (Ray q incidence) = do
let t = abs $ (normal <.> incidence)/(norm_2 normal * norm_2 incidence)
return $! weigh [(t,near),(1-t,far)] |
From Coq Require
Extraction.
From Coq Require Import
ZArith.ZArith.
From DEZ.Offers Require Export
OneSortedIntegerOperations.
From DEZ.Provides Require Export
ZTheorems PolynomialTheorems.
From DEZ.ShouldOffer Require Import
OneSortedArithmeticNotations OneSortedArithmeticOperationNotations.
(** It may not be a good idea to expand all types,
but it does make exploring the extracted code less tedious. *)
Set Extraction TypeExpand.
Extraction Language OCaml.
Cd "gen-ocaml".
Extraction Blacklist Nat.
Recursive Extraction Library ZTheorems.
Recursive Extraction Library PolynomialTheorems.
|
# plotting functions of manifold beliefs
using .Gadfly
using .Colors
export plotCircBeliefs, plotKDECircular
# import ApproxManifoldProducts: plotCircBeliefs, plotKDECircular
function plotCircBeliefs(arr::V;
N::Int=1000,
th = range(-pi, stop=pi-1e-15, length=N),
c=["green"; "blue"; "deepskyblue"; "magenta"; "cyan"],
logpdf::Bool=true,
rVo::Vector{Float64}=[0.0;0.0;0.0],
radix::Float64=1.0,
text::String="",
title::String="",
legend=nothing ) where {V <: Vector}
#
c = ["black";c]
beliefs = Dict{Int, Function}()
beliefs[1] = (x)->1.0
j = 1
# TODO should be passing in addop, and diffop
for ar in arr
j += 1
beliefs[j] = logpdf ? (x)->log(ar(x)+1.0) : (x)->ar(x) #
end
PL = []
# TODO loosing some modes in plotting???
for j in 1:length(beliefs)
obj = zeros(N)
X = zeros(N)
Y = zeros(N)
for i in 1:N
t = th[i]
obj[i] = radix*beliefs[1](t) # = 1.0
obj[i] += (j != 1 ? beliefs[j](t) : 0.0)
# second term directional statistics for plotting (not evaluation)
obj[i] += (j != 1 ? beliefs[j](t-2pi) : 0.0 )
obj[i] += (j != 1 ? beliefs[j](t+2pi) : 0.0 )
xy = TransformUtils.R(rVo[3])*[cos(t)*obj[i]; sin(t)*obj[i]]
X[i] = xy[1] + rVo[1]
Y[i] = xy[2] + rVo[2]
end
push!(PL, Gadfly.layer(x=deepcopy(X), y=deepcopy(Y), label=[text;], Gadfly.Geom.path, Gadfly.Theme(default_color=parse(Colorant,c[j])), Geom.label )[1] )
end
push!(PL, Coord.cartesian(aspect_ratio=1.0))
push!(PL, Guide.title(title))
if legend != nothing
push!(PL, Guide.manual_color_key("Legend", legend, c[2:end]))
end
Gadfly.plot(PL...)
end
function plotKDECircular(bds::Vector{BallTreeDensity};
c=["green"; "blue"; "deepskyblue"; "magenta"; "cyan"],
logpdf::Bool=true,
scale::Float64=0.2,
offset::Float64=0.0,
rVo::Vector{Float64}=[0.0;0.0;0.0],
radix::Float64=1.0,
text::String="",
title::String="",
legend=nothing )
arr = []
for bd in bds
gg = (x::Float64)->scale*bd([x;], false, 1e-3, (addtheta,), (difftheta,))[1]
push!(arr, gg)
end
return plotCircBeliefs(arr, c=c, logpdf=logpdf, rVo=rVo, radix=radix, text=text, title=title, legend=legend )
end
function plotKDECircular(bd::BallTreeDensity;
c=["green";],
logpdf::Bool=true,
scale::Float64=0.2,
rVo::Vector{Float64}=[0.0;0.0;0.0],
radix::Float64=1.0,
text::String="",
title::String="",
legend=nothing )
#
return plotKDECircular([bd;], c=c, logpdf=logpdf, scale=scale, rVo=rVo, radix=radix, text=text, title=title, legend=legend )
end
plotMKD(mkd::ManifoldKernelDensity{M}) where M <: MB.AbstractManifold = plotKDE(mkd.belief)
plotMKD(mkds::AbstractVector{<:ManifoldKernelDensity}) = plotKDE((x->x.belief).(mkds))
# function plotKDE(pp::BallTreeDensity, )
#
#
# end
|
If $p$ divides $q$ and $q \neq 0$, then the degree of $p$ is less than or equal to the degree of $q$. |
struct Simulator{N,T<:AbstractFloat,W<:Wave{N,T},R<:AbstractResource,H<:Tuple}
wave::W
resource::R
hooks::H
duration::T
maxiter::Int
end
function Simulator(wave::Wave{N,T}, hooks...; resource=CPU1(), duration=0.01) where {N,T}
maxiter = ceil(Int, duration / wave.dt)
Simulator{N,T,typeof(wave),typeof(resource),typeof(hooks)}(wave, resource, hooks, T(duration), maxiter)
end
# --------------------------------------------------------------------
function simulator_init(state::State, sim::Simulator)
foreach(hook -> hook_init!(hook, state, sim), sim.hooks)
end
function update!(state::State, backend::Backend, sim::Simulator)
backend_update!(state, backend, sim)
state.previous, state.current = state.current, state.previous
state.t += sim.wave.dt
state.iter += 1
foreach(hook -> hook_update!(hook, state, sim), sim.hooks)
end
function simulate!(state::State, backend::Backend, sim::Simulator)
simulator_init(state, sim)
for _ in 1:sim.maxiter
update!(state, backend, sim)
end
state
end
# --------------------------------------------------------------------
function simulate(f0, sim::Simulator{N,T}, domain::Domain{N}) where {N,T}
backend = backend_init(sim.resource, domain, sim)
state = state_init(f0, backend, domain, sim)
simulate!(state, backend, sim)
backend_cleanup!(backend, state, sim)
state
end
function simulate(sim::Simulator{N,T}, domain::Domain{N}) where {N,T}
backend = backend_init(sim.resource, domain, sim)
state = state_init(backend, domain, sim)
simulate!(state, backend, sim)
backend_cleanup!(backend, state, sim)
state
end
function simulate_gauss(sim::Simulator{N,T}, domain::Domain{N}) where {N,T}
simulate(gauss(domain), sim, domain)
end
|
open Nat
inductive BV : Nat β Type
| nil : BV 0
| cons : β (n) (hd : Bool) (tl : BV n), BV (succ n)
open BV
variable (f : Bool β Bool β Bool)
def map2 : {n : Nat} β BV n β BV n β BV n
| .(0), nil, nil => nil
| .(n+1), cons n b1 v1, cons .(n) b2 v2 => cons n (f b1 b2) (map2 v1 v2)
theorem ex1 : map2 f nil nil = nil :=
rfl
theorem ex2 (n : Nat) (b1 b2 : Bool) (v1 v2 : BV n) : map2 f (cons n b1 v1) (cons n b2 v2) = cons n (f b1 b2) (map2 f v1 v2) :=
rfl
#print map2
def map2' : {n : Nat} β BV n β BV n β BV n
| _, nil, nil => nil
| _, cons _ b1 v1, cons _ b2 v2 => cons _ (f b1 b2) (map2' v1 v2)
theorem ex3 : map2' f nil nil = nil :=
rfl
theorem ex4 (n : Nat) (b1 b2 : Bool) (v1 v2 : BV n) : map2' f (cons n b1 v1) (cons n b2 v2) = cons n (f b1 b2) (map2' f v1 v2) :=
rfl
|
module Idris.Codegen.ExtSTG.SemiDecEq
public export
interface SemiDecEq t where
semiDecEq : (x : t) -> (y : t) -> Maybe (x = y)
export
SemiDecEq Nat where
semiDecEq Z Z = Just Refl
semiDecEq (S n1) (S n2) = do
Refl <- semiDecEq n1 n2
Just Refl
semiDecEq _ _ = Nothing
export
SemiDecEq a => SemiDecEq (List a) where
semiDecEq [] [] = Just Refl
semiDecEq (x :: xs) (y :: ys) = do
Refl <- semiDecEq x y
Refl <- semiDecEq xs ys
Just Refl
semiDecEq _ _ = Nothing
|
! Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
! See https://llvm.org/LICENSE.txt for license information.
! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
! Test of using derived type inside subroutines of a sudmodule
!
MODULE m1
TYPE Base
INTEGER :: a
END TYPE
INTERFACE
MODULE SUBROUTINE sub1(b) ! Module procedure interface body for sub1
TYPE(Base), INTENT(IN) :: b
END SUBROUTINE
END INTERFACE
END MODULE
SUBMODULE (m1) m1sub
CONTAINS
MODULE SUBROUTINE sub1(b) ! Implementation of sub1 declared in m1
TYPE(Base), INTENT(IN) :: b
!PRINT *, "sub1", b
if (b%a .ne. 11) then
print *, "FAIL"
else
print *, "PASS"
end if
END SUBROUTINE
END SUBMODULE
PROGRAM example
USE m1
implicit none
CALL sub1(Base(11))
END PROGRAM
|
module Provider
import DB.SQLite.Effect
import DB.SQLite.SQLiteCodes
import Effects
import Database
import ParserHack
import Queries
import Schema
import SQLiteTypes
%access export
%language TypeProviders
mkDB : ResultSet -> Either String (List (String, Schema))
mkDB [] = Right []
mkDB ([DBText v]::rest) =
case getSchema (toLower v) of
Nothing => Left ( "Couldn't parse schema '" ++ v ++ "'\n")
Just (t, tbl) =>
with Applicative
Right List.(::) <*> Right (t, tbl) <*> mkDB rest
mkDB _ = Left "Couldn't understand SQLite output - wrong type"
getSchemas : (filename : String) -> Eff (Provider (DB filename)) [SQLITE ()]
getSchemas file =
do let ddlQuery = "SELECT `sql` FROM `sqlite_master` " ++
"WHERE NOT (sqlite_master.name LIKE \"sqlite%\");"
resSet <- executeSelect file ddlQuery [] $
do sql <- getColumnText 0
pure [DBText sql]
case resSet of
Left err => pure (Error $ "Error reading '" ++ file ++ "': " ++ (show err))
Right res => case mkDB res of
Left err => pure (Error err)
Right db => pure (Provide (MkDB file db))
getRow : (s : Schema) -> SimpleEff.Eff (Row s) [SQLITE (SQLiteExecuting ValidRow)]
getRow s = go 0 s
where go : Int -> (s : Schema) -> Eff (Row s) [SQLITE (SQLiteExecuting ValidRow)]
go i [] = pure []
go i ((_ ::: ty) :: s) = [| getCol ty :: go (i+1) s |]
where getCol : (t : SQLiteType) -> Eff (interpSql t) [SQLITE (SQLiteExecuting ValidRow)]
getCol TEXT = getColumnText i
getCol INTEGER = do int <- getColumnInt i
pure (cast int)
getCol REAL = getColumnFloat i
getCol (NULLABLE x) = do nullp <- isColumnNull i
case nullp of
True => pure Nothing
False => do val <- getCol x
pure (Just val)
collectRows : (s : Schema) -> Eff (Table s) [SQLITE (SQLiteExecuting ValidRow)] [SQLITE (SQLiteExecuting InvalidRow)]
collectRows s = do row <- getRow s
case !nextRow of
Unstarted => pure $ row :: !(collectRows s)
StepFail => pure $ row :: !(collectRows s)
StepComplete => pure $ row :: !(collectRows s)
NoMoreRows => pure [row]
query : {file : String} -> {db : DB file} -> Query db s -> Eff (Either QueryError (Table s)) [SQLITE ()]
query {file=fn} q =
case !(openDB fn) of
Left err => pure $ Left err
Right () => -- FIXME should really use binding
case !(prepareStatement (compileQuery q)) of
Left err => do cleanupPSFail
pure $ Left err
Right () =>
case !finishBind of
Just err => do cleanupBindFail ; return $ Left err
Nothing =>
case !executeStatement of
Unstarted => do rs <- collectRows _
finalise
closeDB
pure (Right rs)
StepFail => do rs <- collectRows _
finalise
closeDB
pure (Right rs)
StepComplete => do rs <- collectRows _
finalise
closeDB
pure (Right rs)
NoMoreRows => do finalise
closeDB
pure (Right [])
|
(* *********************************************************************)
(* *)
(* The CertiKOS Certified Kit Operating System *)
(* *)
(* The FLINT Group, Yale University *)
(* *)
(* Copyright The FLINT Group, Yale University. All rights reserved. *)
(* This file is distributed under the terms of the Yale University *)
(* Non-Commercial License Agreement. *)
(* *)
(* *********************************************************************)
(* *********************************************************************)
(* *)
(* Frameworks for proving Clight loops: specification and termination *)
(* *)
(* Developed by Xiongnan (Newman) Wu *)
(* *)
(* Yale University *)
(* *)
(* *********************************************************************)
Require Import Coqlib.
Require Import Maps.
Require Import AST.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Events.
Require Import Globalenvs.
Require Import Locations.
Require Import Clight.
Require Import Smallstep.
Require Import ClightBigstep.
Require Import Ctypes.
Require Import Cop.
Require Import ZArith.Zwf.
Require Import Integers.
Require Import CDataTypes.
Module LoopProof.
Section S.
Context `{Hcc: Events.CompilerConfiguration}
`{Hwb: Events.WritableBlock}.
Variables (body: statement) (genv: genv) (env: env)
(P Q: temp_env -> mem -> Prop)
(R: temp_env-> mem -> option (val * type)-> Prop).
Record t : Type := make {
W: Type;
lt: W-> W-> Prop;
lt_wf: well_founded lt;
I: temp_env-> mem-> W-> Prop;
P_implies_I: forall le m, P le m-> exists n0, I le m n0;
I_invariant:
forall le m n, I le m n ->
exists out le' m', exec_stmt genv env le m body E0 le' m' out /\
((out = Out_normal \/ out = Out_continue)-> exists n', lt n' n /\ I le' m' n') /\
(out = Out_break-> Q le' m') /\
(forall v, out = Out_return v-> R le' m' v)
}.
Theorem termination: t -> forall le m, P le m ->
(exists out le' m', exec_stmt genv env le m (Sloop body Sskip) E0 le' m' out /\
((exists v, out = Out_return v /\ R le' m' v) \/ (out = Out_normal /\ Q le' m'))).
Proof.
destruct 1; simpl.
intros.
generalize (P_implies_I0 le m H).
intro.
destruct H0 as [n0].
clear H.
revert le m H0.
induction n0 using (well_founded_ind lt_wf0).
intros.
generalize (I_invariant0 le m n0 H0).
intro I_invariant.
destruct I_invariant as [out tinv].
destruct tinv as [le' tinv].
destruct tinv as [m' tinv].
destruct tinv as [Inv1 tinv].
destruct tinv as [Inv2 tinv].
destruct tinv as [Inv3 Inv4].
destruct out.
(* out = Out_break *)
exists Out_normal.
exists le'.
exists m'.
split.
econstructor.
eassumption.
econstructor.
right.
split.
trivial.
apply Inv3.
trivial.
(* out = Out_continue *)
destruct Inv2 as [n'].
auto.
destruct H1.
generalize (H n' H1 le' m' H2).
intro.
destruct H3 as [out].
destruct H3 as [le'0'].
destruct H3 as [m'0].
destruct H3.
destruct H4.
(* finalout = Out_return *)
destruct H4 as [v].
destruct H4.
esplit. esplit. esplit.
split.
change E0 with (E0 ** E0 ** E0).
eapply exec_Sloop_loop.
eassumption.
econstructor.
econstructor.
eassumption.
subst.
left.
exists v.
auto.
(* finalout = Out_normal *)
destruct H4.
esplit. esplit. esplit.
split.
change E0 with (E0 ** E0 ** E0).
eapply exec_Sloop_loop.
eassumption.
econstructor.
econstructor.
eassumption.
subst.
right.
auto.
(* out = Out_normal *)
destruct Inv2 as [n'].
auto.
destruct H1.
generalize (H n' H1 le' m' H2).
intro.
destruct H3 as [out].
destruct H3 as [le'0'].
destruct H3 as [m'0].
destruct H3.
destruct H4.
(* finalout = Out_return *)
destruct H4 as [v].
destruct H4.
esplit. esplit. esplit.
split.
change E0 with (E0 ** E0 ** E0).
eapply exec_Sloop_loop.
eassumption.
econstructor.
econstructor.
eassumption.
subst.
left.
exists v.
auto.
(* finalout = Out_normal *)
destruct H4.
esplit. esplit. esplit.
split.
change E0 with (E0 ** E0 ** E0).
eapply exec_Sloop_loop.
eassumption.
econstructor.
econstructor.
eassumption.
subst.
right.
auto.
(* out = Out_return *)
exists (Out_return o).
exists le'.
exists m'.
split.
econstructor.
eassumption.
econstructor.
left.
exists o.
auto.
Qed.
End S.
End LoopProof.
Module LoopProofWhileWithContinue.
Section S.
Context `{Hcc: Events.CompilerConfiguration}
`{Hwb: Events.WritableBlock}.
Variables (condition: expr) (body: statement)
(genv: genv) (env: env)
(P Q: temp_env -> mem -> Prop).
Record t : Type := make {
W: Type;
lt: W-> W-> Prop;
lt_wf: well_founded lt;
I: temp_env-> mem-> W-> Prop;
P_implies_I: forall le m, P le m-> exists n0, I le m n0;
I_invariant:
forall le m n, I le m n-> exists v b, (eval_expr genv env le m condition v /\
(bool_val v (typeof condition) = Some b) /\
(b = false -> Q le m) /\
(b = true ->
exists out le' m', exec_stmt genv env le m body E0 le' m' out /\
(out = Out_normal \/ out = Out_continue) /\
exists n', lt n' n /\ I le' m' n'
))
}.
Theorem termination: t -> forall le m, P le m ->
(exists le' m', exec_stmt genv env le m (Swhile condition body) E0 le' m' Out_normal /\ Q le' m').
Proof.
unfold Swhile.
destruct 1; simpl.
intros.
generalize (P_implies_I0 le m H).
intro.
destruct H0 as [n0].
clear H.
revert le m H0.
induction n0 using (well_founded_ind lt_wf0).
intros.
generalize (I_invariant0 le m n0 H0).
intro I_invariant.
destruct I_invariant as [v tinv].
destruct tinv as [b tinv].
destruct tinv as [evalexpr tinv].
destruct tinv as [boolval tinv].
destruct tinv as [condfalse tinv].
destruct b.
(* b = true *)
destruct tinv as [out tinv]; trivial.
destruct tinv as [le' tinv].
destruct tinv as [m' tinv].
destruct tinv as [Inv1 tinv].
destruct tinv as [Inv2 tinv].
destruct tinv as [n' tinv].
destruct tinv as [Inv3 Inv4].
destruct Inv2.
(* out = Out_normal *)
subst.
generalize (H n' Inv3 le' m' Inv4).
intro.
destruct H1 as [le'0'].
destruct H1 as [m'0].
destruct H1.
esplit. esplit.
split.
change E0 with (E0 ** E0 ** E0).
eapply exec_Sloop_loop.
change E0 with (E0 ** E0).
econstructor.
econstructor.
eassumption.
eassumption.
simpl.
econstructor.
eassumption.
econstructor.
econstructor.
eassumption.
eassumption.
(* out = Out_continue *)
subst.
generalize (H n' Inv3 le' m' Inv4).
intro.
destruct H1 as [le'0'].
destruct H1 as [m'0].
destruct H1.
esplit. esplit.
split.
change E0 with (E0 ** E0 ** E0).
eapply exec_Sloop_loop.
change E0 with (E0 ** E0).
econstructor.
econstructor.
eassumption.
eassumption.
simpl.
econstructor.
eassumption.
econstructor.
econstructor.
eassumption.
eassumption.
(* b = false *)
exists le.
exists m.
split.
eapply exec_Sloop_stop1.
econstructor.
econstructor.
eassumption.
eassumption.
simpl.
econstructor.
congruence.
econstructor.
auto.
Qed.
End S.
End LoopProofWhileWithContinue.
Module LoopProofSimpleWhile.
Section S.
Context `{Hcc: Events.CompilerConfiguration}
`{Hwb: Events.WritableBlock}.
Variables (condition: expr) (body: statement)
(genv: genv) (env: env)
(P Q: temp_env -> mem -> Prop).
Record t : Type := make {
W: Type;
lt: W-> W-> Prop;
lt_wf: well_founded lt;
I: temp_env-> mem-> W-> Prop;
P_implies_I: forall le m, P le m-> exists n0, I le m n0;
I_invariant:
forall le m n, I le m n-> exists v b, (eval_expr genv env le m condition v /\
(bool_val v (typeof condition) = Some b) /\
(b = false -> Q le m) /\
(b = true ->
exists le' m', exec_stmt genv env le m body E0 le' m' Out_normal /\
exists n', lt n' n /\ I le' m' n'
))
}.
Theorem termination: t -> forall le m, P le m ->
(exists le' m', exec_stmt genv env le m (Swhile condition body) E0 le' m' Out_normal /\ Q le' m').
Proof.
unfold Swhile.
destruct 1; simpl.
intros.
generalize (P_implies_I0 le m H).
intro.
destruct H0 as [n0].
clear H.
revert le m H0.
induction n0 using (well_founded_ind lt_wf0).
intros.
generalize (I_invariant0 le m n0 H0).
intro I_invariant.
destruct I_invariant as [v tinv].
destruct tinv as [b tinv].
destruct tinv as [evalexpr tinv].
destruct tinv as [boolval tinv].
destruct tinv as [condfalse tinv].
destruct b.
(* b = true *)
destruct tinv as [le' tinv]; trivial.
destruct tinv as [m' tinv].
destruct tinv as [Inv1 tinv].
destruct tinv as [n' tinv].
destruct tinv as [Inv2 Inv3].
generalize (H n' Inv2 le' m' Inv3).
intro.
destruct H1 as [le'0'].
destruct H1 as [m'0].
destruct H1.
esplit. esplit.
split.
change E0 with (E0 ** E0 ** E0).
eapply exec_Sloop_loop.
change E0 with (E0 ** E0).
econstructor.
econstructor.
eassumption.
eassumption.
simpl.
econstructor.
eassumption.
econstructor.
econstructor.
eassumption.
eassumption.
(* b = false *)
exists le.
exists m.
split.
eapply exec_Sloop_stop1.
econstructor.
econstructor.
eassumption.
eassumption.
simpl.
econstructor.
congruence.
econstructor.
auto.
Qed.
End S.
End LoopProofSimpleWhile. |
using DynamicProgrammingFibonacci.Dp
@test fibonacci(0) == 0
@test fibonacci(1) == 1
@test fibonacci(2) == 1
@test fibonacci(4) == 3
@test fibonacci(100) == 354224848179261915075
@test fibonacci(140) == 81055900096023504197206408605
@test fibonacci(300) == 222232244629420445529739893461909967206666939096499764990979600
|
{-# LANGUAGE CPP
, GADTs
, Rank2Types
, DataKinds
, TypeFamilies
, FlexibleContexts
, UndecidableInstances
, LambdaCase
, MultiParamTypeClasses
, OverloadedStrings
#-}
{-# OPTIONS_GHC -Wall -fwarn-tabs -fsimpl-tick-factor=1000 -fno-warn-orphans #-}
module Language.Hakaru.Runtime.LogFloatPrelude where
#if __GLASGOW_HASKELL__ < 710
import Data.Functor ((<$>))
import Control.Applicative (Applicative(..))
#endif
import Data.Foldable as F
import qualified System.Random.MWC as MWC
import qualified System.Random.MWC.Distributions as MWCD
import Data.Number.Natural
import Data.Number.LogFloat hiding (sum, product)
import qualified Data.Number.LogFloat as LF
import Data.STRef
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import Control.Monad
import Control.Monad.ST
import Numeric.SpecFunctions (logBeta)
import Prelude hiding (init, sum, product, exp, log, (**), pi)
import qualified Prelude as P
import Language.Hakaru.Runtime.CmdLine (Parseable(..), Measure(..), makeMeasure)
-- This Read instance really should be the logfloat package
instance Read LogFloat where
readsPrec p s = [(logFloat x, r) | (x, r) <- readsPrec p s]
instance Parseable LogFloat where
parse = return . read
type family MinBoxVec (v1 :: * -> *) (v2 :: * -> *) :: * -> *
type instance MinBoxVec V.Vector v = V.Vector
type instance MinBoxVec v V.Vector = V.Vector
type instance MinBoxVec U.Vector U.Vector = U.Vector
type family MayBoxVec a :: * -> *
type instance MayBoxVec () = U.Vector
type instance MayBoxVec Int = U.Vector
type instance MayBoxVec Double = U.Vector
type instance MayBoxVec LogFloat = U.Vector
type instance MayBoxVec Bool = U.Vector
type instance MayBoxVec (U.Vector a) = V.Vector
type instance MayBoxVec (V.Vector a) = V.Vector
type instance MayBoxVec (a,b) = MinBoxVec (MayBoxVec a) (MayBoxVec b)
newtype instance U.MVector s LogFloat = MV_LogFloat (U.MVector s Double)
newtype instance U.Vector LogFloat = V_LogFloat (U.Vector Double)
instance U.Unbox LogFloat
instance M.MVector U.MVector LogFloat where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
#if __GLASGOW_HASKELL__ > 710
{-# INLINE basicInitialize #-}
#endif
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_LogFloat v) = M.basicLength v
basicUnsafeSlice i n (MV_LogFloat v) = MV_LogFloat $ M.basicUnsafeSlice i n v
basicOverlaps (MV_LogFloat v1) (MV_LogFloat v2) = M.basicOverlaps v1 v2
basicUnsafeNew n = MV_LogFloat `liftM` M.basicUnsafeNew n
#if __GLASGOW_HASKELL__ > 710
basicInitialize (MV_LogFloat v) = M.basicInitialize v
#endif
basicUnsafeReplicate n x = MV_LogFloat `liftM` M.basicUnsafeReplicate n (logFromLogFloat x)
basicUnsafeRead (MV_LogFloat v) i = logToLogFloat `liftM` M.basicUnsafeRead v i
basicUnsafeWrite (MV_LogFloat v) i x = M.basicUnsafeWrite v i (logFromLogFloat x)
basicClear (MV_LogFloat v) = M.basicClear v
basicSet (MV_LogFloat v) x = M.basicSet v (logFromLogFloat x)
basicUnsafeCopy (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeCopy v1 v2
basicUnsafeMove (MV_LogFloat v1) (MV_LogFloat v2) = M.basicUnsafeMove v1 v2
basicUnsafeGrow (MV_LogFloat v) n = MV_LogFloat `liftM` M.basicUnsafeGrow v n
instance G.Vector U.Vector LogFloat where
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicUnsafeFreeze (MV_LogFloat v) = V_LogFloat `liftM` G.basicUnsafeFreeze v
basicUnsafeThaw (V_LogFloat v) = MV_LogFloat `liftM` G.basicUnsafeThaw v
basicLength (V_LogFloat v) = G.basicLength v
basicUnsafeSlice i n (V_LogFloat v) = V_LogFloat $ G.basicUnsafeSlice i n v
basicUnsafeIndexM (V_LogFloat v) i
= logToLogFloat `liftM` G.basicUnsafeIndexM v i
basicUnsafeCopy (MV_LogFloat mv) (V_LogFloat v)
= G.basicUnsafeCopy mv v
elemseq _ x z = G.elemseq (undefined :: U.Vector a) (logFromLogFloat x) z
type Prob = LogFloat
lam :: (a -> b) -> a -> b
lam = id
{-# INLINE lam #-}
app :: (a -> b) -> a -> b
app f x = f x
{-# INLINE app #-}
let_ :: a -> (a -> b) -> b
let_ x f = let x1 = x in f x1
{-# INLINE let_ #-}
ann_ :: a -> b -> b
ann_ _ a = a
{-# INLINE ann_ #-}
exp :: Double -> Prob
exp = logToLogFloat
{-# INLINE exp #-}
log :: Prob -> Double
log = logFromLogFloat
{-# INLINE log #-}
betaFunc :: Prob -> Prob -> Prob
betaFunc a b = exp (logBeta (fromProb a) (fromProb b))
uniform :: Double -> Double -> Measure Double
uniform lo hi = makeMeasure $ MWC.uniformR (lo, hi)
{-# INLINE uniform #-}
normal :: Double -> Prob -> Measure Double
normal mu sd = makeMeasure $ MWCD.normal mu (fromProb sd)
{-# INLINE normal #-}
beta :: Prob -> Prob -> Measure Prob
beta a b = makeMeasure $ \g ->
unsafeProb <$> MWCD.beta (fromProb a) (fromProb b) g
{-# INLINE beta #-}
gamma :: Prob -> Prob -> Measure Prob
gamma a b = makeMeasure $ \g ->
unsafeProb <$> MWCD.gamma (fromProb a) (fromProb b) g
{-# INLINE gamma #-}
categorical :: MayBoxVec Prob Prob -> Measure Int
categorical a = makeMeasure $ MWCD.categorical (U.map prep a)
where prep p = fromLogFloat (p / m)
m = G.maximum a
{-# INLINE categorical #-}
plate :: (G.Vector (MayBoxVec a) a) =>
Int -> (Int -> Measure a) -> Measure (MayBoxVec a a)
plate n f = G.generateM (fromIntegral n) $ \x ->
f (fromIntegral x)
{-# INLINE plate #-}
bucket :: Int -> Int -> (forall s. Reducer () s a) -> a
bucket b e r = runST
$ case r of Reducer{init=initR,accum=accumR,done=doneR} -> do
s' <- initR ()
F.mapM_ (\i -> accumR () i s') [b .. e - 1]
doneR s'
{-# INLINE bucket #-}
data Reducer xs s a =
forall cell.
Reducer { init :: xs -> ST s cell
, accum :: xs -> Int -> cell -> ST s ()
, done :: cell -> ST s a
}
r_fanout :: Reducer xs s a
-> Reducer xs s b
-> Reducer xs s (a,b)
r_fanout Reducer{init=initA,accum=accumA,done=doneA}
Reducer{init=initB,accum=accumB,done=doneB} = Reducer
{ init = \xs -> liftM2 (,) (initA xs) (initB xs)
, accum = \bs i (s1, s2) ->
accumA bs i s1 >> accumB bs i s2
, done = \(s1, s2) -> liftM2 (,) (doneA s1) (doneB s2)
}
{-# INLINE r_fanout #-}
r_index :: (G.Vector (MayBoxVec a) a)
=> (xs -> Int)
-> ((Int, xs) -> Int)
-> Reducer (Int, xs) s a
-> Reducer xs s (MayBoxVec a a)
r_index n f Reducer{init=initR,accum=accumR,done=doneR} = Reducer
{ init = \xs -> V.generateM (n xs) (\b -> initR (b, xs))
, accum = \bs i v ->
let ov = f (i, bs) in
accumR (ov,bs) i (v V.! ov)
, done = \v -> fmap G.convert (V.mapM doneR v)
}
{-# INLINE r_index #-}
r_split :: ((Int, xs) -> Bool)
-> Reducer xs s a
-> Reducer xs s b
-> Reducer xs s (a,b)
r_split b Reducer{init=initA,accum=accumA,done=doneA}
Reducer{init=initB,accum=accumB,done=doneB} = Reducer
{ init = \xs -> liftM2 (,) (initA xs) (initB xs)
, accum = \bs i (s1, s2) ->
if (b (i,bs)) then accumA bs i s1 else accumB bs i s2
, done = \(s1, s2) -> liftM2 (,) (doneA s1) (doneB s2)
}
{-# INLINE r_split #-}
r_add :: Num a => ((Int, xs) -> a) -> Reducer xs s a
r_add e = Reducer
{ init = \_ -> newSTRef 0
, accum = \bs i s ->
modifySTRef' s (+ (e (i,bs)))
, done = readSTRef
}
{-# INLINE r_add #-}
r_nop :: Reducer xs s ()
r_nop = Reducer
{ init = \_ -> return ()
, accum = \_ _ _ -> return ()
, done = \_ -> return ()
}
{-# INLINE r_nop #-}
pair :: a -> b -> (a, b)
pair = (,)
{-# INLINE pair #-}
true, false :: Bool
true = True
false = False
nothing :: Maybe a
nothing = Nothing
just :: a -> Maybe a
just = Just
left :: a -> Either a b
left = Left
right :: b -> Either a b
right = Right
unit :: ()
unit = ()
data Pattern = PVar | PWild
newtype Branch a b =
Branch { extract :: a -> Maybe b }
ptrue, pfalse :: a -> Branch Bool a
ptrue b = Branch { extract = extractBool True b }
pfalse b = Branch { extract = extractBool False b }
{-# INLINE ptrue #-}
{-# INLINE pfalse #-}
extractBool :: Bool -> a -> Bool -> Maybe a
extractBool b a p | p == b = Just a
| otherwise = Nothing
{-# INLINE extractBool #-}
pnothing :: b -> Branch (Maybe a) b
pnothing b = Branch { extract = \ma -> case ma of
Nothing -> Just b
Just _ -> Nothing }
pjust :: Pattern -> (a -> b) -> Branch (Maybe a) b
pjust PVar c = Branch { extract = \ma -> case ma of
Nothing -> Nothing
Just x -> Just (c x) }
pjust _ _ = error "TODO: Runtime.Prelude{pjust}"
pleft :: Pattern -> (a -> c) -> Branch (Either a b) c
pleft PVar f = Branch { extract = \ma -> case ma of
Right _ -> Nothing
Left x -> Just (f x) }
pleft _ _ = error "TODO: Runtime.Prelude{pLeft}"
pright :: Pattern -> (b -> c) -> Branch (Either a b) c
pright PVar f = Branch { extract = \ma -> case ma of
Left _ -> Nothing
Right x -> Just (f x) }
pright _ _ = error "TODO: Runtime.Prelude{pRight}"
ppair :: Pattern -> Pattern -> (x -> y -> b) -> Branch (x,y) b
ppair PVar PVar c = Branch { extract = (\(x,y) -> Just (c x y)) }
ppair _ _ _ = error "ppair: TODO"
uncase_ :: Maybe a -> a
uncase_ (Just a) = a
uncase_ Nothing = error "case_: unable to match any branches"
{-# INLINE uncase_ #-}
case_ :: a -> [Branch a b] -> b
case_ e [c1] = uncase_ (extract c1 e)
case_ e [c1, c2] = uncase_ (extract c1 e `mplus` extract c2 e)
case_ e bs_ = go bs_
where go [] = error "case_: unable to match any branches"
go (b:bs) = case extract b e of
Just b' -> b'
Nothing -> go bs
{-# INLINE case_ #-}
branch :: (c -> Branch a b) -> c -> Branch a b
branch pat body = pat body
{-# INLINE branch #-}
dirac :: a -> Measure a
dirac = return
{-# INLINE dirac #-}
pose :: Prob -> Measure a -> Measure a
pose _ a = a
{-# INLINE pose #-}
superpose :: [(Prob, Measure a)]
-> Measure a
superpose pms = do
i <- categorical (G.fromList $ map fst pms)
snd (pms !! i)
{-# INLINE superpose #-}
reject :: Measure a
reject = Measure $ \_ -> return Nothing
nat_ :: Int -> Int
nat_ = id
int_ :: Int -> Int
int_ = id
unsafeNat :: Int -> Int
unsafeNat = id
nat2prob :: Int -> Prob
nat2prob = fromIntegral
fromInt :: Int -> Double
fromInt = fromIntegral
nat2int :: Int -> Int
nat2int = id
nat2real :: Int -> Double
nat2real = fromIntegral
fromProb :: Prob -> Double
fromProb = fromLogFloat
unsafeProb :: Double -> Prob
unsafeProb = logFloat
real_ :: Rational -> Double
real_ = fromRational
prob_ :: NonNegativeRational -> Prob
prob_ = fromRational . fromNonNegativeRational
infinity :: Double
infinity = 1/0
abs_ :: Num a => a -> a
abs_ = abs
(**) :: Prob -> Double -> Prob
(**) = pow
{-# INLINE (**) #-}
pi :: Prob
pi = unsafeProb P.pi
{-# INLINE pi #-}
thRootOf :: Int -> Prob -> Prob
thRootOf a b = b ** (recip $ fromIntegral a)
{-# INLINE thRootOf #-}
array
:: (G.Vector (MayBoxVec a) a)
=> Int
-> (Int -> a)
-> MayBoxVec a a
array n f = G.generate (fromIntegral n) (f . fromIntegral)
{-# INLINE array #-}
arrayLit :: (G.Vector (MayBoxVec a) a) => [a] -> MayBoxVec a a
arrayLit = G.fromList
{-# INLINE arrayLit #-}
(!) :: (G.Vector (MayBoxVec a) a) => MayBoxVec a a -> Int -> a
a ! b = a G.! (fromIntegral b)
{-# INLINE (!) #-}
size :: (G.Vector (MayBoxVec a) a) => MayBoxVec a a -> Int
size v = fromIntegral (G.length v)
{-# INLINE size #-}
reduce
:: (G.Vector (MayBoxVec a) a)
=> (a -> a -> a)
-> a
-> MayBoxVec a a
-> a
reduce f n v = G.foldr f n v
{-# INLINE reduce #-}
class Num a => Num' a where
product :: Int -> Int -> (Int -> a) -> a
product a b f = F.foldl' (\x y -> x * f y) 1 [a .. b-1]
{-# INLINE product #-}
summate :: Int -> Int -> (Int -> a) -> a
summate a b f = F.foldl' (\x y -> x + f y) 0 [a .. b-1]
{-# INLINE summate #-}
instance Num' Int
instance Num' Double
instance Num' LogFloat where
product a b f = LF.product (map f [a .. b-1])
{-# INLINE product #-}
summate a b f = LF.sum (map f [a .. b-1])
{-# INLINE summate #-}
run :: Show a
=> MWC.GenIO
-> Measure a
-> IO ()
run g k = unMeasure k g >>= \case
Just a -> print a
Nothing -> return ()
iterateM_
:: Monad m
=> (a -> m a)
-> a
-> m b
iterateM_ f = g
where g x = f x >>= g
withPrint :: Show a => (a -> IO b) -> a -> IO b
withPrint f x = print x >> f x
|
A third verse , sometimes added to the rhyme , was first recorded in a 19th @-@ century chapbook and took the form :
|
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_cdf.h>
#include <stdio.h>
void evaluate(double x) {
double probability = gsl_sf_erf(x);
printf(
"The probability that Normal(0, 1) random variable has a value "
"between %g and %g is: %g\n", -x, x, probability
);
double area = 1 - 2 * gsl_cdf_gaussian_P(-x, 1);
printf(
"The integral of a Normal(0, 1) distribution "
"between %g and %g is: %g\n", -x, x, area
);
}
int main() {
evaluate(0.25);
evaluate(1.96);
}
|
module AmbiguousTopLevelModuleName where
import Imports.Ambiguous
|
import matplotlib.pyplot as plt
import numpy as np
import argparse
def make_plot(filename: str, image_file: str):
with open('traces.txt', 'r') as inp_file:
axes = '#'
while axes.startswith('#'):
axes = inp_file.readline()
axes = axes.split('/')
splitted = inp_file.read().split()
x = np.array(np.float64(splitted[0::3]))
teoretical = np.array(np.float64(splitted[1::3]))
measurements = np.array(np.float64(splitted[2::3]))
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
ax1.plot(x, teoretical, label=axes[3].strip().capitalize())
ax1.plot(x, measurements, label=axes[4].strip().capitalize())
ax1.set(xlabel=axes[0].strip(), ylabel=axes[1].strip())
ax1.legend(loc=axes[5].strip().lower(), shadow=True,
fontsize=axes[6].strip().lower())
ax1.grid()
ax2.plot(x, teoretical - measurements)
ax2.set(xlabel=axes[0].strip(), ylabel=axes[2].strip())
ax2.grid()
fig.savefig(image_file)
plt.show()
if __name__ == '__main__':
DESCRIPTION = 'Plot comparision of two graph'
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument('filename', metavar='FILE', type=str,
help='a file name with data')
parser.add_argument('image_name', metavar='PICTURE', type=str, nargs='?',
default='fig.png', help='an image file name')
args = parser.parse_args()
if args.filename:
make_plot(args.filename, args.image_name)
|
module Data.AOC19.Day05
import Data.Fin
import Data.Vect
import Effects
total
slice : (i, n : Nat) -> Vect (i + (n + m)) a -> Vect n a
slice i n = take n . drop i
namespace IntCode
data State : Type where
Running : {n : Nat} -> (ptr : Fin n) -> (state : Vect n Int) -> State
NotRunning : State
data ParameterMode
= PositionMode
| ImmediateMode
data OpCode
= ADD
| MUL
| SET
| PRN
| END
data Program : State -> Type where
Halted : Program NotRunning
MkP : (ptr : Fin n) -> (state : Vect n Int) -> Program (Running ptr state)
data Instruction : Effect where
Add : sig Instruction (Vect (S (S (S (S k)))) Int)
(Program (Running ptr state))
(\state' => Program (Running (shift 4 ptr) state'))
Handler Instruction m where
handle (MkP (ptr state {n=S (S (S (S j)))}) Add k =
let dst = Vect.index (shift 3 ptr) state in
?rhs_1
-- program :: Parser (Vector Int)
-- program = fromList . map fromInteger <$> (natural `sepBy` comma)
-- runProgram :: Vector Int -> Vector Int
-- runProgram = go 0
-- where
-- go n state
-- | state ! n == 99 = state
-- | otherwise = go (n + 4) $ step (toList (V.slice n 4 state))
-- where
-- step [1, x, y, dst] = modify (runOp (+) x y dst) state
-- step [2, x, y, dst] = modify (runOp (*) x y dst) state
-- step _ = state
-- runOp f x y dst v = write v dst =<< f <$> MV.read v x <*> MV.read v y
-- example1 :: Vector Int
-- example1 =
-- case parseString program mempty "1,9,10,3,2,3,11,0,99,30,40,50" of
-- Success prog -> prog
-- Failure reason -> error (show reason)
|
-- Andreas, 2019-04-10, issue #3683 reported by akaposi.
-- Regression in the termination checker introduced together
-- with collecting function calls also in the type signatures
-- (fix of #1556).
data A : Set
data B : A β Set
data A where
a : A
f : B a β A
data B where
module _
(A' : Set)(B' : A' β Set)
(a' : A')(f' : B' a' β A')
where
mutual
elimA : (x : A) β A'
elimA a = a'
elimA (f y) = f' (elimB a y)
-- Call elimA (f y) --> elimB a y
-- Call elimB x y --> elimA x in the type signature
elimB : (x : A) (y : B x) β B' (elimA x)
elimB x ()
-- With counting calls in the type signature as well, we get
--
-- elimA (f _) --> elimB a _ --> elimA a
--
-- which does not pass the naive termination checker, since
-- `a` and `f _` are unrelated in size.
--
-- However a more sophisticated type checker (Hyvernat)
-- will see that the composed call
--
-- elimA (f _) --> elimA a
--
-- is not idempotent; it cannot be composed with itself.
--
-- Thus, it is to be discounted during termination checking.
--
-- Verdict: this test case should pass.
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2018 Robert Bosch GmbH
All rights reserved.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@author: Andreas Doerr
"""
import numpy as np
import tensorflow as tf
from prssm.utils.utils_tf import tf_forward
from prssm.utils.utils_tf import backward
from prssm.utils.utils_tf import variable_summaries
"""
The following snippets are derived from GPFlow V 1.0
(https://github.com/GPflow/GPflow)
Copyright 2017 st--, Mark van der Wilk, licensed under the Apache License, Version 2.0,
cf. 3rd-party-licenses.txt file in the root directory of this source tree.
"""
class RBF:
def __init__(self, input_dim, variance=None, lengthscales=None):
with tf.name_scope('kern'):
self.input_dim = tf.constant(int(input_dim), name='input_dim')
with tf.name_scope('variance'):
variance = variance or 1.0
self.variance_unc = tf.Variable(backward(np.asarray(variance)),
dtype=tf.float64,
collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'hyperparameters'],
name='signal_variance')
self.variance = tf_forward(self.variance_unc)
variable_summaries(self.variance, vector=False)
with tf.name_scope('lengthscales'):
lengthscales = lengthscales or 1.0
self.lengthscales_unc = tf.Variable(backward(np.asarray(lengthscales)) * tf.ones((self.input_dim, ), dtype=tf.float64),
collections=[tf.GraphKeys.GLOBAL_VARIABLES, 'hyperparameters'],
name='lengthscales')
self.lengthscales = tf_forward(self.lengthscales_unc)
variable_summaries(self.lengthscales)
def square_dist(self, X, X2):
X = X / self.lengthscales
Xs = tf.reduce_sum(tf.square(X), 1)
if X2 is None:
return -2 * tf.matmul(X, X, transpose_b=True) + \
tf.reshape(Xs, (-1, 1)) + tf.reshape(Xs, (1, -1))
else:
X2 = X2 / self.lengthscales
X2s = tf.reduce_sum(tf.square(X2), 1)
return -2 * tf.matmul(X, X2, transpose_b=True) + \
tf.reshape(Xs, (-1, 1)) + tf.reshape(X2s, (1, -1))
def euclid_dist(self, X, X2):
r2 = self.square_dist(X, X2)
return tf.sqrt(r2 + 1e-12)
def Kdiag(self, X):
return tf.fill(tf.stack([tf.shape(X)[0]]), tf.squeeze(self.variance))
def K(self, X, X2=None):
return self.variance * tf.exp(-self.square_dist(X, X2) / 2)
def conditional(Xnew, X, kern, f, q_sqrt):
# compute kernel stuff
num_data = tf.shape(X)[0]
Kmn = kern.K(X, Xnew)
Kmm = kern.K(X) + tf.eye(num_data, dtype=tf.float64) * 1e-8
Lm = tf.cholesky(Kmm)
# Compute the projection matrix A
A = tf.matrix_triangular_solve(Lm, Kmn, lower=True)
# compute the covariance due to the conditioning
fvar = kern.Kdiag(Xnew) - tf.reduce_sum(tf.square(A), 0)
shape = tf.stack([tf.shape(f)[1], 1])
fvar = tf.tile(tf.expand_dims(fvar, 0), shape) # D x N x N or D x N
# another backsubstitution in the unwhitened case
A = tf.matrix_triangular_solve(tf.transpose(Lm), A, lower=False)
# construct the conditional mean
fmean = tf.matmul(A, f, transpose_a=True)
LTA = A * tf.expand_dims(tf.transpose(q_sqrt), 2) # D x M x N
fvar = fvar + tf.reduce_sum(tf.square(LTA), 1) # D x N
fvar = tf.transpose(fvar) # N x D or N x N x D
return fmean, fvar
|
/**
*
* @file qwrapper_zlantr.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
void
CORE_zlantr_quark(Quark *quark);
void
CORE_zlantr_f1_quark(Quark *quark);
/***************************************************************************//**
*
**/
void QUARK_CORE_zlantr(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N,
const PLASMA_Complex64_t *A, int LDA, int szeA,
int szeW, double *result)
{
szeW = max(1, szeW);
DAG_CORE_LANGE;
QUARK_Insert_Task(quark, CORE_zlantr_quark, task_flags,
sizeof(PLASMA_enum), &norm, VALUE,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(PLASMA_enum), &diag, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex64_t)*szeA, A, INPUT,
sizeof(int), &LDA, VALUE,
sizeof(double)*szeW, NULL, SCRATCH,
sizeof(double), result, OUTPUT,
0);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlantr_f1(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N,
const PLASMA_Complex64_t *A, int LDA, int szeA,
int szeW, double *result,
double *fake, int szeF)
{
szeW = max(1, szeW);
DAG_CORE_LANGE;
if ( result == fake ) {
QUARK_Insert_Task(quark, CORE_zlantr_quark, task_flags,
sizeof(PLASMA_enum), &norm, VALUE,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(PLASMA_enum), &diag, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex64_t)*szeA, A, INPUT,
sizeof(int), &LDA, VALUE,
sizeof(double)*szeW, NULL, SCRATCH,
sizeof(double), result, OUTPUT | GATHERV,
0);
} else {
QUARK_Insert_Task(quark, CORE_zlantr_f1_quark, task_flags,
sizeof(PLASMA_enum), &norm, VALUE,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(PLASMA_enum), &diag, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex64_t)*szeA, A, INPUT,
sizeof(int), &LDA, VALUE,
sizeof(double)*szeW, NULL, SCRATCH,
sizeof(double), result, OUTPUT,
sizeof(double)*szeF, fake, OUTPUT | GATHERV,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlantr_quark = PCORE_zlantr_quark
#define CORE_zlantr_quark PCORE_zlantr_quark
#endif
void CORE_zlantr_quark(Quark *quark)
{
double *normA;
PLASMA_enum norm, uplo, diag;
int M;
int N;
PLASMA_Complex64_t *A;
int LDA;
double *work;
quark_unpack_args_9(quark, norm, uplo, diag, M, N, A, LDA, work, normA);
*normA = LAPACKE_zlantr_work(
LAPACK_COL_MAJOR,
lapack_const(norm),
lapack_const(uplo),
lapack_const(diag),
M, N, A, LDA, work);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlantr_f1_quark = PCORE_zlantr_f1_quark
#define CORE_zlantr_f1_quark PCORE_zlantr_f1_quark
#endif
void CORE_zlantr_f1_quark(Quark *quark)
{
double *normA;
PLASMA_enum norm, uplo, diag;
int M;
int N;
PLASMA_Complex64_t *A;
int LDA;
double *work;
double *fake;
quark_unpack_args_10(quark, norm, uplo, diag, M, N, A, LDA, work, normA, fake);
*normA = LAPACKE_zlantr_work(
LAPACK_COL_MAJOR,
lapack_const(norm),
lapack_const(uplo),
lapack_const(diag),
M, N, A, LDA, work);
}
|
function [dfuncGrad] = gpsimMapFunctionalLikeGrad2(model, p)
% GPSIMMAPFUNCTIONALLIKEGRAD2 Compute the functional gradient for GPSIMMAP.
% FORMAT
% DESC computes the functional gradient of the log likelihood for
% use in the MAP approximation to the GPSIM posterior solution.
% ARG model : the model for which the gradient is to be computed.
% RETURN p: the gradient of the log likelihood with respect to the
% points of the function.
%
% SEEALSO : gpsimMapLikeGradientImplicit
%
% COPYRIGHT : Pei Gao, Magnus Rattray and Neil D. Lawrence, 2008
% SHEFFIELDML
dfuncGrad = zeros(1, model.numParams-model.kern.nParams);
gB = zeros(model.numGenes, 1);
gD = zeros(model.numGenes, 1);
gS = zeros(model.numGenes, 1);
ngParamk = model.ngParam/model.numGenes;
if isfield(model,'includeNoise') && model.includeNoise
gn = zeros(model.numGenes, 1);
noiseMat = ones(length(model.t),1)*model.noiseVar;
yvar = model.yvar + noiseMat;
else
yvar = model.yvar;
end
if isfield(model, 'includeRepression') && model.includeRepression
galpha = zeros(model.numGenes, 1);
nBaseParams = 4;
else
nBaseParams = 3;
end
if model.ngParam > 0
ggParam= zeros(model.numGenes, ngParamk);
end
numData = length(model.t);
for k = 1:model.numGenes
if model.ngParam
gInd = k;
else
gInd = 1;
end
for i=1:numData
arg = model.t(i)-model.mapt(p);
if arg >= 0
ind = i + (k-1)*numData;
beta_ik=1/yvar(ind);
[dxdB dxdD dxdS dxdalpha dxdgParam] = gpsimXGradient(model, i, k);
gB(k) = gB(k) - beta_ik*model.g_grad(p,gInd)*dxdB*exp(-model.D(k)*arg ...
+log(model.S(k)) +log(model.step));
factor = model.ypred(model.times_index(i), k) - model.y(ind);
gD(k) = gD(k) - beta_ik*model.g_grad(p,gInd)* (dxdD-arg*factor) ...
*exp(-model.D(k)*arg+log(model.S(k)) +log(model.step));
gS(k) = gS(k) - beta_ik*model.g_grad(p,gInd)* (dxdS*model.S(k) + ...
factor) *exp(-model.D(k)*arg+log(model.step));
if isfield(model, 'includeRepression') && model.includeRepression
galpha(k) = galpha(k) - beta_ik*model.g_grad(p,gInd)*dxdalpha ...
*exp(-model.D(k)*arg+log(model.S(k)) +log(model.step));
end
if model.ngParam > 0
ggParam(k,:) = ggParam(k,:) - beta_ik* (model.g_grad(p,gInd)* ...
dxdgParam+factor*model.dggrad(p, gInd)) *exp(-model.D(k)* ...
arg+log(model.S(k))+log(model.step));
end
if isfield(model,'includeNoise') && model.includeNoise
gn(k) = gn(k) + 2*sqrt(model.noiseVar(k))*beta_ik^2* ...
model.g_grad(p,gInd)*model.S(k)*factor*exp(-model.D(k)*arg+log(model.step));
end
end
end
end
geneParam = nBaseParams + ngParamk;
startPoint = 1;
endPoint = geneParam;
for k = 1:model.numGenes
dfuncGrad(startPoint:(startPoint+2)) = [gB(k) gS(k) gD(k)];
if isfield(model, 'includeRepression') && model.includeRepression
dfuncGrad(startPoint+3) = galpha(k);
end
if model.ngParam > 0
dfuncGrad((startPoint+nBaseParams):endPoint) = ggParam(k,:)';
end
startPoint = startPoint + geneParam;
endPoint = endPoint + geneParam;
end
if isfield(model,'includeNoise') && model.includeNoise
dfuncGrad(end-length(gn)+1:end) = gn';
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.