text
stringlengths
14
5.77M
meta
dict
__index_level_0__
int64
0
9.97k
\section{#1}} \renewcommand{\thesection.\arabic{equation}}}{\thesection.\arabic{equation}} \def\titlepage{\@restonecolfalse\if@twocolumn\@restonecoltrue\onecolumn \else \newpage \fi \thispagestyle{empty}\c@page\z@ \def\arabic{footnote}{\fnsymbol{footnote}} } \def\endtitlepage{\if@restonecol\twocolumn \else \fi \def\arabic{footnote}{\arabic{footnote}} \setcounter{footnote}{0}} \relax \hybrid \parskip=0.4em \makeatletter \newdimen\normalarrayskip \newdimen\minarrayskip \normalarrayskip\baselineskip \minarrayskip\jot \newif\ifold \oldtrue \def\oldfalse{\oldfalse} \def\arraymode{\ifold\relax\else\displaystyle\fi} \def\eqnumphantom{\phantom{(\thesection.\arabic{equation}})}} \def\@arrayskip{\ifold\baselineskip\z@\lineskip\z@ \else \baselineskip\minarrayskip\lineskip2\minarrayskip\fi} \def\@arrayclassz{\ifcase \@lastchclass \@acolampacol \or \@ampacol \or \or \or \@addamp \or \@acolampacol \or \@firstampfalse \@acol \fi \edef\@preamble{\@preamble \ifcase \@chnum \hfil$\relax\arraymode\@sharp$\hfil \or $\relax\arraymode\@sharp$\hfil \or \hfil$\relax\arraymode\@sharp$\fi}} \def\@array[#1]#2{\setbox\@arstrutbox=\hbox{\vrule height\arraystretch \ht\strutbox depth\arraystretch \dp\strutbox width\z@}\@mkpream{#2}\edef\@preamble{\halign \noexpand\@halignto \bgroup \tabskip\z@ \@arstrut \@preamble \tabskip\z@ \cr}% \let\@startpbox\@@startpbox \let\@endpbox\@@endpbox \if #1t\vtop \else \if#1b\vbox \else \vcenter \fi\fi \bgroup \let\par\relax \let\@sharp##\let\protect\relax \@arrayskip\@preamble} \def\eqnarray{\stepcounter{equation}% \let\@currentlabel=\thesection.\arabic{equation}} \global\@eqnswtrue \global\@eqcnt\z@ \tabskip\@centering \let\\=\@eqncr $$% \halign to \displaywidth\bgroup \eqnumphantom\@eqnsel\hskip\@centering $\displaystyle \tabskip\z@ {##}$% &\global\@eqcnt\@ne \hskip 2\arraycolsep $\displaystyle\arraymode{##}$\hfil &\global\@eqcnt\tw@ \hskip 2\arraycolsep $\displaystyle\tabskip\z@{##}$\hfil \tabskip\@centering &{##}\tabskip\z@\cr} \makeatother \def\begin{eqnarray}{\begin{eqnarray}} \def\end{eqnarray}{\end{eqnarray}} \def\nonumber{\nonumber} \def1.5{1.5} \def\begin{equation}{\begin{equation}} \def\end{equation}{\end{equation}} \def\beq\new\begin{array}{c}{\begin{equation}\oldfalse\begin{array}{c}} \def\end{array}\eeq{\end{array}\end{equation}} \def\stackreb#1#2{\mathrel{\mathop{#2}\limits_{#1}}} \def{\rm Tr}{{\rm Tr}} \def{\rm res}{{\rm res}} \def{\rm Im}{{\rm Im}} \def\Bf#1{\mbox{\boldmath $#1$}} \def{\Bf\alpha}{{\Bf\alpha}} \def{\Bf\beta}{{\Bf\beta}} \def{\Bf\gamma}{{\Bf\gamma}} \def{\Bf\nu}{{\Bf\nu}} \def{\Bf\mu}{{\Bf\mu}} \def{\Bf\phi}{{\Bf\phi}} \def{\Bf\omega}{{\Bf\omega}} \def{\Bf\lambda}{{\Bf\lambda}} \def{\Bf\rho}{{\Bf\rho}} \def{\bfit\sigma}{{\bfit\sigma}} \def\partial{\partial} \def{1\over 2}{{1\over 2}} \def\der#1#2{\frac{\partial{#1}}{\partial{#2}}} \def\displaystyle{\displaystyle} \begin{document} \begin{titlepage} \setcounter{footnote}0 \begin{center} \hfill FIAN/TD-7/97\\ \hfill ITEP/TH-24/97\\ \hfill hep-th/9706050\\ \vspace{0.3in} {\LARGE\bf Insights and Puzzles from Branes: $4d$ SUSY Yang-Mills from $6d$ Models} \\ \bigskip\bigskip\bigskip {\Large A.Marshakov} \footnote{E-mail address: mars@lpi.ac.ru, andrei@heron.itep.ru, marshakov@nbivms.nbi.dk}, \\ {\it Theory Department, P. N. Lebedev Physics Institute, Leninsky prospect 53, Moscow, ~117924, Russia\\ and\\ ITEP, Moscow, ~117259, Russia}\\ \bigskip {\Large M.Martellini} \footnote{Landau Network at Centro Volta, Como, Italy}\\ {\it Dipt. di Fisica, Univ. of Milano and I.N.F.N. Sez. di Milano, Via Celoria 16, 20133 Italy}\\ and\\ {\Large A.Morozov} \footnote{E-mail address: morozov@vxdesy.desy.de} \\ {\it ITEP, Moscow, ~117 259, Russia}\\ \end{center} \bigskip \bigskip \begin{abstract} $5$-branes of nontrivial topology are associated in the Diaconescu-\-Hanany-\-Witten-\-Witten (DHWW) approach with the Seiberg-\-Witten (SW) theory of low-energy effective actions. There are two different "pictures", related to the IIA and IIB phases of $M$-theory. They differ by the choice of $6d$ theory on the $5$-brane world volume. In the IIB picture it is just the $6d$ SUSY Yang-Mills, while in the IIA picture it is a theory of SUSY self-dual 2-form. These two pictures appear capable to describe the (non-abelian) Lax operator and (abelian) low-energy effective action respectively. Thus IIB-IIA duality is related to the duality between Hitchin and Whitham integrable structures. \end{abstract} \end{titlepage} \newpage \setcounter{footnote}0 \section{Introduction} According to general principles of string program, various quantum field theory models are identified with the various classical configurations (``vacua'') of the string theory, which can be considered as a kind of universal object of the Quantum Field Theory. Recent advances in this direction appeared due to the introduction of the new class of string vacua: described in terms of the BPS-saturated branes. At present stage the focus of research is on the branes of non-trivial topology. In particular, the system of parallel $p$-branes appears to be associated with the $p+1$-dimensional (SUSY) Yang-Mills models \cite{W1} and non-perturbative phenomena in the Yang-Mills theory can be reformulated as interactions of branes. This interaction makes the geometry of branes non-flat and in the low-energy limit the nontrivial geometry plays the same role as compactification, thus effectively reducing the naive number of the space-time dimensions. It opens a way for geometrical reinterpretation of the interaction in Yang-Mills theory: the old dream is getting real. The simplest realization of this idea -- the DHWW construction \cite{D,HW,W2} allows one to associate the non-perturbative low-energy $p$-dimensional SUSY Yang-Mills (SYM) theory with non-trivial vacua of the $p+1$-dimensional SUSY gauge theory of forms on the brane world volume \footnote{The role of non-trivial SYM vacua was emphasised in \cite{W1}. Technically we seem to overcome the argument of \cite{W1} against considering the Dirichlet $5$-branes (i.e. against our type-IIB picture) due to nontrivial boundary conditions for the scalar fields, see sect.4 below.}. This sheds light to the mysteries of the SW theory \cite{SW1,SW2,SW3} of the low-energy effective actions (RG-flows) in $N=2$ SYM theory. In \cite{W2} Witten interpreted the SW curve as topologically nontrivial constituent of the brane configuration. In this paper we discuss how the (Toda chain) Lax operator may arise from the DHWW construction for $p=4$. As anticipated in \cite{MW2,G} this can be understood in terms of $p+1=6$-dimensional SUSY Yang-Mills theory on the world volume of the $5$-brane. While being adequate for the description of renormalization group (RG) flow from a non-abelian theory in the ultraviolet (UV) limit and of emerging integrable structure, such essentially IIB stringy picture is not enough, however, to obtain a simple description of the prepotential. Instead, this is straightforward in the dual IIA-inspired picture \cite{W2} when the SUSY $p+1=6$ dimensional theory on a brane world volume is a theory of self-dual 2-form. The whole construction is a direct developement of Diaconescu's \cite{D} original reasoning for $p=1$ (and its analog for $p=3$), where the Nahm equations \cite{N,CG} arise as non-trivial generalization of the Toda-chain formalism (relevant for $p=4$). It makes the appearence of a complex spectral curve and prepotential a little more natural -- though it is hardly an explanation in intrinsic terms of the SYM theory, and universality of emerging structures is not quite obvious. Even more important, these two ingredients of the SW theory (the curve and the prepotential for the {\it given} curve) remain linked to two different "pictures" in M-theory. Thus the main dynamical question -- of the derivation of the SW ansatz {\it as a whole} -- or \cite{GKMMM,oth}, of the derivation of abelian Whitham effective low-energy dynamics from the non-abelian Yang-Mills-Hitchin one -- is not resolved, but reinterpreted as the question about duality between IIA and IIB-type pictures, i.e. is put closer to the main stream of the studies of string dualities. \section{DHWW construction} In the DHWW construction one essentially considers a $5$-brane in $M$-theory \footnote{Original papers \cite{D} and \cite{HW} deal with various degenerations of this construction, when some compactification radia go to zero, thus giving rise to $1,3,4$-branes. See also \cite{pre} for some important preliminary works and \cite{dev} for more examples.}. In the first-quantized formalism (still the only one available in most string theory considerations), its dynamics is effectively described by the world-volume ($6d$) theory of either the SYM -- in the type IIB picture or the SUSY self-dual 2-form $C = \{C_{MN}\}$, $dC = \ast dC$ -- in the type IIA picture. After compactification on a circle the low-energy theory is $5d$ SYM, and compactification on a Riemann surface (complex curve) $\Sigma$ leads to a world-volume $4d$ $N=2$ SYM. As usual \cite{W1}, the gauge group $SU(N_c)$ is defined by topology of the brane, and in the low-energy regime it is broken down to the abelian $U(1)^{N_c-1}$, with the scalar (adjoint Higgs) vacuum expectation values identified with (some) moduli of the complex structure on $\Sigma$. Most important, in order to allow interpretation in terms of spontaneously broken $SU(N_c)$ gauge symmetry, the choice of the Riemann surface $\Sigma$ is severely restricted: to hyperelliptic complex curves, being at the same time $N_c$-fold coverings of a cylinder and associated to the Toda-chain integrable systems. Their appearance in the form of either $2$-fold or $N_c$-fold covering is responsible for two possible descriptions: in terms of $SU(2)$ and $SU(N_c)$ groups -- well known both in the brane language \cite{HW,W2,dev} and in the approach based on integrable systems \cite{GMMM}. The DHWW construction is essentially as follows \cite{W2}: one starts with embedding the $5$-brane's world-volume into $11$-dimensional target space-time with the co-ordinates $x^0,...,x^{10}$. We further assume that the target space has topology $R^{9}\times T^{2} = R^{9}\times S^1\times S^1$. The second $S^1$ (spanned by $x^{10}$) will be ignored in what follows\footnote{ Of course, it is crucially important for accurate embedding of IIA and IIB strings into generic $M$-theory frame and for the explanation of the {\it origins} of the two pictures and their interrelation -- this is however beyond the scope of present paper.}, while the essential compact co-ordinate will be called $x^9$. Now, one proceeds with a $5$-brane with the world-volume topology $R^5\times S^1$ and parameterized by $(x^0,x^1,x^2,x^3,x^6,x^{9})$, leaves aside four flat dimensions ($x^0,x^1,x^2,x^3$ -- the space-time of the low-energy $4d$ $N=2$ SYM theory), and ends up with a cylinder $R\times S^1$ embedded into the target space along $(x^6,x^9)$ dimensions. We use the notation $z = x^6+ix^9$ for the corresponding complex co-ordinate. Next, in order to get a non-trivial gauge group: spontaneously broken $SU(N_c) \rightarrow U(1)^{N_c-1}$, one needs $N_c$ {\it parallel} copies of the cylinder (see Fig.1). Different cylinders have different positions in ``transverse'' space $V^{\bot} = (x^4,x^5,x^7,x^8)$. Moreover \cite{D}, to get not just a remnant $U(1)^{N_c-1}$, but indeed a spontaneously broken non-abelian theory, these parallel cylinders should come from a {\it bound state} of $N_c$ branes i.e. should be different parts of the {\it same} brane \cite{W2}. It means that the cylinders should be all glued together (see Fig.2). Actually in the weak coupling limit they are glued at infinity, while increasing coupling constant distorts them along their entire length. Since the cylinders are 2-dimensional and parallel, projection of this entire configuration onto $V^{\bot}$ is also 2-dimensional. Supersymmetry requires it to be just a plane in $V^{\bot}$: $C = R^2 \in V^{\bot}$, we will describe it in terms of the complex coordinate $\lambda = x^4 +ix^5$. Introducing coordinate $w = e^{z}$ to describe a cylinder, we see that the system of non-interacting branes (Fig.1) is given by $z$-independent equation \beq\new\begin{array}{c} P_{N_c}(\lambda) = \prod_{\alpha = 1}^{N_c} (\lambda - \lambda_\alpha) = 0, \label{nibr} \end{array}\eeq while their bound state (Fig.2) is described by the complex curve $\Sigma _{N_c}$ \cite{W2}: \beq\new\begin{array}{c} \Lambda^{N_c}\left(w + \frac{1}{w}\right) = 2P_{N_c}(\lambda) \ \ \ \ \ \ \ \ \hbox{or} \nonumber \\ \Lambda^{N_c}\cosh z = P_{N_c}(\lambda) \label{todacur} \end{array}\eeq In the weak-coupling limit $\Lambda \rightarrow 0$ (i.e. $\frac{1}{g^2} \sim \log\Lambda \rightarrow \infty$) one comes back to disjoint branes (\ref{nibr}) \footnote{In other words, for $|z| \ll |\log\Lambda|$, $\lambda$ is almost independent of $z$ and confined to be almost equal to some of $\lambda_\alpha$. Only when $|z| \sim |\log\Lambda|$ coordinate $\lambda$ is allowed to deviate from fixed position and "interpolate" between -- different $\lambda_\alpha$'s. } \footnote{Eq.(\ref{todacur}) and Fig.2 decribe a hyperelliptic curve -- a double covering of a punctured Riemann sphere, \beq\new\begin{array}{c} y^2 = \frac{\Lambda^{2N_c}}{4}\left(w - \frac{1}{w}\right)^2 = P_{N_c}^2(\lambda) - \Lambda^{2N_c} \nonumber \end{array}\eeq Such hyperelliptic curves and their period matrices are the main ingredients of the SW ansatz \cite{KLTY,AF,HO} for the $4d$ $N=2$ SUSY low-energy effective actions.}. Thus we finally got a $5$-brane of topology $R^3\times\Sigma _{N_c}$ embedded into a subspace $R^5\times S^1$ (spanned by $x^1,...,x^6,x^9$) of the full target space. The periodic coordinate is \beq\new\begin{array}{c}\label{perco} x^9 = \arg P_{N_c}(\lambda) = {\rm Im}\log P_{N_c}(\lambda) = \sum _{\alpha = 1}^{N_c} \arg (\lambda - \lambda _{\alpha}) \end{array}\eeq \section{Lax operator} According to \cite{GKMMM}, occurence of the complex curves like $\Sigma _{N_c}$ is a manifestation of hidden integrable structure behind the theory of renormalization group (RG) flows. Namely \cite{GKMMM,MW1,NT,IM3,Mar,Do,Kl}, equation (\ref{todacur}) describes the spectral curves of the ($0+1$-dimensional, $N_c$-periodic) Toda-chain hierarchy: \beq\new\begin{array}{c} \det_{N_c\times N_c} (\Lambda{\cal L}(z) - \lambda\cdot {\bf 1}) = 0, \label{laxtoda} \end{array}\eeq The $SU(N_c)$ Lax operator \beq\new\begin{array}{c}\label{lax} {\cal L}(z) = \vec p \vec H + e^{\vec\alpha_0\vec q}(e^{z} E_{\vec\alpha_0} + e^{-z}E_{-\vec\alpha_0}) + \sum_{\rm simple\ \vec\alpha >0} e^{\vec\alpha\vec q} (E_{\vec\alpha } + E_{-\vec\alpha}) \nonumber \\ \vec\alpha_0 = -\sum_{simple\ \vec\alpha > 0}\vec\alpha \end{array}\eeq where $\vec H$ are the diagonal (Cartan) $SU(N_c)$ matrices and $E_{\vec\alpha }$ are matrices corresponding to the roots of $SU(N_c)$: $E_{\vec\alpha _{ij},mn} = \delta _{mi}\delta _{nj}$. Only the simple roots with $j=i\pm 1$ appear in (\ref{lax}). The Hamiltonians of the Toda chain are symmetric polynomials of parameters $\lambda _{\alpha}$ in (\ref{nibr}), e.g. \beq\new\begin{array}{c} \Lambda ^2h_2 \equiv \Lambda ^2\left( {\vec p}^2 + e^{2\vec\alpha_0\vec q} + \sum_{\rm simple\ \vec\alpha >0} e^{2\vec\alpha\vec q} \right) = \sum _{\alpha < \beta}\lambda _{\alpha}\lambda _{\beta} \end{array}\eeq From the point of view of the DHWW construction the shape of the complex curve $\Sigma_{N_c}$ should not be just guessed or postulated: it describes the eigenvalues of the scalar field $\Phi(z)$ -- the member of the $6d$ supermultiplet, i.e. $\lambda _{\alpha}$'s are solutions of the equation \beq\new\begin{array}{c}\label{curgen} \det_{N_c\times N_c} (\Phi(z) - \lambda\cdot {\bf 1}) = 0, \end{array}\eeq which describes mutual positions of the branes, i.e. our cylinders. Thus, comparing (\ref{laxtoda}) and (\ref{curgen}), we conclude that there is a natural identification \beq\new\begin{array}{c} \Lambda{\cal L}(z) \sim \Phi(z) \end{array}\eeq This is in fact a general point in the Hitchin approach to integrable systems \cite{Hi,GN1,DW} and this was already used many times in applications of this formalism to investigation of the Seiberg-Witten effective theory \cite{DW,Mart,GM,IM1,G}. Thus, now we have something to check: the Lax operator (\ref{lax}) should naturally arise from the equations of motion for the scalar field $\Phi(z)$. Moreover, in order to preserve supersymmetry, it should satisfy an even more restrictive condition: the linear BPS-like equation. \section{The IIB type picture} In order to explain how it happens, let us analyze the DHWW construction in the type IIB picture, when the theory on the $5$-brane world volume is $6d$ SYM. The mutual position of the cylinders on Fig.1 is described by the coordinates in orthogonal space $V^{\bot}$ (spanned by $x^4,x^5,x^7,x^8$), i.e. by four scalar fields $\Phi^{(4)},\Phi^{(5)},\Phi^{(7)},\Phi^{(8)}$ -- the members of the $6d$ SYM gauge multiplet. As usual, they are taking values in the adjoint representation of the gauge group $SU(N_c)$, where $N_c$ is the number of cylinders, i.e. co-ordinates $x^4,\ldots,x^8$ are substituted by non-obligatory commuting matrices $\Phi^{(4)},\ldots, \Phi^{(8)}$. The members of gauge multiplet are associated with the open strings streched between the cylinders, the corresponding $10d$ vector field $A_S=\{ A_M,A_{\mu} \} $ in the bulk naturally decomposes into the components with $M=0,1,2,3,6,9$ -- considered as $6d$ vector from the point of view of the effective theory on the brane -- and with $\mu =4,5,7,8$ -- associated with four above-mentioned scalars. The nonabelian interaction arises due to the processes like in Fig. 3. In a vacuum state the scalar fields satisfy the BPS-like condition \beq\new\begin{array}{c}\label{bps} D_M\Phi \equiv \partial _M\Phi + [A_M,\Phi ] = 0, \ \ \ F_{MN} = 0 \end{array}\eeq This equation is so simple at least when only one of the fields $\Phi^{(4)},\ldots,\Phi^{(8)}$ is nonvanishing. This is essentially the case for the configuration of Fig.2, arising from Fig.1 when the brane interaction is switched on: Fig.2 implies that some scalar field, say $\Phi\equiv \Phi^{(4)}+i\Phi^{(5)}$, develops a nonvanishing $z$-dependent vacuum expectation value -- this is exactly the statement that the cylinders are distorted and glued together. In order to explain/derive Fig.2, it is necessary to demonstrate that eq. (\ref{bps}) has a {\it non-trivial} solution $\Phi (z)\neq const$. The reason for this is that non trivial boundary conditions are imposed on $\Phi$ at $z\rightarrow\pm\infty$. In order to understand how they should be adequately described, let us consider first the UV-finite version of the SW theory and then take the double-scaling limit back to the asymptotically free situation. The way to do this is well known and examined in detail in \cite{SW2,DW,IM1}. One should add to the $4d$ $N=2$ SUSY pure gauge theory an extra matter hypermultiplet in the adjoint representation with the mass $m$. When $m=0$, one gets a theory with $N=4$ SUSY which is UV-finite with the UV coupling constant $\tau = {i\over g_{UV}^2} + {\theta\over 2\pi}$. When $m\neq 0$ it remains UV-finite, but acquires a nontrivial RG-flow. The original pure $N=2$ SYM theory is restored in the double-scaling limit when $\tau\rightarrow i\infty$, $m\rightarrow\infty$, so that $m^{N_c}e^{2\pi i\tau}\equiv\Lambda ^{N_c}$ remains finite. Within the framework of the SW theory this corresponds to a spectral curve -- a cover of a torus (with complex modulus $\tau $) which in the limit $\tau\rightarrow i\infty$ degenerates into a cylinder. Associated integrable system is the elliptic Calogero-Moser model with the coupling constant $m$ \cite{GN2,Mart,GM,IM1} which in the double-scaling limit \cite{Ino} turns into a Toda chain. From the point of view of the brane picture at Fig.1 it means that one should first substitute the cylinders by tori with the same modulus $\tau$. The isolated tori would correspond to the vanishing parameter $m$, while non-vanishing $m$ means that the scalar field $\Phi$ acquires nontrivial boundary consitions, or is a section of a nontrivial (holomorphic) bundle. In other words, when one takes cylinders from Fig.1 and glues the ends to make a torus -- the fields jump, and on the torus the equation (\ref{bps}) acquires a non-zero r.h.s., which survives in the double-scaling limit. More technically, on a torus one cannot fix the gauge ${\bar A} \equiv A_6+iA_9 =0$, by gauge transformation ${\bar A}$ can be at best brought to diagonal form ${\bar A} = diag(a_1,...,a_{N_c})$. Then the corresponding component of equation (\ref{bps}) becomes\footnote {There are different ways to interpret the $\delta $-function in the r.h.s. of (\ref{hi}): one can say, for example \cite{G}, that $z=z_0$ is the point where "vertical brane" of original presentation of \cite{D,HW} intersect the "horisontal branes" -- our tori. In Fig.2 the point $z_0$ is at infinity, i.e. exactly where nontrivial boundary conditions are imposed in eq.(\ref{bps}).} \beq\new\begin{array}{c}\label{hi} \bar\partial\Phi ^{ij} + (a_i-a_j)\Phi ^{ij} = m(1-\delta ^{ij})\delta (z - z_0) \end{array}\eeq so that \beq\new\begin{array}{c} \Phi ^{ij}(z) = p_i\delta ^{ij}+ m(1-\delta ^{ij}) e^{(a_i-a_j)(z-{\bar z})} {\theta (z - z_0 + {a_i-a_j\over\pi{\rm Im}\tau})\over\theta (z - z_0)} \end{array}\eeq To compare with the conventional Lax operator of the elliptic Calogero-Moser model \cite{KriCal}, one should make a gauge transformation \beq\new\begin{array}{c}\label{laxkri} \Phi ^{ij}(z)\rightarrow (U^{-1}\Phi U)^{ij}(z) = p_i\delta ^{ij}+ m(1-\delta ^{ij}) e^{(a_i-a_j)z} {\theta (z - z_0 + {a_i-a_j\over\pi{\rm Im}\tau})\over\theta (z - z_0)} \end{array}\eeq with $U^{ij} = e^{(a_i-a_j){\bar z}}$, then the explicit dependence on ${\bar z}$ is eliminated but $\Phi (z)$ becomes a multivalued function or a section of a nontrivial bundle over torus. The Lax operator (\ref{lax}) is obtained from (\ref{laxkri}) in the double-scaling limit \cite{Ino}. Of course, there is a way to describe relevant nontrivial boundary conditions directly in terms of Fig.2 (without additional compactification-/-decompactification of the $x^6$ dimension), but the above presentation reveals better the origins of what happens. Thus, in the type IIB picture we derived the {\it shape} of the curve (\ref{todacur}), (\ref{laxtoda}), (\ref{curgen}) "from the first principles". The next step would be to derive the effective action of emerging low-energy $4d$ theory. However, here one runs into problems. Since the world-volume action is not quadratic, it is necessary to take non-trivial average over the fields which become massive due to the Higgs mechanism, moreover this average includes non-perturbative corrections. This is more or less the same as the original problem in the SW theory, without any obvious simplifications. As explained in \cite{GKMMM,Mar}, from the point of view of integrable hierarchies the derivation of the low-energy effective action is the aim of the so-called Bogolyubov-Whitham averaging method, which is still far from being throughly developed. Remarkably, despite such problems, the net {\it result} of this procedure can be easily described in terms of period integrals on spectral surfaces, i.e. in the framework of the prepotential theory (or that of the quasiclassical $\tau$-functions) \cite{Kr,Dubr,IM2}, which is in a sense "dual" to the Hitchin theory \cite{Mar,Mar2}. This is exactly in parallel to what happens in SW theory: while there is no clear way to {\it derive} effective action directly, the ansatz can be easily suggested for what it actually is. In other words, despite the brane vacuum configuration is derived exactly in the type IIB picture, this picture is not sufficient itself for the derivation of the effective action (at least it is not straightforward). However, according to \cite{W2}, this problem can be solved in the "dual" type IIA picture. \section{IIA type picture} In this picture instead of the $6d$ SYM one considers a $6d$ SUSY theory of self-dual 2-form $C = \{ C_{MN}\}$, $dC ={\ast} dC$ on the world volume of a $5$-brane. It means, first, that instead of attaching open strings to the $5$-brane, as in Fig.3, one has to consider now "open" membranes, see Fig.4. The important difference with the type IIB picture of the previous section is that in the relevant approximation the theory of 2-forms is essentially abelian. Even if there are matrices $C_{MN}^{ij}$ in the adjoint representation of $SU(N_c)$ associated with the vertical cylinders (membranes) attached between $i$-th and $j$-th horisontal cylinders, no nonabelian interacting theory can arise since such interaction is inconsistent with the gauge invariance. Only non-linear interaction of the non-minimal type can appear -- like ${\rm Tr}(dC)^4$, expressed through the tension of $C$. Such terms, however, contain higher derivatives (powers of momentum) and they seem irrelevant in the low-energy effective actions. This "abelian" nature of the 2-form theory makes the description of the Lax operator (vacuum expectation value of the scalar members of the supermultiplet which describe the transverse fluctuations of the $5$-brane), and thus the derivation of the shape of the curve $\Sigma _{N_c}$ in the type IIA picture, much less straightforward. Instead, exactly due to the fact that the action on (flat) world-volume is essentially quadratic \beq\new\begin{array}{c}\label{act} \int _{d^6x}|dC|^2 + \hbox{SUSY terms}, \end{array}\eeq in this picture there are no corrections to the form of the effective $4d$ action -- once $\Sigma _{N_c}$ is given. It is enough to consider the dimensional reduction of (\ref{act}) from 6 to 4 dimensions \cite{W2}. Such reduction implies that the 2-form $C$ is decomposed as \beq\new\begin{array}{c}\label{ver} C_{\mu z} = \sum _{i=1}^{N_c-1}\left(A_{\mu}^i(x)d\omega _i(z) + {\bar A}_{\mu}^i(x)d{\bar \omega} _i(\bar z)\right) \end{array}\eeq where $d\omega _i$ are canonical holomorphic 1-differentials on $\Sigma _{N_c}$ \footnote{Actually, before the double scaling limit described in the previous section, the curve $\Sigma _{N_c}$ is compact of genus $N_c$ (when the $x^6$ direction is also compactified along with $x^9$) and the curve possesses $N_c$ holomorphic differentials. However, one of them develops a simple pole when $z\rightarrow\infty$ and thus is ignored in (\ref{act}). Also in our simplified description we ignore other components of the 2-form: $C_{z\bar z}$ and $C_{\mu\nu}$ which are related to each other by the selfduality condition $$ \partial _{\lambda}C_{z\bar z} = {1\over\sqrt{g}}\epsilon_{\lambda\mu\nu\rho} \partial _{\rho}C_{\mu\nu} $$ and correspond from the $4d$ point of view to a (real) scalar. The whole picture thus would contain {\it three complex} scalar fields, two of which become massive in the configuration we consider. }, $d{\bar \omega} _i$ -- their complex conjugate, and $A_{\mu}^i$, ${\bar A}_{\mu}^i$ depend only on the four $4d$ co-ordinates $x=\{ x^0,x^1,x^2,x^3\} $. If the metric on $\Sigma _{N_c}$ is chosen so that $\ast d\omega _i = - d\omega _i$, $\ast d{\bar \omega} _i = + d{\bar \omega} _i$, the self-duality of $C$ implies that the 1-forms $A$ and $\bar A$ in (\ref{ver}) correspond to the anti-selfdual and selfdual components of the $4d$ gauge field with the curvature (tension) $G = \{ G_{\mu\nu}\}$: \beq\new\begin{array}{c} dA^i = G^i -{ \ast} G^i \nonumber \\ d{\bar A}^i = G^i +{ \ast} G^i \end{array}\eeq It remains to subsitute this into (\ref{act}) and use the relations \beq\new\begin{array}{c} \int _{\Sigma _{N_c}}d\omega_i\wedge d{\bar \omega} _j = 2i{\rm Im} T_{ij} \nonumber \\ \int _{\Sigma _{N_c}}d\omega_i\wedge d{\omega} _j = 0 \end{array}\eeq where $T_{ij}$ is the period matrix of $\Sigma _{N_c}$ (and depends on the v.e.v.'s of the transverse scalar fields once the shape of the curve $\Sigma _{N_c}$ -- its embedding into the $(x^4,x^5,x^6,x^9)$-space is fixed. The result for the $4d$ effective action is \beq\new\begin{array}{c} \int _{d^4x}{\rm Im} T_{ij}G_{\mu\nu}^iG_{\mu\nu}^j + \hbox{SUSY terms} \end{array}\eeq This is essentially the SW answer of refs. \cite{SW1,SW2}, only the part with the topological $\theta$-term is ignored. It can be restored by more careful treatment of the self-dual 2-forms: the action (\ref{act}) is obviously too naive. There are various approaches developed for this purpose, see for example refs. \cite{V,W3,Schwarz,PST,West} etc. Though in principle dictated by supersymmetry, the analog of expansion (\ref{ver}) is not so trivial for the scalar fields (the superpartners of the antisymmetric form in $6d$ and the vector bosons in $4d$). As usual in the Green-Schwarz formalism on topologically non-trivial manifolds \cite{KM}, like $\Sigma_{N_c}$, the "embedding matrix" $\Pi_z = \partial_z\Phi$ is actually substituted by 1-form on $\Sigma$, with holomorphic zero modes, \beq\new\begin{array}{c} \Pi^{(0)}_z = \sum_{i=1}^{N_c-1} \Pi^i(x) d\omega_i(z) \end{array}\eeq This is important for explanation why $N_c-1$ different scalars emerge from a single $\Phi$, and why the period matrix of $\Sigma$ appears in the scalar Lagrangian. Especially transparent should be (reformulation of) the formalism of ref.\cite{PST}, where appropriate auxiliary field is actually a 1-form on $\Sigma_{N_c}$, which after gauge fixing becomes \beq\new\begin{array}{c} v^{(0)}_z = \sum_{i=1}^{N_c-1} v^i(x) d\omega_i(z) \end{array}\eeq \section{Conclusion} We argued that the recent advance of ref.\cite{W2} (which reformulated the SW anzatz in the language of branes and therefore inspired an anzatz for what the interaction of branes does with the naive DHW construction) still does no resolve the basic problem of all previous considerations: two basic different ingredients of the SW theory (the spectral curve and the prepotential) are well justified in two dual pictures. However, it brings the issue even closer to the main mysteries of string dualities. In particular it helps to approach the (still) anticipated discovery of integrable structures behind the string dynamics. In this framework one expects extrapolation of the known results for $2d$, $3d$ and $4d$ models to higher dimensions. As to the {\it origin} of the integrability in the theory of renormalization group flows, it is a subject of a different investigation. A possible direction has been suggested in ref.\cite{GKMMM}, and emerging relation between the IIB-IIA and the ("nonabelian") Hitchin - ("abelian") Whitham dualities can provide new insights on this way. However, even in the restricted framework -- of generalization of the SW theory to higher dimensions, strings and $M$-theory -- a lot remains obscure. One of the interesting things to do is to find the brane analog/interpretation of the mysterious WDVV-like equations \cite{MMM}, which are peculiar for the majority of SW effective theories in four and five dimensions, are related to multiplication "algebra" of 1-forms and constitute a non-trivial deformation of the WDVV equations for quantum cohomologies \cite{WDVV}. \section{Acknowledgements} We are indebted to many colleagues for valuable discussions concerning the subject of the present paper, especially to E.Akhmedov, M.Bianchi, E.Corrigan, A.Gorsky, A.Mironov, N.Nekrasov, A.Sagnotti, J.Schwarz, M.Tonin and P.West. A.Marshakov and A.Morozov acknowledge the support of the Cariplo Foundation and hospitality of the Milano University and Centro Volta in Como during the work on this paper. This research was partially supported by the grants RFBR 96-02-19085 (A.Marshakov) and RFBR 96-15-96939 (A.Morozov).
{ "redpajama_set_name": "RedPajamaArXiv" }
1,684
{"url":"https:\/\/tex.stackexchange.com\/questions\/331653\/enumerate-list-environment-split-by-equation","text":"# Enumerate list environment split by equation\n\nI need to reproduce the following text:\n\nBasically, I have an enumerate list starting (1.), then an equation environment than some text related to the previously ended point 1. and then after the other enumerated list.\n\nNormally, I would have typed the following code\n\n\\documentclass[12pt, a4widepaper]{article}\n\n\\usepackage{enumerate}\n\\usepackage{enumitem}\n\n\\begin{document}\n\\begin{enumerate}\n\\item Suppose that Susan ... She sets up th regression model:\n\\end{enumerate}\n\\begin{equation*}\nY_i = \\beta_0+ \\beta_i X_i + u_i\n\\end{equation*}\n% TEXT MISSING RELATED TO ITEM ENDED BEFORE EQUATION\n\\begin{enumerate}\n\\item Suppose you are interested ...\n\\end{enumerate}\n\n\\end{document}\n\n\nBy doing so the \"TEXT MISSING RELATED TO ITEM ENDED BEFORE EQUATION\" will be no more considered as part of the \\enumerate environment.\n\nAdditional ending note: Using this code, the equation environment produces white space above and below the equation stated. Is there a way to better present an equation between two paragraphs as in this case?\n\n\u2022 why is it necessary to end the enumerate and restart it? adding \\usepackage{amsmath} in the preamble, and commenting out the \"broken\" enumerate commands, this ran and produced reasonable (if spacy) output. but the spaces can be controlled. (i have to leave now, but there are other people here who can take this on.) \u2013\u00a0barbara beeton Sep 27 '16 at 21:50\n\u2022 Sure! Don't know why I started breaking the enumerate environment. \u2013\u00a0Francesco Bianchi Sep 27 '16 at 22:17\n\nJust type the equations inside the enumerate; there's no reason for ending it.\n\nIf you feel that the spacing around the equations should be reduced in this case, you can use enumitem features, but I don't think you should.\n\n\\documentclass{article}\n\\usepackage{amsmath}\n\\usepackage{enumitem}\n\n\\DeclareMathOperator{\\Var}{Var}\n\\setlist[enumerate]{\nbefore=\\setlength{\\abovedisplayskip}{.5\\abovedisplayskip}%\n\\setlength{\\belowdisplayskip}{\\belowdisplayshortskip},\n}\n\n\\begin{document}\n\n\\begin{enumerate}\n\\item Suppose that Susan is a research analyst working for an insurance\ncompany. She wants to analyze whether the color of a car has a significant\neffect on the probability of its causing an accident. She has a data set\nfor the probability of causing an accident (obtained from other data sources)\n(denoted by~$Y$) and the dummy variable~$X$ which takes the value~$1$ if the\ncar's color is red and $0$~otherwise. The observations $\\{(X_i,Y_i)\\}_{i=1}^n$\nare i.i.d.\\@ and $n=100$. She sets up the regression model:\n\\begin{equation*}\nY_i = \\beta_0+ \\beta_i X_i + u_i\n\\end{equation*}\nand assumes that $\\Var(X_1)>0$ and $E[u_i\\mid X_i]=0$. Susan's regression\nestimate of $\\beta_1$ has turned out to be $0.15$. Provide a verbal\ninterpretation of this result.\n\n\\item Suppose you are interested in estimating the effect of hours spent in\nan SAT preparation course ($\\mathit{hours}$) on SAT score ($\\mathit{sat}$).\nThe population is high school seniors for a particular year. Write the\npopulation regression model as\n\\begin{equation*}\n\\mathit{sat}=\\beta_0+\\beta_1\\mathit{hours}+u.\n\\end{equation*}\nList at least two factors contained in~$u$. Are these likely to have a\nnegative or positive correlation with $\\mathit{hours}$? Analyze the sign\nof the bias of the OLS estimator of $\\beta_1$ in the presence of these\nomitted factors.\n\\end{enumerate}\n\n\\end{document}\n\n\nA few points to note:\n\n1. there is no a4widepaper option\n2. either load enumerate or enumitem, not both; the latter is preferable\n3. I fixed some of the weaknesses in the given example","date":"2021-05-18 21:05:58","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.8543258309364319, \"perplexity\": 2077.996715494422}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 20, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-21\/segments\/1620243991514.63\/warc\/CC-MAIN-20210518191530-20210518221530-00369.warc.gz\"}"}
null
null
Stenoptilia melanoloncha is a moth of the family Pterophoridae. It is known from Kenya. References Endemic moths of Kenya melanoloncha Moths of Africa Moths described in 1927
{ "redpajama_set_name": "RedPajamaWikipedia" }
850
{"url":"http:\/\/www.nealelab.is\/blog\/2017\/9\/13\/heritability-201-types-of-heritability-and-how-we-estimate-it","text":"# Heritability 201 - Types of heritability and how we estimate it\n\nIn Heritability 101 we defined heritability as \u201cthe proportion of variation in a trait explained by inherited genetic variants.\u201d In practice we\u2019ll often rely on variations of this definition, in part because of the differences between this idealized concept of heritability and the reality of what we can actually estimate scientifically. In this post we\u2019ll outline some different \u201cflavors\u201d of heritability, and the ways they can be estimated, with the end goal of explaining what form of heritability we\u2019re reporting from the data of the UK Biobank.\n\n### The quick version:\n\nOur UK Biobank analysis is estimating h2g, or SNP-heritability. This is only the proportion of variation in the trait that can be explained by additive effects of commonly-occurring genetic variants called SNPs (a certain class of DNA mutations), so it\u2019s almost always less than the total heritability (H2) that could be explained by all genetic factors.\n\nWe\u2019re estimating h2g using a method called LD score regression (LDSR); if the choice of method matters to you then you\u2019ll probably appreciate the more technical post here.\n\n### Measuring variation\n\nBefore talking about the different flavors of heritability, it\u2019s useful to define what we mean by \u201cvariation\u201d when we say things like the \u201cthe proportion of variation in a trait explained by\u201d something.\n\nWhen we say \u201cvariation\u201d here what we\u2019re referring to the mathematical concept of \u201cvariance\u201d. Variance is a common metric for measuring how much a trait differs between people in a group. Formally, it\u2019s the average squared difference between a randomly selected person and the \u201caverage\u201d person. For example, across all men and women in the UK Biobank the variance of height in inches is 13.3 (86.0 for height in centimeters), corresponding to a standard deviation of 3.7 inches (9.3 cm). The standard deviation is simply the square root of the variance.\n\nStatisticians like talking about variance (as opposed to more intuitive measures like the range or the mean absolute deviation from average) because it has nice mathematical properties. Most notably, if you have an outcome that is the sum of effects from independent sources (like, say, genes and environment) the variance of the effects from each source add up to the variance of the outcome. Being able to break up the total variance of a trait into different pieces that add up this way is very useful when we want to start talking about the \u201cproportion of variance explained by genetics\u201d, as we will see below.\n\nLastly, talking about variance implicitly means we\u2019re talking about a group or population of individuals. You can\u2019t have an average difference between people with only one person. As we emphasize in Heritability 101, this means that whenever we talk about heritability we are talking about variation in some population of individuals, not about genetics determining some proportion of a trait in any given individual.\n\n### \u201cExplaining\u201d variance\n\nIt\u2019s also worth clarifying the other half of the phrase \u201cthe proportion of variation in a trait explained by\u201d, namely what we mean by \u201cexplained\u201d. In this case, variance that is \u201cexplained\u201d by genetics is variance that could be predicted based on genetic data if we had perfect information about the effects of all genetic variants (which, to be clear, we don\u2019t actually have).\n\nIf you\u2019ve ever heard the phrase \u201ccorrelation is not causation\u201d, that\u2019s the issue were referring to here and why we aren\u2019t simply saying the proportion of variance caused by genetic effects. We are closer to causation since it\u2019s fairly safe to assume that the heritable traits aren\u2019t causing the genetic variants, since our genetics is fixed at conception (with the exception of acquired mutations such as those seen in cancer). It is possible however for genetic variants to be correlated with environmental factors that have a direct causal impact on the trait. That doesn\u2019t mean the genetics aren\u2019t important and informative for that trait, but it does mean we have to be careful about describing effects as causal, even in genetics. So as a precaution against making any premature statements about causality we focus on \u201cexplained\u201d variance instead.\n\nOur starting definition of heritability as \u201cthe proportion of variation in a trait explained by inherited genetic variants\u201d refers to this most general version of heritability. Mathematically, we\u2019d define the broad-sense heritability as:\n\n$H^2&space;=&space;\\frac{\\sigma^2_G}{\\sigma^2_P}$\n\nwhere \ud835\udf0e2G is the variance in the trait explained by genetics (G), and \ud835\udf0e2P is the total variance of the trait in the population.\n\nWe make three important observations about the definition. First, it\u2019s entirely flexible about how specific genetic effects contribute to \ud835\udf0e2G. The broad-sense H2 doesn\u2019t care whether \ud835\udf0e2G \u00a0comes from a single mendelian variant in just one gene, or the small additive effects from variants in 100 different genes, or complex interactions between every variant in the whole genome. We\u2019ll see below that this is an important distinction between broad-sense H2 \u00a0and some of the other types of heritability.\n\nSecond, broad-sense H2 \u00a0is entirely flexible about how \ud835\udf0e2G relates to \ud835\udf0e2P. We could choose to assume that the effects of genes and environment are independent and thus write:\n\n$H^2&space;=&space;\\frac{\\sigma^2_G}{\\sigma^2_G&space;+&space;\\sigma^2_E}$\n\nbut that assumption isn\u2019t required. By simply writing the denominator as \ud835\udf0e2P \u00a0we allow for the possibility that genetic and environmental factors are correlated or interact in some way. This is important since it highlights that the effect of environment on the trait isn\u2019t simply the \u201cremainder\u201d after accounting for all the genetic effects, instead they can overlap and interact in complex ways.\n\n### Narrow-sense heritability (h2)\n\nIn practice, the flexibility of broad-sense H2 \u00a0makes it very hard to estimate without making strong assumptions. Allowing for effects of all possible interactions of all possible genetic variants means having a functionally infinite space of possible effects. One useful way to simplify this is to think of the total variance explained by genetics as a combination of additive effects, dominant\/recessive effects, and interaction effects between different variants.\n\n$\\sigma^2_G&space;=&space;\\sigma^2_A&space;+&space;\\sigma^2_D&space;+&space;\\sigma^2_I$\n\nFor a number of reasons, we might expect the variance explained by additive genetic effects \ud835\udf0e2A to be the largest and most immediately useful portion of the total \ud835\udf0e2G [1]. Focusing on just this additive genetic component leads us to the definition of the narrow-sense heritability h2:\n\n$h^2&space;=&space;\\frac{\\sigma^2_A}{\\sigma^2_P}$\n\nIf there are no dominant\/recessive or interaction effects (i.e. \ud835\udf0e2D = \ud835\udf0e2I = 0) then the narrow-sense and broad-sense heritability are the same (h2 = H2). Otherwise the narrow-sense heritability will be smaller (h2 < H2) since it excludes these other types of genetic effects.\n\nHistorically, most scientific discussion of the heritability of different traits has focused on h2. One of the nice features of h2 is that it implies a simple relationship between between how genetically related two people are and how similar the trait will be for those two people. We can use this relationship to estimate h2 in twin and family studies.\n\nIn the simplest case, we can compare monozygotic twins (often called \u201cidentical\u201d or MZ twins) to dizygotic (\u201cfraternal\u201d or DZ) twins. MZ twins shared all of their DNA [2], while DZ twins share about half of their DNA on average. Twins also largely share the same environment regardless of whether they are MZ or DZ [3]. So to estimate h2 we can observe how correlated a trait is between pairs of MZ twins and how correlated the trait is between DZ twins and see if those correlations are different. If the MZ twins pairs, with their higher genetic similarity, are more strongly correlated than the DZ twin pairs, that suggests that genetics explains some of the variance in the trait [4].\n\nThere has been decades of scientific research on the heritability of human traits using this general approach. Helpfully, a recent effort by Danielle Posthuma and colleagues pooled together much of this work into a single webpage where you can browse twin-based estimates of h2 for a wide variety of traits.\n\n### SNP-heritability (h2g)\n\nThe above flavors of heritability have referred to \u201cgenetic effects\u201d conceptually without requiring any consideration of specific genetic variants and their association with the trait. Now that advances in genetics [5] have made it possible to actually collect data on these specific variants, there\u2019s the opportunity to evaluate how much each of these observed variants contribute to heritability.\n\nIn particular we can consider one type of genetic variant called a single nucleotide polymorphism (SNP), which is a change of a single base pair of DNA at a specific location in the genome. For example, some people may have an A at that location, which other people have a G. There are millions of these locations in the genome that commonly vary between different people, and much of the current research in human genetics is focused on understanding the effects of these variants [6].\n\nSo given a set \u201cS\u201d of SNPs that we\u2019ve observed, how much of the variance in the trait can they explain? That leads us to define the SNP-heritability h2g, the proportion of variance explained by additive effects of the observed SNPs, which we could write as:\n\n$h^2_g&space;=&space;\\frac{\\sigma^2_{SNPs&space;\\in&space;S}}{\\sigma^2_P}$\n\nIf we compare this to the above definitions, it\u2019s evident that h2g \u2266 h2 \u2266 H2 since h2g is limited to additive effects from only a subset of genetic variants.\n\nThis definition of h2g still hides the effects of individual SNPs though, so it\u2019s useful to introduce an alternate version. If we call our trait y, and say each SNP xj has an additive effect \ud835\udefdj [7], then we can write\n\n$y&space;=&space;\\sum_{SNPs&space;\\in&space;S}&space;x_j&space;\\beta_j&space;+&space;\\epsilon$\n\nwhere e is a residual term for effects not explained by the sum of the SNP effects. We can then define h2g based on the variance of this sum of SNP effects compared to the total variance of the trait:\n\n$h^2_g&space;=&space;\\frac{var(\\sum_{SNPs&space;\\in&space;S}&space;x_j&space;\\beta_j)}{var(y)}$\n\nIt\u2019s worth highlighting two key features of h2g. First, you might notice that we\u2019ve defined h2g based on some set of SNPs \u201cS\u201d. In practice, this set of SNPs is going to depend on (a) the SNP data that has been observed and (b) the method used for estimating h2g. This makes it tricky to compare values of h2g between different methods and different studies [8], though in most cases it\u2019s safe to at least assume it refers to commonly-occurring SNPs. Second, the variance explained by SNPs may or may not reflect the effects of those particular SNPs as opposed to the effects of other genetic variants the SNPs are correlated with. This is just an extension of our previous discussion above about the meaning of variance \u201cexplained\u201d, but worth reiterating since it would be easy to misinterpret SNP-heritability as fully excluding the causal effects of other types of genetic variation.\n\nThere are a couple of different methods that have been developed for estimating h2g from observed SNPs. In practice we don\u2019t know the true \ud835\udefdj so we have to use other tricks. The first approach, known as GREML (Genomic relatedness matrix REstricted Maximum Likelihood; commonly implemented in GCTA), uses SNPs to estimate the genetic similarity between random individuals and compare that to their trait similarity. This is conceptually similar to the twin-based estimation described above, but uses the observed low-level genetic similarity in SNP data from individuals who aren\u2019t directly related. You can read about the statistical details here\u00a0with a more recent review here.\n\nA second approach is called linkage disequilibrium (LD) score regression, implemented in ldsc. This is the method we are applying to the UK Biobank data set. LD score regression depends on the key observation that some SNPs are correlated with (i.e. in LD with) other genetic variants, so observing that SNP in turn \u201ctags\u201d information about the effects of other variants. The basic idea then is that if there are lots and lots of small genetic effects spread across the genome (i.e. the trait is \u201cpolygenic\u201d), then the strength of the relationship between each individual SNP and the trait should be (on average) proportional to how much total genetic variation that SNP tags. Statistical details on the LD score regression method can be found here.\n\n### Variance explained by known SNP effects (h2PRS)\n\nAll of the above flavors of heritability are defined based on the \u201ctrue\u201d variance explained by genetic variants. Although we noted above that we don\u2019t know the true effects \ud835\udefdj, we could estimate them from our observed SNP data and then use those estimated values to directly compute:\n\n$h^2_{PRS}&space;=&space;\\frac{var(\\sum_{SNPs&space;\\in&space;S}&space;x_j&space;\\hat{\\beta_j})}{var(y)}$\n\nWe refer to this version of heritability as h2PRS since the sum with estimates \ud835\udefdj is often known as a polygenic risk score (PRS). As with h2g, it depends on the choice of a set S of SNPs. When this set is chosen to be only SNPs reaching genome-wide significance for evidence of association with the trait, this flavor of heritability is sometimes known as h2GWAS.\n\nEstimating h2PRS is valuable because it indicates how well we can predict the trait from the observed SNPs with our current estimates of \ud835\udefdj. In comparison, h2g indicates how well we could theoretically predict the trait from SNPs if we knew their true effect sizes. Inevitably h2PRS \u2266 h2g (\u2266 h2 \u2266 H2) since uncertainty in our estimates of \ud835\udefdj reduces our prediction accuracy, but it\u2019s a useful way to contextualize h2g as the idealized maximum for h2PRS.\n\n### A note on liability vs. observed scale heritability\n\nTo some extent talking about components of the variance of a trait assumes the trait is continuous. For binary traits, such as whether or not someone is diagnosed with a disease, the use of variance as a convenient mathematical quantity becomes problematic.\n\nThe conventional solution is to treat the binary trait as if it has an underlying continuous liability, as depicted above, and then quantify the heritability of that continuous liability. In other words estimate the genetic contribution to the continuous liability as shown in the left plot, based on observing the binary outcome of that liability as shown in the center plot. In some cases we may intentionally select more individuals who have the binary outcome, as shown in the right plot, in which case we have to further adjust the heritability calculations for how that ascertainment has changed the distribution of liability in our sampled individuals.\n\nThe mathematical details of that adjustment to get heritability estimates on the liability scale [9] aren\u2019t critical, but it\u2019s important to be aware that we\u2019re having to make this additional adjustment for binary traits. This adjustment requires making assumptions about the prevalence of the trait in the population, which may or may not be safe in the UK Biobank data depending on the trait. As a result, the estimates of heritability for binary traits should be interpreted carefully, with an expectation that they are at a higher risk of statistical artifacts than than heritability estimates for continuous traits.\n\n### Summary\n\nHopefully we\u2019ve provided some useful context when we say that in UK Biobank data set we\u2019re estimating the SNP-heritability h2g using LD score regression. Assuming our estimate is well calibrated (see Heritability 501\u00a0for lots more discussion of the technical limitations), we can anticipate that this h2g is less than the full contribution of genetics to each trait (h2g \u2266 h2 \u2266 H2) and more than our current ability to predict each trait from the genetic data (h2PRS \u2266 h2g). There will be additional uncertainty in these estimates for binary traits.\n\n### Footnotes\n\n[1]\n\nExcept in extreme edge cases, \ud835\udf0e2A will capture a portion of the variance explained by genetic variants acting through dominant, recessive, or epistatic effects. Additive effects are also well-behaved statistically, making estimation of additive effects easier than the other components of \ud835\udf0e2G. Estimates that have included dominant\/recessive and\/or interaction effects fairly consistently identify \ud835\udf0e2A as the largest component. As a result, most current work on common genetic effects focuses on this additive component. It probably misses some things, but it\u2019s a useful simplification.\n\n[2]\n\nDe novo mutations, mosaicism, etc potentially prevent the whole-genome sequences of monozygotic twins from being truly identical, but it\u2019s close enough for most purposes here.\n\n[3]\n\nAgain we\u2019re simplifying, but for twins raised together we can generally expect them to at least share the same parents, childhood home, schools, neighborhood, etc. There\u2019s plenty of research on this \u201ccommon environment\u201d aspect of twin modelling, for the sake of explanation we\u2019re focusing on the idealized version here.\n\n[4]\n\nSpecifically, given trait correlations rMZ and rDZ between the MZ twin pairs and DZ twin pairs, respectively, the estimate of h2 is 2(rMZ-rDZ).\n\n[5]\n\nThe Human Genome Project to provide a map of the human genome, the HapMap Project identify the structure of genetic variation in the human population, advances in genotyping and sequencing technology to allow robust and efficient measurement of genetic variants, to name a few.\n\n[6]\n\nThis is mostly because they are cheaper and easier to observe. That certainly doesn\u2019t mean there isn\u2019t research on other types of genetic variation though. Insertions, deletions, duplications, and other genetic modifications are all also areas of active research.\n\n[7]\n\nThese are \ud835\udefdj from the best linear predictor of the trait from the set of SNPs S. Importantly, this means these \ud835\udefdj are not the causal effects of each SNP, nor are they the marginal GWAS \ud835\udefdj. Instead, they\u2019re a projection of the causal effects of all genetic variants to the chosen \u201cuniverse\u201d of SNPs. As a result the \ud835\udefdj still exist as population parameters for that projection, but are entirely dependent on the chosen set of SNPs.\n\n[8]\n\nAs an aside for those familiar with LD score regression, this is part of benefit of standardizing analysis to use the common HapMap3 SNPs and pre-computed reference LD scores. It doesn\u2019t fully eliminate the differences between analyses, but it does keep them closer so there\u2019s room for at least some intuition about what constitutes a \u201clarge\u201d or \u201csmall\u201d ldsc h2g.\n\n[9]\n\nMathematically, the conversion between the heritability of the observed binary trait and the more interpretable heritability of the continuous liability is computed as:\n\n$h^2_{liability}&space;=&space;h^2_{observed}&space;\\frac{K(1-K)}{\\varphi(\\Phi^{-1}[K])^2}&space;\\frac{K(1-K)}{P(1-P)}$\n\nwhere K is the frequency of the binary trait in the population, P is the frequency of the binary trait in the observed sample, and the denominator of the first fraction is the squared probability density function evaluated at the K quantile of the inverse cumulative density function of the standard normal distribution. Derivation of this conversion in the genetics context can be found here, but note that does not perfectly resolve the issue of ascertained binary traits.\n\nAuthored by Raymond Walters with contributions from Claire Churchhouse and Rosy Hosking\n\nClaire Churchhouse","date":"2017-09-19 17:13:54","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 9, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.6808953881263733, \"perplexity\": 1263.8650610455652}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2017-39\/segments\/1505818685912.14\/warc\/CC-MAIN-20170919164651-20170919184651-00258.warc.gz\"}"}
null
null
<!DOCTYPE html> <html lang="en"> <!-- CSS --> <link href="../../assets/css/bootstrap.min.css" rel="stylesheet"> <link href="../../assets/main.css" rel="stylesheet"> <link href="../../assets/home.css" rel="stylesheet"> <link href="../../assets/bootstrap-datepicker-1.5.0-dist/css/bootstrap-datepicker.css" rel="stylesheet"> <!-- Script --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript" src="../../assets/bootstrap/js/bootstrap.js"></script> <script type="text/javascript" src="../../assets/bootstrap-datepicker-1.5.0-dist/js/bootstrap-datepicker.js"></script> <head> <title>STOCK MANAGER</title> </head> <body> <div class="container"> <div id="header"> <h1 class="text-center">Edit Histori</h1> </div> <br><br> <div id="content"> <div> <?php include 'sql_connect.php'; $ID = $_GET['id']; $query = "SELECT * FROM histori_penjualan WHERE id='$ID'"; $edit_histori = mysqli_query($con, $query); ?> <?php while($row_edit_histori = mysqli_fetch_array($edit_histori)) { ?> <form id="form-new-histori" class="form-horizontal" method="post" action="edit_histori_into_db?id=<?php echo $ID; ?>"> <div class="form-group"> <label class="col-sm-5 control-label">Tanggal</label> <div class="col-sm-5"> <input id="form-new-histori-tanggal" type="text" name="input-tanggal" class="form-control" placeholder="yyyy-mm-dd Contoh: 2001-12-31" value="<?php echo $row_edit_histori['tanggal'];?>" required> </div> </div> <div class="form-group"> <label class="col-sm-5 control-label">Pembeli</label> <div class="col-sm-5"> <input id="form-new-histori-pembeli" type="text" name="input-pembeli" class="form-control" placeholder="Contoh: Budi" value="<?php echo $row_edit_histori['pembeli'];?>" required> </div> </div> <div class="form-group"> <label class="col-sm-5 control-label">ID komponen</label> <div class="col-sm-3"> <input id="form-new-histori-komponen" type="text" name="input-komponen" class="form-control" placeholder="Contoh: K-1" value="<?php echo $row_edit_histori['komponen'];?>" required> </div> </div> <div class="form-group"> <label class="col-sm-5 control-label">Jumlah</label> <div class="col-sm-5"> <input id="form-new-histori-jumlah" type="number" name="input-jumlah" class="form-control" placeholder="Contoh: 100" min="1" value="<?php echo $row_edit_histori['jumlah_komponen'];?>" required> </div> </div> <div class="form-group"> <label class="col-sm-5 control-label">Harga</label> <div class="col-sm-5"> <input id="form-new-histori-harga" type="number" name="input-harga" class="form-control" placeholder="Contoh: 10000" min="0" value="<?php echo $row_edit_histori['harga'];?>" required> </div> </div> <div class="form-group"> <div class="col-sm-offset-5 col-sm-7"> <button id="form-new-histori-submit" type="submit" class="btn btn-default">Masukkan</button> </div> </div> </form> <?php } ?> </div> </div> </div> </body> <script> $(function(){$("#form-new-histori-tanggal").datepicker({format: 'yyyy-mm-dd', todayHighlight: true, todayBtn: "linked"});}); </script> </html>
{ "redpajama_set_name": "RedPajamaGithub" }
1,578
Antes do protocolo HTTP e da linguagem HTML, existiam tecnologias como o **Gopher** *(The Gopher Project)*. Nela, utilizava-se as setas do teclado para navegar entre as opções de um site. Não haviam imagens, sons, multimídia... Apenas opções para acessar áreas específicas do site que eram navegáveis pelo teclado. ### Primeiro Website Em 6 de Agosto de 1991, foi criado o primeiro website que está ao ar até os dias de hoje e pode ser acessado clicando neste [link](http://info.cern.ch/hypertext/WWW/TheProject.html). ### Navegadores Programas para visualizar as páginas. Em 1991, haviam navegadores como: MidasWWW, ViolaWWW, Cello. Em 1992 surge o navegador Mosaic - desenvolvido no NCSA (Universidade de Illinois). Em 1994 alguns programadores saíram do NCSA e criaram o Netscape. Em 1995 surgiram outros navegadores como IBM WebExplorer, UDI WWW e Internet Explorer. Em 1996, 86% utilizavam Netscape até que dois anos depois (1998) o cenário se inverteu já que o Microsoft Windows utilizava este navegador por padrão - o que gerou conflito entre as duas empresas e processos judiciais. Em 1999, a empresa Netscape foi vendida American Online. Os programadores que fundaram a Netscape resolveram criar outra fundação: Fundação Mozilla. Por quase 10 anos o Mozilla Firefox reinou, até que em 2008 a Google lançou o Google Chrome. Atualmente o cenário de navegadores é balanceado entre Firefox e Chrome. ### Versões do HTML Voltando à primeira versão do HTML, em 1990, era bastante simples, sem muitas funcionalidades mas muito útil pois implementava o sistema de hipertexto. Em 1995 foi criada a segunda versão do HTML, que ficava sob responsabilidade HTML Working Group. Esta segunda versão ganhou cada vez mais adeptos, inclusive empresas de navegadores que estavam auxiliando nas linguagens. No entanto, havia um problema: cada empresa queria criar sua própria tag HTML para seus próprios navegadores. Esse foi um grande problema. Ainda em 1995, foi proposta a terceira versão do HTML, que seria mantida pelo W3C (World Wide Web Consortium), gerenciado por Tim Berners-Lee, o qual determinaria o padrão de criação das tecnologias. Em 1997 foi proposta a quarta versão. Em 2004 o W3C decidiu lançar o XHTML. A Fundação Mozilla, Opera e Apple resolveram criar o WhatWG que desenvolveriam a sua própria versão do HTML. Em 2007, o WhatWG foi apresentado a W3C, que resolveu descontinuar o XHTML e lançando oficialmente o *working draft* do HTML5 em 2008 - que dura até hoje. A quinta versão do HTML possui, como principal diferença, a separação de estilo, semântica e interatividade. Tudo o que é feito é semântico: tem significado! A sua formatação é feita com o CSS, e a interatividade com as páginas utiliza JavaScript.
{ "redpajama_set_name": "RedPajamaGithub" }
6,647
Last Halloween, I proposed a few not-necessarily-horror games to play during this creepiest time of year. I ignored spooky stalwarts like Resident Evil and Silent Hill and focused on subtly scary titles like Batman: Arkham Asylum and Majora's Mask. Now I'm back with five more games that might have slipped your mind this Halloween. Conker isn't all bathroom jokes and sexual innuendo. It's also part gothic horror, at least in chapter seven, appropriately titled "Spooky." Everyone's favorite foul-mouthed squirrel finds himself in a derelict village set on a river of what looks like blood. In order to escape he must fight zombies through a graveyard, confront a vampire bat in a spooky mansion, and toss unsuspecting villagers into a grinder. The Grim Reaper, Gregg, even makes an appearance. As it did with Limbo, developer Playdead manages to spin a delightfully skin-crawling tale with Inside. Players control a vulnerable, fragile young boy who infiltrates a human processing center. Horrors and dangers abound in Inside, including parasitic worms, possessed livestock, and security guards. Scariest of all are the many chase scenes in the game. The young hero must escape from armed men, vicious dogs, and long-haired, ghostly "mermaids." Metroid has long flirted with the macabre, but in Metroid Fusion the developers at Nintendo pushed even further into the realm of suspense and horror with SA-X. Samus Aran's main antagonist in the game, SA-X was the result of a merger between the "X parasite" and pieces of Samus's suit. SA-X appears at random moments throughout Metroid Fusion, forcing an outmatched Samus to run for her life. These moments are some of the most nerve-racking episodes in the entire series. The premise of Resistance —monstrous beings conquering the planet and transforming civilians into otherworldly creatures — is frightening enough. Yet developer Insomniac decided to double down on the scare factor in the sequel, introducing invisible enemies, monster-infested waters, and plenty of claustrophobic passages filled with zombified humans. Demon's Souls is a living nightmare. Through enemy, level, and sound design, developers at From Software created a creaking, groaning, deadly, decaying, and suffocating environment — a world where, excluding the nexus hub, safety feels forever out of reach. Death waits around every corner, whether in the form of the cackling Fat Official or the greasy Depraved Ones, complete with plague doctor beaks. That's my list. Sound off in the comments section with your own! Happy Halloween! We've finally made it to VGChartz's top 10 favourite Final Fantasy songs of all time. These are the ten songs that received the highest number of points during the voting, and they come from five different games that span three different console generations. If you haven't seen the previous articles yet you can view them here: Part 1, Part 2, Part 3, Part 4. It's very interesting that this is the first song from Final Fantasy X that we've seen in this top 50. And that's despite the game receiving more points than any other entry in the series. Naturally, that means you can look forward to seeing a few more songs from it in the top 10. Otherworld is one of the game's two vocal themes and this particular one plays twice over the course of the story. The first time is near the very beginning of the game, when Sin attacks Zanarkand and transports Tidus to Spira. The second one is near the end, during the last real boss fight inside Sin. Otherworld is something of a departure from the series' usual music. A metal track accompanied by harsh vocals sung by Bill Muir, the song's lyrics have sometimes been interpreted as mirroring Tidus' journey throughout Final Fantasy X. It's an unusual song for both the series and Nobuo Uematsu, but no less effective for it, and its placement this high on the list shows the lasting impact it made on those who played Final Fantasy X. When Uematsu began composing the music for Final Fantasy X alongside Masashi Hamauzu and Junya Nakao, he realized that the inclusion of voice acting in the series would necessitate some changes for how the music was handled within the game. In the past the game's music alone had been largely responsible for elevating the drama and mood of a scene, but this time he could rely on the vocals to carry some of that responsibility as well. A Fleeting Dream is one of several arrangements of the game's main vocal theme – Suteki Da Ne. The song is heard a few times, perhaps most notably in the ruins of Zanarkand when the party finally makes its way into the ancient city and towards the Final Aeon. It is a strikingly melancholic song, perfectly fitting the group's mood as it heads towards Lady Yunalesca and what will likely be its final moments together. Perhaps moreso than any other game in the series, Final Fantasy VII's soundtracks is especially well known for its battle music. This is reflected in the selection of songs from the game that got into the top 50 (four out of its eight songs on this list are battle themes). Fight On! is Final Fantasy VII's main boss battle theme and is heard during all of the game's boss fights except in ones against Hojo, Jenova, and Sephiroth. Over the years Fight On! has become one the most recognisable themes in the entire franchise, having been rearranged and performed live numerous times. The opening guitar riff especially has become one of the most easily identifiable musical sections in all of Final Fantasy. You're Not Alone from Final Fantasy IX is one of the most effective songs in terms of emotional impact ever composed for the series. In the game the song begins just as its main protagonist Zidane reaches his lowest point. After numerous hints about his true nature earlier in the game, he has just been told the truth about his origin and the purpose of his existence by Garland, one of the title's main villains. This revelation is what ultimately breaks his spirit and leads him to shun and reject the people closest to him. As the song plays in the background the player is forced to take on a series of increasingly difficult fights, initially with Zidane alone until his friends come to help him one by one, trying to snap him out of his trance. The song perfectly sums up the emotions and mood in these scenes, showing both Zidane's despair and the rest of the characters' compassion towards him, which is also reflected in the song's name. You're Not Alone is the highest ranked song from Final Fantasy IX. There are usually a few specific songs that are brought up time and again when discussing Final Fantasy character themes. Yet few are mentioned as often as the song that accompanies one of the series' most shocking and pivotal moments, namely Aerith's death. It is a startlingly effective scene, notable for its unexpected appearance that left many fans in shock. What made the scene truly magnificent, however, is its masterful use of music. It starts out with minimal background music, until right after Aerith is killed, when her theme begins playing as the camera follows the Holy materia down into the water. The scene itself has become one of the most iconic in video game history, and Aerith's Theme has become almost equally as well known. Aerith's personality and story is translated wonderfully into music through this theme, and Nobuo Uematsu himself has said that the song is one his favourites from Final Fantasy VII. First impressions are crucial as this is when the game needs to hook the player and keep them interested during what is often the game's slowest section. As such, it was imperative that the opening to Final Fantasy VIII was as effective as possible, and in terms of music it certainly was. To this day Liberi Fatali remains one of the most powerful opening themes in video game history. The song's name, roughly translated as Fated Children in English, refers to the game's main cast and their connection to each other and the game's villains. The lyrics, sung in Latin by a full choir, make several references to the characters and hint at the game's storyline. Elements from the song were also included in several other themes in the game's soundtrack. It's an excellent piece of music that does a magnificent job at drawing the player into Final Fantasy VIII. Suteki Da Ne is an interesting vocal theme within the series, as it is one of the few that was not translated into English when the game was brought to the west. Previous themes such as Eyes On Me and Melodies of Life were either written in English from the start or translated during localization. Suteki Da Ne was different, possibly due to it being strongly influenced by Asian music and the game's overall strong Asian tone and style. Uematsu was also interested in Okinawan music at the time, and this played a large role in RIKKI being chosen as the singer for the theme. Suteki Da Ne is essentially Final Fantasy X's main theme and its melody can be found in various other tracks within the game. The song itself plays during one of the game's most important scenes, when Yuna and Tidus share a romantic moment together in the Macalania Woods, while an orchestral version of it plays during the end credits. It's a rare feat when a piece of music from a video game practically transcends the game it is from, but a select few songs have been able to do just that, becoming widely known even among people who don't necessarily play video games. The Super Mario Bros. theme is an obvious example, but as far as music from Final Fantasy is concerned perhaps the strongest argument can be made for One-Winged Angel from Final Fantasy VII. Another example of the power of this song is how it has basically replaced Those Chosen by the Planet as Sephiroth's official theme song, to the point that the former is rarely even brought up these days when talking about the character, despite it being his original character theme. Few songs can claim to have made as huge an impact on the collective memory of gamers everywhere than One-Winged Angel did nearly 20 years ago. It is easily among Nobuo Uematsu's most well known compositions, and has remained a huge fan-favourite ever since the game's original release. The highest ranking song from Final Fantasy VI is the theme for Terra Branford, which is also the map theme for the world of balance and the game's main theme. As such various sections of the song are used in other songs on the soundtrack, usually during scenes focusing on Terra in some way. In addition, it is among the most well known and fondly remembered themes from the entire series. Terra's Theme has a rather sombre melody at its core, echoing both Terra's storyline and in many ways the game itself. It feels like a song with a lot of weight behind it, with many different meanings buried inside. Yet there is also a constant undercurrent of hope that is always present. It's an excellent song that reflects the themes and the world of Final Fantasy VI remarkably well. When the voting for this top 50 began, there was never really any doubt which song would top the list in the end. To Zanarkand from Final Fantasy X was by far the most popular song from the very beginning, amassing nearly twice the amount of points as its closest competition. It also accounted for over half out of all the points FF X received; further proof, if any were needed, of its status as one of the series' most beloved songs. To Zanarkand plays a few times during key moments in the game and is also rearranged several times throughout. It is, together with Suteki Da Ne, effectively the main theme of Final Fantasy X. The song serves as the introduction to the game's world, playing during the opening when the party is sitting around a campfire at the entrance of Zanarkand and about to start the final phase of its journey. It also has an interesting history, as Uematsu had to convince the development team to use the song in specific scenes, but it wasn't until they tried it for the title's opening that they realized how well it actually worked in the game. It is certainly one of Uematsu's best works ever, and is number one on this countdown for good reasons. And that is the end of the countdown. Are there any songs that you were surprised didn't make it onto the list? Feel free to share them in the comments section and, as always, thanks for reading. With Titanfall 2 due out tomorrow, it seems like a good excuse to revisit the 2014 title that started it all. The original Titanfall first appeared on the national radar at E3 2013, where it quickly became a critical darling. It won over 60 awards, including an unprecedented six E3 Critics Awards. Amongst the gaming community, though, the reactions were more mixed. Some saw it as deliverance from an increasingly stale and safe genre. Others dismissed it superciliously as "Call of Duty with mechs." What explains the divergence in opinion? First-person shooter fatigue surely played a part. Yet just as real estate is all about "location, location, location," all too often video games are about exclusives, exclusives, exclusives. The fact that Titanfall found a home on PC, Xbox One, and Xbox 360 — and not PS4 — rubbed some fans the wrong way. As a result we saw many Xbox fans championing the game as the Second Coming, and many PlayStation fans doubting its quality and appeal. So, over two years later, who was right? Well, both sides in a way. On the commercial front, Titanfall failed to capitalize on the enormous level of hype surrounding the title in the months leading to launch in March 2014. Forbes' Paul Tassi wrote in April that "very shortly after release, the buzz seemed to fade abnormally quickly." The exact number of units sold across three platforms is difficult to discern — developer Respawn boasted of 10 million unique players and Electronic Arts CFO Blake Jorgensen stated "a little more than 7 million units". Our estimates currently put it just shy of 5 million sold at retail. Regardless of the actual figure it's safe to say that Titanfall was neither the blockbuster hit nor the Xbox One "killer app" that many anticipated. Why did Titanfall's buzz drop precipitously in the months after launch? I'd argue it hinged on two factors: lack of modes and zero offline content. Although a large number of modern gamers enjoy broadband internet and are accustomed to playing online, many remain wary of online-only games. Server support is finite and can end suddenly. Look at Dead Star, which is losing server support on November 1 after only seven months on the market, leaving only the tutorial playable. The fact that Titanfall launched with only five modes — all multiplayer —also hurt post-launch momentum. A proper single-player campaign would have done wonders, as would a co-op mode or a free-for-all competitive mode. Extra content, including "Frontier Defense" — an addictive co-op mode inspired by Gears of War's "Horde" mode — and "Deadly Ground" did arrive eight months after launch, but it was a case of too little, too late. So on the commercial side of things, the Titanfall detractors were more or less correct. In terms of quality, though, the Titanfall believers found their faith justified. Put simply, Titanfall is one of the most inventive and engaging shooters in years, a must-have title for Xbox One owners, and the all-around best first-person shooter of the eighth generation (so far). Why is it so good? Well, the answer, paradoxically, has a lot to do with why many players ignored or forgot the game: the singular focus on competitive multiplayer. Respawn's deep focus on multiplayer allowed the studio to forge one of the most accessible and balanced shooters in a generation. Staffed with industry veterans who had worked previously on Call of Duty 4: Modern Warfare and its sequel, Respawn was able to draw on its past experiences and pave a road toward the future of the genre, focusing on player mobility, survivability, and the merger of single-player tropes with multiplayer action. On the mobility front, Respawn scored a home run. Titanfall's pilots are fast, agile, and capable of dashing across maps like a ring-tailed lemur. The game features maps that are impressively large, vertical, and open for exploration — a far cry from the plodding, mostly-flat maps in rival shooters. Titans are of course bulkier and slower but add even more flavor to each match. Equally important was survivability. Titanfall producer Drew McCoy explained a few months after the game launched that Respawn "looked at how you increase a player's life span without reducing the lethality of it, because that time from to kill to kill is one of the big hooks. Players like getting constant kills — they don't like being killed constantly." Enter Titanfall's much-maligned AI bots, which ease novice players into the game and act as a buffer of sorts between opposing pilots. Last but not least, Respawn infused elements common to single-player campaigns into Titanfall's competitive multiplayer. With cinematic introductions, AI soldiers dotting the landscape, and an epilogue that follows every victory and defeat, each match feels like a small battle in a much larger war. Even a loss can feel like a live-to-fight-another-day scenario. Although Titanfall failed to reach EA's lofty sales expectations and moved far fewer Xbox One units than anticipated, it stands today as a shining example of the first-person shooting genre. By drawing in creative minds and focusing deeply and intently on a single concept — competitive multiplayer — Respawn created the heir apparent to Modern Warfare, and by prioritizing mobility, survivability, and immersive single-player "moments," forged the most disruptive shooter since 2007. Sony Interactive Entertainment announced MLB: The Show 17 will launch on March 28, 2017 for the PlayStation 4. "For anyone who picked up a baseball glove or a video game controller in the last 25 years, there is no other name more synonymous with baseball in the 90's and 2000's than this year's cover athlete for MLB: The Show 17," said Ramone Russel, the Sr. Community Specialist & Game Designer at San Diego Studio. "Destined for greatness, no player entered the Big League with more hype than the first pick of the 1987 MLB draft, and no player entered baseball's Hall of Fame with a higher percentage of the vote than "The Natural." A legend both on and off the field, "The Kid" inspired a generation of baseball fans with electric play, a contagious smile, enviable flair, and a swing that's been imitated but never duplicated for almost three decades. "Almost twenty years since his last appearance in a baseball video game, Ken Griffey Jr. returns to the digital diamond as the cover athlete of MLB: The Show 17. We'll have more details on the cover athlete who will be featured on the Canadian version of the Standard Edition soon." Pre-orders for the game will include 10 bonus Standard Packs and a Ken Griffey Jr. Card. Pre-orders at GameStop will receive an additional 5 Standard Packs. Pre-orders through the PlayStation Story will earn instantly earn players 11,000 Stubs for MLB: The Show 16. Sony Interactive Entertainment Europe announced three new PlayStation 4 bundles for the region that will be made available in November. All three bundles come with a 1TB PlayStation 4 and a copy of Uncharted 4: A Thief's End, as well as two other games. Microsoft has added three titles to the long list of Xbox 360 games that are playable on the Xbox One through Backward Compatibility. The games are Rage, Killer Is Dead and Shred Nebula. Other recent games include The Orange Box, Joe Danger 2: The Movie, Sonic & All-Stars Racing Transformed, Lost Odyssey, Toy Story 3, Bayonetta, Call of Duty 2, and Red Dead Redemption. Sony Interactive Entertainment has released a behind-the-scenes video for The Last Guardian that showcases the making of the music in the game. "We're happy to announce that a The Last Guardian Composer's Choice PS4 Music App of the score featuring 19 tracks will be available separately at launch via the PlayStation Store," Producer Dais Kawaguchi told PlayStation Blog. "The soundtrack app supports both stereo and surround playback, and also allows users to export all the tracks as stereo MP3 files via a compatible USB drive. The soundtrack will also be available via iTunes at a later date. "For audiophiles and collectors, a Vinyl release of the OST will be available in December. We'll have an update on exact release timing and pricing for that version at a later date." The Last Guardian launches for the PlayStation 4 in North America, Europe and Japan and December 6 and in the UK on December 9. 505 Games announced Abzû will be getting a release on retail shelves for the PlayStation 4 and Xbox One in January 2017 for $19.99. "Abzû is an epic descent into the depths of the sea where players explore the mystery and wonder of the ocean, while the distinct art style blends beautifully rendered ocean environments alongside a deeply emotional narrative," said 505 Games' Dan Hevia. "As 'the Diver,' players will uncover their true connection to the ocean, as the world around them begins to unlock its secrets. Fluid swimming controls allows the Diver to interact with lush kelp forests; thousands of fish and hidden worlds, which await her on her quest." Abzû originally released as a digital title for the PlayStation 4 and Windows PC via Steam in August. This will be the first time the game is made available on the Xbox One. Pokémon Sun and Pokémon Moon are nearly a month from release and it has already broken two records. It is the most pre-ordered game in Nintendo history and is the most downloaded Nintendo 3DS demo ever. Pokémon Sun and Pokémon Moon are due out November 18 in North America and November 23 in Europe for the Nintendo 3DS. Nintendo President Tatsumi Kimishima in an interview with Bloomberg discussed a wide range of topics. He was surprised that Nintendo's stock dropped following the announcement of the Nintendo Switch. He added that Nintendo has a lot more to show with the Nintendo Switch and the console will have a wide range of accessories. "It may be appropriate to call them accessories," said Kimishima. "Or it might be better to call them add-on hardware. It's probably more correct to call them accessories. You can assume that there will be a wider array." Nintendo did not show off or announce specific titles for the Switch during the reveal trailer on purpose. The company wants people to try the device out for themselves and experience the software. "One thing we still can't show is the software lineup," he added. "We want people to touch the device in January and experience the software for themselves." Kimishima ruled out the possibility that the Switch would work with hardware from other companies for now, however, he did say "we are interested in VR." "VR offers new ways of playing, but that depends on what kind of software can be played," he said. "If you ask us whether there are any possibilities, we can't say no. It may be that we will build VR software titles, I think that opportunity is available to us." Nintendo will reveal the release date, price and games lineup for the Switch on January 12.
{ "redpajama_set_name": "RedPajamaC4" }
367
Q: How to make a publicly available contact form in rails served via CDN I want to place a contact form (email, name, message) in public facing pages in my rails app. I want to serve them via a CDN (say Cloudflare). The pages then will be cached by the CDN, including the authenticity_token in the form and the csrf-token in the meta tag. What is the best way to handle this in Rails? A: Caching an authenticity token and csrf-token basically make them useless. If you intent to go forward, you need an open form that doesn't pretend to secure itself. You'll need lots of defenses against spam and should not trust anything submitted via the action. I'm not sure why you would do this as you're unlikely to get that much contact form traffic to require caching it like that. Just let rails render a normal form is my recommendation.
{ "redpajama_set_name": "RedPajamaStackExchange" }
8,805
Australian News Veterans Veterans start own political party 06/07/2015 01/12/2017 Brian Hartigan 4986 Views 3 Comments ADVP Share the post "Veterans start own political party" Australian veterans who started their own political party last year, this year gained sufficient membership to officially register the Australian Defence Veterans Party (ADVP) as a political party with the Australian Electoral Commission (AEC). A party spokesman said that in just under 18 months from the inaugural general meeting held in Canberra on Australia Day 2014, the ADVP had grown to meet the required membership numbers to apply to AEC for registration. "The ADVP was formed so veterans from Defence and emergency services, as well as serving members from these organisations, can have a voice in the political arena," the spokesman said. "For too long our veterans have had to put up with decisions that affect their welfare, such as unfair indexation of pensions, the battle for compensation from injuries sustained during service and the unfair pay deal offered to Defence personnel, just to name a few. "The ADVP gained registration as a political party as of 15 June 2015 and we will carry their voice on the political stage." The ADVP held its second Annual General Meeting in Melbourne to welcome new committee members, table its many policies and communicate the party's constitution to members – and, of course, celebrate a significant milestone – official registration as Australia's newest political party. UPDATE 2017: Like many others, I was excited and enthusiastic to hear that a group of veterans were uniting to throw their hat in the political ring. CONTACT magazine was approached for support by ADVP early on. However, one quick look at their manifesto and I told them "no – CONTACT will not be supporting you" – except I did take their money and carried their paid advertising. Their manifesto was, in my opinion, a ridiculously naive document – a list of little more than hurried outlines of their 'official position' on EVERY topical political issue of the day, and seemed to be attempting to take the most populist stance on each. It also proclaimed to be a party that would 'represent all Australians equally', which of course is IMPOSSIBLE. I take no pleasure in saying "I told you so", because, technically I told no one except the ADVP (and close friends) what I really thought. The ADVP was officially deregistered in February 2017, less than 18 months after being registered. ← BAE Systems and Saab in a bid for new-armoured-vehicle project Britain takes delivery of third A400M → Brian Hartigan Managing Editor Contact Publishing Pty Ltd PO Box 3091 Minnamurra NSW 2533 AUSTRALIA 13/01/2020 Brian Hartigan 0 Invictus Games ticket sales Drug-bust trifecta for Warramunga 3 thoughts on "Veterans start own political party" Donald (Mel) Hawksworth Definitely in as well. Brian HartiganPost author Sorry to disappoint you Mel, but this story was pre the last Federal election and the Veteran's Party tore itself asunder shortly thereafter. It doesn't exist at all any more. Max de Mestre-Allen
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
8,365
{"url":"http:\/\/sioc-journal.cn\/Jwk_yjhx\/CN\/10.6023\/cjoc201905030","text":"### \u57fa\u4e8e1-(4-\u5df1\u6c27)\u82ef\u548c2,4,6-\u4e09\u82ef\u57fa-1,3,5-\u4e09\u55ea\u529f\u80fd\u5316\u82b4\u5355\u5143\u7684\u805a\u5408\u7269\u84dd\u5149\u6750\u6599\u7684\u5408\u6210\u4e0e\u8868\u5f81\n\n1. \u5357\u4eac\u90ae\u7535\u5927\u5b66\u4fe1\u606f\u6750\u6599\u4e0e\u7eb3\u7c73\u6280\u672f\u7814\u7a76\u9662 \u6709\u673a\u7535\u5b50\u4e0e\u4fe1\u606f\u663e\u793a\u56fd\u5bb6\u91cd\u70b9\u5b9e\u9a8c\u5ba4\u57f9\u80b2\u57fa\u5730 \u6c5f\u82cf\u7701\u6709\u673a\u7535\u5b50\u4e0e\u4fe1\u606f\u663e\u793a\u534f\u540c\u521b\u65b0\u4e2d\u5fc3 \u5357\u4eac 210023\n\u2022 \u6536\u7a3f\u65e5\u671f:2019-05-14 \u4fee\u56de\u65e5\u671f:2019-08-16 \u53d1\u5e03\u65e5\u671f:2020-04-02\n\u2022 \u901a\u8baf\u4f5c\u8005: \u59dc\u9e3f\u57fa E-mail:iamhjjiang@njupt.edu.cn\n\u2022 \u57fa\u91d1\u8d44\u52a9:\n\u56fd\u5bb6\u81ea\u7136\u79d1\u5b66\u57fa\u91d1\uff08No.21574068\uff09\u3001\u56fd\u5bb6\u79d1\u6280\u90e8\u91cd\u5927\u57fa\u7840\u7814\u7a76\u8ba1\u5212\uff08No.2012CB933301\uff09\u548c\u6c5f\u82cf\u9ad8\u6821\u4f18\u52bf\u5b66\u79d1\u5efa\u8bbe\u5de5\u7a0b\uff08No.YX03003\uff09\u8d44\u52a9\u9879\u76ee.\n\n### Synthesis and Characterization of Blue Light Emitting Polymer Based on 2,4,6-Triphenyl-1,3,5-triazine and 1-(4-Hexyloxy)-benzene Functionalized Fluorene Units\n\nJiang Hongji, He Xu, Li Xiong\n\n1. Nanjing University of Posts and Telecommunications, Institute of Advanced Materials, Key Laboratory for Organic Electronics and Information Displays and Jiangsu Key Laboratory for Biosensors, Jiangsu National Synergetic Innovation Center for Advanced Materials, Nanjing 210023\n\u2022 Received:2019-05-14 Revised:2019-08-16 Published:2020-04-02\n\u2022 Supported by:\nProject supported by the National Natural Science Foundation of China (No. 21574068), the Major Research Program from the State Ministry of Science and Technology (No. 2012CB933301) and the Priority Academic Program Development of Jiangsu Higher Education Institutions (PAPD, YX030003).\n\nPolymer 3 based on 1-(4-hexyloxy)-benzene and 2,4,6-triphenyl-1,3,5-triazine functionalized fluorene units was synthesized and characterized, whose optoelectronic properties were further compared with those of poly(9,9-dihexyl-fluorene) (1) and poly(9,9-di(1-(4-hexyloxy)-phenyl)-fluorene) (2). The 5% weight loss temperatures of polymers 1, 2 and 3 thin solid powders are 274, 318 and 401\u2103, and their glass transition temperatures in the same state are 91, 120 and 139\u2103, respectively. The maximum absorption and photoluminescent emission peaks of polymers 1, 2 and 3 in toluene solution are 380 and 435 nm, and their optical band gaps in toluene solution are 2.95, 2.95 and 2.91 eV. The triplet energy levels of polymers 1, 2 and 3 are 2.82, 2.81 and 2.97 eV, while their singlet energy levels are 3.14, 3.13 and 3.12 eV, which makes the singlet-triplet energy splitting gaps for polymers 1, 2 and 3 to be 0.32, 0.32 and 0.15 eV. The highest occupied molecular orbital energy levels of polymers 1, 2 and 3 are -5.72, -5.95 and -5.96 eV and the lowest unoccupied molecular orbital energy levels are -2.70, -2.39 and -2.34 eV. The introduction of 4-hexoxybenzene widened the energy band gaps of the polymers, while the electron deficient 2,4,6-triphenyl-1,3,5-triazine made the single-triplet energy splitting gaps of the polymers successively decreased, but it did not endow polymer 3 with thermally activated delayed fluorescence characteristic. With the introduction of rigid and electron deficient 2,4,6-triphenyl-1,3,5-triazine into the 9-carbon of the fluorene units in the polymer, the thermal stability, color purity and photostability of blue light emitting solid were improved in the turn of polymers 1, 2 and 3, which were further validated by the stable electroluminescent spectra of polymer 3. The wide-angle X-ray diffraction results of the polymers 1, 2 and 3 powders show that all polymers have excellent amorphous properties in nature. The phase diversity of polymer 3 powder locates between those of polymers 1 and 2, and the alkoxyl phenyl substituted group on the polymer 2 side chain is helpful to improve the diversity of ordered morphology in solid powder. The random copolymer 3 exhibits much better photoelectric properties than those of polymers 1 and 2.","date":"2022-09-29 02:46:59","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.1820303499698639, \"perplexity\": 2920.810312847707}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2022-40\/segments\/1664030335303.67\/warc\/CC-MAIN-20220929003121-20220929033121-00688.warc.gz\"}"}
null
null
Q: PHP: How to get unique content from array? I have a array and I need unique contents. How can I get rid of duplicates in this $tmparray: array(176) { [0]=> array(2) { [0]=> string(22) "/ads/67006/didi" [1]=> string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg" } [1]=> array(2) { [0]=> string(22) "/ads/67006/didi" [1]=> string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg" } [2]=> array(2) { [0]=> string(22) "/ads/67006/didi" [1]=> string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg" } [3]=> array(2) { [0]=> string(19) "/ads/67010/sylvesta" [1]=> string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg" } [4]=> array(2) { [0]=> string(19) "/ads/67010/sylvesta" [1]=> string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg" } [5]=> array(2) { [0]=> string(19) "/ads/67010/sylvesta" [1]=> string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg" } But I want it to look like: (Only unique contents.) array(176) { [0]=> array(2) { [0]=> string(22) "/ads/67006/didi" [1]=> string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg" } [1]=> array(2) { [0]=> string(19) "/ads/67010/sylvesta" [1]=> string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg" } } I have tried with: array_unique($tmparray); array_unique can't do what I want. Anyone have a idea how to solve this? A: your question seems duplicate of this How to remove duplicate values from a multi-dimensional array in PHP i guess array_map will solve your problem $input = array_map("unserialize", array_unique(array_map("serialize", $input))); A: You can use this code: $newarray= array(); foreach ($tmparray as $value) { if (!in_array($value,$newarray)) { $newarray[ ] = $value; } } var_dump($newarray); A: I assume that by duplicate you mean two items where either elements are matching, since you are mapping ads to their pictures, therefore: $target = array(); $elementCount = count($tmparray); $newElementCount = 0; for ($i = 0; $i < $elementCount; $i++) { $found = false; for ($j = 0; (!$found) && (j < $newElementCount); j++) { $found = $target[$j][0] === $tmparray[$i][0] || $target[$j][1] === $tmparray[$i][1]; } if (!$found) { $target[$newElementCount++]=$tmparray[$i]; } } A: PHP array_unique is used only for single dimensional arrays, for multidimensional you can do this by serializing multidimensional array, like below <?php $dataArray = [ 0=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"], 1=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"], 2=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"], 3=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"], ]; $serilaized = []; $newArr = []; ### serilaize each node of multi array and create a new single dimention array.. foreach($dataArray as $val){ $serilaized[] = serialize($val); } ### now perform array unique.. $serilaized_unique = array_unique($serilaized); ## unserialize each node of uniqur array.. foreach($serilaized_unique as $val){ $newArr[] = unserialize($val); } echo "<pre>";print_r($newArr); ?> This will give you: Array ( [0] => Array ( [0] => /ads/67006/didi [1] => /Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg ) [1] => Array ( [0] => /ads/67010/sylvesta [1] => /Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg ) ) In short you can perform this in single line code with array_map $dataArray = array_map('unserialize', array_unique(array_map('serialize', $dataArray))); A: I got it working with this line: $tmparray = array_unique($tmparray, SORT_REGULAR);
{ "redpajama_set_name": "RedPajamaStackExchange" }
5,357
L'uso dei piaceri (L'Usage des plaisirs, 1984) è un saggio dello storico e filosofo francese Michel Foucault. Prosegue la ricerca iniziata qualche anno prima con La volontà di sapere (1976), continuata nei volume La cura di sé e concluso con Le confessioni della carne (2018) tutti parte dello studio conosciuto come Storia della sessualità. Questa seconda parte ripercorre l'indagine storica sulle fonti della nostra sessualità occidentale. Foucault dichiara di aver dovuto limitare il suo piano originario di ricerca complessa per prendere in esame le fonti antiche, greche e soprattutto romane, vale a dire il periodo pre-cristiano, dove si sono sviluppate le strutture e le forme essenziali della sessualità occidentale. Foucault esplora i concetti di sessualità e di piacere in tutte le loro dimensioni. Discute la questione morale e cosa si intenda per pratiche normali e anormali, secondo categorizzazioni epistemologiche. Foucault è interessato all'istituzione del matrimonio come un'economia che gestisce sia la sessualità sia il piacere e conclude il libro con un capitolo intitolato "Il vero amore". Indice del volume Introduzione 1. Modificazioni 2. Le forme di problematizzazione 3. Morale e pratica di sé I. La problematizzazione morale dei piaceri 1. Aphrodisia 2. Chrēsis 3. Enkrateia 4. Libertà e verità II. Dietetica 1. Del regime in genere 2. La dieta dei piaceri 3. Rischi e pericoli 4. L'atto, il dispendio, la morte III. Economica 1. La saggezza del matrimonio 2. La famiglia di Iscomaco 3. Tre politiche della temperanza IV. Erotica 1. Un rapporto problematico 2. L'onore di un ragazzo 3. L'oggetto del piacere V. Il vero amore Conclusione Edizioni Collegamenti esterni Opere di Michel Foucault Saggi di autori francesi
{ "redpajama_set_name": "RedPajamaWikipedia" }
14
{"url":"https:\/\/brokenco.de\/2011\/05\/20\/playing-with-pointers-and-fire.html","text":"## Playing with pointers, and fire\n\nIt is a little (unknown) fact that my first job as a software developer was writing C code, for the network group at Texas A&M University. Like most student developers, my work never saw the light of day, mostly because I never finished it, but I did learn an incredible amount working on my little project made for one.\n\nI had never expected that 6 years later in my career, I\u2019d somehow still be dealing with some of the same issues, in the same crusty 30 year old language: C. I feel I should note that every job that I\u2019ve ever had, except one, involved writing C code at some point, odd.\n\nTo be honest I\u2019m both surprised and irritated by C\u2019s longevity as a systems language. When I scan the landscape for the titans of modern web software I see it everywhere. Redis, Nginx, Python, Ruby, MySQL, Apache, HAProxy and the list goes on and on. Don\u2019t get me wrong, C is a very fast and suitable tool to build all these services, it\u2019s just so damn dangerous that I\u2019m shocked how much it\u2019s still used.\n\nMy mind immediately goes to this study that I had read at some point regarding comparisons of development costs and defect rates between very similar C and Ada projects. While the study is almost as old as I am, it strikes a chord with me every time I am working on some C-based projects.\n\nTake this code from the Redis code base for example, which I recently had the pleasure of working with. I am aware that Salvatore is a brilliant hacker but this is madness. If you cannot easily grok the code, I\u2019ll clarify what this tiny library does: in order to provide dynamically sizable strings in C, this code will allocate a block of memory for a string that looks like this:\n\n0 9 N\n+---------------------------+\n| struct sdshdr | char * |\n+---------------------------+\n\n\nA little goofy, but easy to understand and deal with. Except for the fact that the pointer that is passed around is to address 9 instead of 0, meaning all operations that work with the entire block perform pointer arithmetic to calculate the appropriate starting address for the block. For example, here\u2019s the sdsfree implementation:\n\nvoid sdsfree(sds s) { \/* sds == char * *\/\nfree(s - sizeof(struct sdshdr));\n}\n\n\nI have two reasons for picking on this specific code, and they were both in the form of gnarly core dumps I\u2019ve spent resolving the past couple days. If at any point in your program you or anybody else accidentally passes a char* into any of these SDS functions, your program will crash and there\u2019s nothing your compiler can do to save you from this. Since the sds is a typedef of char* not only will you never see any compiler warnings, you won\u2019t see any warnings from static analysis tools either.\n\nI\u2019ve heard people say that one of the problems with C++ is that it gives you too much rope with which to hang yourself. If that\u2019s the case, C not only gives the the rope but double-dog dares you to try to hang yourself with it.\n\nPerhaps in another post I\u2019ll detail how pointers and types are handled in Ada, which I think is a major improvement of the C model without sacrificing speed. I don\u2019t mean to imply that everything that is written in C should really be written in Ada, I just find the language\u2019s solution to this problem to be interesting. Instead of Ada, pick Java, Python, Scala, Ruby, D or any other language that\u2019s been developed in the post-K&R world, they all have built on top of the lessons learned from C\u2019s short-comings.\n\nIt\u2019s been almost 40 years since C was first introduced; that\u2019s over two or three generations of programmers hanging themselves.\n\nDisclaimer: I actually like working on projects in C, it\u2019s always an interesting challenge, like starting arguments with my wife I have no chance of winning.","date":"2020-07-04 15:46:10","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.2504091262817383, \"perplexity\": 1184.8370898983367}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2020-29\/segments\/1593655886178.40\/warc\/CC-MAIN-20200704135515-20200704165515-00231.warc.gz\"}"}
null
null
{"url":"https:\/\/www.tutorialspoint.com\/sum-of-the-first-n-terms-of-the-series-2-6-12-20-30-in-c-programming","text":"# Sum of the first N terms of the series 2, 6, 12, 20, 30\u2026. in c programming\n\nTo find the sum of this series, we will first analyze this series.\n\nThe series is: 2,6,12,20,30\u2026\n\n## Example\n\nFor n = 6\nSum = 112\nOn analysis, (1+1),(2+4),(3+9),(4+16)...\n(1+12), (2+22), (3+32), (4+42), can be divided into two series i.e.\ns1:1,2,3,4,5\u2026 andS2: 12,2,32,....\n\nFind the sum of first and second using mathematical formula\n\nSum1 = 1+2+3+4\u2026 , sum1 = n*(n+1)\/2\nSum2 = 12+22+32+42\u2026 , sum1 = n*(n+1)*(2*n +1)\/6\n\n## Example\n\n#include <stdio.h>\nint main() {\nint n = 3;\nint sum = ((n*(n+1))\/2)+((n*(n+1)*(2*n+1))\/6);\nprintf(\"the sum series till %d is %d\", n,sum);\nreturn 0;\n}\n\n## Output\n\nThe sum of series till 3 is 20\nPublished on 09-Aug-2019 11:21:01\nAdvertisements","date":"2019-12-06 17:52:06","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.4579176604747772, \"perplexity\": 6756.264325945494}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": false}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2019-51\/segments\/1575540490743.16\/warc\/CC-MAIN-20191206173152-20191206201152-00038.warc.gz\"}"}
null
null
Эдисон Эдуардо Бономи Варела (; 14 октября 1948,  — 20 февраля 2022) — уругвайский политик и государственный деятель. Биография В 1966—1970 годах играл в футбольной команде «Монтевидео Уондерерс». С 1969 года изучал ветеринарию в Республиканском университете Уругвая. Участник студенческого сопротивления. Вступил в леворадикальную организацию Движение национального освобождения (Тупамарос). В 1972 году за принадлежность к партизанскому движению был арестован и заключён в тюрьму. Вышел на свободу в марте 1985 года по амнистии всех политических заключенных Уругвая. Работал продавцом книг, в рыболовецкой компании. После освобождения с 1987 года был членом Центрального комитета Национального освободительного движения — Тупамарос (MLN-T) и соучредитель «Движения народного участия», состоявшего из бывших бойцов «Тупамарос», в котором в последующие годы занимал ведущую роль. Член Широкого фронта. С 1 марта 2005 года — министр труда и социального обеспечения. Ушёл с поста для участия в Президентских и парламентских выборах в Уругвае в 2009 году. Руководил избирательным штабом Хосе Мухики, ставшего президентом Уругвая. С 1 марта 2010 года до 15 февраля 2020 года — министр внутренних дел Уругвая. Министр экономики и финансов Уругвая (21 декабря 2013 — 30 декабря 2013). Умер 20 февраля 2022 года в Канелонесе. Примечания Ссылки Eduardo Bonomi Con Eduardo Bonomi, ministro de Trabajo y Seguridad Social Министры промышленности и труда Уругвая Министры внутренних дел Уругвая Министры экономики и финансов Уругвая Репрессированные в Уругвае Революционеры Уругвая Тупамарос Сенаторы Уругвая
{ "redpajama_set_name": "RedPajamaWikipedia" }
3,006
"Заман" (; , в превод Време) е османски вестник, излизал в Солун, Османската империя от 28 юли 1908 година до май 1911 година. Публикува се от Мустафа бей и Али Нихад. Вестникът излиза ежедневно и се занимава с политика. Бележки Периодични издания, свързани с Македонския въпрос Вестници в Османската империя Вестници на турски език Спрени вестници в Солун
{ "redpajama_set_name": "RedPajamaWikipedia" }
7,163
\section{Introduction} The decay of the Standard Model Higgs boson to a bottom quark pair ($b\bar{b}$) has the largest branching ratio among all Higgs decay modes, approximately 58\%~\cite{Heinemeyer:2013tqa}. Measuring this decay is therefore crucial, not only for determining the coupling to bottom quarks, but also for constraining the total Higgs boson decay width under reasonably general assumptions~\cite{Lafaye:2009vr,Corbett:2015ksa}. The largest sensitivity to $H \to b\bar{b}$ can be gained from the boosted $VH$ production, where $V$ denotes a $W$ or $Z$ boson that is boosted along the transverse direction; their leptonic decays result in clean signatures which can be efficiently triggered on, while vetoing most of the multi-jet backgrounds~\cite{Butterworth:2008iy, Butterworth:2015bya}. Very recently ATLAS and CMS have reported observed significances of $4.9\sigma$ and $4.8\sigma$ for the $VH(b\bar{b})$ channel, and $5.4\sigma$ and $5.6\sigma$ for the $H \to b\bar{b}$ decay, respectively, in combinations with other Higgs production modes with their Run 1 and Run 2 data~\cite{Aaboud:2018zhk, Sirunyan:2018kst}. Although the $VH(b\bar{b})$ is already very close to a $5\sigma$ significance, each channel of the $VH(b\bar{b})$ process, categorized by the number of observed charged leptons, has a considerably smaller significance. For instance, the observed significance for the two-lepton channel is $3.4 \sigma$ $(1.9 \sigma)$ for ATLAS (CMS) with the $13$~TeV and $79.8~\mathrm{fb}^{-1}_{}$ ($41.3~\mathrm{fb}^{-1}_{}$) of data~\cite{Aaboud:2018zhk, Sirunyan:2018kst}. The significances of all the three channels are comparable~\cite{atlas_hbb,cms_hbb,Aaboud:2018zhk, Sirunyan:2018kst}. Therefore, an improvement in each channel would be important for a larger precision gain in the $H\rightarrow b\bar{b}$ measurement. When a search for the two-lepton $Z(\ell^+\ell^-)H(b\bar{b})$ channel is performed at the Large Hadron Collider (LHC), the dominant background after signal extraction procedures is $Zb\bar{b}$~\cite{atlas_hbb,cms_hbb,Aaboud:2018zhk, Sirunyan:2018kst}. Although many theoretical efforts to identify the $H \to b\bar{b}$ decay have thrived since the pioneering work of Ref.~\cite{Butterworth:2008iy}, the $Z$ polarization has not been exploited to further discriminate the signal from the $Zb\bar{b}$ background\footnote{ATLAS and CMS~\cite{atlas_hbb,cms_hbb,Aaboud:2018zhk, Sirunyan:2018kst} use multivariate analyses to maximize the signal sensitivity. In the two-lepton channel, the variables used for the multivariate analyses include only the two-lepton invariant mass $m_{\ell\ell}^{}$ as the information of the charged leptons. Hence, the information on $Z$ boson polarization is not used.}. In general, the $Z$ polarization can intrinsically differ from one process to another and manifests itself in the $Z\to \ell^+\ell^-$ decay angular distributions. In this paper, we show that the $Z$ boson polarization has relevant information to distinguish the signal from the dominant background, that is currently neglected~\cite{atlas_hbb,cms_hbb,Aaboud:2018zhk, Sirunyan:2018kst}. We present a procedure to maximally exploit this information and estimate the possible sensitivity gains to the LHC analyses. \section{Approach} The differential cross section including the $Z\to \ell^+\ell^-$ decay for both $ZH$ and $Zb\bar{b}$ processes can be expanded in general as (we employ the notation of Ref.~\cite{Hagiwara:1984hi}) % \begin{align} & \frac{d\sigma}{dq_{\mathrm{T}}^2 dY d\cos{\Theta} d\cos{\theta}d\phi} =\nonumber \\ & F_{1}^{} (1+\cos^2_{}{\theta} ) + F_{2}^{} (1-3\cos^2_{}{\theta} ) + F_{3}^{} \sin{2\theta} \cos{\phi} \nonumber \\ & + F_{4}^{} \sin^2_{}{\theta} \cos{2\phi} + F_{5}^{} \cos{\theta} + F_{6}^{} \sin{\theta} \cos{\phi} \nonumber \\ & + F_{7}^{} \sin{\theta} \sin{\phi} + F_{8}^{} \sin{2\theta} \sin{\phi} + F_{9}^{} \sin^2_{}{\theta} \sin{2\phi}\,, \label{differential} \end{align} where $q_{\mathrm{T}}^{}$ is the transverse momentum of the $Z$ boson in the laboratory frame, $Y$ is the rapidity of the $Z+H~(\mathrm{or\ }b\bar{b})$ system in the laboratory frame, $\Theta$ is the polar angle of the $Z$ boson from the collision axis in the $Z+H~(\mathrm{or\ }b\bar{b})$ center-of-mass frame, $\theta$ ($0 \le \theta \le \pi$) and $\phi$ ($0 \le \phi \le 2\pi$) are the polar and azimuthal angles of the lepton ($\ell^-_{}$) in the $Z$ rest frame. We choose the coordinate system of the $Z$ rest frame following Collins and Soper (Collins-Soper frame)~\cite{Collins:1977iv}. This frame is well recognized and the angular coefficients for the Drell-Yan $Z$ production have been measured by ATLAS~\cite{Aad:2016izn, Aaboud:2017ffb} and CMS~\cite{Khachatryan:2015paa}. $F_i^{}$ are functions of only $q_{\mathrm{T}}^{}$, $Y$ and $\Theta$; integrations over other phase space variables are already performed. After integrations over the lepton angles, only $F_1^{}$ remains; $F_{1}^{}$ is directly related to the total cross section and determines the overall normalization of the $Z\to \ell^+\ell^-$ decay angular distributions. The eight functions $F_i^{}$ ($i=2$ to $9$) are described by polarization density matrices of the $Z$ boson. Eq.~\ref{differential} opportunely simplifies for the signal and background processes under consideration. First, we notice that the signal displays two relevant subprocesses: the quark-initiated Drell-Yan like $q\bar{q} \to ZH$ and the loop-induced gluon-fusion ${gg \to ZH}$. They are denoted by $ZH_{\mathrm{DY}}^{}$ and $ZH_{\mathrm{GF}}^{}$, respectively. Despite $ZH_{\mathrm{GF}}^{}$ being $\mathcal{O}(\alpha_s^2)$ suppressed, it results in important contributions at the boosted regime~\cite{Altenkamp:2012sx, Englert:2013vua,Goncalves:2015mfa,Goncalves:2016bkl}. When CP non-conservation is neglected, the three coefficients $F_{7, 8, 9}^{}$ are always zero in tree-level calculations of any process~\cite{Hagiwara:1984hi}, because these are proportional to relative complex phases of scattering amplitudes. $ZH_{\mathrm{DY}}^{}$ can be analytically evaluated without difficulty at the leading-order (LO); we find that the scattering amplitudes for the $J_z^{}=0$ state of the $Z$ boson are zero, therefore $F_{2,3,6}^{}$ are all zero. $F_5^{}$ is totally antisymmetric around $Y=0$, therefore it does not contribute after the integration over $Y$. Consequently, only $F_1^{}$ and $F_4^{}$ contribute after the $Y$ integration in $ZH_{\mathrm{DY}}^{}$. $ZH_{\mathrm{GF}}^{}$ receives constraints from CP conservation and Bose symmetry; as a result, $F_{5,6,8,9}^{}$ are zero at the LO. Although the coefficients $F_{3,7}$ are nonzero in $ZH_{\mathrm{GF}}^{}$, these are totally antisymmetric around $\cos{\Theta}=0$, thus do not contribute after the integration over $\cos{\Theta}$. Consequently, only $F_1^{}$, $F_2^{}$ and $F_4^{}$ contribute after the $\cos{\Theta}$ integration in $ZH_{\mathrm{GF}}^{}$. Estimation of the coefficients apart from $F_{7, 8, 9}^{}$ in the $Zb\bar{b}$ background process is not easy due to the large number of the scattering amplitudes. This process is part of the $\mathcal{O}(\alpha_s^2)$ correction to the Drell-Yan $Z$ production. Although the angular coefficients in this production have been calculated at $\mathcal{O}(\alpha_s^3)$ accuracy~\cite{Gauld:2017tww}, an exclusive calculation of those in the $Zb\bar{b}$ events does not exist in the literature to our knowledge. We have numerically found that only $F_1^{}$, $F_2^{}$ and $F_4^{}$ contribute after the integration over $Y$ and $\cos{\Theta}$, when the signal selections are imposed. The signal selections for the LO analysis are given later in Eq.~\ref{eq:eventcut1} and for the full hadron level study in Sec.~\ref{sec:results}. To conclude, both for the signal and for the $Zb\bar{b}$ background, Eq.~(\ref{differential}) simplifies to \begin{align} & \frac{d\sigma}{dq_{\mathrm{T}}^2 d\cos{\theta}d\phi} = \nonumber \\ &\widehat{F}_{1}^{} \bigl[ 1+\cos^2_{}{\theta} + A_{2}^{} (1-3\cos^2_{}{\theta} ) + A_{4}^{} \sin^2_{}{\theta} \cos{2\phi} \bigr], \label{differential-2} \end{align} where $A_{2} = \widehat{F}_2/\widehat{F}_1$ and $A_4 = \widehat{F}_4/\widehat{F}_1$. The hat above the coefficients implies that the integrations over $\cos{\Theta}$ and $Y$ are performed. For $ZH_{\mathrm{DY}}^{}$, we derive that \begin{align} A_4^{} = - \frac{q_{\mathrm{T}}^2}{ 2 m_Z^2 + q_{\mathrm{T}}^2}, \label{eq:A4} \end{align} which has a large negative value in the high $q_{\mathrm{T}}^{}$ region. Eq.~(\ref{differential-2}) suggests that the angles $\theta$ and $\phi$ can be defined in the restricted ranges $0 \le \theta \le \pi/2$ and $0 \le \phi \le \pi/2$ without losing any information. They can be obtained from \begin{subequations} \label{cosphi} \begin{align} |\cos{\theta}| & = \frac{2 \bigl| q^0_{} p_\ell^3 - q^3_{} p_\ell^0 \bigr|}{Q\sqrt{Q^2_{} + |\vec{q}_{\mathrm{T}}^{}|^2_{} }} \,, \label{costheta} \\ |\cos{\phi}| & = \frac{2}{\sin{\theta}}\frac{ \bigl| Q^2_{} \vec{p}_{\mathrm{T}\ell}^{} \cdot \vec{q}_{\mathrm{T}}^{} - |\vec{q}_{\mathrm{T}}^{}|^2_{} p_\ell^{} \cdot q \bigr|}{Q^2_{}|\vec{q}_{\mathrm{T}}^{}|\sqrt{Q^2_{} + |\vec{q}_{\mathrm{T}}^{}|^2_{}}} \,, \end{align} \end{subequations} where $q^{\mu}_{}=(q^0_{}, \vec{q}_{\mathrm{T}}^{}, q^3_{})$ and $p^{\mu}_{\ell}=(p^0_\ell, \vec{p}_{\mathrm{T}\ell }^{}, p^3_\ell)$ are four-momenta of the reconstructed $Z$ boson and one of the leptons, respectively, in the laboratory frame and $Q$ is the reconstructed $Z$ invariant mass ($Q=m_{\ell\ell}^{}$). We stress that $p_\ell^{\mu}$ can be the momentum of either $\ell^-_{}$ or $\ell^+_{}$ ({\it i.e.} either gives the same $\theta$ and $\phi$ values). This is simply because interchanging $\ell^-_{}$ and $\ell^+_{}$ corresponds to $\theta \to \pi - \theta$ and $\phi \to \phi + \pi$ ({\it i.e.} $\cos{\theta} \to - \cos{\theta}$ and $\cos{\phi} \to - \cos{\phi}$). Practically speaking, we do not need to distinguish $\ell^-_{}$ and $\ell^+_{}$. This feature is particularly important for ${Z \to e^-_{} e^+_{}}$ in which case the charge misidentification rate is not negligible~\cite{atlas_hbb}. To evaluate the two coefficients $A_2$ and $A_4$, we simulate the signal and the background at the LO with {\sc MadGraph5\_aMC@NLO}~\cite{Alwall:2014hca, Hirschi:2015iia}, using the NNPDF2.3~\cite{Ball:2012cx} parton distribution functions. The $Z(\ell\ell)b\bar{b}$ background sample accounts for the interference with $\gamma^{*}(\ell\ell) b\bar{b}$. The events are required to pass the following selections: \begin{align} &75~{\ensuremath\rm GeV} < m_{\ell\ell}^{} < 105~{\ensuremath\rm GeV},\ \ 115~{\ensuremath\rm GeV} < m_{bb} < 135~{\ensuremath\rm GeV},\nonumber \\ &p_{\mathrm{Tb}} > 25\ \mathrm{GeV},\ \ |y_b| < 2.5,\ \ 0.3 < \Delta R_{bb} < 1.2 \,, \label{eq:eventcut1} \end{align} where $\Delta R_{bb}$ is a cone radius between the two b-quarks. In Tab.~\ref{table:asymmetries}, we display the results in two $q_{\mathrm{T}}^{}$ regions. The statistical uncertainty for the last digit is shown in parentheses. We find that both $ZH_{\mathrm{DY}}^{}$ and $ZH_{\mathrm{GF}}^{}$ present very distinct values $A_{2, 4}^{}$ from the $Zb\bar{b}$ background process. It is also observed that the $A_{4}^{}$ values in $ZH_{\mathrm{DY}}^{}$ are consistent with the analytic formula in Eq.~(\ref{eq:A4}). These differences clearly appear in the $(\cos\theta$, $\phi)$ distribution. \begin{table}[th!] \vspace{0.3cm} \begin{ruledtabular} \begin{tabular}{rrrr} & $ZH_{\mathrm{DY}}^{}$ & $ZH_{\mathrm{GF}}^{}$ & $Zb\bar{b}$ \\ \colrule $A_2^{}(q_{\mathrm{T}}^{}>200~{\ensuremath\rm GeV})$ & $0.001(1)$ & $0.026(1)$ & $0.470(1)$ \\ $A_2^{}(q_{\mathrm{T}}^{}>400~{\ensuremath\rm GeV})$ & $-0.002(3)$ & $0.052(8)$ & $0.498(4)$ \\ $A_4^{}(q_{\mathrm{T}}^{}>200~{\ensuremath\rm GeV})$ & $-0.825(2)$ & $-0.972(2)$ & $0.447(2)$ \\ $A_4^{}(q_{\mathrm{T}}^{}>400~{\ensuremath\rm GeV})$ & $-0.947(5)$ & $-0.92(1)$ & $0.462(8)$ \end{tabular} \end{ruledtabular} \caption{Normalized angular coefficients $A_2^{}$ and $A_4^{}$ in two regions of $q_{\mathrm{T}}^{}$ at the LO, after the selection in Eq.~\ref{eq:eventcut1}. The statistical uncertainty for the last digit is shown in the parentheses. \label{table:asymmetries}} \end{table} \begin{figure}[bh!] \includegraphics[scale=0.7]{Fig_CS-Rat-Paper.pdf} \caption{Ratio of the normalized $(\cos{\theta},\phi)$ distribution at the LO for the $ZH_{\mathrm{DY}}^{}$ process to that for the $Zb\bar{b}$ background process, imposing the cuts in Eq.~(\ref{eq:eventcut1}) and $q_{\mathrm{T}}^{}>200$ GeV. \label{figure:csangles}} \end{figure} In Fig.~\ref{figure:csangles}, we show the ratio of the normalized $(\cos{\theta},\phi)$ profile for the $ZH_{\mathrm{DY}}^{}$ process to that for the $Zb\bar{b}$ process, imposing $q_{\mathrm{T}}^{}>200$ GeV. The information on the differences in $A_2^{}$ and $A_4^{}$ between the signal and the background completely appears in this restricted (i.e. $0 \le \theta \le \pi/2$ and $0 \le \phi \le \pi/2$) two-dimensional ${(\cos\theta, \phi)}$ distribution. For example, it is observed that signal events are more distributed at $\phi \sim \pi/2$ and $Zb\bar{b}$ more at ${\phi \sim 0}$, as the consequence of the large difference in $A_4^{}$ between the $ZH_{\mathrm{DY}}^{}$ and $Zb\bar{b}$ processes. Therefore, the $Z\rightarrow \ell^+\ell^-$ decay angular distributions can be useful in distinguishing the signal from the background.\medskip So far, minimum selections in the lepton transverse momentum $p_{\mathrm{T}\ell}^{}$ are not considered. Defining the lepton angles in the Collins-Soper frame has a great advantage: $p_{\mathrm{T}\ell}^{}$ has a simple expression in terms of these angles. In the laboratory frame, in which the $x$-axis is chosen along $\vec{q}_{\mathrm{T}}^{}$, the vectorial transverse momenta of the harder ($\ell_{1}^{}$) and softer $(\ell_2^{})$ leptons are given by \begin{widetext} \begin{subequations} \label{eq:leptonpT} \begin{align} \vec{p}_{\mathrm{T\ell_{1}^{}(\ell_{2}^{})}}^{} = \frac{1}{2} \Bigl( q_{\mathrm{T}}^{} \pm \sqrt{ Q^2_{} + q_{\mathrm{T}}^2 } \sin{\theta} \cos{\phi}, \pm Q\sin{\theta} \sin{\phi} \Bigr)\,. \end{align} Therefore, their absolute values are given by \begin{align} p_{\mathrm{T\ell_{1}^{}(\ell_{2}^{})}}^{} \equiv \bigl|\vec{p}_{\mathrm{T\ell_{1}(\ell_{2})}}^{} \bigr| = \frac{1}{2} \sqrt{ q_{\mathrm{T}}^2 + Q^2_{} \sin^2{\theta} + q_{\mathrm{T}}^2 \sin^2{\theta} \cos^2{\phi} \pm 2 q_{\mathrm{T}}^{} \sqrt{ Q^2_{} + q_{\mathrm{T}}^2 } \sin{\theta} \cos{\phi} }\,, \label{eq:leptonpTmag} \end{align} \end{subequations} \end{widetext} which are now independent of a choice of the $x$-axis in the laboratory frame. In the boosted kinematic region $Q^2_{}/q_{\mathrm{T}}^2 \ll 1$, we derive \begin{align} p_{\mathrm{T}\ell_{1}^{}(\ell_{2}^{})}^{} = \frac{1}{2} q_{\mathrm{T}}^{} \bigl( 1 \pm \sin{\theta} \cos{\phi} + \mathcal{O}\bigl(Q^2_{}/q_{\mathrm{T}}^2\bigr) \bigr).\label{eq:leptonptlimit} \end{align} This in fact shows that $Z$ polarization can largely affect the lepton $p_{\mathrm{T}}^{}$ distributions even if the $Z$ is highly boosted. Representative differences in $p_{\mathrm{T}\ell}^{}$ between the signal and the background can be revealed as follows. In the phase space where the signal is more concentrated $\phi \sim \pi/2$, we find \begin{align} p_{\mathrm{T\ell1}}^{} = p_{\mathrm{T\ell2}}^{} = \frac{1}{2} \sqrt{ q_{\mathrm{T}}^2 + Q^2_{} \sin^2{\theta}}. \label{eq:pTsignal} \end{align} While in the region where the background displays more events ${\phi \sim 0}$, we have \begin{align} p_{\mathrm{T\ell1(2)}}^{} &= \frac{1}{2} \Bigl| q_{\mathrm{T}}^{} \pm \sqrt{ Q^2_{} + q_{\mathrm{T}}^2} \sin{\theta} \Bigr|, \nonumber \\ p_{\mathrm{T\ell1}}^{} - p_{\mathrm{T\ell2}}^{} & = \mathrm{min}\Bigl\{ q_{\mathrm{T}}^{}, \sqrt{ Q^2_{} + q_{\mathrm{T}}^2} \sin{\theta} \Bigr\}.\label{eq:pTback} \end{align} \begin{figure}[t!] \centering \includegraphics[scale=0.48]{Fig_pT13-1.pdf} \includegraphics[scale=0.48]{Fig_pT13-2.pdf} \caption{\small Normalized $p_{\mathrm{T}}^{}$ distributions of the harder lepton (left) and softer lepton (right) for the $ZH_{\mathrm{DY}}^{}$ (solid curve), $ZH_{\mathrm{GF}}^{}$ ($\times$) and $Zb\bar{b}$ (dashed curve) processes. \label{figure:pT}} \end{figure} Eqs.~\ref{eq:pTsignal} and \ref{eq:pTback} tell us that the higher (lower) $p_{\mathrm{T}}^{}$ lepton in the background is predicted to be harder (softer) than that in the signal. To illustrate this feature, we show in Fig.~\ref{figure:pT} the normalized distributions of $p_{\mathrm{T\ell1(2)}}^{}$ for the $ZH_{\mathrm{DY}}^{}$ (solid curve), $ZH_{\mathrm{GF}}^{}$ ($\times$) and $Zb\bar{b}$ (dashed curve) processes at the LO. The cuts in Eq.~\ref{eq:eventcut1}, ${200~{\ensuremath\rm GeV} < q_{\mathrm{T}}^{} <300}$~GeV and a lepton rapidity cut $|y_\ell^{}|<2.5$ are imposed. The distributions roughly follow Eqs.~\ref{eq:pTsignal} and \ref{eq:pTback} which were derived under the extreme conditions ({\it i.e.} $\phi=\pi/2$ and $\phi=0$). This observation confirms that the differences in $p_{\mathrm{T\ell1(2)}}^{}$ distributions are consequences of the difference in the $Z$ polarization. It is, therefore, expected that a lepton $p_{\mathrm{T}}^{}$ selection can partially capture the difference in the $Z$ polarization ($A_4^{}$ in particular) and improve the sensitivity to the signal. We note in passing that the results in Eqs.~\ref{eq:pTsignal} and \ref{eq:pTback} and Fig.~\ref{figure:pT} illustrate the fundamental importance of taking account of the $Z$ polarization in its decays in the Monte Carlo simulations, even without performing a tailored polarization analysis. \section{Results}\label{sec:results} We now estimate the potential sensitive gains from the polarization information to a detailed hadron level ${pp\rightarrow Z(\ell\ell)H(b\bar{b})}$ LHC study. Our signal is characterized by two charged leptons, $\ell=e$ or $\mu$, which reconstruct a boosted $Z$ boson recoiling against two $b$-jets. The major backgrounds are $Zb\bar{b}$, $t\bar{t}$+jets, and $ZZ$. We simulate our samples with Sherpa+OpenLoops~\cite{Gleisberg:2008ta,Cascioli:2011va,Denner:2016kdg}. The $ZH_{\mathrm{DY}}$ and $ZH_{\mathrm{GF}}^{}$ signal and $Zb\bar{b}$ and $ZZ$ background samples are merged at LO up to one extra jet emission via the CKKW algorithm~\cite{Catani:2001cc, Hoeche:2009rj}. The $ZH_{\mathrm{DY}}$, $Zb\bar{b}$ and $ZZ$ cross sections are normalized to the NLO rates obtained from Ref.~\cite{Goncalves:2015mfa}. Finally, the $t\bar{t}$ is generated at NLO with the MC@NLO algorithm~\cite{Frixione:2002ik,Hoeche:2011fd}. Hadronization and underlying event effects are taken into account in our simulation~\cite{Winter:2003tt}. Pile-up is not simulated. The expected effects of pile-up relevant to our analysis are a degradation of the lepton isolation and $b$ tagging performance; see e.g.~Sec. 6.4 of~\cite{Collaboration:2272264}. Pile-up affects both the signal and the dominant background $Zb\bar{b}$ equally, and leads to a lower sensitivity overall. Therefore, it would not alter the main conclusions of our study on the improvement in the signal significance gained from $Z$ polarization. We follow the BDRS~\cite{Butterworth:2008iy} analysis for tagging the $H\to b\bar{b}$ as a well understood benchmark. However, we stress that our proposal uses only the lepton information, completely independent of how the $H\to b\bar{b}$ tagging is performed. We require two leptons, which have the same flavor and opposite-sign charges, with $|\eta_\ell |<2.5$ in the invariant mass range ${75~{\ensuremath\rm GeV}<m_{\ell\ell}<105~{\ensuremath\rm GeV}}$. The $Z$ boson is required to have a large boost $q_{\mathrm{T}}^{}\equiv p_{\mathrm{T}\ell\ell}^{} >200~{\ensuremath\rm GeV}$. The hadronic activity is reclustered with the Cambridge-Aachen jet algorithm~\cite{Dokshitzer:1997in,Wobisch:1998wt,Cacciari:2011ma} with ${R=1.2}$, requiring at least one boosted $(p_{\mathrm{T}J}>200~{\ensuremath\rm GeV})$ and central $(|\eta_{J}|<2.5)$ fat-jet. This must be Higgs-tagged via the BDRS algorithm, demanding three sub-jets with the hardest two being $b$-tagged. Our study assumes a flat 70\% $b$-tagging efficiency and 1\% miss-tag rate. To further enhance the signal to background ratio, we demand the filtered Higgs mass to be in the range ${|m_{H}^{\text{BDRS}}-m_H^{}|<10~{\ensuremath\rm GeV}}$ with $m_H^{}=125$ GeV. The resulting event rate is presented in Tab.~\ref{tab:cuts_analysis}, for which ${p_{\mathrm{T}\ell}>30}$~GeV is imposed. \begin{table}[h!] \begin{tabular}{l || c | c | c | c | c } \multirow{1}{*}{} & \multicolumn{1}{c|}{$ZH_{\mathrm{DY}}^{}$} & \multicolumn{1}{c|}{$ZH_{\mathrm{GF}}^{}$} & \multicolumn{1}{c|}{$Zb\bar{b}$} & \multicolumn{1}{c|}{$t\bar{t}$} & \multicolumn{1}{c}{$ZZ$} \\ \hline {BDRS reconstruction} & \multirow{2}{*}{0.16} & \multirow{2}{*}{0.03} & \multirow{2}{*}{0.35} & \multirow{2}{*}{0.02} & \multirow{2}{*}{0.02} \\ $|m_{H}^{\text{BDRS}}-m_H|<10~{\ensuremath\rm GeV}$ & & & & & \\ \end{tabular} \caption{Signal $ZH_{\mathrm{DY}}^{}$ and $ZH_{\mathrm{GF}}^{}$ and background $Zb\bar{b}$, $t\bar{t}$, and $ZZ$ rate after the BDRS analysis. Hadronization and underlying event effects are taken into account. The rates are given in units of fb and take account of 70\% $b$-tagging efficiency and 1\% misstag rate.} \label{tab:cuts_analysis} \end{table} \begin{figure}[b!] \includegraphics[scale=0.55]{5sigma.pdf} \caption{\small Luminosities required for a $5\sigma$ observation of the two-lepton $pp\rightarrow Z(\ell\ell)H(bb)$ channel as functions of the lepton $p_{\mathrm{T}}^{}$ lower threshold. The solid curve takes the $Z$ polarization into account by performing a two dimensional binned log-likelihood analysis on the $(\cos{\theta},\phi)$ distribution, while the dashed curve accounts only for the rate. \label{figure:luminosity}} \end{figure} To quantify the importance of the $Z$ polarization, we perform a two dimensional binned log-likelihood analysis based on the $(\cos{\theta},\phi)$ distribution with an uniformly $5\times5$ binned grid, invoking the CL$_s$ method~\cite{Read:2002hq}. In Fig.~\ref{figure:luminosity}, we display the luminosities required for a $5\sigma$ observation as functions of the lower $p_{\mathrm{T}\ell}$ threshold. The solid curve represents the result of the polarization analysis, while the dashed curve is the result without the polarization study and thus purely rate based. The latter continuously improves from 385~$\mathrm{fb}^{-1}$ to 355~$\mathrm{fb}^{-1}$ by changing the $p_{\mathrm{T}\ell}^{}$ threshold from 5 to 35~GeV. This is precisely what we have expected as a consequence of the difference in the polarization; see the discussion below Eq.~\ref{eq:pTback}. It does not improve anymore above 35 GeV, because the statistics of the signal is also much depleted. On the other hand, the solid curve shows that the required luminosity monotonically increases with the $p_{\mathrm{T}\ell}^{}$ threshold. This is because the polarization information (more practically the $(\cos{\theta},\phi)$ distribution) is disturbed by the $p_{\mathrm{T}\ell}^{}$ lower cut. This selection can capture the difference in polarization only partially, therefore it is never better than the explicit use of the polarization information. It is, therefore, suggested to define $p_{\mathrm{T}\ell}^{}$ threshold as small as possible and to exploit the difference in the $(\cos{\theta},\phi)$ distribution between the signal and the background. We stress that, because our proposal relies only on lepton reconstruction, it can be readily included in the current ATLAS and CMS studies. The current ATLAS (CMS) study~\cite{Aaboud:2018zhk, Sirunyan:2018kst} uses the $p_{\mathrm{T}\ell}^{}$ threshold 7~GeV (20~GeV), in which case the benefit of exploiting the $Z$ polarization is estimated to be $\sim15\%$ $(\sim10\%)$ in the required luminosity for 5$\sigma$ observation. \begin{figure}[t!] \includegraphics[scale=0.55]{mu_vs_L.pdf} \caption{\small 95\% confidence level bounds for separating an anomalous $Z(\ell\ell)H(b\bar{b})$ signal strength from the Standard Model prediction as a function of the LHC luminosity. The solid curve accounts for the $Z$ polarization via a two dimensional binned log-likelihood analysis on $(\cos{\theta},\phi)$, while the dashed curve accounts only for the rate. We assume a lepton $p_{\mathrm{T}}^{}$ threshold of $p_{\mathrm{T}}^{}>5$~GeV. \label{figure:mu}} \end{figure} In Fig.~\ref{figure:mu}, we show the 95\% confidence level bounds for separating an anomalous $Z(\ell\ell)H(b\bar{b})$ signal strength from the Standard Model prediction as a function of the 13~TeV LHC luminosity. We assume 5\% systematic uncertainties on the backgrounds, which are modeled as nuisance parameters. The result with the polarization considerably enhances the precision on the signal strength determination and makes the bounds less systematic limited at high luminosities. This is a result of the larger $\mathcal{S}/\mathcal{B}$ for several bins in the 2-dimensional phase space $(\cos\theta,\phi)$, see Fig.~\ref{figure:csangles}. While only 1.5~ab$^{-1}$ is required for the polarization analysis to achieve a precision of $29\%$ on the signal strength, if we disregard the polarization, one would demand the double of the data, 3~ab$^{-1}$, to achieve the same precision. \section{Summary and discussion} We have studied the potential of the $Z$ polarization to improve the sensitivity to the signal $pp\rightarrow Z(\ell\ell)H(b\bar{b})$. At first, we have shown that the signal and the $Zb\bar{b}$ dominant background exhibit different states of $Z$ polarization, whose information completely appears as a large difference in the restricted two-dimensional $(\cos\theta,\phi)$ distribution, where $\cos\theta$ and $\phi$ parametrize the lepton momentum in the $Z$ rest frame. This difference can be partially captured by a suitable value for the $p_{\mathrm{T}\ell}^{}$ lower threshold, and fully taken into account by explicitly analyzing the $(\cos\theta,\phi)$ distribution. We have estimated the impact of these two approaches on the $5\sigma$ observation and that of the latter approach on $95\%$ CL upper bound on the uncertainty in the signal strength determination in the two-lepton $Z(\ell\ell)H(b\bar{b})$ channel, and found relevant improvements. Since this proposal relies only on lepton reconstruction, displaying small experimental uncertainties, it can be promptly included in the current ATLAS and CMS studies. In our study, we consider inclusive events in a high $q_{\mathrm{T}}^{}$ region ($q_{\mathrm{T}}^{}>200$ GeV), namely we do not make use of $F_i^{}$ dependences on $q_{\mathrm{T}}^{}$, $Y$ and $\cos{\Theta}$. The $q_{\mathrm{T}}^{}$ dependence is shown in Table~\ref{table:asymmetries}; the difference between $ZH_{\mathrm{DY}}^{}$ and $Zb\bar{b}$ is a little enhanced as $q_{\mathrm{T}}^{}$ becomes high. Some of the $Y$ and $\cos{\Theta}$ dependences are already described above Eq.~(\ref{differential-2}). In the $Z(\ell^+\ell^-)H(b\bar{b})$ channel, $Y$ and $\cos{\Theta}$ can be reconstructed for each event. It may be, therefore, possible, by using these additional information, to achieve a better signal sensitivity. With our encouraging results, our approach could be applicable to other important channels, {\it e.g.}, {\it i)}~$Z(\ell\ell)H(\mathrm{invisible})$ and {\it ii)}~$W(l\nu)H(b\bar{b})$. We conclude with several comments on these two channels. {\it i)}~Needless to say, the $Z$ polarization is independent of how the Higgs boson decays; the $Z$ polarization in the $ZH(\mathrm{invisible})$ is the same as that in the $ZH(b\bar{b})$. The dominant background in this channel is $Z(\ell\ell)Z(\nu\nu)$. The $ZZ$ process shows almost the same $A_{2, 4}^{}$ values as the $Zb\bar{b}$ process. See Ref.~\cite{Goncalves:2018ptp} for more details. {\it ii)} Despite of the neutrino in the final state, by assuming that the charged lepton and the neutrino construct a $W$ boson nominal mass, $|\cos{\theta}|$ and $|\cos{\phi}|$ in Eq.~(\ref{cosphi}) are still uniquely determined~\cite{Hagiwara:1984hi}. Since the $W^-_{}$ and $W^+_{}$ are always in the same state of polarization~\cite{Nakamura:2017ihk}, we can simply add $W^-_{}H$ events and $W^+_{}H$ events. The $WH$ and the irreducible background $Wb\bar{b}$ show the similar $A_{2, 4}^{}$ values as the $ZH_{\mathrm{DY}}^{}$ and the $Zb\bar{b}$, respectively. Details will be published elsewhere~\cite{Goncalves:2018}. \begin{acknowledgments} We thank C. Borschensky and S. Hasegawa for useful discussions. DG was funded by U.S. National Science Foundation under the grant PHY-1519175. JN appreciates the support from the Alexander von Humboldt Foundation. \end{acknowledgments}\medskip
{ "redpajama_set_name": "RedPajamaArXiv" }
8,532
The remarkable life of Lady Rhondda 09 Jan 2022 7 minutes Read Margaret Haig Thomas (1883-1958) by Alice Mary Burton (1893-1968) Parliamentary Art Collection Next week BBC Radio 4 turns its spotlight to Welsh suffragette Margaret Haig Thomas who is more commonly known as Lady Rhondda, as nominated by former President of the Supreme Court, Lady Hale for the Great Lives programme. Lady Hale will be joined by expert Professor Angela V. John to discuss the vivid life of Lady Rhondda who survived the sinking of the Lusitania, went to prison for setting a post box on fire in the name of women's rights and became the first and to-date only female President of the Institute of Directors. The programme will be broadcast next Tuesday 11 January at 4.30pm, and again on Friday 14 at 11pm, after which it will be available to catch-up online. The journalist, businesswoman and tireless champion of women's rights, Margaret Haig Thomas (who became Mrs / Lady Mackworth and from 1918, Lady Rhondda) led a multi-faceted life and powerful life as one of the movers and shakers in Welsh and English society in the first half of the twentieth century. But this life was not without drama and danger as is demonstrated by these three extracts from her biography by Angela V. John, Turning the Tide: The Life of Lady Rhondda, Parthian, 2013: In 1909 Margaret and the militant Annie Kenney, both activists in Mrs Pankhurst's Women's Social and Political Union, held a women's suffrage meeting at the Bowen Jenkins Memorial Hall in Aberdare Margaret was received with cheers, boos and whistles. She first explained the WSPU's main aim, since Annie Kenney had advised her always to state what she wanted and why, followed by how she meant to obtain it. But there followed such a cacophony of sounds – hoots, shouts, a shrill blast from a trumpet, cat-calls, a policeman's whistle and a rattle – that her words were drowned. She persevered, mentioning Asquith (cheers followed) and remarking that she could not understand 'how any Liberal true to his principles can object to the vote being granted to women on the same terms as men'…But 'unseemly gestures', the singing of comic songs and noise from outside where a crowd scratched the rough glass windows, ensured that little more could be said. The women attempted to restore the peace but herrings, ripe tomatoes and cabbages were hurled onto the platform. Even Kenney, a seasoned campaigner, had great difficulty in being heard… The Aberdare meeting rapidly got out of control. Dead mice were hurled onto the platform and live mice let loose in the body of the hall, along with sulphurated hydrogen gas, snuff and cayenne pepper (producing loud sneezes). Window panes were smashed, many chairs were broken and 'some fear was entertained of something approaching a panic'. Although initially refusing to give up, after ten more minutes of attempting in vain to be heard, even Kenney surrendered. The women walked out slowly from the back of the platform into the gymnasium and escaped in a cab. In May 1915, during the First World War, Margaret and her father the industrialist and politician D.A. Thomas, returned from a business trip in the United States. They travelled on the Lusitania and when it was torpedoed not far from the coast of Ireland, she was sucked down with the ship. Margaret found herself deep down under the water in darkness. She was still holding her father's lifebelt. Later she told the press that she was in 'mounting terror' of being drowned by becoming entangled with some part of the ship. But although her wrist caught on a rope and left a lasting mark, she managed to free it. She grasped a piece of wood just a few inches wide and several feet in length. She came to the surface amidst what seemed to be literally a sea of people. They were crammed together with 'boats, hencoops, chairs, rafts, boards and goodness knows what else'…Half-dazed, Margaret was beyond feeling acute fear. She later wrote that with death so close 'the sharp agony of fear is not there; the thing is too overwhelming and stunning for that'… A few boats were visible but it was impossible to swim more than a few strokes and Margaret was loath to abandon her board. It was intensely cold and the swell made her sick. It also caused people and debris to begin drifting apart. She thought of a possible invention: strapping a small bottle of chloroform to each lifebelt would help the drowning person to lose consciousness. Looking up at the sun high in the sky she wished she could do so. That was the last thing she remembered. But after about two-and-three-quarter hours in the water, just as it was growing dark, she was picked up by a rowing boat. She had only been located because a wicker deck chair had floated up under her, raising her a little. A mark in the water was detected and Margaret was discovered. She was presumed dead. She and a number of bodies were transferred to a small patrol steamer called the Bluebell that was patrolling the waters between Kinsale and Ballycotton. She was dumped on deck. Luckily a midshipman thought there was possibly 'some life in this woman' and attended to her. Turning The Tide by Professor Angela V. John After her father obtained permission from the monarch for his daughter to succeed him as a 'Peeress in her own right', the 2nd Viscountess Rhondda argued that she and the two dozen other women in her position should be able to take their seats in the House of Lords. Not so, argued the Earl of Birkenhead who was both Lord Chancellor and the presiding officer of the House of Lords. He reversed the decision to proceed that had been made by a Lords committee. In Birkenhead's view, the judgments and opinions of the 'average' woman were 'more coloured by emotion and by personal considerations' than were the average man's and at times of crisis might 'prove a source of instability and disaster to the State'. The subject of women in the House of Lords touched a raw nerve. It symbolised for Margaret unfinished business and was a natural concomitant to the protracted struggle for the vote, completing women's struggle for parliamentary representation. For Birkenhead it was also linked to the past, reviving visceral sentiments about wild women activists… The notion of women peers spelt much more of a threat to Birkenhead than had women's suffrage. For it struck at the heart of his world. It threatened the male establishment that this clubbable man most cherished, the space and place that nurtured, displayed and applauded his virtuoso performances and the seat of his authority. A verse in Time and Tide [the influential weekly paper that Margaret had founded in 1920 and would edit from 1926] told of 'bold Birkenhead' who thought: 't would put all Heaven in a rage, To see a Peeress in the Gilded Cage. Margaret stood for all that worried Birkenhead and vice versa. Unlike many in the Lords she had spent her adult life working and in the masculine world of business. A cartoon in the Sunday Chronicle depicted Birkenhead as a medieval Horatius holding the bridge as Lady Rhondda and her 'Amazonian cohorts' advanced. His relentless attack on women's rights helped to ensure that Margaret persisted. Turning the Tide is published by Parthian and is available to buy here….. If you'd like to contribute to the appeal for a a statue of Lady Rhondda you can do so here…. Kerry Davies There was a book published last year; Wales' Unknown Hero: Soldier, Spy, Monk: The life of Henry Coombe-Tennant, MC, of Neath.His story is crazy enough but his mother's, Winifred Coombe Tennant, is crazier. She too was a Liberal candidate, a suffragette, a friend of Lloyd Georges but was also Gorsedd Mistress of the Robes and a bard "Mam o'r Nedd" in her own right. She was married to an older man and wanted another child so slept with one of the Balfours to have Henry at 39 years of age. Her life's work was bound up in art and she… Read more » Jane Winter Good for Lady Hale for nominating Lady Rhondda. Many women have made important contributions to the work of the House of Lords(!) since Lady Rhondda broke the mould. Angela John's biography of Lady Rhondda is fascinating and well worth a read. She truly was a remarkable woman to which women today owe a debt of gratitude. We use cookies to ensure that we give you the best experience on our website. If you are ok with anonymous tracking please click okOkPrivacy policy
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
6,993
Which is the best state to insure an Audi A4? The Audi A4 is arguably one of the most versatile Audi cars in the market. It is available as a sedan or wagon today, though it also went through a convertible phase before Audi A5 took over the convertible version of the A4. The greater variations in the prices of Audi A4 (compared to the rates of A3) are in tune with the facelift given to the vehicle several times since its launch in 1994. Although the A4 series has a larger percentage of insurance to be paid, the average prices are relatively lower. The most expensive price tag of vehicle can be found in the state of North Dakota where the median price is as high as $30,990 and an additional 4% of the amount is required to insure the vehicle. The state of Oklahoma, on the other hand, has a median price as low as $11,517. On the flipside, the buyer will have to shell out the highest percentage, i.e., 19% of the price for insurance. Georgia has the next highest percentage of insurance, i.e., 12% for the vehicle. For a median price of $25,500, the buyer will have to pay an additional average amount of $3,151 towards this end. Wisconsin, Utah, Idaho and Tennessee are some of the best places to buy the vehicle from. A used Audi A4 can be bought for less than $18,000 in these states and the insurance ranges from 7% to 9% of the price. The state of New Mexico also offers an affordable deal. At $14,950, the car can be purchased by shelling an additional 9% towards insurance costs. Buyers from Minnesota, Missouri, New Jersey, and Ohio may find themselves paying relatively higher prices for the vehicle. The Audi A4 costs above $23,000, especially in Minnesota where it is $29,500, the car also has a steep insurance rate.
{ "redpajama_set_name": "RedPajamaC4" }
2,358
FL45-E100 100M Ethernet signal surge protector is designed by IEC61000-4-5 and ITU-TK20&K21 standard. It adopts multilevel protective circuit and the newest high-speed surge protection device which has quick response, low residual voltage output and excellent transmission performance. The interface is RJ45 which is easy to use and suit for 10/100M Ethernet device protection, such as lightning protection for web cams, HUB, switch, router. FL45-E100 100M Ethernet signal lightning protector is designed and manufactured on the principle of discharge, limited current, clamping, stabilivolt. When signal wire gets an overvoltage and overcurrent shock, it will put lightning power or its jamming signal into the ground. Overvoltage restriction enables electrical equipment to operate safely within allowable range.
{ "redpajama_set_name": "RedPajamaC4" }
5,623
Correction to: Online tools supporting the conduct and reporting of systematic reviews and systematic maps: a case study on CADIMA and review of existing tools Christian Kohl ORCID: orcid.org/0000-0001-6524-83711 na1, Emma J. McIntosh2 na1, Stefan Unger1 na1, Neal R. Haddaway3, Steffen Kecke1, Joachim Schiemann1 & Ralf Wilhelm1 The Original Article was published on 01 February 2018 Correction to: Environ Evid (2018) 7:8 https://doi.org/10.1186/s13750-018-0115-5 The authors wish to update information about the software DistillerSR in Tables 1 and 3 which we were alerted to following the publication of original article [1]. In addition to the analysis provided, DistillerSR does support protocol development (Pi) e.g. assistance to determine appropriate PICO elements, and critical appraisal (Cr) as 'stages of the SR process supported'. This information was not originally included in the assessment due to a lack of clarity on the service providers' website. No further updates to this manuscript will be possible for this or other software, in line with the general disclaimer below. The review of systematic review support software represents an independent assessment by EJ McIntosh based on publicly available information on each software package. This assessment represents an attempt to best capture information located via service providers' websites, in academic publications, user manuals and via free trials or software demonstrations. Occasionally, relevant information was not publicly available or may have been difficult to access or interpret. This assessment does not represent the views or opinions of any of the software developers or service providers. The review of software was completed in mid-2017, readers should visit the software providers' websites (linked in Table 1) to check for updates, for further information and to seek clarification where necessary. Kohl C, McIntosh EJ, Unger S, Haddaway NR, Kecke S, Schiemann J, Wilhelm R. Online tools supporting the conduct and reporting of systematic reviews and systematic maps: a case study on CADIMA and review of existing tools. Environ Evid. 2018;7:8. https://doi.org/10.1186/s13750-018-0115-5. Christian Kohl, Emma J. McIntosh and Stefan Unger contributed equally to this work Julius Kühn-Institut (JKI), Federal Research Centre for Cultivated Plants, Erwin-Baur-Strasse 27, 06484, Quedlinburg, Germany Christian Kohl, Stefan Unger, Steffen Kecke, Joachim Schiemann & Ralf Wilhelm School of Geography and the Environment, University of Oxford, South Parks Road, Oxford, OX1 3QY, UK Emma J. McIntosh Mistra EviEM, Stockholm Environment Institute, 10451, Stockholm, Sweden Neal R. Haddaway Christian Kohl Stefan Unger Steffen Kecke Joachim Schiemann Ralf Wilhelm Correspondence to Christian Kohl. The original article can be found online at https://doi.org/10.1186/s13750-018-0115-5. Kohl, C., McIntosh, E.J., Unger, S. et al. Correction to: Online tools supporting the conduct and reporting of systematic reviews and systematic maps: a case study on CADIMA and review of existing tools. Environ Evid 7, 12 (2018). https://doi.org/10.1186/s13750-018-0124-4
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
4,771
Медија центар "Одбрана"" је специјализована војна установа Управе за односе са јавношћу Министарства одбране Републике Србије која извршава задатке у оквиру новинско-информативне и издавачке делатности и организације догађаја у згради Дома Војске Србије. Центар је формиран почетком 2010. године, у оквиру реорганизације Министарства одбране. У том процесу објединио је све делатности и задатке некадашњег Новинског центра "Одбрана", Војноиздавачког завода и Централног дома Војске Србије. Спољашње везе Медији у Београду
{ "redpajama_set_name": "RedPajamaWikipedia" }
457
@class User; @class ServiceProvider; @interface _Super_UserAccount : NSObject <PFModelObject, Serializable>{ NSString* ID; NSDate* dateCreated; NSDate* dateModified; User* user; ServiceProvider* serviceProvider; NSString* accessToken; NSString* refreshToken; NSString* accountId; BOOL isSupended; BOOL isAdmin; BOOL isShell; } @property (nonatomic, retain) NSString* ID; @property (nonatomic, retain) NSDate* dateCreated; @property (nonatomic, retain) NSDate* dateModified; @property (nonatomic, retain) User* user; @property (nonatomic, retain) ServiceProvider* serviceProvider; @property (nonatomic, retain) NSString* accessToken; @property (nonatomic, retain) NSString* refreshToken; @property (nonatomic, retain) NSString* accountId; @property (nonatomic) BOOL isSupended; @property (nonatomic) BOOL isAdmin; @property(nonatomic) BOOL isShell; @end
{ "redpajama_set_name": "RedPajamaGithub" }
96
During his 24th visit to the United States, SGI President Ikeda penned the iconic poem "The Sun of Jiyu Over a New Land." Los Angeles youth gather in front of a plaque emblazoned with the poem "The Sun of Jiyu Over a New Land" at the SGI-USA Los Angeles Friendship Center, October 2017. During his 24th visit to the United States, SGI President Ikeda penned the iconic poem "The Sun of Jiyu Over a New Land," which was presented on January 27, 1993, to the members at the Second SGI-USA General Meeting in Santa Monica, California. Although wwritten about the city of Los Angeles, President Ikeda said at the time that the poem was intended for all members: "I would like to present this poem with my infinite hopes and expectations for the members of Los Angeles and the United States" (My Dear Friends in America, third edition, p. 202). In the spring of 1992, the world's eyes were on Los Angeles, as the verdict in the Rodney King trial sparked massive social unrest and a national debate about police brutality, racial discrimination and economic inequality. SGI President and Mrs. Ikeda meet with and encourage Future Division members for the future of American kosen-rufu in Santa Monica, California, January 31, 1993. Photo: Seikyo Press. The SGI-USA was also undergoing a period of great change. Three years earlier, in February 1990, President Ikeda canceled his trip to South America to extend his visit to the United States at a critical juncture for the American organization. During his 17 days in Los Angeles, he attended general meetings and training sessions in which he especially focused on fostering youthful successors. In his guidance, he left behind a roadmap for kosen-rufu in the United States (see My Dear Friends in America, pp. 1–106), conveying in deep detail the essence of Buddhist humanism, the role religion must play in serving people in the 21st century, the spirit of leadership within the SGI and the dynamic inner transformation that occurs when people base their lives on the oneness of mentor and disciple. These themes became that much more significant when, on November 28, 1991, the Nichiren Shoshu priesthood excommunicated the SGI's 10 million lay members in a perverse attempt to wrest control of the membership. The priesthood had strongly advocated a doctrine of absolute superiority and authority of priests over laity—one that contradicts the spirit of equality that pervades Nichiren Daishonin's teachings. The vast majority of members throughout the world recognized the corruption, inhumanity and doctrinal distortion behind the priesthood's actions and chose to continue practicing within the SGI under the leadership of President Ikeda. state of jiyu, Bodhisattva of the Earth, within. —What has become of the ideals of this country? President Ikeda then urges us to "Awaken to the life of Jiyu within"! January 27 marks 25 years since this poem was presented to the members of the SGI-USA. President Ikeda's message is perhaps even more relevant now. In a society where the division between people and nations grows deeper still, in the poem he calls on us to usher in the Second American Renaissance, in which we advance from "divisiveness to union," "conflict to coexistence" and "hatred to fraternity." He continues, "In our struggle, in our fight, there cannot be even a moment's pause or stagnation." This timeless poem expresses his wish and expectation that America, as a multicultural nation, lead the way for all humanity. Andrea Locke, who lived with her husband and four young children just blocks from the looting and fires, said she chanted Nam-myoho-renge-kyo fiercely to the Gohonzon for peace and protection. She made a pact with her husband then to focus on education and their Buddhist practice to ensure a peaceful future for her children. Ms. Locke recalled having tears in her eyes when President Ikeda presented the poem to the members. It became her personal message from him and the blueprint for her life. Over the years, studying this poem has allowed her to return to her mission as a Bodhisattva of the Earth and continue challenging her own human revolution to create the type of society that President Ikeda envisioned in the poem. As we charge ahead toward our historic 50,000 Lions of Justice Festival, we are entering a new phase of American kosen-rufu with our mentor, President Ikeda. The message, though, remains the same: Awaken to the life state of jiyu within and usher in a new age of hope and respect for all humanity.
{ "redpajama_set_name": "RedPajamaC4" }
7,580
Remember Me is a new perfume by Jovoy for women and men and was released in 2018. The scent is sweet-gourmand. It is still in production. This is my Jovoy Remember Me Fragrance Review on YouTube. A fragrance I sampled at Esxence in April of 2018 which I enjoyed but after I received this fragrance for this review video I even enjoyed much more. Given I was sick with a cold during Esxence so I wasn't smelling much. Remember Me is absolutely a very delicious composition created by Cecile Zarokian for Jovoy. In Remember Me you have big dominant delicious tea note, very beautiful and aromatic, spicy, cardamom note, and an overdose of creamy, decadent milky woody notes. Chai Tea Latte anyone? Make sure you order it Breve! To find out more about Remember Me by Jovoy please watch my review over at YouTube. Thank you so much. IMO starts like a sweet, gourmand Dior Homme.
{ "redpajama_set_name": "RedPajamaC4" }
6,489
\section{INTRODUCTION} The ordered configuration space of $k$ distinct points of a topological space $X$ (see \cite{fadell1962configuration}) is the subset \[F(X,k)=\{(x_1,\cdots,x_k)\in X^k\mid ~~x_i\neq x_j\text{ for all } i\neq j \}\] topologised, as a subspace of the Cartesian power $X^k$. This space has been used in robotics when one controls multiple objects simultaneously, trying to avoid collisions between them \cite{farber2008invitation}. The first definition of category was given by Lusternik and Schnirelmann \cite{lusternik}. Their definition was a consequence of an investigation to obtain numerical bounds for the number of critical points of a smooth function on a manifold. Here we follow a definition of category, one greater than category given in \cite{cornea2003lusternik}. We say that the Lusternik-Schnirelmann category or category of a topological space $X$, denoted $cat(X)$, is the least integer $m$ such that $X$ can be covered with $m$ open sets, which are all contractible within $X$. One of the basic properties of $cat(X)$ is its homotopy invariance (\cite{cornea2003lusternik}, Theorem 1.30). Proposition \ref{prop 1} belows gives the general lower and upper bound of the category of a space $X$: \begin{prop}\label{prop 1} \begin{enumerate} \item[(1)] (\cite{roth2008category}, Section 2, Proposition 2.1-5), pg. 451) If $X$ is an $(n-1)-$connected CW-complex, then \[cat(X)\leq \frac{dim(X)}{n}+1.\] \item[(2)] Let $R$ be a commutative ring with unit and $X$ be a space. We have \[1+cup_R(X)\leq cat(X)\] where $cup_R(X)$ is the least integer $n$ such that all $(n+1)-$fold cup products vanish in the reduced cohomology $\widetilde{H^\star}(X;R)$ (\cite{cornea2003lusternik}, Theorem 1.5, pg. 2). \end{enumerate} \end{prop} On the other hand we recall the definition of topological complexity (see \cite{farber2003topological} for more details). The \textit{Topological complexity} of a path-connected space $X$ is the least integer $m$ such that the Cartesian product $X\times X$ can be covered with $m$ open subsets $U_i$, \begin{equation*} X \times X = U_1 \cup U_2 \cup\cdots \cup U_m \end{equation*} such that for any $i = 1, 2, \ldots , m$ there exists a continuous function $s_i : U_i \longrightarrow PX$, $\pi\circ s_i = id$ over $U_i$. If no such $m$ exists we will set $TC(X)=\infty$. Where $PX$ denote the space of all continuous paths $\gamma: [0,1] \longrightarrow X$ in $X$ and $\pi: PX \longrightarrow X \times X$ denotes the map associating to any path $\gamma\in PX$ the pair of its initial and end points $\pi(\gamma)=(\gamma(0),\gamma(1))$. Equip the path space $PX$ with the compact-open topology. The central motivating result of this paper is the Lusternik-Schnirelmann category of the configuration space of $2$ distinct points in Complex Projective $n-$space for all $n\geq 1$, \begin{thm}\label{theor} For $n\geq 1$, \[cat(F(\mathbb{CP}^n,2))=2n.\] \end{thm} As an application we have the following statement. \begin{cor}\label{coro} For $n\geq 1$, \[TC(F(\mathbb{CP}^n,2))=4n-1.\] \end{cor} \section{PROOF} In this section we proof Theorem \ref{theor} and Corollary \ref{coro}. We begin by proving two lemmas needed for our proofs. \begin{lem} For $n\geq 1$, \[H_q(F(\mathbb{CP}^n,2);\mathbb{Z})=\left\{ \begin{array}{ll} \mathbb{Z}^{\oplus (\frac{q}{2}+1)}, & \hbox{$q=0,2,4,\cdots,2(n-1)$;} \\ \mathbb{Z}^{\oplus (2n-\frac{q}{2})} , & \hbox{$q=2n,2n+2,2n+4,\cdots,2n+2(n-1)$;} \\ 0, & \hbox{otherwise.} \end{array} \right. \] \end{lem} \begin{proof} By the Leray-Serre espectral sequence (\cite{mccleary2001user}, Theorem 5.4, pg. 139) of the fibration $F(\mathbb{CP}^n,2)\longrightarrow \mathbb{CP}^n,~(x,y)\mapsto x$ with fibre $\mathbb{CP}^{n-1}$ (\cite{fadell1962configuration}, Theorem 1), we have the $E^2-$term\[E^2_{p,q}=H_p(\mathbb{CP}^n;\mathbb{Z})\otimes H_q(\mathbb{CP}^{n-1};\mathbb{Z}) \] and all those differentials are zero (see Figure \ref{seq}). So this Lemma follows. \end{proof} \begin{figure}[!h] \caption{$E^2-$term.} \label{seq} \centering \includegraphics[scale=0.5]{cpn2.pdf} \end{figure} We recall that $F(\mathbb{CP}^n,2)$ is simply-connected, since $\mathbb{CP}^n$ and $\mathbb{CP}^{n-1}$ are. By (\cite{hatcher2002algebraic}, Proposition 4C.1) we have: \begin{cor}\label{coro2} The configuration space of complex projective space $F(\mathbb{CP}^n,2)$ has the homotopy type of a CW complex which has $j+1$\quad $2j-$cells ($j=0,1,\ldots ,n-1$), and $2n-j$\quad $2j-$cells ($j=n,n+1,n+2,\ldots,n+(n-1)$). In particular, $F(\mathbb{CP}^n,2)$ has the homotopy type of a $2(2n-1)-$dimensional finite CW complex. \end{cor} The multiplicative structure of the cohomological algebra of the configuration space $F(\mathbb{C}P^n,2)$ was given by (\cite{sohail2010cohomology}, Theorem 2, pg. 412): \[H^\star(F(\mathbb{CP}^n,2);\mathbb{C})=\dfrac{\mathbb{C}[a_1,a_2]}{\langle r_n(a_1,a_2);a_1^{n+1};a_2^{n+1}\rangle},\] where $deg (a_1)=deg (a_2)=2$ and $r_n(x,y)=x^n+x^{n-1}y+\cdots +y^n$. Thus, we can conclude $a_1^na_2^n=0$ and $a_1^{n-1}a_2^n\neq 0$, since $a_1^na_2^n=r_n(a_1,a_2)a_2^n=0$ and $a_1^{n-1}a_2^n$ is a unique (up to sign) generator of $H^{4n-2}=\mathbb{C}$. \begin{lem}\label{lem3} \[cup_{\mathbb{C}}(F(\mathbb{CP}^n,2))=2n-1.\] \end{lem} \begin{proof} We just have to note that $a_1^na_2^n=0$ and $a_1^{n-1}a_2^n\neq 0$. \end{proof} \noindent \textit{Proof of Theorem \ref{theor}.} It follows using Corrollary \ref{coro2}, Lemma \ref{lem3} and Proposition \ref{prop 1}. \begin{flushright} $\square$ \end{flushright} \noindent \textit{Proof of corollary \ref{coro}.} Since $F(\mathbb{CP}^n,2)$ is path-connected and paracompact, the inequality \[TC(F(\mathbb{CP}^n,2))\leq 4n-1\] follows from Theorem \ref{theor} and (\cite{farber2003topological}, Section 3, Theorem 5, pg. 215). On the other hand, $1\otimes a_1-a_1\otimes 1$ and $1\otimes a_2-a_2\otimes 1\in H^\star(F(\mathbb{CP}^n,2);\mathbb{C})\otimes H^\star(F(\mathbb{CP}^n,2);\mathbb{C})$ are zero-divisors whose $(2n-1)-$th power \begin{eqnarray*} (1\otimes a_1-a_1\otimes 1)^{2n-1} &=& pa_1^{n-1}\otimes a_1^n+qa_1^{n}\otimes a_1^{n-1}; \\ (1\otimes a_2-a_2\otimes 1)^{2n-1} &=& pa_2^{n-1}\otimes a_2^n+qa_2^{n}\otimes a_2^{n-1}, \end{eqnarray*} where $p=(-1)^{n-1}{2n-1 \choose n-1} $ and $q=(-1)^{n}{2n-1 \choose n} $. Thus, we have \begin{equation*} (1\otimes a_1-a_1\otimes 1)^{2n-1}(1\otimes a_2-a_2\otimes 1)^{2n-1} = 2p^2 a_1^{n-1}a_2^n\otimes a_1^{n-1}a_2^n \end{equation*} does not vanish. The opposite inequality \[TC(F(\mathbb{CP}^n,2))\geq 4n-1\] now follows from (\cite{farber2003topological}, Theorem 7). \begin{flushright} $\square$ \end{flushright} \begin{rem} Corollary \ref{coro} in the case $n=1$ also was calculated by Michael Farber and Daniel Cohen in (\cite{cohen2011topological}, Theorem A). \end{rem} \begin{rem} Theorem \ref{theor} shows that the configuration space $F(\mathbb{CP}^n,2)$ satisfies the Ganea's conjecture, because $cat(F(\mathbb{CP}^n,2))=cup_{\mathbb{C}}(F(\mathbb{CP}^n,2))+1$. \end{rem} \begin{rem} By (\cite{farber2003topologicalproj}, Corollary 3.2) we have \begin{equation} TC(M)=dim(M)+1\label{symplectic} \end{equation} when $M$ is a closed simply connected symplectic manifold. Corollary \ref{coro} shows that the analogous statement (\ref{symplectic}) for non compact cases does not hold. \end{rem} \begin{rem} We will compare the result stated in Corollary \ref{coro} with the topological complexity of the Cartesian product $\mathbb{CP}^n\times \mathbb{CP}^n$. By (\cite{farber2003topologicalproj}, Corollary 3.2) we have \begin{equation*} TC(\mathbb{CP}^n\times \mathbb{CP}^n) = 4n+1. \end{equation*} Thus, on the complex projective space $\mathbb{CP}^n$, the complexity of the collision-free motion planning problem for $2$ robots is \textit{less} complicated than the complexity of the similar problem when the robots are allowed to collide. This example also\footnote{This phenomenon occurs also on a surface of high genus (see \cite{cohen2011topological}).} provides an illustration of the fact that the concept $TC(X)$ reflects only the \textit{topological} complexity, which is just a part of the \textit{total} complexity of the problem. \end{rem} \begin{rem} We note that the configuration space $F(\mathbb{CP}^n,2)$ is the space of all lines in the complex projective space $\mathbb{CP}^n$, since two points in $\mathbb{CP}^n$ generate a subspace of dimension 1. More general, \cite{berceanu2012braid} the ordered configuration space $F(\mathbb{CP}^n,k)$ has a stratification with complex submanifolds as follows: \[F(\mathbb{CP}^n,k)=\coprod_{i=1}^{n}F^i(\mathbb{CP}^n,k),\] where $F^i(\mathbb{CP}^n,k)$ is the ordered configuration space of all $k$ points in $\mathbb{CP}^n$ generating a subspace of dimension $i$. \end{rem} \begin{rem} There is no discussion of what might happen for more than two points. Thus, it is interesting to calculate the TC for the ordered configuration space $F(\mathbb{CP}^n,k)$ when $k\geq 3$. In general, calculate the TC for the ordered configuration space $F(V,k)$ where $V$ is a smooth complex projective variety. \end{rem} \noindent \textbf{Acknowledgments} I am very grateful to Jesús González and my advisor Denise de Mattos for their comments and encouraging remarks which were of invaluable mental support. Also, the author wishes to acknowledge support for this research, from FAPESP 2016/18714-8.
{ "redpajama_set_name": "RedPajamaArXiv" }
3,338
This exhibition at The Art Gallery of Ontario examined the connections between painting and film in Schnabel's work, tracing how his paintings exist in dialogue with the cinema. Film emerges as an organizing principle that constantly structures the narratives and pictorial range of his painting. Julian Schnabel: Art and Film surveys Schnabel's work as a painter from the mid-1970s to the present and features more than 50 key works, each revealing how Schnabel's abstract and figurative paintings, photographs and sculptures articulate his fascination with cinema.
{ "redpajama_set_name": "RedPajamaC4" }
4,048
History of science and technology in China (Redirected from History of Science and Technology in China) For the history of science and technology of modern China, see History of science and technology in the People's Republic of China. For the science and technology of modern China, see Science and technology in the People's Republic of China. For the science and technology of modern Taiwan, see Ministry of Science and Technology (Republic of China). Instructions for making astronomical instruments from the time of the Qing Dynasty. Ancient Chinese scientists and engineers made significant scientific innovations, findings and technological advances across various scientific disciplines including the natural sciences, engineering, medicine, military technology, mathematics, geology and astronomy. Among the earliest inventions were the abacus, the "shadow clock," and the first items such as Kongming lanterns.[citation needed] The Four Great Inventions,the compass, gunpowder, papermaking, and printing – were among the most important technological advances, only known to Europe by the end of the Middle Ages 1000 years later. The Tang dynasty (AD 618–906) in particular was a time of great innovation.[citation needed] A good deal of exchange occurred between Western and Chinese discoveries up to the Qing dynasty. The Jesuit China missions of the 16th and 17th centuries introduced Western science and astronomy, then undergoing its own revolution, to China, and knowledge of Chinese technology was brought to Europe.[1][2] In the 19th and 20th centuries the introduction of Western technology was a major factor in the modernization of China. Much of the early Western work in the history of science in China was done by Joseph Needham. 1 Mo Di and the School of Names 2 Han dynasty 3 "Four Great Inventions" 4 China's scientific revolution 4.1 Song Dynasty 4.1.1 Archaeology 4.1.2 Geology and climatology 4.2 Mongol transmission 4.3 Theory and hypothesis 4.4 Pharmacology 4.5 Horology and clockworks 4.6 Magnetism and metallurgy 4.7 Mathematics 4.8 Alchemy and Taoism 4.9 Gunpowder warfare 5 Jesuit activity in China 6 Scientific and technological stagnation 7 The Republic of China (1912–49) 8 People's Republic of China 10.1 Citations 10.2 Sources Mo Di and the School of Names The Warring States period began 2500 years ago at the time of the invention of the crossbow.[3] Needham notes that the invention of the crossbow "far outstripped the progress in defensive armor", which made the wearing of armor useless to the princes and dukes of the states.[4] At this time, there were also many nascent schools of thought in China—the Hundred Schools of Thought (諸子百家), scattered among many polities. The schools served as communities which advised the rulers of these states. Mo Di (墨翟 Mozi, 470 BCE–c. 391 BCE) introduced concepts useful to one of those rulers, such as defensive fortification. One of these concepts, fa (法 principle or method)[5] was extended by the School of Names (名家 Ming jia, ming=name), which began a systematic exploration of logic. The development of a school of logic was cut short by the defeat of Mohism's political sponsors by the Qin dynasty, and the subsumption of fa as law rather than method by the Legalists (法家 Fa jia). Needham further notes that the Han dynasty, which conquered the short-lived Qin, were made aware of the need for law by Lu Chia and by Shu-Sun Thung, as defined by the scholars, rather than the generals.[4] You conquered the empire on horseback, but from horseback you will never succeed in ruling it. —  Lu Chia[6] Derived from Taoist philosophy, one of the newest longstanding contributions of the ancient Chinese are in Traditional Chinese medicine, including acupuncture and herbal medicine. The practice of acupuncture can be traced back as far as the 1st millennium BC and some scientists believe that there is evidence that practices similar to acupuncture were used in Eurasia during the early Bronze Age.[7] Using shadow clocks and the abacus (both invented in the ancient Near East before spreading to China), the Chinese were able to record observations, documenting the first recorded solar eclipse in 2137 BC, and making the first recording of any planetary grouping in 500 BC.[8] These claims, however, are highly disputed and rely on much supposition.[9][10] The Book of Silk was the first definitive atlas of comets, written c. 400 BC. It listed 29 comets (referred to as sweeping stars) that appeared over a period of about 300 years, with renderings of comets describing an event its appearance corresponded to.[8] In architecture, the pinnacle of Chinese technology manifested itself in the Great Wall of China, under the first Chinese Emperor Qin Shi Huang between 220 and 200 BC. Typical Chinese architecture changed little from the succeeding Han dynasty until the 19th century.[citation needed] The Qin dynasty also developed the crossbow, which later became the mainstream weapon in Europe. Several remains of crossbows have been found among the soldiers of the Terracotta Army in the tomb of Qin Shi Huang.[11] Remains of a Chinese crossbow, 2nd century BC. Main article: Science and technology of the Han dynasty The Eastern Han dynasty scholar and astronomer Zhang Heng (78–139 AD) invented the first water-powered rotating armillary sphere (the first armillary sphere having been invented by the Greek Eratosthenes), and catalogued 2,500 stars and over 100 constellations. In 132, he invented the first seismological detector, called the "Houfeng Didong Yi" ("Instrument for inquiring into the wind and the shaking of the earth").[12] According to the History of Later Han Dynasty (25–220 AD), this seismograph was an urn-like instrument, which would drop one of eight balls to indicate when and in which direction an earthquake had occurred.[12] On June 13, 2005, Chinese seismologists announced that they had created a replica of the instrument.[12] The mechanical engineer Ma Jun (c. 200–265 AD) was another impressive figure from ancient China. Ma Jun improved the design of the silk loom,[13] designed mechanical chain pumps to irrigate palatial gardens,[13] and created a large and intricate mechanical puppet theatre for Emperor Ming of Wei, which was operated by a large hidden waterwheel.[14] However, Ma Jun's most impressive invention was the south-pointing chariot, a complex mechanical device that acted as a mechanical compass vehicle. It incorporated the use of a differential gear in order to apply equal amount of torque to wheels rotating at different speeds, a device that is found in all modern automobiles.[15] Sliding calipers were invented in China almost 2,000 years ago.[citation needed] The Chinese civilization was the earliest civilization to experiment successfully with aviation, with the kite and Kongming lantern (proto Hot air balloon) being the first flying machines. "Four Great Inventions" The intricate frontispiece of the Diamond Sutra from Tang dynasty China, 868 AD (British Library) Main article: Four Great Inventions The "Four Great Inventions" (simplified Chinese: 四大发明; traditional Chinese: 四大發明; pinyin: sì dà fāmíng) are the compass, gunpowder, papermaking and printing. Paper and printing were developed first. Printing was recorded in China in the Tang Dynasty, although the earliest surviving examples of printed cloth patterns date to before 220.[16] Pin-pointing the development of the compass can be difficult: the magnetic attraction of a needle is attested by the Louen-heng, composed between AD 20 and 100,[17] although the first undisputed magnetized needles in Chinese literature appear in 1086.[18] By AD 300, Ge Hong, an alchemist of the Jin dynasty, conclusively recorded the chemical reactions caused when saltpetre, pine resin and charcoal were heated together, in Book of the Master of the Preservations of Solidarity.[19] Another early record of gunpowder, a Chinese book from c. 850 AD, indicates: "Some have heated together sulfur, realgar and saltpeter with honey; smoke and flames result, so that their hands and faces have been burnt, and even the whole house where they were working burned down."[20] These four discoveries had an enormous impact on the development of Chinese civilization and a far-ranging global impact. Gunpowder, for example, spread to the Arabs in the 13th century and thence to Europe.[21] According to English philosopher Francis Bacon, writing in Novum Organum: Printing, gunpowder and the compass: These three have changed the whole face and state of things throughout the world; the first in literature, the second in warfare, the third in navigation; whence have followed innumerable changes, in so much that no empire, no sect, no star seems to have exerted greater power and influence in human affairs than these mechanical discoveries. —  [22] One of the most important military treatises of all Chinese history was the Huo Long Jing written by Jiao Yu in the 14th century. For gunpowder weapons, it outlined the use of fire arrows and rockets, fire lances and firearms, land mines and naval mines, bombards and cannons, two stage rockets, along with different compositions of gunpowder, including 'magic gunpowder', 'poisonous gunpowder', and 'blinding and burning gunpowder' (refer to his article). For the 11th century invention of ceramic movable type printing by Bi Sheng (990–1051), it was enhanced by the wooden movable type of Wang Zhen in 1298 and the bronze metal movable type of Hua Sui in 1490. China's scientific revolution Ships of the world in 1460 (Fra Mauro map). Chinese junks are described as very large, three or four-masted ships. Among the engineering accomplishments of early China were matches, dry docks, the double-action piston pump, cast iron, the iron plough, the horse collar, the multi-tube seed drill, the wheelbarrow, the suspension bridge, the parachute, natural gas as fuel, the raised-relief map, the propeller, the sluice gate, and the pound lock. The Tang dynasty (AD 618–907) and Song dynasty (AD 960–1279) in particular were periods of great innovation.[citation needed] In the 7th century, book-printing was developed in China, Korea and Japan, using delicate hand-carved wooden blocks to print individual pages.[citation needed] The 9th century Diamond Sutra is the earliest known printed document.[citation needed] Movable type was also used in China for a time, but was abandoned because of the number of characters needed; it would not be until Johannes Gutenberg that the technique was reinvented in a suitable environment.[citation needed] In addition to gunpowder, the Chinese also developed improved delivery systems for the Byzantine weapon of Greek fire, Meng Huo You and Pen Huo Qi first used in China c. 900.[23] Chinese illustrations were more realistic than in Byzantine manuscripts,[23] and detailed accounts from 1044 recommending its use on city walls and ramparts show the brass container as fitted with a horizontal pump, and a nozzle of small diameter.[23] The records of a battle on the Yangtze near Nanjing in 975 offer an insight into the dangers of the weapon, as a change of wind direction blew the fire back onto the Song forces.[23] Main article: Technology of the Song Dynasty The Song dynasty (960–1279) brought a new stability for China after a century of civil war, and started a new area of modernisation by encouraging examinations and meritocracy. The first Song Emperor created political institutions that allowed a great deal of freedom of discourse and thought, which facilitated the growth of scientific advance, economic reforms, and achievements in arts and literature.[24] Trade flourished both within China and overseas, and the encouragement of technology allowed the mints at Kaifeng and Hangzhou to gradually increase in production.[24] In 1080, the mints of Emperor Shenzong had produced 5 billion coins (roughly 50 per Chinese citizen), and the first banknotes were produced in 1023.[24] These coins were so durable that they would still be in use 700 years later, in the 18th century.[24] There were many famous inventors and early scientists in the Song Dynasty period. The statesman Shen Kuo is best known for his book known as the Dream Pool Essays (1088 AD). In it, he wrote of use for a drydock to repair boats, the navigational magnetic compass, and the discovery of the concept of true north (with magnetic declination towards the North Pole). Shen Kuo also devised a geological theory for land formation, or geomorphology, and theorized that there was climate change in geological regions over an enormous span of time. The equally talented statesman Su Song was best known for his engineering project of the Astronomical Clock Tower of Kaifeng, by 1088 AD. The clock tower was driven by a rotating waterwheel and escapement mechanism. Crowning the top of the clock tower was the large bronze, mechanically-driven, rotating armillary sphere. In 1070, Su Song also compiled the Ben Cao Tu Jing (Illustrated Pharmacopoeia, original source material from 1058–1061 AD) with a team of scholars. This pharmaceutical treatise covered a wide range of other related subjects, including botany, zoology, mineralogy, and metallurgy. Chinese astronomers were the first to record observations of a supernova, the first being the SN 185, recorded during the Han dynasty. Chinese astronomers made two more notable supernova observations during the Song Dynasty: the SN 1006, the brightest recorded supernova in history; and the SN 1054, making the Crab Nebula the first astronomical object recognized as being connected to a supernova explosion.[25] During the early half of the Song dynasty (960–1279), the study of archaeology developed out of the antiquarian interests of the educated gentry and their desire to revive the use of ancient vessels in state rituals and ceremonies.[26] This and the belief that ancient vessels were products of 'sages' and not common people was criticized by Shen Kuo, who took an interdisciplinary approach to archaeology, incorporating his archaeological findings into studies on metallurgy, optics, astronomy, geometry, and ancient music measures.[26] His contemporary Ouyang Xiu (1007–1072) compiled an analytical catalogue of ancient rubbings on stone and bronze, which Patricia B. Ebrey says pioneered ideas in early epigraphy and archaeology.[27] In accordance with the beliefs of the later Leopold von Ranke (1795–1886), some Song gentry—such as Zhao Mingcheng (1081–1129)—supported the primacy of contemporaneous archaeological finds of ancient inscriptions over historical works written after the fact, which they contested to be unreliable in regard to the former evidence.[28] Hong Mai (1123–1202) used ancient Han Dynasty era vessels to debunk what he found to be fallacious descriptions of Han vessels in the Bogutu archaeological catalogue compiled during the latter half of Huizong's reign (1100–1125).[28] Geology and climatology In addition to his studies in meteorology, astronomy, and archaeology mentioned above, Shen Kuo also made hypotheses in regards to geology and climatology in his Dream Pool Essays of 1088, specifically his claims regarding geomorphology and climate change. Shen believed that land was reshaped over time due to perpetual erosion, uplift, and deposition of silt, and cited his observance of horizontal strata of fossils embedded in a cliffside at Taihang as evidence that the area was once the location of an ancient seashore that had shifted hundreds of miles east over an enormous span of time.[29][30][31] Shen also wrote that since petrified bamboos were found underground in a dry northern climate zone where they had never been known to grow, climates naturally shifted geographically over time.[31][32] Mongol transmission Mongol rule under the Yuan dynasty saw technological advances from an economic perspective, with the first mass production of paper banknotes by Kublai Khan in the 13th century.[citation needed] Numerous contacts between Europe and the Mongols occurred in the 13th century, particularly through the unstable Franco-Mongol alliance. Chinese corps, expert in siege warfare, formed an integral part of the Mongol armies campaigning in the West. In 1259–1260 military alliance of the Franks knights of the ruler of Antioch, Bohemond VI and his father-in-law Hetoum I with the Mongols under Hulagu, in which they fought together for the conquests of Muslim Syria, taking together the city of Aleppo, and later Damascus.[33] William of Rubruck, an ambassador to the Mongols in 1254–1255, a personal friend of Roger Bacon, is also often designated as a possible intermediary in the transmission of gunpowder know-how between the East and the West.[34] The compass is often said to have been introduced by the Master of the Knights Templar Pierre de Montaigu between 1219 and 1223, from one of his travels to visit the Mongols in Persia.[35] Chinese and Arabic astronomy intermingled under Mongol rule. Muslim astronomers worked in the Chinese Astronomical Bureau established by Kublai Khan, while some Chinese astronomers also worked at the Persian Maragha observatory.[36] Before this, in ancient times, Indian astronomers had lent their expertise to the Chinese court.[37] Theory and hypothesis A 1726 illustration of Haidao Suanjing, written by Liu Hui in the 3rd century. As Toby E. Huff notes, pre-modern Chinese science developed precariously without solid scientific theory, while there was a lacking of consistent systemic treatment in comparison to contemporaneous European works such as the Concordance and Discordant Canons by Gratian of Bologna (fl. 12th century).[38] This drawback to Chinese science was lamented even by the mathematician Yang Hui (1238–1298), who criticized earlier mathematicians such as Li Chunfeng (602–670) who were content with using methods without working out their theoretical origins or principle, stating: The men of old changed the name of their methods from problem to problem, so that as no specific explanation was given, there is no way of telling their theoretical origin or basis. Despite this, Chinese thinkers of the Middle Ages proposed some hypotheses which are in accordance with modern principles of science. Yang Hui provided theoretical proof for the proposition that the complements of the parallelograms which are about the diameter of any given parallelogram are equal to one another.[39] Sun Sikong (1015–1076) proposed the idea that rainbows were the result of the contact between sunlight and moisture in the air, while Shen Kuo (1031–1095) expanded upon this with description of atmospheric refraction.[40][41][42] Shen believed that rays of sunlight refracted before reaching the surface of the earth, hence the appearance of the observed sun from earth did not match its exact location.[42] Coinciding with the astronomical work of his colleague Wei Pu, Shen and Wei realized that the old calculation technique for the mean sun was inaccurate compared to the apparent sun, since the latter was ahead of it in the accelerated phase of motion, and behind it in the retarded phase.[43] Shen supported and expanded upon beliefs earlier proposed by Han dynasty (202 BCE–220 CE) scholars such as Jing Fang (78–37 BCE) and Zhang Heng (78–139 CE) that lunar eclipse occurs when the earth obstructs the sunlight traveling towards the moon, a solar eclipse is the moon's obstruction of sunlight reaching earth, the moon is spherical like a ball and not flat like a disc, and moonlight is merely sunlight reflected from the moon's surface.[44] Shen also explained that the observance of a full moon occurred when the sun's light was slanting at a certain degree and that crescent phases of the moon proved that the moon was spherical, using a metaphor of observing different angles of a silver ball with white powder thrown onto one side.[45][46] Although the Chinese accepted the idea of spherical-shaped heavenly bodies, the concept of a spherical earth (as opposed to a flat earth) was not accepted in Chinese thought until the works of Italian Jesuit Matteo Ricci (1552–1610) and Chinese astronomer Xu Guangqi (1562–1633) in the early 17th century.[47] Main article: Traditional Chinese medicine There were noted advances in traditional Chinese medicine during the Middle Ages. Emperor Gaozong (reigned 649–683) of the Tang dynasty (618–907) commissioned the scholarly compilation of a materia medica in 657 that documented 833 medicinal substances taken from stones, minerals, metals, plants, herbs, animals, vegetables, fruits, and cereal crops.[48] In his Bencao Tujing ('Illustrated Pharmacopoeia'), the scholar-official Su Song (1020–1101) not only systematically categorized herbs and minerals according to their pharmaceutical uses, but he also took an interest in zoology.[49][50][51][52] For example, Su made systematic descriptions of animal species and the environmental regions they could be found, such as the freshwater crab Eriocher sinensis found in the Huai River running through Anhui, in waterways near the capital city, as well as reservoirs and marshes of Hebei.[53] Muhammad ibn Zakariya al-Razi in 896, mentions the popular introduction of various Chinese herbs and aloes in Baghdad. Horology and clockworks Although the Bencao Tujing was an important pharmaceutical work of the age, Su Song is perhaps better known for his work in horology. His book Xinyi Xiangfayao (新儀象法要; lit. 'Essentials of a New Method for Mechanizing the Rotation of an Armillary Sphere and a Celestial Globe') documented the intricate mechanics of his astronomical clock tower in Kaifeng. This included the use of an escapement mechanism and world's first known chain drive to power the rotating armillary sphere crowning the top as well as the 133 clock jack figurines positioned on a rotating wheel that sounded the hours by banging drums, clashing gongs, striking bells, and holding plaques with special announcements appearing from open-and-close shutter windows.[54][55][56][57] While it had been Zhang Heng who applied the first motive power to the armillary sphere via hydraulics in 125 CE,[58][59] it was Yi Xing (683–727) in 725 CE who first applied an escapement mechanism to a water-powered celestial globe and striking clock.[60] The early Song Dynasty horologist Zhang Sixun (fl. late 10th century) employed liquid mercury in his astronomical clock because there were complaints that water would freeze too easily in the clepsydra tanks during winter.[61] The elephant clock in a manuscript by Al-Jazari (1206 AD) from The Book of Knowledge of Ingenious Mechanical Devices.[62] Al-Jazari (1136–1206), a Muslim engineer and inventor of various clocks, including the Elephant clock, wrote: "[T]he elephant represents the Indian and African cultures, the two dragons represents Chinese culture, the phoenix represents Persian culture, the water work represents ancient Greek culture, and the turban represents Islamic culture".[citation needed] Magnetism and metallurgy Shen Kuo's written work of 1088 also contains the first written description of the magnetic needle compass, the first description in China of experiments with camera obscura, the invention of movable type printing by the artisan Bi Sheng (990–1051), a method of repeated forging of cast iron under a cold blast similar to the modern Bessemer process, and the mathematical basis for spherical trigonometry that would later be mastered by the astronomer and engineer Guo Shoujing (1231–1316).[63][64][65][66][67][68][69] While using a sighting tube of improved width to correct the position of the pole star (which had shifted over the centuries), Shen discovered the concept of true north and magnetic declination towards the North Magnetic Pole, a concept which would aid navigators in the years to come.[70][71] In addition to the method similar to the Bessemer process mentioned above, there were other notable advancements in Chinese metallurgy during the Middle Ages. During the 11th century, the growth of the iron industry caused vast deforestation due to the use of charcoal in the smelting process.[72][73] To remedy the problem of deforestation, the Song Chinese discovered how to produce coke from bituminous coal as a substitute for charcoal.[72][73] Although hydraulic-powered bellows for heating the blast furnace had been written of since Du Shi's (d. 38) invention of the 1st century CE, the first known drawn and printed illustration of it in operation is found in a book written in 1313 by Wang Zhen (fl. 1290–1333).[74] Main article: Chinese mathematics Qin Jiushao (c. 1202–1261) was the first to introduce the zero symbol into Chinese mathematics.[75] Before this innovation, blank spaces were used instead of zeros in the system of counting rods.[76] Pascal's triangle was first illustrated in China by Yang Hui in his book Xiangjie Jiuzhang Suanfa (详解九章算法), although it was described earlier around 1100 by Jia Xian.[77] Although the Introduction to Computational Studies (算学启蒙) written by Zhu Shijie (fl. 13th century) in 1299 contained nothing new in Chinese algebra, it had a great impact on the development of Japanese mathematics.[78] Alchemy and Taoism Stoneware bombs, known in Japanese as Tetsuhau (iron bomb), or in Chinese as Zhentianlei (thunder crash bomb), excavated from the Takashima shipwreck, October 2011. Excavated bombs contain a 3-6cm opening at the top where the fuse was placed. Once the fuse was lit, the bomb was thrown either by hand or catapult. According to the Mōko Shūrai Ekotoba scroll, these bombs made a large noise and emitted bright fire upon explosion. Prior to the shipwreck's discovery, observers believed the bombs depicted in the scroll were a later addition. Main article: Chinese alchemy In their pursuit for an elixir of life and desire to create gold from various mixtures of materials, Taoists became heavily associated with alchemy.[79] Joseph Needham labeled their pursuits as proto-scientific rather than merely pseudoscience.[79] Fairbank and Goldman write that the futile experiments of Chinese alchemists did lead to the discovery of new metal alloys, porcelain types, and dyes.[79] However, Nathan Sivin discounts such a close connection between Taoism and alchemy, which some sinologists have asserted, stating that alchemy was more prevalent in the secular sphere and practiced by laymen.[80] Experimentation with various materials and ingredients in China during the middle period led to the discovery of many ointments, creams, and other mixtures with practical uses. In a 9th-century Arab work Kitāb al-Khawāss al Kabīr, there are numerous products listed that were native to China, including waterproof and dust-repelling cream or varnish for clothes and weapons, a Chinese lacquer, varnish, or cream that protected leather items, a completely fire-proof cement for glass and porcelain, recipes for Chinese and Indian ink, a waterproof cream for the silk garments of underwater divers, and a cream specifically used for polishing mirrors.[81] Gunpowder warfare The significant change that distinguished Medieval warfare to early Modern warfare was the use of gunpowder weaponry in battle. A 10th-century silken banner from Dunhuang portrays the first artistic depiction of a fire lance, a prototype of the gun.[82] The Wujing Zongyao military manuscript of 1044 listed the first known written formulas for gunpowder, meant for light-weight bombs lobbed from catapults or thrown down from defenders behind city walls.[83] By the 13th century, the iron-cased bomb shell, hand cannon, land mine, and rocket were developed.[84][85] As evidenced by the Huolongjing of Jiao Yu and Liu Bowen, by the 14th century the Chinese had developed the heavy cannon, hollow and gunpowder-packed exploding cannonballs, the two-stage rocket with a booster rocket, the naval mine and wheellock mechanism to ignite trains of fuses.[86][87] Jesuit activity in China Jesuits in China. The Jesuit China missions of the 16th and 17th centuries introduced Western science and astronomy, then undergoing its own revolution, to China. One modern historian writes that in late Ming courts, the Jesuits were "regarded as impressive especially for their knowledge of astronomy, calendar-making, mathematics, hydraulics, and geography."[88] The Society of Jesus introduced, according to Thomas Woods, "a substantial body of scientific knowledge and a vast array of mental tools for understanding the physical universe, including the Euclidean geometry that made planetary motion comprehensible."[1] Another expert quoted by Woods said the scientific revolution brought by the Jesuits coincided with a time when science was at a very low level in China: [The Jesuits] made efforts to translate western mathematical and astronomical works into Chinese and aroused the interest of Chinese scholars in these sciences. They made very extensive astronomical observation and carried out the first modern cartographic work in China. They also learned to appreciate the scientific achievements of this ancient culture and made them known in Europe. Through their correspondence European scientists first learned about the Chinese science and culture. —  [2] Conversely, the Jesuits were very active in transmitting Chinese knowledge to Europe. Confucius's works were translated into European languages through the agency of Jesuit scholars stationed in China. Matteo Ricci started to report on the thoughts of Confucius, and Father Prospero Intorcetta published the life and works of Confucius into Latin in 1687.[89] It is thought that such works had considerable importance on European thinkers of the period, particularly among the Deists and other philosophical groups of the Enlightenment who were interested by the integration of the system of morality of Confucius into Christianity.[90][91] The followers of the French physiocrat François Quesnay habitually referred to him as "the Confucius of Europe", and he personally identified himself with the Chinese sage.[92] The doctrine and even the name of "Laissez-faire" may have been inspired by the Chinese concept of Wu wei.[93][94] However, the economic insights of ancient Chinese political thought had otherwise little impact outside China in later centuries.[95] Goethe, was known as "the Confucius of Weimar".[96] Scientific and technological stagnation Further information: Great Divergence One question that has been the subject of debate among historians has been why China did not develop a scientific revolution and why Chinese technology fell behind that of Europe. Many hypotheses have been proposed ranging from the cultural to the political and economic. John K. Fairbank, for example, argued that the Chinese political system was hostile to scientific progress. As for Needham, he wrote that cultural factors prevented traditional Chinese achievements from developing into what could be called "science." It was the religious and philosophical framework of the Chinese intellectuals which made them unable to believe in the ideas of laws of nature: It was not that there was no order in nature for the Chinese, but rather that it was not an order ordained by a rational personal being, and hence there was no conviction that rational personal beings would be able to spell out in their lesser earthly languages the divine code of laws which he had decreed aforetime. The Taoists, indeed, would have scorned such an idea as being too naïve for the subtlety and complexity of the universe as they intuited it. Another prominent historian of science, Nathan Sivin, has argued that China indeed had a scientific revolution in the 17th century but it's just that we are still not able to really understand the scientific revolution that took place in China. Sivin suggests that we need to look at the scientific development in China on its own terms.[98] There are also questions about the philosophy behind traditional Chinese medicine, which, derived partly from Taoist philosophy, reflects the classical Chinese belief that individual human experiences express causative principles effective in the environment at all scales. Because its theory predates use of the scientific method, it has received various criticisms based on scientific thinking. Philosopher Robert Todd Carroll, a member of the Skeptics Society, deemed acupuncture a pseudoscience because it "confuse(s) metaphysical claims with empirical claims".[99] More recent historians have questioned political and cultural explanations and have put greater focus on economic causes. Mark Elvin's high level equilibrium trap is one well-known example of this line of thought. It argues that the Chinese population was large enough, workers cheap enough, and agrarian productivity high enough to not require mechanization: thousands of Chinese workers were perfectly able to quickly perform any needed task. Other events such as Haijin, the Opium Wars and the resulting hate of European influence prevented China from undergoing an Industrial Revolution; copying Europe's progress on a large scale would be impossible for a lengthy period of time. Political instability under Cixi rule (opposition and frequent oscillation between modernists and conservatives), the Republican wars (1911–1933), the Sino-Japanese War (1933–1945), the Communist/Nationalist War (1945–1949) as well as the later Cultural Revolution isolated China at the most critical times. Kenneth Pomeranz has made the argument that the substantial resources taken from the New World to Europe made the crucial difference between European and Chinese development. In his book Guns, Germs, and Steel, Jared Diamond postulates that the lack of geographic barriers within much of China—essentially a wide plain with two large navigable rivers and a relatively smooth coastline—led to a single government without competition. At the whim of a ruler who disliked new inventions, technology could be stifled for half a century or more. In contrast, Europe's barriers of the Pyrenees, the Alps, and the various defensible peninsulas (Denmark, Scandinavia, Italy, Greece, etc.) and islands (Britain, Ireland, Sicily, etc.) led to smaller countries in constant competition with each other. If a ruler chose to ignore a scientific advancement (especially a military or economic one), his more-advanced neighbors would soon usurp his throne. This explanation, however, ignores the fact that China had been politically fragmented in the past, and was thus not inherently disposed to political unification.[100] The Republic of China (1912–49) The Republic of China (1912–49) saw the introduction in earnest of modern science to China. Large numbers of Chinese students studied abroad in Japan and in Europe and the US. Many returned to help teach and to found numerous schools and universities. Among them were numerous outstanding figures, including Cai Yuanpei, Hu Shih, Weng Wenhao, Ding Wenjiang, Fu Ssu-nien, and many others. As a result, there was a tremendous growth of modern science in China. As the Communist Party took over China's mainland in 1949, some of these Chinese scientists and institutions moved to Taiwan. The central science academy, Academia Sinica, also moved there. Main article: History of science and technology in the People's Republic of China See also: Science and technology in the People's Republic of China After the establishment of the People's Republic in 1949, China reorganized its science establishment along Soviet lines. Although the country regressed scientifically as a result of government policies which led to famine during the Great Leap Forward and political chaos during the Cultural Revolution, scientific research in nuclear weapons and satellite launching still gained great success. From 1975, science and technology was one of the Four Modernizations, and its high-speed development was declared essential to all national economic development by Deng Xiaoping. Other civilian technologies such as superconductivity and high-yield hybrid rice led to new developments due to the application of science to industry and foreign technology transfer. As the People's Republic of China becomes better connected to the global economy, the government has placed more emphasis on science and technology. This has led to increases in funding, improved scientific structure, and more money for research. These factors have led to advancements in agriculture, medicine, genetics, and global change. In 2003, the Chinese space program allowed China to become the third country to send humans into space, and ambition to put a man on mars by 2030. In the 2000s and 2010s, China became a top scientific and industrial power in more advanced fields such as super computing, artificial intelligence, bullet trains, aeronautics, nuclear physics researches and other fields. In 2016, China became the country with the highest science output, as measured in publications. While the US had been the biggest producer of scientific studies until then, China published 426,000 studies in 2016 while the US published 409,000.[101] However, the numbers are somewhat relative, as it also depends how authorship on international collaborations is counted (e.g. if one paper is counted per person or whether authorship is split among authors).[101] China portal History portal Technology portal Chinese astronomy Chinese mathematics History of Chinese archaeology List of Chinese discoveries List of Chinese inventions Military history of China History of canals in China Science and Civilization in China Two Bombs, One Satellite Yongle Encyclopedia ^ a b Thomas Woods, How the Catholic Church Built Western Civilization (Washington, DC: Regenery, 2005) ^ a b Agustín Udías, p. 53. ^ Needham, Robinson & Huang 2004, p. 218. ^ a b Needham, Robinson & Huang 2004, p. 10. ^ Needham 1956 p. 185. ^ Lu Chia (196 BCE, 前漢書 (Chi'en Han Shu) (History of the former Han dynasty) ch. 43, p. 6b and Tung Chien Kang Mu (Essential Mirror of Universal History) ch. 3, p. 46b) as referenced in Needham, Robinson & Huang 2004, p. 10. ^ "Archived copy". Archived from the original on 2006-12-08. Retrieved 2007-02-19. CS1 maint: archived copy as title (link), [1] ^ a b Ancient Chinese Astronomy Archived 2006-02-22 at the Wayback Machine ^ F. Espenak. "Solar Eclipses of Historical Interest". Archived from the original on 2008-03-09. ^ F.R. Stephenson (1997). Historical Eclipses and Earth's Rotation. Cambridge University Press. ^ Weapons of the terracotta army ^ a b c english@peopledaily.com.cn. "People's Daily Online -- China resurrects world's earliest seismograph". english.people.com.cn. ^ a b Needham, Volume 4, Part 2, 39. ^ Needham, Volume 4, Part 2, 158. ^ Needham, Volume 4, Part 2, 40. ^ Shelagh Vainker ^ "A lodestone attracts a needle." Li Shu-hua, p. 176. ^ Li Shu-hua, p. 182f. ^ Liang, pp. Appendix C VII ^ Kelly, p. 4. ^ Kelly, p. 22. "Around 1240 the Arabs acquired knowledge of saltpeter ("Chinese snow") from the East, perhaps through India. They knew of gunpowder soon afterward. They also learned about fireworks ("Chinese flowers") and rockets ("Chinese arrows")." ^ Novum Organum, Liber I, CXXIX – Adapted from the 1863 translation ^ a b c d Turnbull, p. 43. ^ a b c d Money of the World Special Christmas Edition, Orbis Publishing Ltd, 1998. ^ Mayall N.U. (1939), The Crab Nebula, a Probable Supernova, Astronomical Society of the Pacific Leaflets, v. 3, p. 145. ^ a b Julius Thomas Fraser and Francis C. Haber, Time, Science, and Society in China and the West (Amherst: University of Massachusetts Press, ISBN 0-87023-495-1, 1986), pp. 227. ^ Patricia B. Ebrey, The Cambridge Illustrated History of China (Cambridge: Cambridge University Press, 1999, ISBN 0-521-66991-X), pp. 148. ^ a b Rudolph, R.C. "Preliminary Notes on Sung Archaeology," The Journal of Asian Studies (Volume 22, Number 2, 1963): 169–177. ^ Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 603–604, 618. ^ Nathan Sivin, Science in Ancient China: Researches and Reflections. (Brookfield, Vermont: VARIORUM, Ashgate Publishing, 1995), Chapter III, pp. 23. ^ a b Alan Kam-leung Chan, Gregory K. Clancey, and Hui-Chieh Loy, Historical Perspectives on East Asian Science, Technology and Medicine (Singapore: Singapore University Press, 2002, ISBN 9971-69-259-7) pp. 15. ^ Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 618. ^ "Histoire des Croisades", René Grousset, p. 581, ISBN 2-262-02569-X ^ "The Eastern Origins of Western Civilization", John M.Hobson, p. 186, ISBN 0-521-54724-5 ^ "Grand maitre". templis.free.fr. ^ Vesel, Živa (15 May 2004). "" Islamic and Chinese Astronomy under the Mongols: a Little-Known Case of Transmission ", in : Yvonne Dold-Samplonius, Joseph W. Dauben, Menso Folkerts & Benno van Dalen, éds., From China to Paris. 2000 Years Transmission of Mathematical Ideas. Series: Boethius 46, Stuttgart (Steiner), 2002, pp. 327–356". Abstracta Iranica. Revue Bibliographique Pour le Domaine Irano-aryen (Volume 25) – via abstractairanica.revues.org. ^ "Home" – via www.nybooks.com. ^ Toby E. Huff, The Rise of Early Modern Science: Islam, China, and the West (Cambridge: Cambridge University Press, 2003, ISBN 0-521-52994-8) pp 303. ^ a b Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 104. ^ Yung Sik Kim, The Natural Philosophy of Chu Hsi (1130–1200) (DIANE Publishing, 2002, ISBN 0-87169-235-X), pp. 171. ^ a b Paul Dong, China's Major Mysteries: Paranormal Phenomena and the Unexplained in the People's Republic (San Francisco: China Books and Periodicals, Inc., 2000, ISBN 0-8351-2676-5), pp. 72. ^ Nathan Sivin, Science in Ancient China: Researches and Reflections. (Brookfield, Vermont: VARIORUM, Ashgate Publishing, 1995), Chapter III, pp. 16–19. ^ Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 227 & 414–416. ^ "Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 415–416. ^ Paul Dong, China's Major Mysteries: Paranormal Phenomena and the Unexplained in the People's Republic (San Francisco: China Books and Periodicals, Inc., 2000, ISBN 0-8351-2676-5), pp. 71–72. ^ Dainian Fan and Robert Sonné Cohen, Chinese Studies in the History and Philosophy of Science and Technology (Dordrecht: Kluwer Academic Publishers, 1996, ISBN 0-7923-3463-9), pp. 431–432. ^ Charles Benn, China's Golden Age: Everyday Life in the Tang Dynasty. Oxford University Press, 2002, ISBN 0-19-517665-0), pp. 235. ^ Wu Jing-nuan, An Illustrated Chinese Materia Medica. (New York: Oxford University Press, 2005), pp. 5. ^ Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 648–649. ^ Joseph Needham, Science and Civilization in China: Volume 6, Biology and Biological Technology, Part 1, Botany. (Taipei: Caves Books Ltd., 1986), pp. 174–175. ^ Schafer, Edward H. "Orpiment and Realgar in Chinese Technology and Tradition," Journal of the American Oriental Society (Volume 75, Number 2, 1955): 73–89. ^ West, Stephen H. "Cilia, Scale and Bristle: The Consumption of Fish and Shellfish in The Eastern Capital of The Northern Song," Harvard Journal of Asiatic Studies (Volume 47, Number 2, 1987): 595–634. ^ Joseph Needham, Science and Civilization in China: Volume 4, Physics and Physical Technology, Part 2: Mechanical Engineering (Taipei: Caves Books, Ltd. 1986) pp. 111 & 165 & 445–448. ^ Liu, Heping. ""The Water Mill" and Northern Song Imperial Patronage of Art, Commerce, and Science," The Art Bulletin (Volume 84, Number 4, 2002): 566–595. ^ Tony Fry, The Architectural Theory Review: Archineering in Chinatime (Sydney: University of Sydney, 2001), pp. 10–11. ^ Derk Bodde, Chinese Thought, Society, and Science (Honolulu: University of Hawaii Press, 1991), pp. 140. ^ Joseph Needham, Science and Civilization in China: Volume 4, Physics and Physical Technology, Part 2: Mechanical Engineering (Taipei: Caves Books, Ltd. 1986), pp. 30. ^ W. Scott Morton and Charlton M. Lewis, China: Its History and Culture. (New York: McGraw-Hill, Inc., 2005), pp. 70. ^ Joseph Needham, Science and Civilization in China: Volume 4, Physics and Physical Technology, Part 2: Mechanical Engineering (Taipei: Caves Books, Ltd. 1986) pp. 470–475. ^ Joseph Needham, Science and Civilization in China: Volume 4, Physics and Physical Technology, Part 2: Mechanical Engineering (Taipei: Caves Books, Ltd. 1986), pp. 469–471. ^ Ibn al-Razzaz Al-Jazari (ed. 1974), The Book of Knowledge of Ingenious Mechanical Devices. Translated and annotated by Donald Routledge Hill, Dordrecht/D. Reidel. ^ Sal Restivo, Mathematics in Society and History: Sociological Inquiries (Dordrecht: Kluwer Academic Publishers, 1992, ISBN 1-4020-0039-1), pp 32. ^ Nathan Sivin, Science in Ancient China: Researches and Reflections. (Brookfield, Vermont: VARIORUM, Ashgate Publishing, 1995), Chapter III, pp. 21, 27, & 34. ^ Joseph Needham, Science and Civilization in China: Volume 4, Physics and Physical Technology, Part 1, Physics (Taipei: Caves Books Ltd., 1986), pp. 98 & 252. ^ Hsu, Mei-ling. "Chinese Marine Cartography: Sea Charts of Pre-Modern China," Imago Mundi (Volume 40, 1988): 96–112. ^ Jacques Gernet, A History of Chinese Civilization (Cambridge: Cambridge University Press, 1996, ISBN 0-521-49781-7), pp. 335. ^ Joseph Needham, Science and Civilization in China: Volume 5, Chemistry and Chemical Technology, Part 1: Paper and Printing (Taipei: Caves Books, Ltd, 1986), pp 201. ^ Hartwell, Robert (1966). "Markets, Technology, and the Structure of Enterprise in the Development of the Eleventh-Century Chinese Iron and Steel Industry". The Journal of Economic History. 26: 29–58. doi:10.1017/S0022050700061842. ^ Peter Mohn, Magnetism in the Solid State: An Introduction (New York: Springer-Verlag Inc., 2003, ISBN 3-540-43183-7), pp. 1. ^ a b Wagner, Donald B. "The Administration of the Iron Industry in Eleventh-Century China," Journal of the Economic and Social History of the Orient (Volume 44 2001): 175–197. ^ a b Patricia B. Ebrey, Anne Walthall, and James B. Palais, East Asia: A Cultural, Social, and Political History (Boston: Houghton Mifflin Company, 2006, ISBN 0-618-13384-4), pp. 158. ^ Joseph Needham, Science and Civilization in China: Volume 4, Physics and Physical Technology, Part 2, Mechanical Engineering (Taipei: Caves Books, Ltd., 1986), pp. 376. ^ Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 43. ^ Joseph Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 62–63. ^ Needham, Science and Civilization in China: Volume 3, Mathematics and the Sciences of the Heavens and the Earth (Taipei: Caves Books, Ltd., 1986) pp. 134–137. ^ a b c John King Fairbank and Merle Goldman, China: A New History (Cambridge: MA; London: The Belknap Press of Harvard University Press, 2nd ed., 2006, ISBN 0-674-01828-1), pp. 81. ^ Nathan Sivin, "Taoism and Science" in Medicine, Philosophy and Religion in Ancient China Archived 2008-06-23 at the Wayback Machine (Variorum, 1995). Retrieved on 2008-08-13. ^ Joseph Needham, Science and Civilization in China: Volume 5, Chemistry and Chemical Technology, Part 4, Spagyrical Discovery and Invention: Apparatus, Theories and Gifts (Taipei: Caves Books Ltd., 1986), pp. 452. ^ Joseph Needham, Science and Civilization in China: Volume 5, Chemistry and Chemical Technology, Part 7, Military Technology; the Gunpowder Epic (Taipei: Caves Books, Ltd., 1986), pp. 220–262. ^ Joseph Needham, Science and Civilization in China: Volume 5, Chemistry and Chemical Technology, Part 7, Military Technology; the Gunpowder Epic (Taipei: Caves Books, Ltd., 1986), pp. 70–73 & 117–124. ^ Joseph Needham, Science and Civilization in China: Volume 5, Chemistry and Chemical Technology, Part 7, Military Technology; the Gunpowder Epic (Taipei: Caves Books, Ltd., 1986), pp. 173–174, 192, 290, & 477. ^ Alfred W. Crosby, Throwing Fire: Projectile Technology Through History (Cambridge: Cambridge University Press, 2002, ISBN 0-521-79158-8), pp. 100–103. ^ Joseph Needham, Science and Civilization in China: Volume 5, Chemistry and Chemical Technology, Part 7, Military Technology; the Gunpowder Epic (Taipei: Caves Books, Ltd., 1986), pp. 203–205, 264, 508. ^ John Norris, Early Gunpowder Artillery: 1300–1600 (Marlborough: The Crowood Press, Ltd., 2003), pp. 11. ^ Patricia Buckley Ebrey, p. 212. ^ "Windows into China", John Parker, p. 25. ^ "Windows into China", John Parker, p. 25, ISBN 0-89073-050-4 ^ "The Eastern origins of Western civilization", John Hobson, p. 194-195, ISBN 0-521-54724-5 ^ Rothbard, p 366 ^ Science, London School of Economics and Political. "Department of Economic History" (PDF). lse.ac.uk. ^ "The Eastern Origins of Western Civilization", John M. Hobson, p. 196 ^ Rothbard, p 23 ^ Huanyin, Yang (1993). "Confucius (K'ung Tzu)" (PDF). Prospects: The Quarterly Review of Comparative Education. XXIII (1/2): 211–19. doi:10.1007/bf02195036. ^ Needham & Wang 1954, p. 581. ^ "pseudoscience - The Skeptic's Dictionary - Skepdic.com". skepdic.com. ^ James M. Blaut, "Environmentalism and Eurocentrism," Geographical Review 89.3 (1999): 391–408. ^ a b Tollefson, Jeff (2018-01-18). "China declared world's largest producer of scientific articles". Bibcode:2018Natur.553..390T. doi:10.1038/d41586-018-00927-4. Retrieved 2018-01-26. Patricia Buckley Ebrey, The Cambridge Illustrated History of China. Cambridge, New York and Melbourne: Cambridge University Press, 1996. ISBN 0-521-43519-6. Mark Elvin, "The high-level equilibrium trap: the causes of the decline of invention in the traditional Chinese textile industries" in W. E. Willmott, Economic Organization in Chinese Society, (Stanford, Calif., Stanford University Press, 1972) pp. 137–172. "The High-level Equilibrium Trap" (PDF). (64.3 KB) Kelly, Jack (2004). Gunpowder: Alchemy, Bombards, & Pyrotechnics: The History of the Explosive that Changed the World. Basic Books. ISBN 978-0-465-03718-6. Liang, Jieming (2006). Chinese Siege Warfare: Mechanical Artillery & Siege Weapons of Antiquity. Singapore, Republic of Singapore: Leong Kit Meng. ISBN 978-981-05-5380-7. Needham, Joseph; Wang, Ling (王玲) (1954). "Science and Civilisation in China". 1 Introductory Orientations. Cambridge University Press. Cite journal requires |journal= (help) Needham, Joseph (1956). Science and Civilisation in China. 2 History of Scientific Thought. p. 697. ISBN 978-0-521-05800-1. Joseph Needham (1986). Science and Civilization in China, Volume 4, Part 2: Mechanical Engineering. Taipei: Caves Books Pty. Ltd. Needham, Joseph; Robinson, Kenneth G.; Huang, Jen-Yü (2004). "Science and Civilisation in China". 7, part II General Conclusions and Reflections. Cambridge University Press. Cite journal requires |journal= (help) Li Shu-hua, "Origine de la Boussole 11. Aimant et Boussole," Isis, Vol. 45, No. 2. (Jul., 1954) Rothbard, Murray N. (2006). Economic thought before Adam Smith: An Austrian Perspective on the History of Economic Thought. Cheltnam, UK: Edward Elgar. ISBN 978-0-945466-48-2. Stephen Turnbull, The Walls of Constantinople, AD 324–1453, Osprey Publishing, ISBN 1-84176-759-X Agustín Udías, Searching the Heavens and the Earth: The History of Jesuit Observatories (Dordrecht, The Netherlands: Kluwer Academic Publishers, 2003) Shelagh Vainker in Anne Farrer (ed), "Caves of the Thousand Buddhas", 1990, British Museum publications, ISBN 0-7141-1447-2 Sivin, Nathan. "Science and medicine in imperial China—The state of the field." Journal of Asian Studies 47.1 (1988): 41-90. Sivin, Nathan. 2005. "A Multi-dimensional Approach to Research on Ancient Science". East Asian Science, Technology, and Medicine, no. 23. Temporary Publisher: 10–25. JSTOR 43150669. Thomas Woods, How the Catholic Church Built Western Civilization, (Washington, DC: Regenery, 2005), ISBN 0-89526-038-7 Wikimedia Commons has media related to History of science and technology in China. Institute for the History of Natural Science, Chinese Academy of Sciences Chinese Society for the History of Science and Technology Popular Science Alliance Network, Internet Society of China China Association for Science and Technology China International Association for Promotion of Science and Technology (CIAPST) China Popular Science Network China Research Institute for Science Popularization Science Education Network China Association of Children's Science Instructors China Science China Statistical Yearbook on Science and Technology 1991–2015 Retrieved from "https://en.wikipedia.org/w/index.php?title=History_of_science_and_technology_in_China&oldid=935888821"
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
5,114
Wilhelm Lambrecht (* 3. August 1834 in Wolbrechtshausen; † 17. Juni 1904 in Göttingen) war ein deutscher Mechaniker und Unternehmer im Bereich der meteorologischen Messtechnik. Leben Nach seinem Schulabschluss absolvierte Lambrecht eine Lehre als Mechaniker in Einbeck. Bereits in dieser Zeit interessierte er sich für den Bau von Messinstrumenten. Auf die Ausbildung folgte eine mehrjährige Gesellenwanderung, die ihn nach Paris und Berlin, unter anderem zu Siemens & Halske führten. 1859 gründete er in Einbeck eine Werkstatt, die er aber schon 1864 nach Göttingen verlagerte. Dort trat er in Kontakt mit mehreren bekannten Göttinger Naturwissenschaftlern wie Friedrich Wöhler, Wilhelm Eduard Weber und Wilhelm Klinkerfues. In Zusammenarbeit mit Klinkerfues erfand er einen Zünder für Gaslaternen. Als die Vermarktung desselben aufgrund der schweren Börsenkrise von 1873 fehlschlug, wandte man sich wieder den Messinstrumenten, insbesondere im meteorologischen Bereich zu. Hierbei entwickelte Lambrecht zuerst ein von Klinkerfues entworfenes Haarhygrometer weiter. Nach einem Streit trennten sich die beiden, und Lambrecht entwickelte von nun an eigene Messgeräte. Dabei gelang ihm ab 1873 die Entwicklung eines Taupunktspiegelhygrometers, eines Polymeters, eines Aspirations-Psychrometers, mehrerer Wettertelegrafen und Wettersäulen. Seine meteorologischen Produkte fanden vor dem Ersten Weltkrieg in vielen großen Städten und Kurorten Anklang. Neben der Entwicklung meteorologischer Messinstrumente entwickelte Lambrecht auch eine Bauart des Minimumthermometer für medizinische Verwendung. Das von ihm gegründete und nach ihm benannte Unternehmen existiert bis heute in Göttingen. Außerdem ist eine Straße im Göttinger Industriegebiet nach ihm benannt. Schriften Wilhelm Klinkerfues, Wilhelm Lambrecht: Kurze Beschreibung und Anleitung zum Gebrauch des Klinkerfues'schen Patent-Hygrometers für praktische Meteorologie und Freunde der Naturwissenschaft, construirt und fabricirt von Wilh. Lambrecht. Hofer, Göttingen 1877. Wilhelm Lambrecht: Ein Nimbus und sein Werth oder Klinkerfues und sein Wettercompass. Antwort auf fortgesetzte Herausforderungen. Spielmeyer, Göttingen 1881. Literatur Otto Behrendsen: Die mechanischen Werkstätten der Stadt Göttingen. Geschichte und ihre gegenwärtige Einrichtung. Denkschrift hrsg. bei Gelegenheit der im Jahre 1900 zu Paris stattfindenden Weltausstellung von den vereinigten Mechanikern Göttingens. Haag, Melle in Hannover 1901, Seite 26–28, Seite 68–87. (online als PDF) Wilhelm Klinkerfues: Für meine Freunde! Vertheidigung gegen einen mir von meinem bisherigen Fabrikanten W. Lambrecht gemachten Vorwurf eines in Wettersachen an seinem geistigen Eigenthum begangenen Diebstahls. Göttingen 1880. (Nachdruck in: #Lambrecht 1881, Seite 2–4.) Weblinks Homepage der LAMBRECHT meteo GmbH Einzelnachweise Unternehmer (19. Jahrhundert) Person (Göttingen) Deutscher Geboren 1834 Gestorben 1904 Mann
{ "redpajama_set_name": "RedPajamaWikipedia" }
5,873
\section{#1}} \newcommand{{\mathbb Q}}{{\mathbb Q}} \renewcommand{\H}{{\mathbb H}} \newcommand{\Fp}{{\mathbb F}_p} \newcommand{\cic}[1]{{\mathbb Z}/#1{\mathbb Z}} \newcommand{\adic}[1]{\hat{{\mathbb Z}}_{#1}} \newcommand{{}_{p}^{\wedge}}{{}_{p}^{\wedge}} \newcommand{_{2}^{\wedge}}{_{2}^{\wedge}} \newcommand{\com}[1]{_{#1}^{\wedge}} \newcommand{\Z_{(p)}}{{\mathbb Z}_{(p)}} \newcommand{\Omega}{\Omega} \DeclareMathAlphabet\EuR{U}{eur}{m}{n} \SetMathAlphabet\EuR{bold}{U}{eur}{b}{n} \newcommand{\operatorname{Res}\nolimits}{\operatorname{Res}\nolimits} \newcommand{\operatorname{Tor}\nolimits}{\operatorname{Tor}\nolimits} \newcommand{\operatorname{Ext}\nolimits}{\operatorname{Ext}\nolimits} \newcommand{\operatorname{Inj}\nolimits}{\operatorname{Inj}\nolimits} \newcommand{\operatorname{Eq}\nolimits}{\operatorname{Eq}\nolimits} \newcommand{\operatorname{SEq}\nolimits}{\operatorname{SEq}\nolimits} \newcommand{\pi_0\he}{\pi_0\operatorname{Eq}\nolimits} \newcommand{\operatorname{diag}\nolimits}{\operatorname{diag}\nolimits} \newcommand{\coho}[3]{H^{#1}(#2; #3)} \newcommand{\cohoF}[2]{H^{#1}(#2)} \newcommand{\overset{\text{\textup{def}}}{=}}{\overset{\text{\textup{def}}}{=}} \newcommand{\operatorname{pr}\nolimits}{\operatorname{pr}\nolimits} \newcommand{\textup{ev}}{\textup{ev}} \newcommand{\lcj}[2]{{}^{#1}\hskip-1pt #2} \renewcommand{\:}{\colon} \newcommand{\operatornamewithlimits{\hbox{$\varprojlim$}}}{\operatornamewithlimits{\hbox{$\varprojlim$}}} \newcommand{\limn}[1]{\operatornamewithlimits{\hbox{$\varprojlim^{#1}$}}} \newcommand{\operatornamewithlimits{\hbox{$\varinjlim$}}}{\operatornamewithlimits{\hbox{$\varinjlim$}}} \newcommand{\operatornamewithlimits{\hbox{$\varprojlim^i$}}}{\operatornamewithlimits{\hbox{$\varprojlim^i$}}} \newcommand{\operatornamewithlimits{\hbox{$\varprojlim^0$}}}{\operatornamewithlimits{\hbox{$\varprojlim^0$}}} \newcommand{\operatornamewithlimits{colim}}{\operatornamewithlimits{colim}} \newcommand{\operatornamewithlimits{holim}}{\operatornamewithlimits{holim}} \newcommand{\operatorname{hofib}\nolimits}{\operatorname{hofib}\nolimits} \newcommand{\operatorname{hocofib}\nolimits}{\operatorname{hocofib}\nolimits} \newcommand{\limt}[1]{\mathop{\mbox{lim }}\limits_{\pile{\scriptstyle\longleftarrow\\\scriptstyle #1}}} \newcommand{\lims}[2]{\mathop{\mbox{lim}^{#1}}\limits_{\scriptstyle #2}} \newcommand{\mathcal{A}}{\mathcal{A}} \newcommand{\mathcal{B}}{\mathcal{B}} \newcommand{\mathcal{C}}{\mathcal{C}} \newcommand{\mathcal{D}}{\mathcal{D}} \newcommand{\mathcal{E}}{\mathcal{E}} \newcommand{\mathcal{F}}{\mathcal{F}} \newcommand{\mathcal{I}}{\mathcal{I}} \newcommand{\mathcal{L}}{\mathcal{L}} \newcommand{\mathcal{N}}{\mathcal{N}} \newcommand{\mathcal{P}}{\mathcal{P}} \newcommand{\calq}{\mathcal{P}} \newcommand{\mathcal{R}}{\mathcal{R}} \newcommand{\mathcal{S}}{\mathcal{S}} \newcommand{\mathcal{T}}{\mathcal{T}} \newcommand{\mathcal{Z}}{\mathcal{Z}} \let\cent=\mathcal{Z} \newcommand{\textbf{M}_{\scriptscriptstyle\bullet}}{\textbf{M}_{\scriptscriptstyle\bullet}} \newcommand{\mdot^c}{\textbf{M}_{\scriptscriptstyle\bullet}^c} \newcommand{\mathcal{L}_p}{\mathcal{L}_p} \newcommand{\call_p^c}{\mathcal{L}_p^c} \newcommand{\call_p^{\calc}}{\mathcal{L}_p^{\mathcal{C}}} \newcommand{\widebar{\call}}{\widebar{\mathcal{L}}} \newcommand{\bcall_p}{\widebar{\call}_p} \newcommand{\bcall_p^c}{\widebar{\call}_p^c} \newcommand{\bcallp^{\calc}}{\bcall_p^{\mathcal{C}}} \newcommand{\bcall_S^c}{\widebar{\call}_S^c} \newcommand{\bcall_S^{cr}}{\widebar{\call}_S^{cr}} \newcommand{\mathcal{P}_p}{\mathcal{P}_p} \newcommand{\mathcal{P}_p^c}{\mathcal{P}_p^c} \newcommand{\mathcal{P}_p}{\mathcal{P}_p} \newcommand{\mathcal{P}_p^c}{\mathcal{P}_p^c} \newcommand{\mathcal{O}}{\mathcal{O}} \newcommand{\orB}[3]{\mathcal{O}_{#1}^{#2}(#3)} \newcommand{\orbp}[1]{\mathcal{O}_p(#1)} \newcommand{\orbpc}[1]{\mathcal{O}_p^c(#1)} \newcommand{\orbpC}[1]{\mathcal{O}_p^{\mathcal{C}}(#1)} \newcommand{\orbL}[1]{\mathcal{O}_{\mathcal{L}}(#1)} \newcommand{\orbS}[1]{\mathcal{O}_{S}(#1)} \newcommand{\orbLc}[1]{\mathcal{O}_{\mathcal{L}}^{c}(#1)} \newcommand{\orbSc}[1]{\mathcal{O}_{S}^{c}(#1)} \newcommand{\orbScs}[1]{\mathcal{O}_{S}^{cs}(#1)} \newcommand{\orbbar}[3]{\widebar{\mathcal{O}}_{#1}^{#2}(#3)} \newcommand{\orbbarp}[1]{\orbbar{p}{}{#1}} \newcommand{\orbbarpc}[1]{\orbbar{p}{c}{#1}} \newcommand{\calpcat}[2]{\mathcal{P}_p^{#1}(#2)} \newcommand{\calqcat}[2]{\mathcal{L}_p^{#1}(#2)} \newcommand{\orbcat}[2]{\mathcal{O}_p^{#1}(#2)} \newcommand{\orbbarcat}[2]{\orbbar{p}{#1}{#2}} \newcommand{\mathcal{A}ut} %%%{\EuR{Aut}}{\mathcal{A}ut} \newcommand{\mathcal{E}qv} %%%{\EuR{Eqv}}{\mathcal{E}qv} \newcommand{\boldsymbol\Omega}{\boldsymbol\Omega} \newcommand{\mathbf P}{\mathbf P} \newcommand{\nv}[1]{|#1|} \newcommand{\nvp}[1]{\nv{#1}{}_{p}^{\wedge}} \newcommand{\mathcal{Q}_p^{\mathcal{C}}}{\mathcal{Q}_p^{\mathcal{C}}} \newcommand{\mathcal{Q}_S}{\mathcal{Q}_S} \newcommand{\mathcal{Q}_\call}{\mathcal{Q}_\mathcal{L}} \newcommand{\calQ}[3]{\mathcal{L}_{#1}^{#2}(#3)} \newcommand{\mathcal{Q}_S}{\mathcal{Q}_S} \newcommand{\mathcal{Q}_\call}{\mathcal{Q}_\mathcal{L}} \newcommand{\calP}[3]{\mathcal{P}_{#1}^{#2}(#3)} \newcommand{\mathcal{S}ets}{\mathcal{S}ets} \newcommand{\EuR{Gr}}{\EuR{Gr}} \newcommand{\pgr}{p\mbox{-}\EuR{Gr}} \newcommand{\EuR}{\EuR} \newcommand{\curs{Ab}}{\EuR{Ab}} \newcommand{\curs{Sets}}{\EuR{Sets}} \newcommand{\curs{Spaces}}{\EuR{Spaces}} \renewcommand{\mod}{\mbox{-}\EuR{mod}} \newcommand{\widebar}[1]{\overset{\mskip3mu\hrulefill\mskip3mu}{#1} \vphantom{#1}} \newcommand{\smallsetminus}{\smallsetminus} \newcommand{\,|\,}{\,|\,} \newcommand{\vartriangleleft}{\vartriangleleft} \newcommand{\operatorname{proj}\nolimits}{\operatorname{proj}\nolimits} \newcommand{\operatorname{Equiv}\nolimits}{\operatorname{Equiv}\nolimits} \newcommand{\operatorname{conj}\nolimits}{\operatorname{conj}\nolimits} \newcommand{^{\textup{op}}}{^{\textup{op}}} \newcommand{\isotyp}{_{\textup{typ}}} \newcommand{_{\scriptscriptstyle\bullet}}{_{\scriptscriptstyle\bullet}} \newcommand{_{\textup{fus}}}{_{\textup{fus}}} \let\oldcirc=\circ \renewcommand{\circ}{\mathchoice {\mathbin{\scriptstyle\oldcirc}}{\mathbin{\scriptstyle\oldcirc}} {\mathbin{\scriptscriptstyle\oldcirc}} {\mathbin{\scriptscriptstyle\oldcirc}}} \let\crc=\circ \newcommand{\hclim}[1]{\setbox1=\hbox{\rm hocolim} \setbox2=\hbox to \wd1{\rightarrowfill} \ht2=0pt \dp2=-1pt \mathop{\vtop{\baselineskip=5pt\box1\box2}} _{#1}} \newcommand{\hcl}[2]{\hclim{#1}{\bigl(#2\bigr)}} \newcommand{\higherlim}[2]{\displaystyle\setbox1=\hbox{\rm lim} \setbox2=\hbox to \wd1{\leftarrowfill} \ht2=0pt \dp2=-1pt \setbox3=\hbox{$\scriptstyle{#1}$} \ifdim\wd1<\wd3 \mathop{\hphantom{^{#2}}\vtop{\baselineskip=5pt\box1\box2}^{#2}}_{#1} \else \mathop{\vtop{\baselineskip=5pt\box1\box2}}\limits_{#1}\nolimits^{#2} \fi} \newcommand{\invlim}[1]{\higherlim{#1}{}} \newcommand{\operatorname{Map}\nolimits}{\operatorname{Map}\nolimits} \renewcommand{\hom}{\operatorname{Hom}\nolimits} \newcommand{\operatorname{Rep}\nolimits}{\operatorname{Rep}\nolimits} \newcommand{\aut}{\operatorname{aut}\nolimits \newcommand{\operatorname{End}\nolimits}{\operatorname{End}\nolimits} \newcommand{\operatorname{Tor}\nolimits}{\operatorname{Tor}\nolimits} \newcommand{\operatorname{Gal}\nolimits}{\operatorname{Gal}\nolimits} \renewcommand{\ker}{\operatorname{Ker}\nolimits} \newcommand{\operatorname{Im}\nolimits}{\operatorname{Im}\nolimits} \renewcommand{\Im}{\operatorname{Im}\nolimits} \newcommand{\operatorname{\operatorname{Coker}\nolimits}\nolimits}{\operatorname{\operatorname{Coker}\nolimits}\nolimits} \newcommand{\operatorname{Coker}\nolimits}{\operatorname{Coker}\nolimits} \newcommand{\operatorname{rk}\nolimits}{\operatorname{rk}\nolimits} \newcommand{\p}[1]{c_{#1}} \renewcommand{\b}[1]{\widetilde{#1}} \newcommand{\q}[1]{\widehat{#1}} \newcommand{\0}[1]{\overset{\circ}{#1}} \let\from=\leftarrow \newcommand{\longleft}[1]{\;{\leftarrow% \count255=0 \loop \mathrel{\mkern-6mu}% \relbar\advance\count255 by1\ifnum\count255<#1\repeat}\;} \newcommand{\longright}[1]{\;{\count255=0 \loop \relbar\mathrel{\mkern-6mu}% \advance\count255 by1\ifnum\count255<#1\repeat\rightarrow}\;} \newcommand{\Right}[2]{\overset{#2}{\longright#1}} \newcommand{\RIGHT}[3]{\mathrel{\mathop{\kern0pt\longright#1} \limits^{#2}_{#3}}} \newcommand{\Left}[2]{{\buildrel #2 \over {\longleft#1}}} \newcommand{\LEFT}[3]{\mathrel{\mathop{\kern0pt\longleft#1}\limits^{#2}_{#3}} } \newcommand{\dRIGHT}[3]{\mathrel{% \mathop{\vcenter{\baselineskip=0pt\hbox{$\kern0pt\longright#1$}% \hbox{$\kern0pt\longright#1$}}}\limits^{#2}_{#3}}} \newcommand{\LRIGHT}[3]{\mathrel{% \mathop{\vcenter{\baselineskip=0pt\hbox{$\kern0pt\longleft#1$}% \hbox{$\kern0pt\longright#1$}}}\limits^{#2}_{#3}}} \newcommand{\RLEFT}[3]{\mathrel{% \mathop{\vcenter{\baselineskip=0pt\hbox{$\kern0pt\longright#1$}% \hbox{$\kern0pt\longleft#1$}}}\limits^{#2}_{#3}}} \newcommand{\onto}[1]{\;{\count255=0 \loop \relbar\joinrel \advance\count255 by1 \ifnum\count255<#1 \repeat \twoheadrightarrow}\;} \newcommand{\Onto}[2]{\overset{#2}{\onto#1}} \newcommand{{\downarrow}}{{\downarrow}} \newcommand{\operatorname{H}}{\operatorname{H}} \newcommand{\mathfrak{a}}{\mathfrak{a}} \newcommand{\mathfrak{b}}{\mathfrak{b}} \newcommand{\mathfrak{c}}{\mathfrak{c}} \newcommand{\mathfrak{f}}{\mathfrak{f}} \newcommand{\HH({\ma,\mb})}%{H_{P,Q}}{\operatorname{H}({\mathfrak{a},\mathfrak{b}}) \newcommand{\HH({\mb,\mc})}{\operatorname{H}({\mathfrak{b},\mathfrak{c}})} \newcommand{\HH({\ma,\mc})}{\operatorname{H}({\mathfrak{a},\mathfrak{c}})} \newcommand{\HH({\mb,\ma})}{\operatorname{H}({\mathfrak{b},\mathfrak{a}})} \newtheoremstyle{slant}{}{}{\slshape}{}{\bfseries}{.}{.5em}{}% \newtheoremstyle{special}{}{}{\slshape}{}{\bfseries}{.}{.5em}{\thmnote{#3}} \newtheorem{Thm}{Theorem}[section] \newtheorem{Prop}[Thm]{Proposition} \newtheorem{Cor}[Thm]{Corollary} \newtheorem{Lem}[Thm]{Lemma} \newtheorem{Claim}[Thm]{Claim} \newtheorem{Ass}[Thm]{Assumption} \newtheorem{Defi}[Thm]{Definition} \newtheorem{Th}{Theorem} \newtheorem{Coro}[Th]{Corollary} \renewcommand{\theTh}{\Alph{Th}} \newtheorem{Cj}[Th]{Conjecture} \newtheorem{Rmk}[Thm]{Remark} \newtheorem{Ex}[Thm]{Example} \theoremstyle{remark} \newtheorem*{Not}{Notation} \newenvironment{smallpmatrix} {\bigl(\begin{smallmatrix}}{\end{smallmatrix}\bigr)} \newenvironment{Note}{\begin{quote}\small\noindent \underline{Note:}\hskip1em{}}{\end{quote}} \linespread{1.1} \newcommand{\notealex}[1]{\bigskip \noindent \textbf{\textcolor{blue}{[ALEX SAYS: #1]}}\bigskip} \begin{document} \begin{abstract} A partial group is a generalization of the concept of group recently introduced by A. Chermak in \cite{Chermak}. By considering partial groups as simplicial sets, we propose an extension theory for partial groups using the concept of (simplicial) fibre bundle. This way, the classical extension theory for groups naturally extends to an extension theory of partial groups. In particular, we show that the category of partial groups is closed by extensions. We also describe the cohomological obstructions for existence and uniqueness of extensions, generalizing the usual obstructions for group extensions. The second part of the paper considers extensions of (finite) localities, which are a particular type of partial group, mimicking the $p$-local structure of finite groups. The goal here is to give sufficient conditions for an extension of localities to produce a new locality. \end{abstract} \title{An extension theory for partial groups and localities} \author{A. Gonz\'alez} \address{Department of Mathematics\\ Kansas State University\\ 66506 Manhattan KS\\ United States of America} \email{agondem@math.ksu.edu} \maketitle \tableofcontents The theory of $p$-local finite groups emerged from work by Puig in \cite{Puig1} and \cite{Puig2} from an algebraic point of view, and from work of Broto, Levi and Oliver (et al.) in \cite{BLO1} and \cite{BLO2} from a topological point of view. Roughly speaking, this theory provides an axiomatic characterization of the $p$-local structure of finite groups. In these notes, we introduce an extension theory for $p$-local finite groups. Several partial results exist in the literature about extensions of $p$-local finite groups, for example \cite{OV} or \cite{BCGLO2}, each treating a particular situation. One of the advantages of our approach is that it provides a unifying extension theory. A second major advantage is that our theory also includes (and generalizes) the existing extension theory for groups. In order to develop our theory, we first need a slight change of point of view. The categorical language of $p$-local finite groups becomes rather heavy when dealing with extensions. Instead, we use the recently introduced \emph{partial groups} of \cite{Chermak}. Chermak introduced these objects, together with the so-called localities (a specialization of partial groups), in order to solve (positively) a famous conjecture on $p$-local finite groups. As pointed out to the author by Broto, the definition of partial group carries intrinsically a simplicial structure. From this point of view, an \emph{extension of partial groups} is simply a fibre bundle of the simplicial objects. \begin{Th}\label{ThmA} The category of partial groups is closed by extensions. \end{Th} Furthermore, this extension theory allows a cohomological obstruction theory for existence and uniqueness of extensions, which essentially generalizes the known obstruction theory for existence and uniqueness of group extensions (see \cite[Chapter IV]{Brown} or \cite[Chapter IV]{MacLane}). \begin{Coro}\label{CorB} Let $\text{\bbfamily M}', \text{\bbfamily M}''$ be partial groups, and let $\varepsilon \colon \text{\bbfamily M}'' \to \operatorname{Out}\nolimits(\text{\bbfamily M}')$ be an outer action. \begin{enumerate}[(i)] \item There is an obstruction class $[\kappa] \in H^3(\text{\bbfamily M}''; Z(\text{\bbfamily M}'))$ to the existence of extensions of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$: such extensions exist if and only if $[\kappa] = 0$. \item If there is any, the set of isomorphism classes of extensions of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$ is in one-to-one correspondence with the set $H^2(\text{\bbfamily M}''; Z(\text{\bbfamily M}'))$. \end{enumerate} \end{Coro} The proof of the above results, and specially of Theorem \ref{ThmA}, require an exhaustive analysis of the category of partial groups, both from an algebraic and a simplicial points of view. Once this is proved, we specialize our study to extensions of localities. Essentially, we give sufficient conditions for an extension of localities to produce a new locality. Let $\text{\bbfamily L}' \to \text{\bbfamily L} \to \text{\bbfamily L}''$ be an extension of partial groups, where in addition we assume that $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ are both localities. Under these assumptions, we see (Proposition \ref{propext3-1}) that such an extension determines a certain locality $(\text{\bbfamily T}, \Delta, S)$, with $\text{\bbfamily T} \subseteq \text{\bbfamily L}$. The extension $\text{\bbfamily L}' \to \text{\bbfamily L} \to \text{\bbfamily L}''$ is called \emph{good} if both $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ are saturated, $\text{\bbfamily T}$ contains $\text{\bbfamily L}'$ as a normal partial subgroup and $\Delta$ contains all the centric radicals of the fusion system associated to $\text{\bbfamily T}$. \begin{Th}\label{ThmC} If an extension $\text{\bbfamily L}' \to \text{\bbfamily L} \to \text{\bbfamily L}''$ is good, then the following holds. \begin{enumerate}[(i)] \item The fusion system associated to $\text{\bbfamily T}$ is saturated, and the $p$-completed nerve of $\text{\bbfamily T}$ is equivalent to the classifying space of a $p$-local finite group. \item The inclusion $\text{\bbfamily T} \subseteq \text{\bbfamily L}$ induces an equivalence of $p$-completed nerves. \item $\mathcal{F}'$ is a normal subsystem of $\mathcal{F}$. \end{enumerate} \end{Th} We also give sufficient conditions for an extension to be good in the above sense. To this end, we define the concepts of \emph{rigid} extension (to make sure that $\text{\bbfamily L}' \subseteq \text{\bbfamily T}$) and \emph{admissible} extension (to make sure that $\Delta$ contains all centric radical subgroups). In particular, the latter is inspired in and generalizes the concept introduced in \cite{OV}. See \ref{rigidext} for the exact definition. \begin{Th}\label{ThmD} If an extension $\text{\bbfamily L}' \to \text{\bbfamily L} \to \text{\bbfamily L}''$ is both rigid and admissible, then it is good. \end{Th} As an immediate consequence we deduce the following. \begin{Coro}\label{CorE} Every extension of finite groups gives rise to a good extension of localities. \end{Coro} The following result, partially communicated to the author by R. Levi, is another application of our results, which also illustrates a different point of view for our results. Let $F \to X \to B$ be a fibration where both $F$ and $B$ are $p$-good in the sense of \cite{BK}. In general it is not known whether $X$ is also $p$-good, since $p$-completion does not preserve fibrations. In this sense, the above result gives sufficient conditions for the space $X$ to be $p$-good, in the particular case where both $F$ and $B$ are nerves of partial groups. \begin{Coro}\label{CorF} Let $F \to X \to B$ be a fibration where both $B$ and $F$ are homotopy equivalent to classifying spaces of $p$-local finite groups. Then, $X$ is homotopy equivalent to the classifying space of a $p$-local finite group. Moreover, there exist proper localities $(\text{\bbfamily L}_F, \Delta_F, S_F)$ and $(\text{\bbfamily L}_B, \Delta_B, S_B)$, and a commutative diagram of fibre bundles $$ \xymatrix{ F \ar[r] & X \ar[r] & B \\ |\text{\bbfamily L}_F| \ar[u] \ar[r] & |\text{\bbfamily L}| \ar[r] \ar[u] & |\text{\bbfamily L}_B| \ar[u] } $$ where the bottom row is (the realization of) a good extension and all the vertical arrows are equivalences after $p$-completion. \end{Coro} Recently, Chermak has announced a construction of quotients of localities by partial normal subgroups, in \cite{Chermak2, Chermak3}. His constructions seem to describe the converse process to our extension construction for localities, and we plan to study the relation between Chermak's work and the present work as a sequel in collaboration with O. Garaialde. \emph{Organization of the paper.} The paper is organized as follows. In Section \ref{Sploc} we briefly review some basic facts about $p$-local finite groups. In Section \ref{partial} we review the theory of partial groups. Section \ref{simplicial} is a review on simplicial sets. In Section \ref{Spgsimp} we describe partial groups as simplicial sets. Section \ref{Maps} analyzes morphisms of partial groups from both an algebraic and a simplicial points of view. In Section \ref{FBPG} we introduce extensions of partial groups (as fibre bundles), and prove Theorem \ref{ThmA} and Corollary \ref{CorB}. In Section \ref{isoext} we specialize to extensions of localities, culminating in the proof of Theorems \ref{ThmC} and Theorem \ref{ThmD}. Section \ref{Sapp} contains the proofs of Corollaries \ref{CorE} and \ref{CorF}. Finally, we include Appendix \ref{AppA}, where we analyze the homotopy type of the nerve of a transporter system and the associated locality. \emph{A note to the reader.} The duality in nature of partial groups, algebraic and simplicial, and extension theory for partial groups described in these notes is joint work with Carles Broto. In this sense, the first part of this paper overlaps undergoing work of the author with Broto. This leads to some differences in notation, which still do not represent any difference in the results common to both papers. \emph{Acknowledgements.} The author is extremely thankful to Carles Broto, whose inspiring ideas originated and shaped this paper, and to Andy Chermak, for several discussions and a seminar that helped consolidate our results. The author would like to thank also Oihana Garaialde for a careful reading of the notes and many fruitful conversations. \section{Background on $p$-local finite groups}\label{Sploc} In this section we review some basic facts about $p$-local finite groups that we will use throughout this paper. The reader is referred to \cite{BLO2} for further reference. \begin{defi} A \emph{fusion system} over a finite $p$-group $S$ is a category $\mathcal{F}$ whose object set is the collection of all subgroups of $S$ and whose morphism sets satisfy the following conditions: \begin{enumerate}[(i)] \item $\operatorname{Hom}\nolimits_S(P,Q) \subseteq \operatorname{Hom}\nolimits_{\mathcal{F}}(P,Q) \subseteq \operatorname{Inj}\nolimits(P,Q)$ for all $P, Q \in \operatorname{Ob}\nolimits(\mathcal{F})$; and \item every morphism in $\mathcal{F}$ factors as an isomorphism in $\mathcal{F}$ followed by an inclusion. \end{enumerate} \end{defi} Given a fusion system $\mathcal{F}$, we say that $P,Q \in \operatorname{Ob}\nolimits(\mathcal{F})$ are \emph{$\mathcal{F}$-conjugate} if they are isomorphic as objects in $\mathcal{F}$. The $\mathcal{F}$-conjugacy class of an object $P$ is denoted by $P^{\mathcal{F}}$. \begin{defi}\label{defisat} Let $\mathcal{F}$ be a fusion system over a finite $p$-group $S$, and let $P \leq S$. \begin{itemize} \item $P$ is \emph{fully $\mathcal{F}$-centralized} if $|C_S(P)| \geq |C_S(Q)|$ for all $Q \in P^{\mathcal{F}}$. \item $P$ is \emph{fully $\mathcal{F}$-normalized} if $|N_S(P)| \geq |N_S(Q)|$ for all $Q \in P^{\mathcal{F}}$. \end{itemize} The fusion system $\mathcal{F}$ is \emph{saturated} if the following three conditions hold. \begin{enumerate}[(I)] \item For each $P \leq S$ which is fully $\mathcal{F}$-normalized, $P$ is fully $\mathcal{F}$-centralized, $\operatorname{Out}\nolimits_{\mathcal{F}}(P)$ is finite and $\operatorname{Out}\nolimits_S(P) \in \operatorname{Syl}\nolimits_p(\operatorname{Out}\nolimits_{\mathcal{F}}(P))$. \item If $P \leq S$ and $f \in \operatorname{Hom}\nolimits_{\mathcal{F}}(P,S)$ are such that $f(P)$ is fully $\mathcal{F}$-centralized, and if we set $$ N_f = \{g \in N_S(P) \,\, | \,\, f \circ c_g \circ f^{-1} \in \mathrm{Aut}_S(f(P))\}, $$ there there is $\widetilde{f} \in \operatorname{Hom}\nolimits_{\mathcal{F}}(N_f, S)$ such that $\widetilde{f}|_P = f$. \end{enumerate} \end{defi} \begin{rmk} The above definition of saturation is taken from \cite{BLO2}, although several other definitions of saturation exist in the literature, for example see \cite{AKO} or \cite{Chermak}. All these definitions have been proved to be equivalent, and the reader can switch to her or his favorite definition, since this does not make any difference in this paper. \end{rmk} \begin{defi}\label{definormalA} Let $\mathcal{F}$ be a saturated fusion system over a finite $p$-group $S$. \begin{itemize} \item A subgroup $P \leq S$ is \emph{$\mathcal{F}$-centric} if $C_S(Q) = Z(Q)$ for all $Q \in P^{\mathcal{F}}$. \item A subgroup $P \leq S$ is \emph{$\mathcal{F}$-radical} if $\operatorname{Out}\nolimits_{\mathcal{F}}(P)$ contains no nontrivial normal $p$-subgroup. \item A subgroup $A \leq S$ is \emph{weakly $\mathcal{F}$-closed} if $f(A) = A$ for all $f \in \operatorname{Hom}\nolimits_{\mathcal{F}}(A, S)$. \item A subgroup $A \leq S$ is \emph{strongly $\mathcal{F}$-closed} if, for all $P \leq S$ and all $f \in \operatorname{Hom}\nolimits_{\mathcal{F}}(P,S)$, $f(P \cap A) \leq A$. \item A subgroup $A \leq S$ is \emph{$\mathcal{F}$-normal} if, for all $P \leq S$ and all $f \in \operatorname{Hom}\nolimits_{\mathcal{F}}(P,S)$, there is $\gamma \in \operatorname{Hom}\nolimits_{\mathcal{F}}(P\cdot A, S)$ such that $\gamma|_P = f$ and $\gamma|_A \in \mathrm{Aut}_{\mathcal{F}}(A)$. \item A subgroup $A \leq S$ is \emph{$\mathcal{F}$-central} if $A$ is $\mathcal{F}$-normal and $\mathrm{Aut}_{\mathcal{F}}(A) = \{\operatorname{Id}\nolimits\}$. \end{itemize} The \emph{center} of $\mathcal{F}$, denoted by $Z(\mathcal{F})$, is the maximal subgroup of $Z(S)$ that is $\mathcal{F}$-central. \end{defi} Given a saturated fusion system $\mathcal{F}$ over a finite $p$-group $S$, we denote by $\mathcal{F}^c$ and $\mathcal{F}^r$ the full subcategories of $\mathcal{F}$ with object sets the collections of $\mathcal{F}$-centric and $\mathcal{F}$-radical subgroups, respectively. We also set $\mathcal{F}^{cr} \subseteq \mathcal{F}$ for the full subcategory of $\mathcal{F}$-centric $\mathcal{F}$-radical subgroups. It is an easy exercise to check that an $\mathcal{F}$-normal subgroup is always strongly $\mathcal{F}$-closed, and a strongly $\mathcal{F}$-closed subgroup is also weakly $\mathcal{F}$-closed. In particular, if $A \leq S$ satisfies any of these three properties then $A$ is a normal subgroup of $S$. Regarding the definition of $\mathcal{F}$-central subgroup, note that if $A$ is $\mathcal{F}$-central then $A$ must be abelian, since $\mathrm{Aut}_{\mathcal{F}}(A) = \{\operatorname{Id}\nolimits\}$. Next we review Aschbacher's definition of normal subsystem, as stated in \cite{Aschbacher}. \begin{defi}\label{normalF} Let $\mathcal{F}$ be a saturated fusion system over a finite $p$-group $S$, and let $\varepsilon \subseteq \mathcal{F}$ be a subsystem over a subgroup $R \leq S$. Then, $\varepsilon$ is a \emph{normal subsystem} of $\mathcal{F}$ if the following conditions are satisfied. \begin{itemize} \item[(N1)] $\varepsilon$ is a saturated fusion system over $R$. \item[(N2)] $R$ is strongly $\mathcal{F}$-closed. \item[(N3)] For each $P \leq Q \leq R$ and each $\gamma \in \operatorname{Hom}\nolimits_{\mathcal{F}}(Q,S)$, the map sending $f \in \operatorname{Hom}\nolimits_{\varepsilon}(P,Q)$ to $\gamma \circ f \circ \gamma^{-1}$ is a bijection between the sets $\operatorname{Hom}\nolimits_{\varepsilon}(P,Q)$ and $\operatorname{Hom}\nolimits_{\varepsilon}(\gamma(P), \gamma(Q))$. \item[(N4)] For each $f \in \mathrm{Aut}_{\varepsilon}(R)$ there is some extension $\widetilde{f} \in \mathrm{Aut}_{\mathcal{F}}(R \cdot C_S(R))$ such that $$ [\widetilde{f}, C_S(R)] \stackrel{def} = \{\widetilde{f}(x) \cdot x^{-1} \, \big| \, x \in C_S(R)\} \leq Z(R). $$ \end{itemize} \end{defi} The concept of transporter system associated to a fusion system was originally introduced in \cite{OV}. Let $G$ be a group and let $\mathcal{H}$ be a family of subgroups of $G$ which is invariant under $G$-conjugacy and overgroups. The transporter category of $G$ with respect to $\mathcal{H}$ is the category $\mathcal{T}_{\mathcal{H}}(G)$ with object set $\mathcal{H}$ and morphism sets $$ \operatorname{Mor}\nolimits_{\mathcal{T}_{\mathcal{H}}(G)}(P,Q) = \{x \in G \,\, | \,\, x \cdot P \cdot x^{-1} \leq Q\} $$ for each pair of subgroups $P,Q \in \mathcal{H}$. \begin{defi}\label{defitransporter} Let $\mathcal{F}$ be a fusion system over a finite $p$-group $S$. A \emph{transporter system} associated to $\mathcal{F}$ is a nonempty category $\mathcal{T}$ such that $\operatorname{Ob}\nolimits(\mathcal{T}) \subseteq \operatorname{Ob}\nolimits(\mathcal{F})$ is closed under $\mathcal{F}$-conjugacy and overgroups, together with a pair of functors $$ \mathcal{T}_{\operatorname{Ob}\nolimits(\mathcal{T})}(S) \Right4{\varepsilon} \mathcal{T} \qquad \mbox{and} \qquad \mathcal{T} \Right4{\rho} \mathcal{F} $$ satisfying the following conditions. \begin{itemize} \item[(A1)] The functor $\varepsilon$ is the identity on objects and an inclusion on morphism sets, and the functor $\rho$ is the inclusion on objects and a surjection on morphism sets. \item[(A2)] For each $P, Q \in \operatorname{Ob}\nolimits(\mathcal{T})$, the kernel $$ E(P) \stackrel{def} = \operatorname{Ker}\nolimits \big[\rho_P \colon \mathrm{Aut}_{\mathcal{T}}(P) \Right2{} \mathrm{Aut}_{\mathcal{F}}(P) \big] $$ acts freely on $\operatorname{Mor}\nolimits_{\mathcal{T}}(P,Q)$ by right composition, and $\rho_{P,Q}$ is the orbit map of this action. Also, $E(Q)$ acts freely on $\operatorname{Mor}\nolimits_{\mathcal{T}}(P,Q)$ by left composition. \item[(B)] For each $P,Q \in \operatorname{Ob}\nolimits(\mathcal{T})$, $\varepsilon_{P,Q} \colon N_S(P,Q) \to \operatorname{Mor}\nolimits_{\mathcal{T}}(P,Q)$ is injective, and the composite $\rho_{P,Q} \circ \varepsilon_{P,Q}$ sends $g \in N_S(P,Q)$ to $c_g \in \operatorname{Hom}\nolimits_{\mathcal{F}}(P,Q)$. \item[(C)] For all $\varphi \in \operatorname{Mor}\nolimits_{\mathcal{T}}(P,Q)$ and all $g \in P$, the diagram $$ \xymatrix{ P \ar[r]^{\varphi} \ar[d]_{\varepsilon_P(g)} & Q \ar[d]^{\varepsilon_Q(\rho(\varphi)(g))} \\ P \ar[r]_{\varphi} & Q } $$ commutes in $\mathcal{T}$. \item[(I)] Each $\mathcal{F}$-conjugacy class of subgroups in $\operatorname{Ob}\nolimits(\mathcal{T})$ contains a subgroup $P$ such that $\varepsilon_P(N_S(P)) \in \operatorname{Syl}\nolimits_p(\mathrm{Aut}_{\mathcal{T}}(P))$; that is, such that $[\mathrm{Aut}_{\mathcal{T}}(P)\colon \varepsilon(N_S(P))]$ is finite and prime to $p$. \item[(II)] Let $\varphi \in \operatorname{Iso}\nolimits_{\mathcal{T}}(P,Q)$, $P \lhd \widetilde{P} \leq S$ and $Q \lhd \widetilde{Q} \leq S$ be such that $\varphi \circ \varepsilon_P(\widetilde{P}) \circ \varphi^{-1} \leq \varepsilon_Q(\widetilde{Q})$. Then there is some $\widetilde{\varphi} \in \operatorname{Mor}\nolimits_{\mathcal{T}}(\widetilde{P}, \widetilde{Q})$ such that $\widetilde{\varphi} \circ \varepsilon_{P, \widetilde{P}}(1) = \varepsilon_{Q, \widetilde{Q}}(1) \circ \varphi$. \end{itemize} A \emph{centric linking system} associated to a saturated fusion system $\mathcal{F}$ is a transporter system $\mathcal{L}$ such that $\operatorname{Ob}\nolimits(\mathcal{L})$ is the collection of all $\mathcal{F}$-centric subgroups of $S$ and $E(P) = Z(P)$ for all $P \in \operatorname{Ob}\nolimits(\mathcal{L})$. \end{defi} \begin{defi} A \emph{$p$-local finite group} is a triple $\mathcal{G} = (S, \FF, \LL)$, where $S$ is a finite $p$-group, $\mathcal{F}$ is a saturated fusion system over $S$, and $\mathcal{L}$ is a centric linking system associated to $\mathcal{F}$. The \emph{classifying space} of a $p$-local compact group $\mathcal{G}$ is the $p$-completed nerve of $\mathcal{L}$, denoted by $B\mathcal{G} = |\mathcal{L}|^{\wedge}_p$. The \emph{center} of $\mathcal{G}$ is the center of the fusion system $\mathcal{F}$, and is denoted by $Z(\mathcal{G})$. \end{defi} \begin{rmk} Given a saturated fusion system $\mathcal{F}$ over a finite $p$-group $S$, Chermak and Oliver proved, in \cite{Chermak} and \cite{Oliver} respectively, that there is an essentially unique centric linking system $\mathcal{L}$ associated to $\mathcal{F}$. \end{rmk} Eventually, we deal in this paper with fibrations involving classifying spaces of $p$-local finite groups. To this end, we recall the description of the topological monoid of self-equivalences of the classifying space of a $p$-local finite group. \begin{defi} Let $\mathcal{G} = (S, \FF, \LL)$ be a $p$-local finite group. An automorphism $\Psi \colon \mathcal{L} \Right2{\cong} \mathcal{L}$ is \textit{isotypical} if $\Psi(\varepsilon_P(P)) = \varepsilon_{\Psi(P)}(\Psi(P))$ for each $P \in \operatorname{Ob}\nolimits(\mathcal{L})$. \end{defi} Let $\mathrm{Aut}_{\mathrm{typ}}^I(\mathcal{L})$ be the collection of isotypical automorphisms of $\mathcal{L}$ which send inclusions to inclusions. That is, $\Psi \in \mathrm{Aut}_{\mathrm{typ}}^I(\mathcal{L})$ if $\Psi(\varepsilon_{P,Q}(1)) = \varepsilon_{\Psi(P), \Psi(Q)}(1)$ whenever $P \leq Q$. This collection turns out to be a group by \cite[Lemma 1.14]{AOV}. The elements of $\mathrm{Aut}_{\mathcal{L}}(S)$ induce isotypical automorphisms of $\mathcal{L}$ by conjugation, as follows. Fix $\varphi \in \mathrm{Aut}_{\mathcal{L}}(S)$, and define $c_{\varphi}$ by $$ c_{\varphi}(P) = \rho(\varphi)(P) \qquad \mbox{and} \qquad c_{\varphi}(\psi) = (\varphi|_{Q, c_{\varphi}(Q)}) \circ \psi \circ (\varphi^{-1}|_{c_{\varphi}(P), P}) $$ for each $P,Q \in \operatorname{Ob}\nolimits(\mathcal{L})$ and all $\psi \in \operatorname{Mor}\nolimits_{\mathcal{L}}(P,Q)$. Notice that $c_{\varphi} \in \mathrm{Aut}_{\mathrm{typ}}^I(\mathcal{L})$ by construction. Actually, $\{c_{\varphi} \,| \, \varphi \in \mathrm{Aut}_{\mathcal{L}}(S)\}$ is a normal subgroup of $\mathrm{Aut}_{\mathrm{typ}}^I(\mathcal{L})$, so we can define $\operatorname{Out}\nolimits_{\mathrm{typ}}(\mathcal{L}) \stackrel{def} = \mathrm{Aut}_{\mathrm{typ}}^I(\mathcal{L})/\{c_{\varphi} \,| \, \varphi \in \mathrm{Aut}_{\mathcal{L}}(S)\}$. The following is a simplification of \cite[Theorem 8.1]{BLO2}. \begin{prop}\label{auttyp} Let $\mathcal{G} = (S, \FF, \LL)$ be a $p$-local finite group. Then, $$ \pi_i(\underline{\aut}(B\mathcal{G})) \cong \left\{ \begin{array}{ll} \operatorname{Out}\nolimits_{\mathrm{typ}}(\mathcal{L}) & i = 0 \\ Z(\mathcal{G}) & i = 1 \\ \{0\} & i \geq 2 \\ \end{array} \right. $$ \end{prop} \section{Background on partial groups and localities}\label{partial} In this section we review the definitions of partial groups and localities as they appeared in the seminal paper \cite{Chermak}. Roughly speaking, a partial group is a set with an associative operation (multiplication), a unit and an inversion (just like a group), but where some of the possible products are undefined. From this point of view, a partial group is formed by four pieces of data: a set of basic elements $\mathcal{M}$, a subset $\mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ of the free monoid on $\mathcal{M}$, a multiplication function $\Pi \colon \mathbb{D}} %before it was \operatorname{D(\mathcal{M}) \to \mathcal{M}$, and an inversion $(-)^{-1}$. A note of warning about this section. The convention in \cite{Chermak} is that maps apply \emph{from the right}, whereas our convention is that maps apply \emph{from the left}. For the sake of coherence, we present partial groups with the original notation and convention from \cite{Chermak}. In later sections we will adapt notation to make both conventions compatible with each other. Let us start by fixing some notation. Let $\mathcal{M}$ be a set, not necessarily finite, and let $\mathbb{W}} %before it was \operatorname{W(\mathcal{M})$ be the free monoid on the set $\mathcal{M}$. An element in $\mathbb{W}} %before it was \operatorname{W(\mathcal{M})$ (also called a \emph{word in} $\mathbb{W}} %before it was \operatorname{W(\mathcal{M})$) is a finite sequence of elements of $\mathcal{M}$. The word $u \in \mathbb{W}} %before it was \operatorname{W(\mathcal{M})$ formed by the letters $x_1, \ldots, x_n \in \mathcal{M}$ will be represented by the symbol $$ u = (x_1, \ldots, x_n). $$ More generally, given words $u = (x_1, \ldots, x_n)$ and $v= (y_1, \ldots, y_m)$ in $\mathbb{W}} %before it was \operatorname{W(\mathcal{M})$, its concatenation will be abbreviated by $u \circ v = (x_1, \ldots, x_n, y_1, \ldots, y_m)$. Associated to $\mathbb{W}} %before it was \operatorname{W(\mathcal{M})$ there is a \emph{length function} $l\colon \mathbb{W}} %before it was \operatorname{W(\mathcal{M}) \to \mathbb{N}$ which sends each element $w \in \mathbb{W}} %before it was \operatorname{W(\mathcal{M})$ to the length of the sequence of elements of $\mathcal{M}$ which forms $w$. The \emph{empty word}, represented by $(\emptyset)$, is the unique word of length $0$. When there is no place for confusion we may abbreviate the notation by writing $\mathbb{W}} %before it was \operatorname{W$ instead of $\mathbb{W}} %before it was \operatorname{W(\mathcal{M})$. \begin{defi}\label{pgroup} Let $\mathcal{M}$ be a set, and let $\mathbb{D}} %before it was \operatorname{D(\mathcal{M}) \subseteq \mathbb{W}} %before it was \operatorname{W(\mathcal{M})$ be a subset such that \begin{enumerate}[(i)] \item $\mathcal{M} \subseteq \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$; \item $u \circ v \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M}) \Longrightarrow u, v \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ \end{enumerate} (in particular, $(\emptyset) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$). A mapping $\Pi \colon \mathbb{D}} %before it was \operatorname{D(\mathcal{M}) \to \mathcal{M}$ is a \emph{product} if \begin{itemize} \item[(P1)] $\Pi$ restricts to the identity map on $\mathcal{M}$; \item[(P2)] if $u \circ v \circ w \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ then $u \circ \Pi(v) \circ w \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ and $$ \Pi(u \circ v \circ w) = \Pi(u \circ \Pi(v) \circ w). $$ \end{itemize} The \emph{unit} of a product $\Pi$ is defined as $1 = \Pi(\emptyset)$. A \emph{partial monoid} is a triple $(\mathcal{M}, \mathbb{D}} %before it was \operatorname{D(\mathcal{M}), \Pi)$, where $\Pi$ is a product defined on $\mathbb{D}} %before it was \operatorname{D(\mathcal{M})$. An \emph{inversion} on $\mathcal{M}$ is an involutory bijection $x \mapsto x^{-1}$ on $\mathcal{M}$ together with the mapping $u \mapsto u^{-1}$ on $\mathbb{W}} %before it was \operatorname{W(\mathcal{M})$ given by $$ u = (x_1, \ldots, x_n) \mapsto (x_n^{-1}, \ldots, x_1^{-1}) = u^{-1}. $$ A \emph{partial group} is a tuple $(\mathcal{M}, \mathbb{D}} %before it was \operatorname{D(\mathcal{M}), \Pi, (-)^{-1})$ where $\Pi$ is a product on $\mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, and $(-)^{-1}$ is an inversion on $\mathcal{M}$ satisfying \begin{itemize} \item[(I1)] if $u \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ then $(u^{-1},u) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ and $\Pi(u^{-1}, u) = 1$. \end{itemize} \end{defi} To simplify the notation, we will use $\mathcal{M}$ to refer to a partial group $(\mathcal{M}, \mathbb{D}} %before it was \operatorname{D(\mathcal{M}), \Pi, (-)^{-1})$ (or partial monoid) if the rest of the data is understood. The following is a summary of the basic properties of partial groups, as stated in \cite{Chermak}. \begin{lmm}\label{2.2Ch} Let $\mathcal{M}$ be a partial group. Then, \begin{enumerate}[(i)] \item $\Pi$ is $\mathbb{D}} %before it was \operatorname{D(\mathcal{M})$-multiplicative. That is, if $u \circ v \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, then $\Pi(u)\circ \Pi(v)\in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, and $$ \Pi(u \circ v) = \Pi(\Pi(u) \circ \Pi(v)); $$ \item $\Pi$ is $\mathbb{D}} %before it was \operatorname{D(\mathcal{M})$-associative. That is, if $u \circ v \circ w \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, then $$ \Pi(\Pi(u \circ v) \circ w) = \Pi(u \circ \Pi(v \circ w)); $$ \item if $u \circ v \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, then $u \circ 1 \circ v \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ and $$ \Pi(u \circ 1 \circ v) = \Pi(u \circ v); $$ \item if $u \circ v \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, then $w = u^{-1} \circ u \circ v, w' = u \circ v \circ v^{-1} \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, and $$ \begin{array}{ccc} \Pi(w) = \Pi(v) & \mbox{ and } & \Pi(w') = \Pi(u);\\ \end{array} $$ \item the left cancellation rule (similarly for right cancellation): if $u \circ v, u \circ w \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ and we have $\Pi(u \circ v) = \Pi(u \circ w)$, then $$ \Pi(v) = \Pi(w); $$ \item if $u \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, then $u^{-1} \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, and $\Pi(u^{-1}) = \Pi(u)^{-1}$. In particular, $(1)^{-1} = 1$; \item the left uncancellation rule (similarly for right uncancellation): let $u,v,w \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ and suppose that $a = u \circ v, b = u \circ w \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ with $\Pi(v) = \Pi(w)$. Then, $$ \Pi(a) = \Pi(b). $$ \end{enumerate} \end{lmm} \begin{rmk}\label{2.3Ch} Let $\mathcal{M}$ be a partial group. If $\mathbb{D}} %before it was \operatorname{D(\mathcal{M}) = \mathbb{W}} %before it was \operatorname{W(\mathcal{M})$, then $\mathcal{M}$ is an actual group via the binary operation $(u,v) \mapsto \Pi(u \circ v)$. \end{rmk} Let $\mathcal{M}$ be a partial group, and let $\mathcal{H} \subseteq \mathcal{M}$ be a non-empty subset. Set also $\mathbb{D}} %before it was \operatorname{D(\mathcal{H}) = \mathbb{D}} %before it was \operatorname{D(\mathcal{M}) \cap \mathbb{W}} %before it was \operatorname{W(\mathcal{H})$. Then, $\mathcal{H}$ is called a \emph{partial subgroup} of $\mathcal{M}$ if $\mathcal{H}$ is closed under inversion and with respect to products: if $w \in \mathbb{D}} %before it was \operatorname{D(\mathcal{H})$, then $\Pi(w) \in \mathcal{H}$. If in addition, $\mathbb{D}} %before it was \operatorname{D(\mathcal{H}) = \mathbb{W}} %before it was \operatorname{W(\mathcal{H})$, then $\mathcal{H}$ is a \emph{subgroup} of $\mathcal{M}$. We will use calligraphic letters $\mathcal{H}, \mathcal{K}, \ldots$ to denote partial subgroups, and straight letters $H, K, \ldots$ to denote subgroups of a given partial group $\mathcal{M}$. Let $u \in \mathcal{M}$, and set $\mathbb{D}} %before it was \operatorname{D(u) \stackrel{def} = \{x \in \mathcal{M} \mbox{ } | \mbox{ } (u^{-1}, x, u) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})\}$. There is an obvious mapping \begin{equation}\label{conjugation} \xymatrix@R=1mm{ \mathbb{D}} %before it was \operatorname{D(u) \ar[rr]^{c_u} & & \mathcal{M} \\ x \ar@{|->}[rr] & & (x)c_u = \Pi(u^{-1},x, u) \\ } \end{equation} We also adopt the following convention: given elements $u, x \in \mathcal{M}$, the symbol $x^u$ stands for $(x)c_u = \Pi(u, x, u^{-1})$, and in particular includes the assumption that $x \in \mathbb{D}} %before it was \operatorname{D(u)$. Notice that even if $x, y \in \mathbb{D}} %before it was \operatorname{D(u)$ and $(x, y) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, it is possible that $(u^{-1},x \cdot y, u) \notin \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$. \begin{lmm}\label{2.5Ch} Let $\mathcal{M}$ be a partial group and let $u \in \mathcal{M}$. Then, \begin{enumerate}[(i)] \item $1 \in \mathbb{D}} %before it was \operatorname{D(u)$ and $(1)c_u = 1$; \item $\mathbb{D}} %before it was \operatorname{D(u)$ is closed under inversion and $(x^{-1})c_u = ((x)c_u)^{-1}$ for all $x \in \mathbb{D}} %before it was \operatorname{D(u)$; \item $c_u$ is a bijection $\mathbb{D}} %before it was \operatorname{D(u) \to \mathbb{D}} %before it was \operatorname{D(u^{-1})$, and $c_{u^{-1}} = (c_u)^{-1}$; \item $\mathcal{M} = \mathbb{D}} %before it was \operatorname{D(1)$ and $(x)c_1 = x$ for all $x \in \mathcal{M}$. \end{enumerate} \end{lmm} If $H \leq \mathcal{M}$ is a subgroup and $H \subseteq \mathbb{D}} %before it was \operatorname{D(u)$ for some $u \in \mathcal{M}$, we write $H^u = \{(x)c_u \, | \, x \in H\}$. More generally, given subgroups $H, K \leq \mathcal{M}$, define $$ \begin{array}{l} N_{\mathcal{M}}(H, K) \stackrel{def} = \{u \in \mathcal{M} \, | \, H \subseteq \mathbb{D}} %before it was \operatorname{D(u) \mbox{ and } H^u \leq K\} \\ N_{\mathcal{M}}(H) \stackrel{def} = \{u \in \mathcal{M} \, | \, H \subseteq \mathbb{D}} %before it was \operatorname{D(u) \mbox{ and } H^u \leq H\} \\ C_{\mathcal{M}}(H) \stackrel{def} = \{u \in \mathcal{M} \, | \, x^u = x \mbox{ for all } x \in H\} \end{array} $$ Notice that, $H^u$ need not be a group with respect to $\Pi$, even if $H$ is! Furthermore, the induced map $c_u \colon H \to K$, mapping $h \mapsto h^u$, is not in general a group homomorphism. \begin{defi}\label{morphpg} Let $\mathcal{M}, \mathcal{M}'$ be partial groups, with $\mathbb{D}} %before it was \operatorname{D(\mathcal{M}), \mathbb{D}} %before it was \operatorname{D(\mathcal{M})'$, multiplications $\Pi, \Pi'$ and units $1, 1'$ respectively. A mapping $\beta\colon \mathcal{M} \Right1{} \mathcal{M}'$ is called a \emph{morphism of partial groups} if \begin{enumerate}[(i)] \item $(\mathbb{D}} %before it was \operatorname{D(\mathcal{M}))\beta^{\ast} \subseteq \mathbb{D}} %before it was \operatorname{D(\mathcal{M})'$; and \item $(\Pi(u))\beta = \Pi'((u)\beta^{\ast})$ for all $u \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$, \end{enumerate} where $\beta^{\ast}\colon \mathbb{W}} %before it was \operatorname{W(\mathcal{M}) \to \mathbb{W}} %before it was \operatorname{W(\mathcal{M}')$ is the map induced by $\beta$. The morphism $\beta$ is an \emph{isomorphism} if there is a homomorphism $\beta'\colon \mathcal{M}' \to \mathcal{M}$ such that $\beta \circ \beta' = \operatorname{Id}\nolimits_{\mathcal{M}}$ and $\beta' \circ \beta = \operatorname{Id}\nolimits_{\mathcal{M}'}$. \end{defi} Homomorphisms of partial groups satisfy similar properties to those of group homomorphisms (see \cite[Lemma 3.2]{Chermak} for further details). Namely, if $\beta\colon \mathcal{M} \to \mathcal{M}'$ is a homomorphism of partial groups, then \begin{enumerate}[(a)] \item $(1)\beta = 1'$; and \item $(u^{-1})\beta = ((u)\beta)^{-1}$ for all $u \in \mathcal{M}$. \end{enumerate} With this notion of morphism, partial groups form a category. \begin{defi}\label{npg} Let $\mathcal{M}$ be a partial group, and let $\mathcal{N} \leq \mathcal{M}$ be a partial subgroup. We say that $\mathcal{N}$ is a \emph{partial normal subgroup} of $\mathcal{M}$ if $x^g \in \mathcal{N}$ whenever $x \in \mathcal{N} \cap \mathbb{D}} %before it was \operatorname{D(g)$. \end{defi} \begin{lmm}\label{npg1} Let $\beta \colon \mathcal{M} \to \mathcal{M}'$ be a morphism of partial groups, and define the \emph{kernel of $\beta$} as $\operatorname{Ker}\nolimits(\beta) = \{x \in \mathcal{M} \, | \, (x)\beta = 1'\}$. Then $\operatorname{Ker}\nolimits(\beta)$ is a partial normal subgroup of $\mathcal{M}$. \end{lmm} \begin{proof} This is \cite[Lemma 3.3]{Chermak}. \end{proof} \begin{defi}\label{opgroup} Let $\mathcal{M}$ be a partial group, and let $\Delta$ be a collection of subgroups of $\mathcal{M}$. Define also $$ \mathbb{D}} %before it was \operatorname{D_{\Delta} \stackrel{def} = \{w = (u_1, \ldots, u_n) \in \mathbb{W}} %before it was \operatorname{W(\mathcal{M}) \, | \, \exists X_0, \ldots, X_n \in \Delta \colon X_{i-1}^{u_i} = X_i, \, i = 1, \ldots, n\}. $$ The pair $(\mathcal{M}, \Delta)$ is an \emph{objective partial group} if \begin{itemize} \item[(O1)] $\mathbb{D}} %before it was \operatorname{D(\mathcal{M}) = \mathbb{D}} %before it was \operatorname{D_{\Delta}$; and \item[(O2)] if $X,Z \in \Delta$, $Y \leq Z$, and $u \in \mathcal{M}$ are such that $X^u \subseteq Y$, then $N_Y(X^u) \in \Delta$. In particular, $X^u \in \Delta$. \end{itemize} \end{defi} \begin{defi}\label{asscat} Given an objective partial group $(\mathcal{M}, \Delta)$, we can form the following associated categories. \begin{itemize} \item The \emph{transporter category} of $(\mathcal{M}, \Delta)$, $\mathcal{C} = \mathcal{C}_{\Delta}(\mathcal{M})$, whose set of objects is $\Delta$ and with morphism sets $\operatorname{Mor}\nolimits_{\mathcal{C}}(X,Y) = N_{\mathcal{M}}(X,Y)$ for each pair $X,Y \in \Delta$. Whenever $X \leq Y$, the morphism $1 \in \operatorname{Mor}\nolimits_{\mathcal{C}}(X,Y)$ is called an \emph{inclusion morphism}. Note that every morphism in $\mathcal{C}$ factors uniquely as an inclusion morphism followed by an isomorphism. \item The \emph{fusion category} of $(\mathcal{M}, \Delta)$, $\mathcal{F} = \mathcal{F}_{\Delta}(\mathcal{M})$, whose objects are the groups $U$ such that $U \leq X$ for some $X \in \Delta$, and whose morphisms are compositions of restrictions of conjugation homomorphisms $c_u\colon X \to Y$ between objects in $\Delta$ (note that morphisms in $\mathcal{F}$ are group homomorphisms). \end{itemize} \end{defi} We are ready now to define localities. A (finite) group $G$ is of \emph{characteristic $p$} if $C_G(O_p(G)) \leq O_p(G)$. Roughly speaking, a locality is a partial group with a Sylow $p$-subgroup. \begin{defi}\label{locality} A \emph{locality} is a triple $(\LL, \Delta, S)$, where $\mathcal{L}$ is a finite partial group (i.e., $\mathcal{L}$ is a finite set and has the structure of a partial group), $S$ is a finite $p$-subgroup of $\mathcal{L}$, and $\Delta$ is a collection of subgroups of $S$, with $S \in \Delta$, and subject to the following conditions. \begin{itemize} \item[(L1)] $(\mathcal{M}, \Delta)$ is an objective partial group; and \item[(L2)] $S$ is maximal in the poset (ordered by inclusion) of $p$-subgroups of $\mathcal{M}$. \end{itemize} A locality $(\LL, \Delta, S)$ is \emph{proper} if it satisfies the following properties. \begin{itemize} \item[(PL1)] $\Delta$ contains all the $\mathcal{F}$-centric $\mathcal{F}$-radical subgroups. \item[(PL2)] For each $P \in \Delta$, the group $N_{\mathcal{L}}(P)$ is of characteristic $p$. \end{itemize} More generally, a locality is \emph{saturated} if it satisfies condition (PL1) above. \end{defi} Note that, in particular, if $(\LL, \Delta, S)$ is a saturated locality, then $\mathcal{F}_{\Delta}(\text{\bbfamily L})$ is a saturated fusion system fby \cite[Theorem A]{BCGLO1}. In \cite[Appendix A]{Chermak} the author describes a bijective correspondence between isomorphism classes of localities and isomorphism classes of transporter systems, which specializes to a correspondence between proper localities and linking systems. The reader is referred there for further details. \begin{lmm} Let $(\mathcal{L}, \Delta, S)$ be a locality. Then, for each $(x_1, \ldots, x_n) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$ and each $(s_1, \ldots, s_m) \in \mathbb{W}} %before it was \operatorname{W(N_{\mathcal{L}}(S))$, we have \begin{enumerate}[(i)] \item $(x_1, \ldots, x_n, s_1, \ldots, s_m) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$; and \item $(s_1, \ldots, s_m, x_1, \ldots, x_n) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$. \end{enumerate} In particular, $\mathcal{L}$ is an $(S,S)$-biset. \end{lmm} \begin{proof} We prove (i) and leave (ii) to the reader. Since $(x_1, \ldots, x_n) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$, there exist $H_0, \ldots, H_n \in \Delta$ such that $H_{i-1}^{x_i} = H_i$ for all $i = 1, \ldots, n$. Note also that $(s_1, \ldots, s_m) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$ via the subgroup $S \in \Delta$, since $S^{s_j} = S$ for all $j = 1, \ldots, m$. Thus, $(x_1, \ldots, x_n, s_1, \ldots, s_m) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$ via the sequence $H_0, \ldots, H_n, H_{n+1}, \ldots, H_{n+m} \in \Delta$, where $H_{n+j} = ((H_n^{s_1})^{s_2} \ldots)^{s_j}$ for all $j = 1, \ldots, m$. \end{proof} Let $(\LL, \Delta, S)$ be a locality, and let $\omega = (x_1, \ldots, x_n) \in \mathbb{W}} %before it was \operatorname{W(\mathcal{L})$ be a word. Define \begin{equation}\label{SwSu0} \begin{array}{l} R_{\omega} = \{g_0 \in S \, | \, \exists g_0, \ldots, g_n \in S \mbox{ such that } (g_{i-1})^{x_i} = g_i \mbox{ for all } i = 1, \ldots, n\} \\ L_{\omega} = \{(((g_0)^{x_1})^{x_2} \ldots)^{x_n} \, | \, g_0 \in R_w\}. \end{array} \end{equation} Notice that $L_{\omega} = R_{\omega^{-1}}$, where $\omega^{-1} = (x_n^{-1}, \ldots, x_1^{-1})$. By \cite[Lemma 2.14]{Chermak}, $R_{\omega}$ and $L_{\omega}$ are subgroups of $S$, and $\omega \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$ if and only if $R_{\omega}, L_{\omega} \in \Delta$. A note the the reader, the original notation for $R_{\omega}$ in \cite{Chermak} was $S_{\omega}$. We opted for altering this in order to accommodate the left/right conjugation conventions mentioned at the beginning of this section. This way, $R_{\omega}$ stands for the biggest subgroup of $S$ that can be \emph{right conjugated} by $\omega$ into $S$, while $L_{\omega}$ stands for the biggest subgroup of $S$ that can be \emph{left conjugated} by $\omega$ into $S$. \begin{lmm}\label{SwSu} Let $(\LL, \Delta, S)$ be a locality, and let $\omega \in \mathbb{W}} %before it was \operatorname{W(\mathcal{L})$, with $\omega = u \circ v$. Then, \begin{enumerate}[(i)] \item $R_{\omega} = R_u \cap (L_u \cap R_v)^{u^{-1}}$; and \item if $\omega \in \mathbb{D}} %before it was \operatorname{D(\mathcal{L})$, then $R_{\omega} \leq R_{\Pi(\omega)}$. \end{enumerate} \end{lmm} \begin{proof} This is immediate by definition. \end{proof} \section{Background on simplicial sets}\label{simplicial} Let $\Delta$ denote the category of finite ordered sets. A \emph{simplicial set} is a functor $$ X\colon \Delta ^{\textup{op}} \longrightarrow \mathrm{\mathbf{Sets}} $$ Usually, we will replace $\Delta$ by the skeletal subcategory which whose objects are the sets $[n] = \{0, 1, \ldots, n\}$, for $n \geq 0$, and we will refer to this subcategory also as $\Delta$. Hence, we can think of a simplicial set as a sequence of sets $X_n = X([n])$, together with maps among them induced by non-decreasing functions $\varphi\colon [n] \to [m]$. Simplicial sets form a category whose morphisms are natural transformations among functors. If $\Delta_n$ denotes the standard Euclidean $n$-simplex, then the assignment $[n] \in \Delta \mapsto \Delta_n \in \mathrm{\mathbf{Top}}$ forms a functor by assigning to each morphism in $\Delta$ the corresponding sequence of inclusions and/or collapsing of faces in the usual way. The geometric realization of a simplicial set is the CW-complex defined as $$ |X| = \left(\coprod_n \Delta_n \times X_n\right)/\sim $$ where for each non-decreasing function $\varphi\colon [n] \to [m]$, if $t \in \Delta_m$ and $x \in X_n$, we identify $(\varphi(t),x)$ with $(t, X(\varphi(x)))$. Conversely, the set of singular simplices $\sigma: \Delta_n \to T$ of a topological space $T$ forms a simplicial set $\mathrm{Sing}(T)$. The geometric realization and the singular simplicial set form a pair of adjoint functors defining an equivalence between the homotopy categories of topological spaces and of simplicial sets. In this way, simplicial sets become convenient combinatorial models for topological spaces. Finally, let us fix some notation. Given simplicial sets $X$ and $Y$, \begin{itemize} \item $\underline{\mathrm{hom}}(X,Y)$ is the simplicial set of maps from $X$ to $Y$: $(\underline{\mathrm{hom}}(X,Y))_n$ is the set of simplicial maps $\Delta[n] \times X \to Y$; \item $\underline{\aut}(X)$ is the maximal subgroup inside the function complex $\underline{\mathrm{hom}}(X,X)$; and \item $\operatorname{Out}\nolimits(X) \stackrel{def} = \pi_0(\underline{\aut}(X))$. \end{itemize} The face and degeneracy operators on $\Delta^{^{\textup{op}}}$ naturally induce on $\underline{\mathrm{hom}}(X,Y)$ the structure of a simplicial set. Furthermore, when $X = Y$, we can define in addition a multiplication in $\underline{\mathrm{hom}}(X,Y)$ $$ (\Delta[n] \times X \stackrel{\sigma} \to X) \cdot (\Delta[n] \times X \stackrel{\tau} \to X) = (\Delta[n] \times X \stackrel{\mathrm{pr}_1 \times \sigma} \longrightarrow \Delta[n] \times X \stackrel{\tau} \to X). $$ There is an obvious group homomorphism $\mathrm{Aut}(X) \to \underline{\aut}(X)$ which sends $f \in \mathrm{Aut}(X)$ to the corresponding vertex in $\underline{\aut}(X)$, so in fact $\mathrm{Aut}(X)$ is a discretization of $\underline{\aut}(X)$. Let us formalize certain operations that one can perform on the collection of simplices of any simplicial set, such as ``extracting'' the $r$-th front face of the $s$-th back face, or listing the edges. These operations will play a crucial role when studying partial groups from a simplicial point of view. To simplify notation, $d_m^k$ will denote the $k$-th iteration of the face operator $d_m$ on a given simplicial set. \begin{defi}\label{frontbackop} Let $X$ be a simplicial set, and let $r \in \mathbb{N}$. The \emph{$r$-front face operator} on $X$, $F_r$, is the collection of all set maps $F_{r,n}$, $n \geq r$, defined by $$ \xymatrix@R=1mm{ X_n \ar[rr]^{F_{r,n}} & & X_r \\ (\Delta[n] \stackrel{\sigma} \to X) \ar@{|->}[rr] & & (\Delta[r] \stackrel{F^r} \to \Delta[n] \stackrel{\sigma} \to X) } $$ where $F^r(i) = i$ for all $i \in \Delta[r]$. Similarly, for $s \in \mathbb{N}$, the \emph{$s$-back face operator} on $X$, $B_s$, is the collection of all set maps $B_{s,n}$, $n \geq s$, defined by $$ \xymatrix@R=1mm{ X_n \ar[rr]^{B_{s,n}} & & X_s \\ (\Delta[n] \stackrel{\sigma} \to X) \ar@{|->}[rr] & & (\Delta[s] \stackrel{B^s} \to \Delta[n] \stackrel{\sigma} \to X)\\ } $$ where $B^s(j) = n-s+j$ for all $j \in \Delta[s]$. \end{defi} Clearly, these operators are meaningless when applied to simplices of too small dimension. One could define them to be the identity in these situations, but this will not make a difference here. Whenever $r + s = n$, these operators combine as $D_{r,s} = (F_r, B_s)\colon X_n \to X_r \times X_s$. This can be iterated in different ways to define operators $D_{r_1, r_2, \ldots, r_l}\colon X_n \to X_{r_1} \times X_{r_2} \times \ldots \times X_{r_l}$, which are of not much relevance in this paper in general. There is, however, a particular case which is of interest to us. \begin{lmm}\label{ident1} Let $X$ be a simplicial set, and let $\omega \in X_n$. Then, \begin{enumerate}[(i)] \item for all $j = 0, \ldots, n$, $$ \begin{array}{ccc} F_{n-j}(\omega) = d_n^j(\omega) & \mbox{ and } & B_{n-j}(\omega) = d_0^j(\omega) \\ \end{array} $$ \item for all $i = 1, \ldots, n-1$, $$ F_k(d_i(\omega)) = \left\{ \begin{array}{ll} d_i(F_k(\omega)) & \mbox{, if } k> i\\ d_i(F_{k+1}(\omega)) & \mbox{, if } k = i\\ \end{array} \right. $$ \item for all $i = 1, \ldots, n-1$, $$ B_k(d_i(\omega)) = \left\{ \begin{array}{ll} d_i(B_k(\omega)) & \mbox{, if } k< i\\ d_i(B_{k+1}(\omega)) & \mbox{, if } k = i\\ \end{array} \right. $$ \end{enumerate} \end{lmm} \begin{defi}\label{enumop} Let $X$ be a simplicial set. The \emph{enumerating operator}, $E$, is the collection of set maps $E_n$, $n \geq 1$, defined by \begin{equation}\label{En} E_n = D_{1, 1, \ldots, 1} \colon X_n \Right8{(F_{n-1},B_1)} X_{n-1} \times X_1 \Right8{(F_{n-2}, B_1)\times \operatorname{Id}\nolimits} \ldots \Right8{(F_1, B_1) \times \operatorname{Id}\nolimits} \underbrace{X_1 \times \ldots \times X_1}_{\mbox{$n$ times}}. \end{equation} \end{defi} The name of the above operator comes from the fact that, for each $n$, the operator $E_n$ enumerates the edges of an arbitrary $n$-simplex in $X$. To simplify the notation we will write $E(\sigma)$ instead of $E_n(\sigma)$ for an $n$-simplex $\sigma \in X$ whenever its dimension is understood. \begin{rmk}\label{enumop2} Notice that, for each $n$, the operator $E_n$ can actually be defined in several ways, all giving the same result. For instance, for $n = 3$ we have $$ \xymatrix{ & & X_2 \times X_1 \ar[rrd]^{(F_1, B_1) \times \operatorname{Id}\nolimits} & & \\ X_3 \ar[rrrr]|{E_3} \ar[rru]^{(F_2, B_1)} \ar[rrd]_{(F_1, B_2)} & & & & X_1 \times X_1 \times X_1 \\ & & X_1 \times X_2 \ar[rru]_{\operatorname{Id}\nolimits \times (F_1, B_1)} & & \\ } $$ We will not enumerate here all the different decompositions of $E_n$ for a general $n$ since this would require an unnecessary amount of combinatorics, but we will use any equivalent definition of $E$ without further mention. \end{rmk} \begin{lmm}\label{propE} The operator $E$ satisfies the following properties. \begin{enumerate}[(i)] \item Let $X$ be a simplicial set. Then, for each $n$ and each $0 \leq i \leq n$ there is a commutative diagram $$ \xymatrix@R=15mm@C=15mm{ X_n \ar[r]^{s_i} \ar[d]_{E} & X_{n+1} \ar[d]^{E} \\ \hbox{$\underbrace{{X_1\times\dots \times X_1}}_{\text{$n$ times}}$} \ar[r]_{s_i} & \hbox{$\underbrace{{X_1\times\dots \times X_1}}_{\text{$n+1$ times}}$} \\ } $$ where the bottom horizontal map is defined as $$ s_i(x_1,\ldots, x_i, \ldots, x_n) = \left\{ \begin{array}{ll} (s_0(d_1(x_1)), x_1, \ldots, x_n) & i = 0;\\ (x_1, \ldots, x_i, s_0(d_0(x_i)), x_{i+1}, \ldots, x_n) & 1 \leq i \leq n. \end{array} \right. $$ \item Let $f\colon X \to Y$ be a simplicial map. Then, for each $n$ there is a commutative diagram $$ \xymatrix@R=15mm@C=15mm{ X_n \ar[r]^{f} \ar[d]_{E} & Y_n \ar[d]^{E} \\ \hbox{$\underbrace{{X_1\times\dots \times X_1}}_{\text{$n$ times}}$} \ar[r]_{f \times \ldots \times f} & \hbox{$\underbrace{{Y_1\times\dots \times Y_1}}_{\text{$n$ times}}$} } $$ \end{enumerate} \end{lmm} \begin{defi}\label{prodop} Let $X$ be a simplicial set. The \emph{product operator}, $\Pi$, is the collection of maps $\Pi_n$, $n \geq 0$, defined by $$ \xymatrix@R=1mm{ X_n \ar[rr]^{\Pi_n} & & X_1 \\ (\Delta[n] \stackrel{f} \to X) \ar@{|->}[rr] & & (\Delta[1] \stackrel{\pi^n} \to \Delta[n] \stackrel{f} \to X) } $$ where $\pi^n(0) = 0$ and $\pi^n(1) = n$. \end{defi} \begin{rmk} Note that, for each $n$, the map $\Pi_n$ is $d_1^{n-1}$, the face operator $d_1$ iterated $(n-1)$ times. \end{rmk} Eventually we may also use a variation of the product operator, which we call the \emph{$(r+s)$-product operator}, $\Pi_{r,s}$. This is just the collection of maps $\Pi_{r,s,n}$, $n \geq 0$, defined by $$ \xymatrix@R=1mm{ X_n \ar[rr]^{\Pi_{r,s,n}} & & X_2 \\ (\Delta[n] \stackrel{f} \to X) \ar@{|->}[rr] & & (\Delta[2] \stackrel{\pi^{r,s}} \to \Delta[n] \stackrel{f} \to X) } $$ where $\pi^{r,s}(0) = 0$, $\pi^{r,s}(1) = r$ and $\pi^{r,s}(2) = n$. \begin{lmm}\label{simprop} Let $X$ be a simplicial set. Then, for each $n = r + s$, $\Pi = \Pi \circ \Pi_{r,s}$, and there is a commutative diagram $$ \xymatrix@R=15mm@C=15mm{ X_n \ar@/^2pc/[rr]^\Pi \ar[r]^{\Pi_{r,s}} \ar[d]_{D_{r,s}} & X_2 \ar[r]^{\Pi} \ar[d]^{E} & X_1 \\ X_r \times X_s \ar[r]_{\Pi \times \Pi} & X_1 \times X_1 } $$ \end{lmm} \begin{proof} This is immediate by definition. \end{proof} The rest of this section consists of a brief review of the necessary definitions and results about fibre bundles. For further reference the reader is directed to \cite{BGM}, \cite{BLO6}, \cite{Curtis} and \cite{GoJa}. \begin{defi}\label{FB} A simplicial map $\tau\colon X \to B$ is called a \emph{fibre bundle} if $\tau$ is onto and, for each simplex $b \in B$ there is an equivalence $\alpha(b)$ between the fibre over $b$ and a fixed simplicial set $F$ (which does not depend on $b$), making the following diagram strictly commutative $$ \xymatrix{ F \times \Delta[n] \ar[r]^{\alpha(b)} \ar[d] & X^b \ar[r] \ar[d]^{\tau^b} & X \ar[d]^{\tau} \\ \Delta[n] \ar[r]_{\operatorname{Id}\nolimits} & \Delta[n] \ar[r]_{b} & B } $$ The space $F$ is called the \emph{fibre of $\tau$}, and the collection $\{\alpha(b)\}_{b \in B}$ is called an \emph{atlas of $\tau$}. \end{defi} Let $\tau \colon X \to B$ be a fibre bundle with fibre $F$. Note that there may be more than one choice of an atlas for $\tau$. However, given atlases $\{\alpha(b)\}$ and $\{\beta(b)\}$, it is immediate that, for each $b \in B_n$, $$ \alpha(b)^{-1} \cdot \beta(b) \in \underline{\aut}_n(F). $$ \begin{defi}\label{TCP} Given simplicial sets $B$ and $F$, a twisting function amounts to a collection $\{\phi_n \colon B_n \to \underline{\aut}_{n-1}(F)\}_{n \geq 1}$ such that, for all $n \geq 1$ and all $b \in B_n$, the following equations hold \begin{itemize} \item[($\tau_1$)] $\phi_{n-1}(d_i(b)) = d_{i-1}(\phi_n(b))$ for $2 \leq i \leq n$; \item[($\tau_2$)] $\phi_{n-1}(d_1(b)) = d_0(\phi_n(b)) \cdot \phi_{n-1}(d_0(b))$; \item[($\tau_3$)] $\phi_{n+1}(s_i(b)) = s_{i-1}(\phi_n(b))$ for $i \geq 1$; and \item[($\tau_4$)] $\phi_{n+1}(s_0(b)) = 1 \in \underline{\aut}_n(F)$. \end{itemize} Given a twisting function $\{\phi_n \colon B_n \to \underline{\aut}_{n-1}(F)\}_{n \geq 1}$, the associated \emph{regular twisted Cartesian product} (RTCP for short) $X = F \times_{\phi} B$ is the simplicial set with $X_n = F_n \times B_n$, $n \geq 0$, and such that, for all $g \in F_n$, $b \in B_n$, \begin{enumerate}[(i)] \item $d_i(g,b) = (d_i(g), d_i(b))$, for all $n>0$ and all $0 < i \leq n$; and \item $d_0(g,b) = (\phi(g,b) \cdot d_0(g), d_0(b))$. \end{enumerate} \end{defi} By \cite[Proposition IV.5.3]{BGM}, an RTCP is a fibre-bundle via the projection map onto the second coordinate. Every RTCP in this paper will be considered as a fibre bundle this way, even if the projection map is not explicitly mentioned. \begin{defi} A \emph{map of fibre bundles} from $\tau \colon X \to B$ to $\chi \colon Y \to C$ is a pair of maps $f \colon X \to Y$ and $g \colon B \to C$ such that $$ g \circ \tau = \chi \circ f. $$ This way, an \emph{equivalence} of fibre bundles is a pair $(f,g)$ where both $f$ and $g$ are equivalences, and the pair $(f,g)$ is a \emph{strong equivalence} if in addition $g = \operatorname{Id}\nolimits$. \end{defi} Let $\tau \colon X \to B$ be a fibre bundle with fibre $F$. Let also $\{\alpha(b)\}_{b \in B}$ be a choice of an atlas for $\tau$. For each $b \in B_n$ and each $i = 1, \ldots, n$, there is an isomorphism $\alpha_i(b) \colon F \times \Delta[n-1] \to X^{d_i(b)}$ making the following diagram commutative $$ \xymatrix{ F \times \Delta[n] \ar[r]^{\alpha(b)} & X^b \ar[r] & X \\ F \times \Delta[n-1] \ar[r]_{\alpha_i(b)} \ar[u]^{\operatorname{Id}\nolimits \times s_i} & X^{d_i(b)} \ar[r] \ar[u] & X \ar@{=}[u]\\ } $$ However, it is not true in general that $\alpha_i(b) = \alpha(d_i(b))$, and hence we can define the \emph{transformation elements} $$ \psi_i(b) = (\alpha(d_i(b)))^{-1} \cdot \alpha_i(b). $$ It is easy to check that $\psi_i(b) \in \underline{\aut}_{n-1}(F)$ for all $b \in B_n$ and all $i = 1, \ldots, n$. Let $\Gamma \leq \underline{\aut}(F)$. An atlas $\{\alpha(b)\}$ for $\tau$ is a \emph{$\Gamma$-atlas} if all of its transformation elements live in $\Gamma$. Two atlases $\{\alpha(b)\}, \{\beta(b)\}$ for $\tau$ are \emph{$\Gamma$-equivalent} if, for each $b \in B$, $$ \beta(b) = \alpha(b) \circ \gamma(b) $$ for some $\gamma(b) \in \Gamma \leq \underline{\aut}(F)$. Clearly this is an equivalence relation on the set of all atlases of $\tau$. The following is \cite[Definition IV.2.4]{BGM}. \begin{defi}\label{GFB} Let $\Gamma \leq \underline{\aut}(F)$. A fibre bundle with fibre $F$ together with a given $\Gamma$-equivalence class of $\Gamma$-atlases is called a \emph{$\Gamma$-bundle}. \end{defi} Similarly, we may talk about $\Gamma$-RTCPs. In particular, if $\Gamma = \underline{\aut}(F)$ then we will simply refer to fibre bundles and RTCPs. Let $\tau \colon X \to B$ and $\chi \colon Y \to C$ be $\Gamma$-bundles. A map $(f, g) \colon (X,B) \to (Y,C)$ is a \emph{$\Gamma$-map} if for each $b \in B$ $$ (\beta(g(b)))^{-1} \circ f \circ \alpha(b) \in \Gamma $$ provided that $\{\alpha(b)\}$ and $\{\beta(b)\}$ belong to the given $\Gamma$-equivalence classes of atlases of $\tau$ and $\chi$ respectively. In particular we may talk about \emph{$\Gamma$-equivalences} and \emph{strong $\Gamma$-equivalences}. \begin{prop}\label{strongequiv} Every $\Gamma$-bundle is strongly equivalent to a $\Gamma$-RTCP. \end{prop} \begin{proof} This is \cite[Proposition IV.3.2]{BGM}. \end{proof} \begin{rmk} Let $\tau \colon X \to B$ be a $\Gamma$-bundle with fibre $F$. By \cite[Theorem B and Corollary 0.6]{Weingram}, the realization of $\tau$ is a Serre fibration $|\tau| \colon |X| \to |B|$ with fibre $|F|$ and structural group $|\Gamma|$. We will use this property without any further mention. \end{rmk} \section{Partial groups from a simplicial point of view}\label{Spgsimp} In this section we present a rather natural construction that allows one to consider partial groups as simplicial sets. The main goal of this section is to characterize all simplicial sets associated to partial groups. Recall that a simplicial set $X$ is \emph{reduced} if it has a single vertex. \begin{defi}\label{BNsimpsets} Let $X$ be a simplicial set. We say that $X$ is an \emph{$N$-simplicial set} if $X$ satisfies \begin{itemize} \item[(N)] the enumerating operator $E \colon X_n \to X_1 \times \ldots \times X_1$ is injective for all $n \geq 1$. \end{itemize} If in addition $X$ is a reduced $N$-simplicial set, with $X_0 = \{v\}$, then the \emph{unit} of $X$ is the $1$-simplex $1_X =s_0(v)$ obtained by applying the degeneracy operator to $v$. \end{defi} Notice that the nerve of every small category is an $N$-simplicial set, hence the name. A particular example is the nerve of a group (i.e., a category with one object all of whose morphisms are invertible), whose nerve is the so-called \emph{bar construction}. We borrow from this example the notation for simplices in an $N$-simplicial set. More precisely, let $X$ be an $N$-simplicial set, and let $\omega \in X_n$ be a simplex. By definition $\omega$ is determined by its image through the enumerating operator, $E(\omega) = (x_1, \ldots, x_n)$, and we adopt the following notation $$ \omega = [x_1|\ldots|x_n] $$ for a simplex $\omega \in X_n$ with $E(\omega) = (x_1, \ldots, x_n)$. With this notation, the action of the product operator is expressed by $$ \Pi(\omega) = [x_1 \cdot \ldots \cdot x_n]. $$ \begin{rmk} Note that not every tuple $(x_1, \ldots, x_n) \in X_1 \times \ldots \times X_1$ defines an $n$-simplex. \end{rmk} Next we define a notion of \emph{inversion} for reduced $N$-simplicial sets. Consider the mapping $\chi_n\colon [n] \to [n]$ determined by $i \mapsto n-i$, and also let $\mathrm{op}: \Delta \to \Delta$ be the identity on objects. On morphisms, $$ (f\colon [n] \to [m]) \mapsto \big((\chi_m \circ f)\colon [n] \to [m]\big). $$ Given a simplicial set $X: \Delta^{\textup{op}} \to \mathrm{\mathbf{Sets}}$, define the \emph{opposite simplicial set} $X^{\textup{op}}$ as the composition $X^{\textup{op}}: \Delta^{\textup{op}} \Right1{^{\textup{op}}} \Delta^{\textup{op}} \Right1{X} \mathrm{\mathbf{Sets}}$. By definition, $(X^{\textup{op}})_n = X_n$, and $(d^{\textup{op}})_i = d_{n-i}, (s^{\textup{op}})_i = s_{n-i}$ for $0 \leq i \leq n$. An \emph{anti-involution} of a simplicial set $X$ is a simplicial map $\nu: X \to X^{\textup{op}}$ such that $\nu^2 = \nu \circ \nu^{\textup{op}} = \operatorname{Id}\nolimits_X$. Note that for each $n$, $(X^{\textup{op}})_n = X_n$, and $\nu_n = (\nu^{\textup{op}})_n$ as maps of sets. In particular, if $\nu$ as above exists, it has to be an isomorphism of simplicial sets. \begin{defi}\label{inversion} Let $X$ be a reduced $N$-simplicial set. An \emph{inversion} in $X$ is an anti-involution $\nu: X \to X^{\textup{op}}$ such that for any $n \geq 1$ and any $x \in X_n$, $L(x) = [\nu(x)|x]$ is a simplex in $X_{2n}$ and $\Pi(L(x)) = 1_X$. \end{defi} The rest of this section is devoted to show that the category of partial groups is equivalent to the full subcategory of $\mathrm{\mathbf{sSets}}$ of reduced $N$-simplicial sets with inversion. This is done in Theorem \ref{isocat} below. \begin{lmm} Let $X$ be a reduced $N$-simplicial set, with unit $1_X$, and let $\omega = [x_1|\ldots|x_n] \in X_n$. \begin{enumerate}[(i)] \item For all $0 \leq r \leq n$ we have $\sigma_r = [x_1\cdot \ldots \cdot x_r| x_{r+1} \cdot \ldots \cdot x_n] \in X_2$ and $\Pi(\sigma_r) = \Pi(\omega)$. \item For all $i = 0, \ldots, n$ we have $\omega_i = [x_1|\ldots|x_i|1_X|x_{i+1}|\ldots|x_n] \in X_{n+1}$ and $\Pi(\omega_i) = \Pi(\omega)$. \end{enumerate} \end{lmm} \begin{proof} Both (i) and (ii) follow easily from the simplicial structure of $X$ and the definition of (reduced) $N$-simplicial set. In particular, (i) follows from Lemma \ref{simprop}, and (ii) follows since $\omega_i = s_i(\omega)$. \end{proof} \begin{rmk} In particular, for each $[x_1|x_2|x_3] \in X_3$ and each $[y] \in X_1$, we have the following identities $$ \Pi[x_1 \cdot x_2|x_3] = \Pi[x_1|x_2|x_3] = \Pi[x_1|x_2 \cdot x_3] \qquad \mbox{and} \qquad \Pi[1_X|y] = [y] = \Pi[y|1_X]. $$ \end{rmk} \begin{lmm}\label{maps} Let $Y$ be a reduced $N$-simplicial set (with inversion), and let $f\colon X \to Y$ be a simplicial map. Then, $f$ is determined by its restriction to the $1$-skeleton of $X$. \end{lmm} \begin{proof} First note that since $Y$ is reduced, $Y_0 = \{e\}$, and thus $f(v) = e$ for any vertex $v \in X_0$. Assume also that we know the values of $f(x)$, for all $x \in X_1$, and let $\omega \in X_n$, with $E(\omega) = (x_1, \ldots, x_n) \in X_1 \times \ldots \times X_1$. Since $f$ is simplicial, it follows from Lemma \ref{propE} (ii) that $$ E(f(\omega)) = f^n(E(\omega)) = (f(x_1), \ldots, f(x_n)) \in Y_1 \times \ldots \times Y_1. $$ Thus, $f(\omega) = [f(x_1)|\ldots |f(x_n)]$. Finally, since $Y$ is and $N$-simplicial set, there can be a most one $n$-simplex $\sigma \in Y_n$ with $E(\sigma) = (f(x_1), \ldots, f(x_n))$. Hence, $f^n(E(\omega))$ determines $f(\omega)$. \end{proof} \begin{rmk} In the situation above, a map $f_1\colon X^1 \to Y^1$ between the corresponding $1$-skeleton does not necessarily extend to a map $f\colon X \to Y$. \end{rmk} \begin{thm}\label{isocat} The category of partial groups is equivalent to the full subcategory of $\mathrm{\mathbf{sSets}}$ of reduced $N$-simplicial sets with inversion. \end{thm} \begin{proof} Let $(\mathcal{M},\mathbb{D}} %before it was \operatorname{D(\mathcal{M}), \Pi, (-)^{-1})$ be a partial group with identity $1$, and define a simplicial set $\text{\bbfamily M}$ as follows. The set $\text{\bbfamily M}_n$ contains one simplex $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}$ for each word $(x_1, \ldots, x_n) \in \mathbb{D}} %before it was \operatorname{D(\mathcal{M})$ of length $n$. The face operators are defined by $$ d_i(\omega) = \left\{\begin{array}{ll} [x_2|\ldots|x_n] & i = 0\\ [x_1| \ldots | x_i \cdot x_{i+1} | x_{i+2} | \ldots |x_n] & 1 \leq i \leq n-1 \\ [x_1|\ldots|x_{n-1}] & i = n\\ \end{array} \right. $$ while the degeneracy operators are defined, for $i = 0, \ldots, n$, by $$ s_i(\omega) = [x_1|\ldots|x_i|1|x_{i+1}|\ldots |x_n]. $$ This makes $\text{\bbfamily M}$ into a simplicial set. Furthermore, the inversion in $\mathcal{M}$ induces naturally an inversion of this simplicial set, and now it is obvious that $\text{\bbfamily M}$ is a standard $N$-simplicial set with inversion. Conversely, if $X$ is a standard $N$-simplicial set with inversion, then set $\mathcal{M} = X_1$, the collection of $1$-simplices of $X$. It is clear that the operator $\Pi$ on $X$ defines a product for $\mathcal{M}$, and the inversion on $X$ induces an inversion on $\mathcal{M}$. As a consequence of Lemma \ref{maps}, a morphism between partial groups determines and is determined by a simplicial map between the induced simplicial sets: a simplicial map $f\colon X \to Y$ between reduced $N$-simplicial sets with inversion determines and is determined by a multiplicative map between the partial monoids in degree $1$. \end{proof} \begin{rmk}\label{autsMautM} For simplicity, it is convenient to drop the partial group notation from Section \ref{partial}, and work only with simplicial sets. Thus, if $(\mathcal{M}, \mathbb{D}} %before it was \operatorname{D(\mathcal{M}), \Pi, (-)^{-1})$ is a partial group and $\text{\bbfamily M}$ is the corresponding simplicial set, we will refer to $\text{\bbfamily M}$ as a partial group, assuming without further mention the equivalence proved above. Actually, this identification goes beyond the partial group itself: the group of automorphisms $\mathrm{Aut}(\mathcal{M})$ is clearly isomorphic to the group of invertible simplicial maps from $\text{\bbfamily M}$ to itself, $\mathrm{Aut}(\text{\bbfamily M})$, and we also identify these two groups. \end{rmk} \section{Homomorphisms of partial groups}\label{Maps} The goal of this section is to describe the automorphism simplicial set of a given partial group in terms of the algebraic structure of the partial group. In general, describing the automorphism complex of a simplicial set is a rather unaccessible problem, but in the case of partial groups the algebraic structure provides a beautifully simple description of the automorphism complex. Thus, given a partial group $\text{\bbfamily M}$, Theorem \ref{AutX0} provides a description of $\underline{\mathrm{aut}}(\text{\bbfamily M})$ in terms of $\text{\bbfamily M}$ and $\mathrm{Aut}(\text{\bbfamily M})$, while Theorem \ref{autX} describes some homotopical properties of $\underline{\mathrm{aut}}(\text{\bbfamily M})$ again in terms of $\text{\bbfamily M}$ and $\mathrm{Aut}(\text{\bbfamily M})$. In this section we adopt again the convention that morphisms apply from the left. This affects essentially to conjugation by elements in a partial group, where we talk of \emph{left conjugation} by $[g]$, meaning ``$[g \cdot a \cdot g^{-1}]$'', and \emph{right conjugation} by $[g]$, meaning ``$[g^{-1} \cdot a \cdot g]$'', and which is the convention of \cite{Chermak}. To this end we also introduce the notation $$ [\9{g}a] = [g \cdot a \cdot g^{-1}], $$ to avoid confusion with (\ref{conjugation}). Given a partial group $\text{\bbfamily M}$, we will denote by $v_{\text{\bbfamily M}}$ the single vertex of the associated simplicial set. Also, $\Delta[n]$ will denote the standard $n$-simplex. More specifically, $\Delta[n]$ is the nerve of the category $\Delta_n$ with objects $\bullet_0, \bullet_1, \ldots, \bullet_n$, and such that $$ \operatorname{Mor}\nolimits_{\Delta_n}(k-1, k) = \{\iota_k \colon k-1 \to k\} $$ for $k = 1, \ldots, n$. Thus, $\iota_1, \ldots, \iota_n$ also denote the non-degenerate $1$-simplices of $\Delta[n]$. For instance, $\Delta[1]$ will be represented by $$ \bullet_0 \Right4{\iota_1} \bullet_1. $$ \begin{lmm}\label{homotopies} Let $f, g\colon \text{\bbfamily M} \to \text{\bbfamily M}'$ be two simplicial maps between partial groups. A simplicial homotopy $F: \text{\bbfamily M} \times \Delta[1] \to \text{\bbfamily M}'$ with $f = F|_{\text{\bbfamily L} \times \{\bullet_0\}}$ and $g = F|_{\text{\bbfamily L} \times \{\bullet_1\}}$ is completely determined by the element $$ [\eta] \stackrel{def} = F(v_\text{\bbfamily M}, \iota_1) \in \text{\bbfamily M}'_1. $$ \end{lmm} As we show in the proof of the statement above, we can interpret the action of $[\eta]$ as conjugating $f(\text{\bbfamily M})$ to $g(\text{\bbfamily M})$ (in a rather loose sense), so we can think of the homotopy itself as ``(left) conjugation by the element $[\eta]$''. \begin{proof} For each simplex $\omega \in \text{\bbfamily M}_n$, let $F_{\sigma} = F|_{\Delta[n] \times \Delta[1]} = F \circ (\omega \times \operatorname{Id}\nolimits)$: $$ F_{\omega}\colon \Delta[n] \times \Delta[1] \to X \times \Delta[1] \to Y. $$ Since $\text{\bbfamily M}$ is the colimit of its simplices, $F$ is determined by $\{F_{\omega}\}_{\omega \in \text{\bbfamily M}}$, subject to the corresponding simplicial restrictions. For $n = 0$, $F$ is completely determined since $\text{\bbfamily M}_0 = \{v_{\text{\bbfamily M}}\}$, $\text{\bbfamily M}'_0 = \{v_{\text{\bbfamily M}'}\}$. Indeed, there is essentially one map $v_{\text{\bbfamily M}}: \Delta[0] \to \text{\bbfamily M}$, and the map $F_{v_{\text{\bbfamily M}}}: \Delta[0] \times \Delta[1] \to \text{\bbfamily M}'$ is determined by the element $[\eta] = F(v_{\text{\bbfamily M}}, \iota_1)$. Let now $n = 1$, and let $\omega\colon \Delta[1] \to \text{\bbfamily M}$. The product $\Delta[1] \times \Delta[1]$ can be thought of as a square, and as such its sets of vertices and edges are, respectively, $$ V = \{\bullet_{(0,0)}, \bullet_{(0,1)}, \bullet_{(1,0)}, \bullet_{(1,1)}\} \qquad E = \{(0, \iota_1), (1, \iota_1), (\iota_1,0),(\iota_1,1),(\iota_1, \iota_1)\}. $$ The map $F_{\omega}$ has to send all the vertices of $\Delta[1] \times \Delta[1]$ to the unique vertex $v_{\text{\bbfamily M}'} \in \text{\bbfamily M}'_0$. Also, it is easy to see that $F_{\omega}$ has the following effect $$ \xymatrix@R=1mm{ (0,\iota_1) \ar@{|->}[rr] & & [\eta] & & (\iota_1, 0) \ar@{|->}[rr] & & [f(\omega)] \\ (1,\iota_1) \ar@{|->}[rr] & & [\eta] & & (\iota_1, 1) \ar@{|->}[rr] & & [g(\omega)] \\ } $$ where the left column follows from the case $n = 0$. The following diagram represents the map $F_{\omega} \colon \Delta[1] \times \Delta[1] \to \text{\bbfamily M}'$ in dimensions $0$ and $1$. $$ \xymatrix{ \bullet_{(0,1)} \ar[rr]^{(\iota_1,1)} & & \bullet_{(1,1)} & & & & v_{\text{\bbfamily M}'} \ar@{-}[dd]_{[\eta]} & & & v_{\text{\bbfamily M}'} \ar@{-}[lll]_{[g(\omega)]} \ar@{-}[dd]^{[\eta]} \ar@{-}[llldd]|{F(\iota_1,\iota_1)}\\ & & & \ar@{|->}[rr]^{F_{\omega}} & & & & & & \\ \bullet_{(0,0)} \ar[rr]_{(\iota_1,0)} \ar[uu]^{(0,\iota_1)} \ar[rruu]|{(\iota_1,\iota_1)} & & \bullet_{(0,1)} \ar[uu]_{(1, \iota_1)} & & & & v_{\text{\bbfamily M}'} & & & v_{\text{\bbfamily M}'} \ar@{-}[lll]^{[f(\omega)]}\\ } $$ Let now $a$ and $b$ be the non-degenerate $2$-simplices of $\Delta[1] \times \Delta[1]$, with edges $(0,\iota_1), (\iota_1, 1)$ and $(\iota_1,0), (1, \iota_1)$ respectively. Then, by Lemma \ref{maps}, $$ \xymatrix@R=1mm{ a \ar@{|->}[rr] & & [\eta|g(\omega)] & & b \ar@{|->}[rr] & & [f(\omega)|\eta] \\ } $$ and it follows that \begin{equation}\label{conjeta} \begin{aligned}\relax [\eta \cdot g(\omega)] & = \Pi[\eta|g(\omega)] = d_1(F_{\omega}(a)) = F_{\omega}(d_1(a)) = \\ & = F_{\omega}(\iota_1,\iota_1) = F_{\omega}(d_1(b)) = d_1(F_{\omega}(b)) = \Pi[f(\omega)|\eta] = [f(\omega) \cdot \eta]. \end{aligned} \end{equation} Finally, let $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}$. The product $\Delta[n] \times \Delta[1]$ is subdivided into $n+1$ simplices, $a_0, \ldots, a_n$, of dimension $(n+1)$, and subject to obvious simplicial relations. The image of $F_{\omega}$ on each $a_i$ is easily determined by Lemma \ref{maps} as \begin{equation}\label{homotopyn} F_{\omega}(a_i) = [f(x_1)|\ldots|f(x_i)|\eta|g(x_{i+1})|\ldots|g(x_n)]. \end{equation} Furthermore, the set $\{F_{\omega}(a_i)\}_{0 \leq i \leq n}$ satisfies $\Pi(F_{\omega}(a_0)) = \Pi(F_{\omega}(a_1)) = \ldots = \Pi(F_{\omega}(a_n))$, or equivalently $$ \begin{aligned} \relax [\eta \cdot g(x_1) \cdot \ldots \cdot g(x_n)] & = [f(x_1) \cdot \eta \cdot g(x_2) \cdot \ldots \cdot g(x_n)] = \\ & = [f(x_1) \cdot f(x_2) \cdot \eta \cdot g(x_3) \cdot \ldots \cdot g(x_n)] = \ldots = \\ & = [f(x_1) \cdot \ldots \cdot f(x_n) \cdot \eta]. \end{aligned} $$ This finishes the proof. \end{proof} It is now evident what we mean when we say that $[\eta]$ conjugates $f(\text{\bbfamily M})$ to $g(\text{\bbfamily M})$: the equation (\ref{conjeta}) is very close from the conjugation formula $``f(\omega) = \eta \cdot g(\omega) \cdot \eta^{-1}$''. Lemma \ref{homotopies} is a particular case of the following result, where we describe simplicial maps $F\colon \text{\bbfamily M} \times \Delta[m] \to \text{\bbfamily M}'$ for any $m$. Let $\bullet_0, \bullet_1, \ldots, \bullet_m$ be the set of vertices of $\Delta[m]$, and let $F\colon \text{\bbfamily M} \times \Delta[m] \to \text{\bbfamily M}'$ be a simplicial map. \begin{prop}\label{nhom} Let $\text{\bbfamily M}$ and $\text{\bbfamily M}'$ be partial groups, and let $F\colon \text{\bbfamily M} \times \Delta[m] \to \text{\bbfamily M}'$ be a simplicial map. Then $F$ is completely determined by the following data \begin{enumerate}[(i)] \item the maps $f_i = F|_{\text{\bbfamily M} \times \{\bullet_i\}} \colon \text{\bbfamily M} \times \Delta[0] \Right4{\operatorname{Id}\nolimits \times \{\bullet_i\}} \text{\bbfamily M} \times \Delta[m] \Right4{F} \text{\bbfamily M}'$, for $i = 0, \ldots, m$; and \item the elements $[\eta_k] = F(v_{\text{\bbfamily M}},\iota_k) \in \text{\bbfamily M}'_1 , \quad k=1,\ldots,m$. \end{enumerate} \end{prop} \begin{proof} The map $F$ is determined by the collection of all restrictions $F_{\omega}$, where $\omega$ runs among all the simplices in $\text{\bbfamily M}$, $F_{\omega}\colon \Delta[n] \times \Delta[m] \Right2{\omega \times \operatorname{Id}\nolimits} \text{\bbfamily M} \times \Delta[m] \Right2{F} \text{\bbfamily M}'$. To avoid confusion between $\Delta[n]$ and $\Delta[m]$, label the vertices of $\Delta[n]$ simply by $0, 1, \ldots, n$, and the non-degenerate $1$-simplices of $\Delta[n]$ by $\mu_1, \ldots, \mu_n$. The vertices of $\Delta[m]$ are denoted by $\bullet_0, \ldots, \bullet_m$, and its non-degenerate $1$-simplices by $\iota_1, \ldots, \iota_m$. Fix some $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}_n$, and consider $F_{\omega}$. Since $\text{\bbfamily M}'_0 = \{v\}$, the map $F_{\omega}$ sends all the vertices of $\Delta[n] \times \Delta[m]$ to $v$. Consider now the set of (non-degenerate) $1$-simplices of $\Delta[n] \times \Delta[m]$. Then $F_{\omega}(j,\iota_i) = [\eta_i]$ and $F_{\omega}(\mu_j, \bullet_i) = [f_i(x_j)]$. Let now $\Gamma$ be the grid of size $n\times m$ determined by the $1$-skeleton of $\Delta[n] \times \Delta[m]$ (represented in the diagram below): the vertices of $\Gamma$ are the pairs $(j, \bullet_i)$, $0 \leq j \leq n$, $0 \leq i \leq m$, the horizontal edges of $\Gamma$ are the pairs $(\mu_j, \bullet_i)$, $1 \leq j \leq n$, $0 \leq i \leq m$, and the vertical edges of $\Gamma$ are the pairs $(j, \iota_i)$, $0 \leq j \leq n$, $1 \leq i \leq m$. The number of $(n+m)$-simplices subdividing $\Delta[n] \times \Delta[m]$ is the binomial coefficient $\binom{n+m}{n}$, which also corresponds to the number of walks of $n+m$ steps in $\Gamma$ which start on the vertex $(0, \bullet_0)$ and end in the vertex $(n, \bullet_m)$. \footnotesize $$ \xymatrix@R=12mm@C=18mm{ *+[F]{(0,\bullet_m)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_1,\bullet_m)} & *+[F]{(1, \bullet_m)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_2,\bullet_m)} & \ldots \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_{n-1},\bullet_m)} & *+[F]{(n-1,\bullet_m)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_{n},\bullet_m)} & *+[F]{(n,\bullet_m)} \\ *+[F]{(0,\bullet_{m-1})} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_1,\bullet_{m-1})} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(0, \iota_m)} & *+[F]{(1,\bullet_{m-1})} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_2,\bullet_{m-1})} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(1, \iota_m)} & \ldots \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^(.4){(\mu_{n-1}, \bullet_{m-1})} & *+[F]{(n-1,\bullet_{m-1})} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_n,\bullet_{m-1})} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(n-1, \iota_m)} & *+[F]{(n,\bullet_{m-1})} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}_{(n, \iota_m)}\\ \vdots \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(0, \iota_{m-1})} & \vdots \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(1, \iota_{m-1})} & \ddots & \vdots \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(n-1, \iota_{m-1})} & \vdots \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}_{(n, \iota_{m-1})}\\ *+[F]{(0,\bullet_1)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_1,\bullet_1)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(0, \iota_2)} & *+[F]{(1,\bullet_1)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_2,\bullet_1)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(1, \iota_2)} & \ldots \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^(.4){(\mu_{n-1}, \bullet_1)} & *+[F]{(n-1,\bullet_1)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_n,\bullet_1)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(n-1, \iota_2)} & *+[F]{(n,\bullet_1)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}_{(n, \iota_2)}\\ *+[F]{(0,\bullet_0)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_1,\bullet_0)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(0, \iota_1)} & *+[F]{(1,\bullet_0)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_2,\bullet_0)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(1, \iota_1)} & \ldots \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^(.4){(\mu_{n-1}, \bullet_0)} & *+[F]{(n-1,\bullet_0)} \ar@{-}[r]|-{\SelectTips{cm}{}\object@{>}}^{(\mu_n,\bullet_0)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}^{(n-1, \iota_1)} & *+[F]{(n,\bullet_0)} \ar@{-}[u]|-{\SelectTips{cm}{}\object@{>}}_{(n, \iota_1)}\\ } $$ \normalsize Let $\gamma = ((0, \bullet_0) \Right2{y_1} \ldots \Right2{y_{n+m}} (n, \bullet_m))$ be any of these walks, where $y_k$ denotes the $k$-th step in the walk $\gamma$. By definition, $y_k$ is either of the form $(j, \iota_i)$ or $(\mu_j, \bullet_i)$. Let also $a \subseteq \Delta[n] \times \Delta[m]$ be the $(n+m)$-simplex associated to $\gamma$. The image of $F_{\omega}$ is known on all the edges of $\Gamma$, and hence by Lemma \ref{maps}, $$ F_{\omega}(a) = [F_{\omega}(y_1)|\ldots|F_{\omega}(y_{n+m})] \in \text{\bbfamily M}_{n+m}. $$ For instance, we have $$ \begin{aligned} F_{\omega}\big((0,\bullet_0) \Right2{(\mu_1, \bullet_0)} (1,\bullet_0) \Right2{(\mu_2, \bullet_0)} & \ldots \Right2{(\mu_n, \bullet_0)} (n,\bullet_0) \Right2{(n, \iota_1)} (n, \bullet_1) \Right2{(n, \iota_2)} \ldots \Right2{(n, \iota_m)} (n, \bullet_m) \big) = \\[6pt] & = [f_0(x_1)|\ldots|f_0(x_n)|\eta_1 |\ldots|\eta_m] \\[6pt] F_{\omega}\big((0,\bullet_0) \Right2{(0, \iota_1)} (0,\bullet_1) \Right2{(0, \iota_2)} & \ldots \Right2{(0, \iota_m)} (0,\bullet_m) \Right2{(\mu_1, \bullet_m)} (1, \bullet_m) \Right2{(\mu_2, \bullet_m)} \ldots \Right2{(\mu_n, \bullet_m)} (n, \bullet_m) \big) = \\[6pt] & = [\eta_1|\ldots|\eta_m|f_m(x_1)|\ldots|f_m(x_n)] \end{aligned} $$ Clearly, describing the image of $F_{\omega}$ on each of the (non-degenerate) $(n+m)$-simplices of $\Delta[n] \times \Delta[m]$ is enough to describe $F_{\omega}$, and this proves the statement. Notice that for any two $(n+m)$-simplices as above, namely $a$ and $b$, we have $\Pi(a) = \Pi(b)$. \end{proof} Given a discrete group, left or right conjugation by any element of the group produces a self-equivalence of its nerve, which in addition is homotopic to the identity. This situation motivates the following definition. \begin{defi}\label{definorm} Let $\text{\bbfamily M}$ be a partial group with nerve $\text{\bbfamily M}$. The \emph{normalizer} of $\text{\bbfamily M}$, denoted by $N(\text{\bbfamily M})$, is the set of elements $[\eta] \in \text{\bbfamily M}$ satisfying the following properties. \begin{enumerate}[(i)] \item For each $[x] \in \text{\bbfamily M}$, we have $[\eta|x|\eta^{-1}] \in \text{\bbfamily M}$, and the mapping defined by $[x] \mapsto [\9{\eta}x] = [\eta \cdot x \cdot \eta^{-1}]$ extends to an automorphism of $\text{\bbfamily M}$. \item For each simplex $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}_n$, we have $\omega_i = [\9{\eta}x_1|\ldots|\9{\eta}x_i|\eta|x_{i+1}|\ldots|x_n] \in \text{\bbfamily M}$, for $i = 0, \ldots, n$, and $$ \Pi(\omega_0) = \Pi(\omega_1) = \ldots = \Pi(\omega_n). $$ \end{enumerate} The \emph{center} of $\text{\bbfamily M}$ is defined as the subset $Z(\text{\bbfamily M}) \subseteq N(\text{\bbfamily M})$ of elements $[\eta] \in N(\text{\bbfamily M})$ such that $[\9{\eta}x] = [x]$ for all $[x] \in \text{\bbfamily M}$. Finally, we say that $\alpha \in \mathrm{Aut}(\text{\bbfamily M})$ is an \emph{inner automorphism} of $\text{\bbfamily M}$ if there is a homotopy $F$ from $\alpha$ to $\operatorname{Id}\nolimits_{\text{\bbfamily M}}$. We will denote the set of all inner automorphisms by $\operatorname{Inn}\nolimits(\text{\bbfamily M})$. \end{defi} \begin{lmm}\label{N1homotopies} Let $\text{\bbfamily M}$ be a partial group with nerve $\text{\bbfamily M}$, and let $F\colon \text{\bbfamily M} \times \Delta[m] \to \text{\bbfamily M}$ be a simplex in $\underline{\aut}(\text{\bbfamily M})_m$. Then, for $1 \leq i \leq m$, $$ [\eta_i] = F(v_{\text{\bbfamily M}}, \iota_i) \in N(\text{\bbfamily M}). $$ \end{lmm} \begin{proof} The proof is straightforward by definition of $N(\text{\bbfamily M})$ and Proposition \ref{nhom}. \end{proof} \begin{lmm} Let $\text{\bbfamily M}$ be a partial group. Then the following holds. \begin{enumerate}[(i)] \item $\Psi[\eta] \in N(\text{\bbfamily M})$ for each $[\eta] \in N(\text{\bbfamily M})$ and each $\Psi \in \mathrm{Aut}(\text{\bbfamily M})$. \item Let $[\eta] \in N(\text{\bbfamily M})$ and let $\alpha \in \mathrm{Aut}(\text{\bbfamily M})$ be the left conjugation automorphism induced by $[\eta]$. Then $[\eta]$ determines a homotopy from $\alpha$ to $\operatorname{Id}\nolimits$. \item $\operatorname{Inn}\nolimits(\text{\bbfamily M})$ is a normal subgroup of $\mathrm{Aut}(\text{\bbfamily M})$. \end{enumerate} \end{lmm} \begin{proof} Let $[\eta] \in N(\text{\bbfamily M})$ and let $\Psi \in \mathrm{Aut}(\text{\bbfamily M})$. Let also $\alpha \in \mathrm{Aut}(\text{\bbfamily M})$ be the left conjugation automorphism induced by $[\eta]$. In particular, for each $[x] \in \text{\bbfamily M}$, we have $[\eta|x|\eta^{-1}] \in \text{\bbfamily M}$ and $\alpha[x] = [\eta \cdot x \cdot \eta^{-1}] = [\9{\eta}x]$. Applying $\Psi$ we get $[\Psi(\eta)|\Psi(x)|\Psi(\eta^{-1})] \in \text{\bbfamily M}$ and $$ \Psi(\alpha[x]) = \Pi[\Psi(\eta)|\Psi(x)|\Psi(\eta)^{-1}]. $$ This implies that left conjugation by $\Psi[\eta]$ extends to an automorphism of $\text{\bbfamily M}$, and $\Psi[\eta]$ satisfies condition (i) in Definition \ref{definorm}. Furthermore, the above also shows that the left conjugation automorphism induced by $\Psi[\eta]$ corresponds to $\Psi \circ \alpha \circ \Psi^{-1}$. To show that $\Psi[\eta]$ also satisfies condition (ii) in \ref{definorm}, let $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}$. By definition, we have $\omega_i = [\9{\eta}x_1|\ldots|\9{\eta}x_i|\eta|x_{i+1}|\ldots|x_n] \in \text{\bbfamily M}$, for $i = 0, \ldots, n$, with $\Pi(\omega_0) = \ldots = \Pi(\omega_n)$. By applying $\Psi$ to $\omega_i$, we get $$ \begin{aligned} \Psi(\omega_i) & = [\Psi(\9{\eta}x_1)|\ldots|\Psi(\9{\eta}x_i)|\Psi(\eta)|\Psi(x_{i+1})|\ldots|\Psi(x_n)] = \\ & = [\9{\Psi(\eta)}\Psi(x_1)|\ldots|\9{\Psi(\eta)}\Psi(x_i)|\Psi(\eta)|\Psi(x_{i+1})|\ldots|\Psi(x_n)] \in \text{\bbfamily M}, \end{aligned} $$ with $\Pi(\Psi(\omega_0)) = \ldots = \Pi(\Psi(\omega_n))$. Since $\Psi$ is an automorphism, condition (ii) in \ref{definorm} follows. Thus $\Psi[\eta] \in N(\text{\bbfamily M})$. Part (ii) in the statement follows easily from the properties of $N(\text{\bbfamily M})$. Indeed, let $[\eta] \in N(\text{\bbfamily M})$, and let $\alpha \in \mathrm{Aut}(\text{\bbfamily M})$ be the left conjugation automorphism defined by $[\eta]$. Then, using property (ii) in Definition \ref{definorm}, it is clear that we can inductively construct a homotopy $F \colon \text{\bbfamily M} \times \Delta[1] \to \text{\bbfamily M}$ from $\alpha$ to $\operatorname{Id}\nolimits$, following the reverse process that we followed in the proof of Lemma \ref{homotopies}. Finally, part (iii) of the statement is a straightforward consequence of parts (i) and (ii). Let $\alpha \in \operatorname{Inn}\nolimits(\text{\bbfamily M})$ and let $\Psi \in \mathrm{Aut}(\text{\bbfamily M})$. By definition of $\operatorname{Inn}\nolimits(\text{\bbfamily M})$, there exists a homotopy $F \colon \text{\bbfamily M} \times \Delta[1] \to \text{\bbfamily M}$ from $\alpha$ to $\operatorname{Id}\nolimits$. As discussed above, the composition $\beta = \Psi \circ \alpha \circ \Psi^{-1}$ corresponds to conjugation $\Psi[\eta] \in N(\text{\bbfamily M})$, and part (ii) implies that $\Psi[\eta]$ determines a homotopy from $\beta$ to $\operatorname{Id}\nolimits$. \end{proof} \begin{defi} The outer automorphism group of a partial group $\text{\bbfamily M}$ is the quotient $\operatorname{Out}\nolimits(\text{\bbfamily M}) = \mathrm{Aut}(\text{\bbfamily M})/\operatorname{Inn}\nolimits(\text{\bbfamily M})$. \end{defi} \begin{lmm}\label{norm-cent-inn} Let $\text{\bbfamily M}$ be a partial group. Then, the following holds. \begin{enumerate}[(i)] \item $N(\text{\bbfamily M})$ is a subgroup of $\text{\bbfamily M}$; \item $Z(\text{\bbfamily M})$ is an abelian subgroup of $\text{\bbfamily M}$; and \item $\operatorname{Inn}\nolimits(\text{\bbfamily M}) \cong N(\text{\bbfamily M})/Z(\text{\bbfamily M})$. \end{enumerate} \end{lmm} \begin{proof} Let us start by (i). By definition of partial group, $1_{\text{\bbfamily M}} \in N(\text{\bbfamily M})$. We start by showing that, for each sequence $\eta_1, \ldots, \eta_m \in N(\text{\bbfamily M})$, $\omega = [\eta_1|\ldots|\eta_m] \in \text{\bbfamily M}_m$ and $\Pi(\omega) \in N(\text{\bbfamily M})$. Let $\eta_1, \eta_2, \ldots, \eta_m \in N(\text{\bbfamily M})$. By condition (ii) in Definition \ref{definorm}, we see inductively that $[\eta_1|\ldots|\eta_m]$ is a simplex in $\text{\bbfamily M}$, and thus we can consider $\sigma = \Pi[\eta_1|\ldots|\eta_m] \in \text{\bbfamily M}$. Let us check now that $\sigma \in N(\text{\bbfamily M})$. For each $[x] \in \text{\bbfamily M}_1$ let $$ [\9{\sigma}x] \stackrel{def} = \big[\, \9{\eta_1}(\ldots\9{\eta_{m-1}}(\9{\eta_m}x))\big]. $$ This way, it is clear that left conjugation by $\sigma$ induces an automorphism of $\text{\bbfamily M}$, which actually corresponds to $\alpha_1 \circ \ldots \circ \alpha_m$, where $\alpha_i$ is the left conjugation automorphism induced by $[\eta_i]$. Thus, $\sigma$ satisfies property (i) in Definition \ref{definorm}. Fix now $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}_n$. Since $\eta_1, \ldots, \eta_m \in N(\text{\bbfamily M})$, by successively applying property (ii) in Definition \ref{definorm} we get simplices $$ \begin{array}{l} \omega_i^{(m)} = [\9{\eta_m}x_1|\ldots|\9{\eta_m}x_i|\eta_m|x_{i+1}|\ldots|x_n] \in \text{\bbfamily M}_{n+1} \\[10pt] \omega_i^{(m-1)} = [\9{\eta_{m-1}}(\9{\eta_m}x_1)|\ldots|\9{\eta_{m-1}}(\9{\eta_m}x_i)|\eta_{m-1}|\eta_m|x_{i+1}|\ldots|x_n] \in \text{\bbfamily M}_{n+2} \\ \qquad \vdots \\ \omega_i^{(1)} = [\9{\sigma}x_1|\ldots|\9{\sigma}x_i|\eta_1|\ldots|\eta_m|x_{i+1}|\ldots|x_n] \in \text{\bbfamily M}_{n+m} \end{array} $$ and the appropriate application of $\Pi$ produces the simplex $\omega_i = [\9{\sigma}x_1|\ldots|\9{\sigma}x_i|\sigma|x_{i+1}|\ldots|x_n] \in \text{\bbfamily M}_{n+1}$. Furthermore, we have $\Pi(\omega_0) = \ldots = \Pi(\omega_m)$ by construction, and thus $\sigma \in N(\text{\bbfamily M})$. To finish the proof of part (i) in the statement, we have to show that $N(\text{\bbfamily M})$ is closed by inversion. Fix some $[\eta] \in N(\text{\bbfamily M})$, and let $\alpha \in \mathrm{Aut}(\text{\bbfamily M})$ be the left conjugation automorphism induced by $[\eta]$. By property (i) in Definition \ref{definorm}, for each $[y] \in \text{\bbfamily M}$ we have $[\eta|y|\eta^{-1}] \in \text{\bbfamily M}$, and thus we also have $[\eta^{-1}|y^{-1}|\eta] \in \text{\bbfamily M}$. In particular, left conjugation by $[\eta^{-1}]$ induces the automorphism $\alpha^{-1}$, and thus $[\eta^{-1}]$ satisfies property (i) in \ref{definorm}. To show that $[\eta^{-1}]$ also satisfies property (ii) in \ref{definorm}, fix some simplex $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}$, and set $$ \mu = [y_1|\ldots|y_n] \stackrel{def} = \alpha^{-1}(\omega^{-1}). $$ In particular, $[y_i] = [\9{\eta^{-1}}(x_{n-i}^{-1}] = [(\9{\eta^{-1}}x_{n-1})^{-1}]$ for $i = 1, \ldots, n$. Now, since $[\eta] \in N(\text{\bbfamily M})$, we can apply property (ii) in \ref{definorm} to get the simplices $$ \mu_i = [\9{\eta}y_1|\ldots|\9{\eta}y_{n-i+1}|\eta|y_{n-i}|\ldots|y_n] = [x_n^{-1}|\ldots|x_{i+1}^{-1}|\eta|(\9{\eta^{-1}}x_i)^{-1}|\ldots |\9{\eta^{-1}}x_1)^{-1}] \in \text{\bbfamily M}_{n+1}. $$ This way, we have $\omega_i = \mu_i^{-1} = [\9{\eta^{-1}}x_1|\ldots|\9{\eta^{-1}}x_i|\eta^{-1}|x_{i+1}|\ldots|x_n] \in \text{\bbfamily M}_{n+1}$ for each $i$. Moreover, it follows by construction that $\Pi(\omega_0) = \ldots = \Pi(\omega_n)$, and thus $[\eta^{-1}] \in N(\text{\bbfamily M})$. Restricting the above to elements of $N(\text{\bbfamily M})$ which induce the identity on $\text{\bbfamily M}$ is a closed operation, and thus it follows that $Z(\text{\bbfamily M})$ is a subgroup of $N(\text{\bbfamily M})$. It is left to check that it is also abelian. Let $[\eta], [\sigma] \in Z(\text{\bbfamily M})$ be any two elements. By condition (ii) in Definition \ref{definorm}, $[\eta| \sigma], [\9{\eta}\sigma| \eta]$ are both simplices in $\text{\bbfamily M}$, with $\Pi[\eta|\sigma] = \Pi[\9{\eta}\sigma|\eta]$. On the other hand, since $\eta \in Z(\text{\bbfamily M})$, we have $[\9{\eta}\sigma] = [\sigma]$, and thus $\Pi[\sigma|\eta] = \Pi[\eta|\sigma]$. It follows that $Z(\text{\bbfamily M})$ is abelian. Finally, let us check (iii). First, we have to check that each inner automorphism of $\text{\bbfamily M}$ is the left conjugation automorphism induced by some $[\eta] \in N(\text{\bbfamily M})$. Let $\alpha$ be an inner automorphism. By definition, there is a homotopy $F$ from $\alpha$ to $\operatorname{Id}\nolimits_{\text{\bbfamily M}}$, and this homotopy is determined by a distinguished element $[\eta] \in N(\text{\bbfamily M})$, by Lemma \ref{homotopies} and Lemma \ref{N1homotopies}. We claim that $\alpha$ is the left conjugation automorphism induced by $[\eta]$. By Lemma \ref{N1homotopies}, for each $[x] \in \text{\bbfamily M}$ we have $[\alpha(x)|\eta], [\eta|x] \in \text{\bbfamily M}$, and $\Pi[\alpha(x)|\eta] = \Pi[\eta|x]$. On the other hand, since $[\eta] \in N(\text{\bbfamily M})$, we have $[\9{\eta}x|\eta] \in \text{\bbfamily M}$, and $\Pi[\9{\eta}|x] = \Pi[\eta|x]$. Combining these two multiplications, and by the cancellation rule (Lemma \ref{2.2Ch} (v)) we deduce that $\alpha[x] = [\9{\eta}x]$ for all $[x] \in \text{\bbfamily M}_1$, and this proves the claim. It is now easy to finish the proof of (iii). Let $[\eta] \in N(\text{\bbfamily M})$, let $[z] \in Z(\text{\bbfamily M})$, and let $[\sigma] = [z \cdot \eta] \in N(\text{\bbfamily M})$. Let also $\alpha$ and $\beta$ be the left conjugation automorphisms induced by $[\eta]$ and $[\sigma]$ respectively. It is clear that $\alpha = \beta$. Conversely, if $[\sigma] \in N(\text{\bbfamily M})$ induces the same left conjugation automorphism $\alpha$, then it is easy to check that $[\sigma \cdot \eta^{-1}] \in Z(\text{\bbfamily M})$. \end{proof} We now focus on describing $\underline{\aut}(\text{\bbfamily M})$ for a partial group $\text{\bbfamily M}$. Let $F \in \underline{\aut}(\text{\bbfamily M})_n$ be an $n$-simplex. Let also $\Psi_0, \ldots, \Psi_n \in \mathrm{Aut}(\text{\bbfamily M})$ be the automorphisms of $\text{\bbfamily M}$ obtained by restricting $F$ to the vertices of $\Delta[n]$, and let $[\eta_1], \ldots, [\eta_n] \in N(\text{\bbfamily M})$ be the elements determined by $F$ by Lemma \ref{N1homotopies}. Notice that $F$ is completely determined by this data. \begin{lmm} For $i = 1,2$, let $F_i$ be a homotopy from $\Psi_i$ to $\Psi_{i-1}$, determined by an element $[\eta_i] \in N(\text{\bbfamily M})$. Then, $[\eta_1 \cdot \eta_2] \in N(\text{\bbfamily M})$ determines a homotopy $F$ from $\Psi_2$ to $\Psi_0$. \end{lmm} \begin{proof} For each simplex $\omega = [x_1|\ldots|x_n] \in \text{\bbfamily M}_n$, let $$ F_{1,\omega} \colon \Delta[n] \times \Delta[1] \Right3{\omega \times \operatorname{Id}\nolimits} \text{\bbfamily M} \times \Delta[1] \Right3{F_1} \text{\bbfamily M}. $$ If we denote by $a_0, \ldots, a_n$ the $(n+1)$-simplices subdividing $\Delta[n] \times \Delta[1]$, then $F_{1,\omega}$ maps the simplex $a_i$ to $$ \omega_i = [\Psi_0(x_1)|\ldots|\Psi_0(x_i)|\eta_1|\Psi_1(x_{i+1})|\ldots|\Psi_1(x_n)]. $$ If we apply now $\Psi_1^{-1}$ to $\omega_i$ we get $$ \Psi_1^{-1}(\omega_i) = [(\Psi_1^{-1} \circ \Psi_0)(x_1)| \ldots | (\Psi_1^{-1} \circ \Psi_0)(x_i)| \Psi_1^{-1}(\eta_1)|x_{i+1}|\ldots|x_n]. $$ Finally, the homotopy $F_2$ applied on $\Psi_1^{-1}(\omega_i)$ produces, in particular, the simplex $$ [\Psi_0(x_1)|\ldots|\Psi_0(x_i)|\eta_1|\eta_2|\Psi_2(x_{i+1})|\ldots|\Psi_2(x_n)], $$ and thus $\sigma_i = [\Psi_0(x_1)|\ldots|\Psi_0(x_i)|\eta_1\cdot \eta_2|\Psi_2(x_{i+1})|\ldots|\Psi_2(x_n)] \in \text{\bbfamily M}$. Notice that $\Pi(\sigma_0) = \ldots = \Pi(\sigma_n)$ by definition. Using the formulae (\ref{homotopyn}) we see how $[\eta_1 \cdot \eta_2] \in N(\text{\bbfamily M})$ determines a homotopy from $\Psi_2$ to $\Psi_0$. \end{proof} \begin{defi}\label{calautM} Define the category $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ as follows. Its object set is $\operatorname{Ob}\nolimits(\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})) = \mathrm{Aut}(\text{\bbfamily M})$, and its morphism sets are $$ \operatorname{Mor}\nolimits_{\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})}(\Phi, \Psi) = \{\eta \,\, \big| \,\, [\eta] = F(v, \iota_1) \in N(\text{\bbfamily M}) \mbox{ for a homotopy } F \mbox{ from } \Psi \mbox{ to } \Phi\}. $$ A morphism in this category will be represented by $(\Phi \Left1{\eta} \Psi)$. With this notation the composition of morphisms in this category is given by multiplication in $\text{\bbfamily M}$: $$ \big(\Psi_0 \Left3{\eta_1} \Psi_1\big) \circ \big(\Psi_1 \Left3{\eta_2} \Psi_2\big) = \big(\Psi_0 \Left6{\eta_1 \cdot \eta_2} \Psi_2\big). $$ \end{defi} Actually, the category $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ is strict monoidal, as we describe next. Let $(\Psi_0 \Left1{\eta} \Psi_1)$ be a morphism in $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$. Seen as a homotopy $F \colon \text{\bbfamily M} \times \Delta[1] \to \text{\bbfamily M}$, the morphism $(\Psi_0 \Left1{\eta} \Psi_1)$ has the following effect on a $1$-simplex $[x] \in \text{\bbfamily M}$: \begin{equation}\label{action1} (\Psi_0 \Left3{\eta} \Psi_1) \cdot [x] = [\Psi_0(x) \cdot \eta] = [\eta \cdot \Psi_1(x)], \end{equation} where the rightmorst equality follows from Lemma \ref{homotopies}. If $(\Phi_0 \Left1{\omega} \Phi_1)$ is another morphism in $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$, the above formula implies $$ \begin{aligned} (\Phi_0 \Left3{\omega} \Phi_1) \cdot & \big((\Psi_0 \Left3{\eta} \Psi_1) \cdot [x] \big) = \\ & = (\Phi_0 \Left3{\omega} \Phi_1) \cdot [\Psi_0(x) \cdot \eta] = (\Phi_0 \Left3{\omega} \Phi_1) \cdot [\eta \cdot \Psi_1(x)] = \\ & = [\Phi_0(\Psi_0(x) \cdot \eta) \cdot \omega] = [\omega \cdot \Phi_1(\eta \cdot \Psi_1(x))] = \\ & = (\Phi_0 \circ \Psi_0 \LEFT6{\Phi_0(\eta) \omega = }{= \omega \Phi_1(\eta)} \Phi_1 \circ \Psi_1) \cdot [x]. \end{aligned} $$ Using this formula we can now define an operation on $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ as follows. \begin{equation}\label{productdim1} \xymatrix@R=1mm{ \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \times \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \ar[rr]^{\otimes} & & \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \\ (\Phi, \Psi) \ar@{|->}[rr] & & \Phi \circ \Psi \\ \big((\Phi_0 \Left1{\omega} \Phi_1), (\Psi_0 \Left1{\eta} \Psi_1) \big) \ar@{|->}[rr] & & (\Phi_0 \circ \Psi_0 \LEFT6{\Phi_0(\eta) \omega = }{= \omega \Phi_1(\eta)} \Phi_1 \circ \Psi_1) } \end{equation} The unit for this operation is $(\operatorname{Id}\nolimits_{\text{\bbfamily M}} \Left1{1_{\text{\bbfamily M}}} \operatorname{Id}\nolimits_{\text{\bbfamily M}})$, and the inverse is given by \begin{equation}\label{inverse1} (\Psi_0 \Left3{\eta} \Psi_1)^{-1} = (\Psi_0^{-1} \LEFT8{\Psi_0^{-1}(\eta^{-1}) = }{ = \Psi_1^{-1}(\eta^{-1})} \Psi_1^{-1}). \end{equation} In later sections we will need generalized versions of some of the formulas showed above, in particular of (\ref{action1}) and (\ref{inverse1}). Let $(\Psi_0 \Left1{\eta_1} \ldots \Left1{\eta_n} \Psi_n)$ be an $n$-simplex in $N \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$. Formula (\ref{action1}) generalizes to \begin{equation}\label{actionn} \begin{aligned} (\Psi_0 \Left1{\eta_1} \Psi_1 \Left1{\eta_2} \ldots \Left1{\eta_n} \Psi_n) \cdot [x_1|\ldots|x_n] & = [\Psi_0(x_1) \cdot \eta_1 | \Psi_1(x_2) \eta_2 |\ldots |\Psi_{n-1}(x_n) \cdot \eta_n] = \\ & = [\eta_1 \cdot \Psi_1(x_1)| \eta_2 \cdot \Psi_2(x_2)| \ldots |\eta_n \Psi_n(x_n)]. \end{aligned} \end{equation} while formula (\ref{inverse1}) generalizes as follows \begin{equation}\label{inversen} \begin{aligned} (\Psi_0 \Left3{\eta_1} \Psi_1 & \Left3{\eta_2} \ldots \Left3{\eta_n} \Psi_n)^{-1} = \\ & = (\Psi_0^{-1} \LEFT8{\Psi_1^{-1}(\eta_1^{-1}) = }{= \Psi_0^{-1}(\eta_1^{-1})} \Psi_1^{-1} \LEFT8{\Psi_2^{-1}(\eta_2^{-1}) = }{= \Psi_1^{-1}(\eta_2^{-1})} \ldots \LEFT8{\Psi_n^{-1}(\eta_n^{-1}) = }{= \Psi_{n-1}^{-1}(\eta_n^{-1})} \Psi_n^{-1}). \end{aligned} \end{equation} For the sake of completeness we also include the formula for the product in $N_n \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$, although it plays no relevant role in these notes. $$ \begin{aligned} (\Phi_0 \Left3{\omega_1} \Phi_1 & \Left3{\omega_2} \ldots \Left3{\omega_n} \Phi_n) \otimes (\Psi_0 \Left3{\eta_1} \Psi_1 \Left3{\eta_2} \ldots \Left3{\eta_n} \Psi_n) = \\[6pt] & = (\Phi_0 \circ \Psi_0 \LEFT8{\omega_1 \Phi_1(\eta_1) = }{ = \Phi_0(\eta_1) \omega_1} \Phi_1 \circ \Psi_1 \LEFT8{\omega_2 \Phi_2(\eta_2) = }{ = \Phi_1(\eta_2) \omega_2} \ldots \LEFT8{\omega_n \Phi_n(\eta_n) = }{ = \Phi_{n-1}(\eta_n) \omega_n} \Phi_n \circ \Psi_n). \end{aligned} $$ \begin{thm}\label{AutX0} Let $\text{\bbfamily M}$ be a partial group. Then, there is an equivalence of simplicial groups $$ N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \cong \underline{\mathrm{aut}}(\text{\bbfamily M}). $$ \end{thm} \begin{proof} Consider the evaluation map $N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \times \text{\bbfamily M} \Right2{\kappa} \text{\bbfamily M}$, whose effect on $1$-simplices is given by formula (\ref{action1}): $$ \kappa\big((\Psi_0 \Left3{\eta} \Psi_1), [x] \big) = [\Psi_0(x) \cdot \eta] = [\eta \cdot \Psi_1(x)]. $$ Recall that this is enough to determine $\kappa$ by Lemma \ref{maps}. One checks easily that this action of $N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ on $\text{\bbfamily M}$ is associative, and hence induces by adjunction a simplicial map $$ N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \Right2{\tilde{\kappa}} \underline{\aut}(\text{\bbfamily M}). $$ By definition of $N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ and $\underline{\aut}(\text{\bbfamily M})$, together with Lemma \ref{homotopies}, it is clear that $\tilde{\kappa}$ is injective. By Proposition \ref{nhom} it also follows easily that $\tilde{\kappa}$ is surjective. \end{proof} For simplicity, we will identify from now on the simplicial groups $\underline{\aut}(\text{\bbfamily M})$ and $N \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$. Next we give a description of the homotopy type of $N \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$, or rather of its \emph{classifying space} $B\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$, in terms of the partial group $\text{\bbfamily M}$. This classifying space is obtained via the so-called \emph{$W$-construction}, which we omit in these notes for the sake of brevity. The interested reader is referred to \cite[Section IV.5]{BGM} for further details. \begin{thm}\label{autX} Let $\text{\bbfamily M}$ be a partial group. Then, the following holds \begin{enumerate}[(i)] \item for each connected component $\mathcal{A}_i \subseteq N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ there is an equivalence $\mathcal{A}_i \simeq BZ(\text{\bbfamily M})$; \item there is a fibration $B^2Z(\text{\bbfamily M}) \longrightarrow B\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \longrightarrow B\operatorname{Out}\nolimits(\text{\bbfamily M})$; \item there is an exact sequence of groups $\{1\} \to Z(\text{\bbfamily M}) \to N(\text{\bbfamily M}) \to \mathrm{Aut}(\text{\bbfamily M}) \to \operatorname{Out}\nolimits(\text{\bbfamily M}) \to \{1\}$. \end{enumerate} \end{thm} \begin{proof} The connected components of $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ correspond to $\operatorname{Out}\nolimits(\text{\bbfamily M})$. Also, for each automorphism $\Psi \in \mathrm{Aut}(\text{\bbfamily M})$, $\mathrm{Aut}_{\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})}(\Psi) = Z(\text{\bbfamily M})$ by definition of $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$. Thus, the nerve $N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$ is a simplicial group with $$ \operatorname{Out}\nolimits(\text{\bbfamily M}) = \pi_0(N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})), $$ and each component is equivalent to $BZ(\text{\bbfamily M})$. This proves points (i). Furthermore, the classifying space of $N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$, $B\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M})$, has fundamental group $\operatorname{Out}\nolimits(\text{\bbfamily M})$ and universal cover $B^2Z(\text{\bbfamily M})$, that is, there is a fibration $$ B^2Z(\text{\bbfamily M}) \longrightarrow B\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}) \longrightarrow B\operatorname{Out}\nolimits(\text{\bbfamily M}) $$ and this proves point (ii). Finally, the exact sequence in (iii) is a direct consequence of Lemma \ref{norm-cent-inn} (iii), since $\operatorname{Inn}\nolimits(\text{\bbfamily M}) \cong N(\text{\bbfamily M})/Z(\text{\bbfamily M})$. \end{proof} To finish this section we analyze the automorphism complex of a locality $(\text{\bbfamily L}, \Delta, S)$. By definition, $\text{\bbfamily L}$ contains the $p$-group $S$ as a subgroup, and we can define $$ \mathrm{Aut}_(\text{\bbfamily L};S) \stackrel{def} = \{\Psi \in \mathrm{Aut}(\text{\bbfamily L}) \,\, \big| \,\, \Psi(S) = S\} \leq \mathrm{Aut}(\text{\bbfamily L}). $$ We can define a category $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)$ by means of $\mathrm{Aut}(\text{\bbfamily L};S)$ and $N_{\text{\bbfamily L}}(S)$ as we did with $\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L})$. \begin{lmm}\label{autloc0} Let $\underline{\aut}(\text{\bbfamily L};S) \subseteq \underline{\aut}(\text{\bbfamily L})$ be the simplicial subset with vertex set $\mathrm{Aut}(\text{\bbfamily L};S)$. Then there is an equivalence $N \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S) \cong \underline{\aut}(\text{\bbfamily L};S)$. In particular, $$ \pi_0(\underline{\aut}(\text{\bbfamily L};S)) \cong \operatorname{Out}\nolimits(\text{\bbfamily L};S) \quad \mbox{and} \quad \pi_i(\underline{\aut}(\text{\bbfamily L};S)) \cong \left\{ \begin{array}{ll} Z(\text{\bbfamily L}) & \mbox{if } i = 1;\\ 0 & \mbox{if } i \geq 2. \end{array} \right. $$ \end{lmm} If we set $\operatorname{Out}\nolimits(\text{\bbfamily L};S) \stackrel{def} = \pi_0(\underline{\aut}(\text{\bbfamily L};S))$ then it is an easy exercise to check that there is an isomorphism $\operatorname{Out}\nolimits(\text{\bbfamily L};S) \cong \mathrm{Aut}(\text{\bbfamily L};S)/(N_{\text{\bbfamily L}}(S)/Z(\text{\bbfamily L}))$, and hence there is an exact sequence $$ \{1\} \to Z(\text{\bbfamily L}) \Right4{} N_{\text{\bbfamily L}}(S) \Right4{} \mathrm{Aut}(\text{\bbfamily L};S) \Right4{} \operatorname{Out}\nolimits(\text{\bbfamily L};S) \to \{1\}. $$ The reader can compare this exact sequence with that in Theorem \ref{autX} (iii) and that in \cite[Lemma 1.14]{AOV}. \begin{lmm}\label{autloc1} There is a commutative diagram of exact sequences $$ \xymatrix{ \{1\} \ar[r] & Z(\text{\bbfamily L}) \ar[r] &N(\text{\bbfamily L}) \ar[r] & \mathrm{Aut}(\text{\bbfamily L}) \ar[r] & \operatorname{Out}\nolimits(\text{\bbfamily L}) \ar[r] & \{1\} \\ \{1\} \ar[r] & Z(\text{\bbfamily L}) \ar@{=}[u] \ar[r] & N_{\text{\bbfamily L}}(S) \ar[u]^{\operatorname{incl}\nolimits} \ar[r] & \mathrm{Aut}(\text{\bbfamily L};S) \ar[u]_{\operatorname{incl}\nolimits} \ar[r] & \operatorname{Out}\nolimits(\text{\bbfamily L};S) \ar[u] \ar[r] & \{1\} } $$ where all the vertical arrows are monomorphisms. \end{lmm} \begin{lmm} Let $\mathcal{G} = (S, \FF, \LL)$ be a $p$-local finite group and let $(\text{\bbfamily L}, \Delta, S)$ be the associated locality. Then, there are isomorphisms $$ \mathrm{Aut}(\text{\bbfamily L};S) \cong \mathrm{Aut}_{\mathrm{typ}}^{I}(\mathcal{L}) \qquad\mbox{and} \qquad \operatorname{Out}\nolimits(\text{\bbfamily L};S) \cong \operatorname{Out}\nolimits_{\mathrm{typ}}(\mathcal{L}). $$ \end{lmm} The following is an immediate consequence of Lemma \ref{autloc0} and \cite[Theorem 7.1]{BLO3}. \begin{cor}\label{autloc2} Let $\mathcal{G} = (S, \FF, \LL)$ be a $p$-local finite group and let $(\text{\bbfamily L}, \Delta, S)$ be its associated locality. Then there are homotopy equivalences of topological monoids $$ |\underline{\aut}(\text{\bbfamily L};S)| \simeq |\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)| \simeq \mathrm{Aut}(B\mathcal{G}). $$ \end{cor} \section{Extensions of partial groups}\label{FBPG} In the previous sections we have seen how partial groups can be treated as simplicial objects. Following this point of view, we now show that the total space of a fibre bundle where both base and fibre are partial groups is always a partial group. This will lead to the definition of extension of partial groups. By \cite[Proposition IV.3.2]{BGM} we know that every fibre bundle is strongly equivalent to an RTCP. Thus, we start by studying RTCPs of partial groups, and in particular we start by describing twisting functions in this setting. Let $\text{\bbfamily M}'$ and $\text{\bbfamily M}''$ be partial groups. Recall that a twisting function is a collection $$ \{\phi_n \colon \text{\bbfamily M}''_n \to \underline{\aut}_{n-1}(\text{\bbfamily M}') = N_{n-1} \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}')\}_{n \geq 1}, $$ of functions satisfying conditions ($\tau_1$)-($\tau_4$) in Definition \ref{TCP}. \begin{defi}\label{twistpair} A \emph{twisting pair} is a pair of functions $t \colon \text{\bbfamily M}''_1 \to \mathrm{Aut}(\text{\bbfamily M}')$ and $\eta \colon \text{\bbfamily M}''_2 \to N(\text{\bbfamily M}')$, satisfying the following conditions: \begin{enumerate}[(a)] \item $t(1) = \operatorname{Id}\nolimits$ and $\eta(1,g) = [1] = \eta(g,1)$ for all $[g] \in \text{\bbfamily M}''_1$; and \item (the cocycle formula) for each $[g|h|k] \in \text{\bbfamily M}''_3$, \begin{equation}\label{coboundary2} \Psi_{g}(\eta(h,k)) \cdot \eta(g, hk) = \eta(g, h) \cdot \eta(gh,k). \end{equation} \end{enumerate} \end{defi} \begin{lmm}\label{twistingn} A twisting pair $(t, \eta)$ determines a a twisting function, $\{\phi_n \colon \text{\bbfamily M}''_n \to \underline{\aut}_{n-1}(\text{\bbfamily M}') = N_{n-1} \mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}')\}_{n \geq 1}$ with $$ \begin{array}{l} \phi_1 \colon [g] \in \text{\bbfamily M}''_1 \longmapsto t(g) \in \mathrm{Aut}(\text{\bbfamily M}') = \underline{\aut}_0(\text{\bbfamily M}')\\ \phi_2 \colon [g|h] \in \text{\bbfamily M}''_2 \longmapsto \big(t(g) \Left3{\eta(g,h)} t(gh) \circ t(h)^{-1} \big) \in \operatorname{Mor}\nolimits(\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily M}')) = \underline{\aut}_1(\text{\bbfamily M}')\\ \end{array} $$ Moreover, every twisting function $\{\phi_n \colon \text{\bbfamily M}''_n \to \underline{\aut}_{n-1}(\text{\bbfamily M}')\}_{n \geq 1}$ is of this form. \end{lmm} \begin{proof} Let $(t, \eta)$ be a twisting pair. For each $n \geq 1$ and each $[g_1|\ldots|g_n] \in \text{\bbfamily M}''$, define $$ \phi_n[g_1|\ldots|g_n] = \big(\alpha_0 \Left2{\eta_1} \ldots \Left2{\eta_{n-1}} \alpha_{n-1} \big) $$ as follows. Set $\alpha_0 = t(g_1)$, $\eta_1 = \eta(g_1, g_2)$, and set \begin{itemize} \item[(T1)] $\alpha_j = t(g_1\ldots g_j) \circ t(g_2 \ldots g_j)^{-1}$, for $j = 2, \ldots, n-1$; and \item[(T2)] $\eta_k = \eta(g_1, g_2 \ldots g_k)^{-1} \cdot \eta(g_1, g_2 \ldots g_{k+1})$, for $k = 2, \ldots n-1$. \end{itemize} We claim that these formulas define a twisting function. Fix $\omega = [g_1|\ldots|g_n] \in \text{\bbfamily M}''_n$, with, $$ \phi_n(\omega) = \big(\alpha_0 \Left2{\eta_1} \ldots \Left2{\eta_{n-1}} \alpha_{n-1} \big) $$ as above. We check conditions ($\tau_1$)-($\tau_4$) of twisting functions. \textbf{Condition ($\tau_1$).} We have to check that $\phi_{n-1}(d_i(\omega)) = d_{i-1}(\phi_n(\omega))$. Note that $$ \begin{aligned} d_{i-1}(\phi_n(\omega)) & = d_{i-1}\big(\alpha_0 \Left2{\eta_1} \ldots \Left2{\eta_{n-1}} \alpha_{n-1} \big) = \\ & = \big(\alpha_0 \Left2{\eta_1} \ldots \Left2{} \alpha_{i-2} \Left3{\eta_{i-1} \eta_i} \alpha_i \Left2{} \ldots \Left2{\eta_{n-1}} \alpha_{n-1} \big). \end{aligned} $$ We may distinguish two cases, namely $i = 2$ and $i \geq 3$. When $i = 2$, we have $\eta_1 \eta_2 = \eta(g_1, g_2g_3)$, and formulas (T1) and (T2) imply that $$ \begin{aligned} \big(\alpha_0 \Left3{\eta_1 \eta_2} \alpha_2 \Left2{\eta_3} \ldots \Left2{\eta_{n-1}} \alpha_{n-1}\big) & = d_1\big(\alpha_0 \Left2{\eta_1} \ldots \Left2{\eta_{n-1}} \alpha_{n-1} \big) = \\ & = \phi_{n-1}[g_1g_2|g_3|\ldots|g_n]. \end{aligned} $$ When $i \geq 3$, we have $\eta_{i-1} \eta_i = \eta(g_1, g_2\ldots g_{i-1})^{-1} \eta(g_1, g_2\ldots g_{i+1})$, and condition ($\tau_1$) follows easily again from the formulas (T1) and (T2). \textbf{Condition ($\tau_2$).} We check the case $n = 3$, with the general case being an obvious generalization. Given $[g|h|k] \in \text{\bbfamily M}''_3$, we have by definition $$ \phi_3[g|h|k] = \big(t(g) \Left3{\eta(g,h)} t(gh) \circ t(h)^{-1} \Left9{\eta(g,h)^{-1} \eta(g, hk)} t(ghk) \circ t(hk)^{-1}\big). $$ We have to show that $\phi_1[gh|k] = d_0(\phi_3[g|h|k]) \otimes \phi_1[h|k]$. We have \begin{itemize} \item $\phi_1[gh|k] = (t(gh) \Left3{\eta(gh, k)} t(ghk) \circ t(k)^{-1})$; \item $d_0(\phi_3[g|h|k]) = (t(gh) \circ t(h)^{-1} \Left9{\eta(g,h)^{-1} \eta(g, hk)} t(ghk) \circ t(hk)^{-1})$; and \item $\phi_1[h|k] = (t(h) \Left3{\eta(h,k)} t(hk) \circ t(k)^{-1})$. \end{itemize} Applying (\ref{productdim1}), we get $$ d_0(\phi_3[g|h|k]) \otimes \phi_1[h|k] = (t(gh) \Left3{x} t(ghk) \circ t(k)^{-1}), $$ where $x = (t(gh) \circ t(h)^{-1})(\eta(h,k)) \cdot \eta(g,h)^{-1} \cdot \eta(g, hk)$. To check that $x = \eta(gh, k)$, recall that $\eta(g,h)$ determines a homotopy $(t(g) \Left2{\eta(g,h)} t(gh) \circ t(h)^{-1})$, which implies that $$ (t(gh) \circ t(h)^{-1})(y) = \eta(g,h)^{-1} \cdot t(g)(y) \cdot \eta(g,h) $$ for all $y \in \text{\bbfamily M}'_1$. Thus, we have $$ \begin{aligned} X & = (t(gh) \circ t(h)^{-1})(\eta(h,k)) \cdot \eta(g,h)^{-1} \cdot \eta(g, hk) = \\ & = \eta(g,h)^{-1} \cdot t(g)(\eta(h,k)) \cdot \eta(g,h) \cdot \eta(g,h)^{-1} \cdot \eta(g,hk) = \\ & = \eta(g,h)^{-1} \cdot t(g)(\eta(h,k)) \cdot \eta(g,hk) = \eta(gh, k) \end{aligned} $$ where the last equality follows from property (b) of twisting pairs. \textbf{Conditions ($\tau_3$) and ($\tau_4$).} These two conditions follow easily from the defining formulas (T1) and (T2), together with property (a) of twisting pairs. To finish the proof we have to show that every twisting function is defined by formulas (T1) and (T2) for some twisting pair $(t, \eta)$. Thus, let $\{\phi_n \colon \text{\bbfamily M}''_n \to \underline{\aut}_{n-1}(\text{\bbfamily M}')\}_{n \geq 1}$ be a twisting function, and define functions $$ t \colon \text{\bbfamily M}''_1 \Right2{} \mathrm{Aut}(\text{\bbfamily M}') \qquad \mbox{and} \qquad \eta \colon \text{\bbfamily M}''_2 \Right2{} N(\text{\bbfamily M}') $$ as follows: \begin{itemize} \item $t(g) = \phi_1[g]$ for each $[g] \in \text{\bbfamily M}''_1$; and \item $\eta(g,h)$ is given by $\phi_2[g|h] = (\alpha \Left2{\eta(g,h)} \beta)$ for each $[g|h] \in \text{\bbfamily M}''_2$. \end{itemize} We have to check that these two functions satisfy conditions (a) and (b) of twisting pairs, and that the original twisting function is determined by the pair $(t, \eta)$ according to formulas (T1) and (T2). \textbf{Step 1.} The twisting function for $n = 2$ and property (a). Let $[g|h] \in \text{\bbfamily M}''_2$, and set $$ \phi_2[g|h] = (\alpha \Left3{\eta(g,h)} \beta). $$ We seek to determine $\alpha$ and $\beta$ in terms of the function $t$ and the simplex $[g|h]$. To do so, apply properties ($\tau_1$) and ($\tau_2$) of twisting functions to get $$ \phi_1(d_0[g|h]) = \phi_1[h] = t(h) \qquad \phi_1(d_1[g|h]) = \phi_1[gh] = t(gh) \qquad \phi_1(d_2[g|h]) = \phi_1[g] = t(g). $$ This way, $\alpha = d_1(\alpha \Left3{\eta(g,h)} \beta) = t(g)$ and $\beta = d_0(\alpha \Left3{\eta(g,h)} \beta) = t(gh) \circ t(h)^{-1}$, and $$ \phi_2[g|h] = (t(g) \Left3{\eta(g,h)} t(gh) \circ t(h)^{-1}). $$ Furthermore, by properties ($\tau_3$) and ($\tau_4$) of twisting functions, we have \begin{align*} \phi_2[g|1] = \phi_2(s_1[g]) = & s_0(\phi_1[g]) = s_0(t(g)) = (t(g) \Left2{1} t(g)) \\ \phi_2[1|g] = \phi_2(s_0[g]) = & (\operatorname{Id}\nolimits \Left2{1} \operatorname{Id}\nolimits) \end{align*} Thus, $\eta(g,1) = 1 = \eta(1,g)$. To see that $t(1) = \operatorname{Id}\nolimits$, it is enough to apply property ($\tau2$) of twisting functions to the simplex $[1|1] \in \text{\bbfamily M}''_2$. \textbf{Step 2.} Property (b) of twisting pairs and the formulae (T1) and (T2). To check that property (b) holds, we have to show that $$ t(g)(\eta(h,k)) \cdot \eta(g,hk) = \eta(g,h) \cdot \eta(gh, k) $$ for all $[g|h|k] in \text{\bbfamily M}''_3$. Fix elements $[g|h|k] in \text{\bbfamily M}''_3$, and set $\phi_3[g|h|k] = (\alpha_0 \Left2{\eta_1} \alpha_1 \Left2{\eta_2} \alpha_2)$. Applying property ($\tau_1$) with $i = 3, 2$ respectively, we get \begin{align*} (t(g) \Left3{\eta(g,h)} t(gh) \circ t(h)^{-1}) & = (\alpha_0 \Left2{\eta_1} \alpha_1) \\ (t(g) \Left3{\eta(g, hk)} t(ghk) \circ t(hk)^{-1}) & = (\alpha_0 \Left2{\eta_1 \eta_2} \alpha_2)\\ \end{align*} Thus, $\phi_3[g|h|k] = (t(g) \Left3{\eta(g,h)} t(gh) \circ t(h)^{-1} \Left9{\eta(g,h)^{-1} \eta(g,hk)} t(ghk) \circ t(hk)^{-1})$. On the other hand, applying property ($\tau_2$) of twisting functions, together with (\ref{productdim1}), we get the following. \begin{align*} (\alpha_1 \Left2{\eta_2} \alpha_2) & = d_0(\phi_3[g|h|k]) = \phi_2[gh|k] \otimes \phi_2[h|k]^{-1} = \\ & = (t(gh) \Left3{\eta(gh,k)} t(ghk) \circ t(k)^{-1}) \otimes (t(h) \Left3{\eta(h,k)} t(hk) \circ t(k)^{-1})^{-1} = \\ & = (t(gh) \circ t(h)^{-1} \,\, \Left9{(t(gh) \circ t(h)^{-1})(\eta(h,k)^{-1}) \eta(gh,k)} \,\, t(ghk) \circ t(hk)^{-1}).\\ \end{align*} Note that $\eta(g,h)$ determines a homotopy $(t(g) \Left2{\eta(g,h)} t(gh) \circ t(h)^{-1})$, and in particular this means that $$ (t(gh) \circ t(h)^{-1})(y) = \eta(g,h)^{-1} \cdot t(g)(y) \cdot \eta(g,h) $$ for all $y \in \text{\bbfamily M}$. Combining this with the above description of $\phi_3[g|h|k]$, we deduce the following. \begin{align*} \eta(g,h)^{-1} \cdot \eta(g,hk) & = \eta_2 = (t(gh) \circ t(h)^{-1})(\eta(h,k)^{-1}) \eta(gh,k) = \\ & = \eta(g,h)^{-1} \cdot t(g)(\eta(h,k)^{-1}) \cdot \eta(g,h) \cdot \eta(gh,k). \end{align*} Property (b) of twisting pairs follows immediately. To finish the proof we have to show that $\phi_n[g_1|\ldots|g_n]$ is given by the formulae (T1) and (T2) above, and this is actually easily checked inductively by applying property ($\tau1$) with $i = n-1, n$ to $\phi_n[g_1|\ldots|g_n]$. \end{proof} \begin{rmk}\label{etagh} Notice that $\eta(g_1,g_2) \in N(\text{\bbfamily M})$ determines a homotopy from $\Psi_{g_1 g_2} \circ \Psi_{g_2}^{-1}$ to $\Psi_{g_1}$. By Lemma \ref{homotopies}, this implies the following equality for all $[x] \in \text{\bbfamily M}'$ $$ [(\Psi_{g_1} \circ \Psi_{g_2})(x)] = [\eta(g_1,g_2) \cdot \Psi_{g_1 g_2}(x) \cdot \eta(g_1,g_2)^{-1}] $$ This useful interpretation of the elements $\eta(g_1, g_2)$ will be tacitly applied from now on. \end{rmk} The simplex $\phi_n[g_1|\ldots|g_n]^{-1}$ plays a crucial role in the simplicial structure of a TCP and it is interesting to have an explicit formula for it. In the notation above we have \begin{equation}\label{twistingninv} \big(\phi_n[g_1|\ldots|g_n]\big)^{-1} = (\varphi_1^{-1} \Left6{\omega_{1,2}} \varphi_2^{-1} \Left6{\omega_{2,3}} \ldots \Left6{\omega_{n-1,n}} \varphi_n^{-1}), \end{equation} where $\omega_{1,2} = \varphi_1^{-1}(\eta(g_1,g_2)^{-1})$ and $\omega_{k, k+1} = \varphi_k^{-1}(\eta(g_1\ldots g_k, g_{k+1})^{-1}) \cdot \eta(g_2 \ldots g_k, g_{k+1})$ for every $k = 2, \ldots, n-1$. \begin{thm}\label{extension1} The category of partial groups is closed by fibre bundles. \end{thm} \begin{proof} We have to show that every fibre bundle of partial groups is again a partial group. By Theorem \ref{isocat} and by \cite[Proposition IV.3.2]{BGM}, it is enough to show that every RTCP of partial groups is a reduced $N$-simplicial set with inversion. Let $\text{\bbfamily M}'$ and $\text{\bbfamily M}''$ be partial groups, and let $X = (\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}'')$ be a RTCP. Note first that, since $\text{\bbfamily M}'$ and $\text{\bbfamily M}''$ are reduced, then so is $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$. Next let us check that the enumerating operator on $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ is injective for all $n$. Let $$ \omega_n = \big([y_1|\ldots|y_n],[g_1|\ldots|g_n] \big), $$ where $[y_1|\ldots|y_n] \in \text{\bbfamily M}'_n$ and $[g_1|\ldots|g_n] \in \text{\bbfamily M}''_n$, and recall that the enumerating operator $E_n$ is defined recursively as $E_1 = \operatorname{Id}\nolimits$ and $$ E_n \colon X_n \Right8{(F_1, d_0)} X_1 \times X_{n-1} \Right8{\operatorname{Id}\nolimits \times E_{n-1}} \underbrace{X_1 \times \ldots \times X_1}_{\mbox{$n$ times}}, $$ where $F_1 = d_2 \circ \ldots \circ d_n$. For $n = 1$, the enumerating operator is the identity, so there is nothing to check. For $n = 2$, we have $$ E_2(w_2) = \Big(([y_1],[g_1]), \big([\Psi_{g_1}^{-1}(y_2 \cdot \eta(g_1,g_2)^{-1})],[g_2]\big) \Big). $$ Describing $E_3$ will be enough to deduce the general case. Using Lemma \ref{twistingn} and the formula (\ref{twistingninv}), we have the following expression of $\phi_3[g_1|g_2|g_3]^{-1}$: $$ \xymatrix{ (\Psi_{g_1}^{-1} & & & \Psi_{g_2} \circ \Psi_{g_1g_2}^{-1} \ar[lll]_{\Psi_{g_1}^{-1}(\eta(g_1,g_2)^{-1})} & & & & & \Psi_{g_2g_3} \circ \Psi_{g_1g_2g_3}^{-1}), \ar[lllll]_{(\Psi_{g_2} \circ \Psi_{g_1g_2}^{-1})(\eta(g_1g_2,g_3)^{-1}) \cdot \eta(g_2,g_3)} } $$ from where we deduce the following, using formula (\ref{actionn}): $$ \phi_3[g_1|g_2|g_3]^{-1} \cdot [y_2|y_3] = [\Psi_{g_1}^{-1}(y_2 \cdot \eta(g_1,g_2)^{-1})|(\Psi_{g_2} \circ \Psi_{g_1g_2}^{-1})(y_3 \cdot \eta(g_1g_2,g_3)^{-1}) \cdot \eta(g_2,g_3)]. $$ Thus, given $\omega_3 = ([y_1|y_2|y_3], [g_1|g_2|g_3]) \in X_3$, the enumerating operator $E_3$ has the following effect: \small $$ \begin{aligned} E(\omega_3) & = \big((\operatorname{Id}\nolimits \times E_2) \circ (F_1, d_0)\big)(\omega_3) \\[4pt] & = (\operatorname{Id}\nolimits \times E_2)\bigg(\big([y_1], [g_1]\big), \big([\Psi_{g_1}^{-1}(y_2 \cdot \eta(g_1,g_2)^{-1})|(\Psi_{g_2} \circ \Psi_{g_1g_2}^{-1})(y_3 \cdot \eta(g_1g_2,g_3)^{-1}) \cdot \eta(g_2,g_3)], [g_2|g_3]\big) \bigg) \\[4pt] & = \Big(([y_1],[g_1])\, , \, ([\Psi_{g_1}^{-1}(y_2 \cdot \eta(g_1,g_2)^{-1})],[g_2])\, , \, ([\Psi_{g_1g_2}^{-1}(y_3 \cdot \eta(g_1g_2,g_3)^{-1})],[g_3]) \Big). \end{aligned} $$ \normalsize In general, the enumerating operator $E_n$ is given by the formula $$ E_n([y_1|\ldots|y_n],[g_1|\ldots|g_n]) = \Big(([z_1],[g_1]), ([z_2],[g_2]), \ldots, ([z_n],[g_n]) \Big), $$ where $z_1 = y_1$ and, for $k = 2, \ldots, n$, $z_k = \Psi_{g_1 \ldots g_{k-1}}^{-1}(y_k \cdot \eta(g_1 \ldots g_{k-1}, g_k)^{-1})$. It is clear now that $E_n$ is injective on $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$, since multiplication on the right by $\eta(g_1 \ldots g_{k-1}, g_k)^{-1}$ is a free action, and $\Psi_{g_1 \ldots g_{k-1}}^{-1}$ is an automorphism of partial groups. Finally, we have to check that $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ has an inversion. This follows immediately since the face operator $d_0$ is not involved in the definition of the product operator $\Pi$, and hence we can use the inversions on $\text{\bbfamily M}'$ and $\text{\bbfamily M}''$ to define an inversion on $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$. \end{proof} Let now $\text{\bbfamily M}', \text{\bbfamily M}''$ be partial groups, and let $\Gamma \leq \underline{\aut}(\text{\bbfamily M}')$. Let also $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ be a $\Gamma$-RTCP. We can define the associated \emph{outer action} of $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ by \begin{equation}\label{oaction} \xymatrix@R=1mm@C=15mm{ \varepsilon \colon \text{\bbfamily M}'' \ar[r] & \pi_0(\Gamma) \ar[r]^{\operatorname{incl}\nolimits_{\ast}} & \operatorname{Out}\nolimits(\text{\bbfamily M}')\\ [g] \ar@{|->}[rr] & & \overline{\phi[g]} } \end{equation} \begin{lmm} The map $\varepsilon$ in (\ref{oaction}) is a morphism of partial groups. \end{lmm} \begin{proof} This is immediate by definition. \end{proof} \begin{defi}\label{extBI} Let $\text{\bbfamily M}', \text{\bbfamily M}''$ be partial groups and let $\Gamma \leq \underline{\aut}(\text{\bbfamily M}')$. \begin{enumerate}[(i)] \item An \emph{outer action} of $\text{\bbfamily M}''$ on $\text{\bbfamily M}'$ is a morphism of partial groups $\varepsilon \colon \text{\bbfamily M}'' \to \operatorname{Out}\nolimits(\text{\bbfamily M}')$. \item Given a $\Gamma$-RTCP $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$, the \emph{associated outer action} is the morphism of partial groups $\varepsilon \colon \text{\bbfamily M}'' \to \operatorname{Out}\nolimits(\text{\bbfamily M}')$ defined in (\ref{oaction}). \item Let $\varepsilon \colon \text{\bbfamily M}'' \to \operatorname{Out}\nolimits(\text{\bbfamily M}')$ be an outer action that satisfies $$ \Im(\varepsilon) \subseteq \operatorname{incl}\nolimits_{\ast}(\pi_0(\Gamma)) \subseteq \pi_0(\underline{\aut}(\text{\bbfamily M}')) = \operatorname{Out}\nolimits(\text{\bbfamily M}'). $$ A \emph{$\Gamma$-extension of $\text{\bbfamily M}''$ by $\text{\bbfamily M}'$ with action $\varepsilon$}, or simply a $\Gamma$-extension of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$, is a $\Gamma$-RTCP $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ whose associated outer action is $\varepsilon$. \end{enumerate} \end{defi} Let $X = \text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ be a $\Gamma$-extension of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$. The partial group structure of $X$ is encrypted in the description of $X$ as an RTCP. For this reason, we now introduce a simplicial set $\text{\bbfamily M}$ which is strongly equivalent to $X$ and where the partial group structure is evident. \begin{prop}\label{TCP1} Let $X = \text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ be a $\Gamma$-extension of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$, where the twisting function $\phi$ is determined by $$ \big\{\phi[g] = \Psi_g \in \mathrm{Aut}(\text{\bbfamily M}')\big\}_{[g] \in \text{\bbfamily M}''} \qquad \mbox{and} \qquad \big\{\phi[g_1|g_2] = (\Psi_{g_1} \Left3{\eta(g_1,g_2)} \Psi_{g_1g_2} \circ \Psi_{g_2}^{-1})\big\}_{[g_1|g_2] \in \text{\bbfamily M}''}, $$ and by Lemma \ref{twistingn}. Let also $\text{\bbfamily M} = \{[(v_{\text{\bbfamily M}'}, v_{\text{\bbfamily M}''})]\} \coprod_{n \geq 1} \text{\bbfamily M}_n$, where, for each $n \geq 0$ the set $\text{\bbfamily M}_n$ is the collection of symbols $$ [(x_1,g_1)|(x_2,g_2)|\ldots|(x_n,g_n)] \in (\text{\bbfamily M}'_1 \times \text{\bbfamily M}''_1)^n, $$ subject to the following conditions \begin{enumerate}[(a)] \item $[x_1| \Psi_{g_1}(x_2) \cdot \eta(g_1,g_2)| \Psi_{g_1g_2}(x_3) \cdot \eta(g_1g_2,g_3)|\ldots |\Psi_{g_1\ldots g_{n-1}} (x_n) \cdot \eta(g_1\ldots g_{n-1},g_n)] \in \text{\bbfamily M}'_n$;\\[1pt] \item $[g_1|\ldots|g_n] \in \text{\bbfamily M}''_n$. \end{enumerate} Set also $s_0[(v_{\text{\bbfamily M}'}, v_{\text{\bbfamily M}''})] = [(1,1)]$ and, for each $n \geq 1$ and each $[(x_1,g_1)|\ldots|(x_n,g_n)] \in \text{\bbfamily M}_n$, set $$ d_i(w_n) = \left\{ \begin{array}{ll} [(x_2,g_2)|\ldots|(x_n,g_n)] & i = 0 \\[2pt] [(x_1,g_1)|\ldots |(x_i \cdot \Psi_{g_i}(x_{i+1}) \cdot \eta(g_i,g_{i+1}),g_i g_{i+1})| \ldots |(x_n,g_n)] & 1 \leq i \leq n-1 \\[2pt] [(x_1,g_1)|\ldots|(x_{n-1},g_{n-1})] & i = n \end{array} \right. $$ $$ s_i[(x_1,g_1)|(x_2,g_2)|\ldots|(x_n,g_n)] = [(x_1,g_1)|\ldots|(x_i,g_i)|(1,1)|(x_{i+1}, g_{i+1})|\ldots |(x_n,g_n)]. \phantom{AAA} $$ Finally, let $\tau \colon \text{\bbfamily M} \to \text{\bbfamily M}''$ be defined by $[(x_1,g_1)|(x_2,g_2)|\ldots|(x_n,g_n)] \mapsto [g_1|g_2|\ldots|g_n]$. Then, the following holds. \begin{enumerate}[(i)] \item $\text{\bbfamily M}$ is a simplicial set. \item $\tau \colon \text{\bbfamily M} \to \text{\bbfamily M}''$ is a $\Gamma$-bundle. \item $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ is strongly equivalent to $\tau \colon \text{\bbfamily M} \to \text{\bbfamily M}''$. \end{enumerate} In particular, $\text{\bbfamily M}$ is a partial group. \end{prop} \begin{proof} For each $n$ let $\alpha_n \colon \text{\bbfamily M}_n \to (\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}'')_n = \text{\bbfamily M}' \times \text{\bbfamily M}''$ be the map defined by $$ \begin{aligned} \alpha_n[(x_1,g_1)| & \ldots |(x_n,g_n)] =\\ & = \big([x_1| \Psi_{g_1}(x_2) \cdot \eta(g_1,g_2)| \ldots |\Psi_{g_1\ldots g_{n-1}} (x_n) \cdot \eta(g_1\ldots g_{n-1},g_n)] \, , \, [g_1|\ldots|g_n] \big). \end{aligned} $$ The maps $\alpha_n$ are clearly bijective for all $n$, and furthermore they are defined to commute with the simplicial operators on $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ and the operators $d_i$, $s_i$ defined above. This makes $\text{\bbfamily M}$ into a simplicial set. It is also clear that the map $\tau$is a $\Gamma$-fibre bundle, and it is strongly equivalent to $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ by construction. Since $X$ is a partial group, then so is $\text{\bbfamily M}$. \end{proof} The following is an alternative condition for (i) above. It will be useful in later sections. \begin{lmm}\label{alternativecond} Let $\text{\bbfamily M}', \text{\bbfamily M}''$ be partial groups and let $\Gamma \leq \underline{\aut}(\text{\bbfamily M}')$ be a subgroup. Let also $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ be a $\Gamma$-TCP, and let $[(x_1,g_1)], \ldots, [(x_n, g_n)] \in \text{\bbfamily M}'_1 \times \text{\bbfamily M}''_1$ be such that $[g_1|\ldots |g_n] \in \text{\bbfamily M}''_n$. Then, the following statements are equivalent. \begin{itemize} \item[(i)] $[x_1| \Psi_{g_1}(x_2) \cdot \eta(g_1,g_2)| \Psi_{g_1g_2}(x_3) \cdot \eta(g_1g_2,g_3)|\ldots |\Psi_{g_1\ldots g_{n-1}} (x_n) \cdot \eta(g_1\ldots g_{n-1},g_n)] \in \text{\bbfamily M}'_n$.\\[2pt] \item[(i')] $[x_1|\Psi_{g_1}(x_2)| (\Psi_{g_1} \circ \Psi_{g_2})(x_3)|\ldots |(\Psi_{g_1} \circ \ldots \Psi_{g_{n-1}})(x_n)] \in \text{\bbfamily M}'_n$. \end{itemize} \end{lmm} \begin{proof} This follows since $[\eta(g_1 \ldots g_k, g_{k+1})] \in N(\text{\bbfamily M})$ for all $k = 1, \ldots, n-1$ and because, by definition, $[\eta(g_1\ldots g_k, g_{k+1})]$ defines a homotopy from $\Psi_{g_1 \ldots g_{k+1}} \circ \Psi_{g_{k+1}}^{-1}$ to $\Psi_{g_1\ldots g_k}$. \end{proof} \begin{rmk}\label{represext} Let $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ and $\tau \colon \text{\bbfamily M} \to \text{\bbfamily M}''$ be as defined in Proposition \ref{TCP1}. The obvious inclusion of $\text{\bbfamily M}'$ into $\text{\bbfamily M}$, defined by $[x] \mapsto [(x,1)]$, is actually a map of simplicial sets, namely $\iota \colon \text{\bbfamily M}' \to \text{\bbfamily M}$. We will represent the extension $\text{\bbfamily M}' \times_{\phi} \text{\bbfamily M}''$ by $$ \text{\bbfamily M}' \Right4{\iota} \text{\bbfamily M} \Right4{\tau} \text{\bbfamily M}'', $$ with multiplication and inversion rules in $\text{\bbfamily M}$ given by the formulas \begin{equation}\label{prodext} \begin{array}{l} \Pi[(x_1,g_1)|(x_2,g_2)] = [(x_1 \cdot \Psi_{g_1}(x_2) \cdot \eta(g_1, g_2), g_1 \cdot g_2)] \\[2pt] \relax [(x,g)]^{-1} = [(\eta(g^{-1},g)^{-1} \cdot \Psi_{g^{-1}}(x^{-1}), g^{-1})]. \end{array} \end{equation} These generalize the usual multiplication and inversion formulae in group extensions, see \cite[Chapter IV]{MacLane} or \cite[Chapter IV]{Brown} for further details. \end{rmk} Finally, we describe the cohomological obstructions to the existence and uniqueness of extensions of partial groups (given some initial data). Unsurprisingly, the result generalizes the existing obstructions for existence and uniqueness of extensions of finite groups. Let us be more precise. Let $\text{\bbfamily M}', \text{\bbfamily M}''$ be partial groups, and let $\varepsilon \colon \text{\bbfamily M}'' \to \overline{\Gamma} \leq \operatorname{Out}\nolimits(\text{\bbfamily M}')$ be an outer action. Let also $\Gamma^{\ast} \leq \underline{\aut}(\text{\bbfamily M}')$ be the pre-image of $\overline{\Gamma}$, so $\pi_0(\Gamma^{\ast}) = \overline{\Gamma}$. With this initial data, we define obstructions to the existence and uniqueness of $\Gamma^{\ast}$-extensions of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$. Such obstructions are described as cohomology classes of the space $\text{\bbfamily M}''$ with \emph{local coefficients} in $Z(\text{\bbfamily M}')$. The precise description of the cohomology groups in Theorem \ref{classext} below is in \cite{DK2}, and the reader is referred to this source for further details. \begin{thm}\label{classext} Let $\text{\bbfamily M}', \text{\bbfamily M}''$ be partial groups, and let $\varepsilon\colon \text{\bbfamily M}'' \to \overline{\Gamma} \leq \operatorname{Out}\nolimits(\text{\bbfamily M}')$ be an outer action. Then, the following holds. \begin{enumerate}[(i)] \item There is an obstruction class $[\kappa] \in H^3(\text{\bbfamily M}'';Z(\text{\bbfamily M}'))$ to the existence of $\Gamma^{\ast}$-extensions of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$: such extensions exist if and only if the class $[\kappa] = 0$. \item If there is any, the set of isomorphism classes of $\Gamma^{\ast}$-extensions of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$ is in one-to-one correspondence with the set $H^2(\text{\bbfamily M}'';Z(\text{\bbfamily M}'))$. \end{enumerate} \end{thm} \begin{proof} By \cite[\S 5]{BGM}, existence and uniqueness of $\Gamma^{\ast}$-extensions of $(\text{\bbfamily M}', \text{\bbfamily M}'', \varepsilon)$ correspond to existence and uniqueness of liftings of the induced map $\text{\bbfamily M}'' \to B\overline{\Gamma} \leq B\operatorname{Out}\nolimits(\text{\bbfamily M}')$ to $B\Gamma^{\ast} \subseteq B\underline{\aut}(\text{\bbfamily M}')$: each lifting $$ \widetilde{\varepsilon} \colon \text{\bbfamily M}'' \Right3{} B \Gamma^{\ast} \subseteq B \underline{\aut}(\text{\bbfamily M}') $$ corresponds to an isomorphism class of such extensions. Now, by Theorem \ref{autX} and by definition of $\Gamma^{\ast}$, there is a fibration $B^2Z(\text{\bbfamily M}') \to B\Gamma^{\ast} \to B\operatorname{Out}\nolimits(\text{\bbfamily M}')$, and the proof is finished by classical obstruction theory \cite{DK2}. \end{proof} \begin{rmk} Let $(\text{\bbfamily L}', \Delta', S')$ be a locality and let $\overline{\Gamma} = \operatorname{Out}\nolimits(\text{\bbfamily L}';S') \leq \operatorname{Out}\nolimits(\text{\bbfamily L}')$. Then it follows from Lemma \ref{autloc0} that $\Gamma^{\ast} = \underline{\aut}(\text{\bbfamily L}';S')$. \end{rmk} Let us briefly discuss the classification of extensions of partial groups attained in Theorem \ref{classext}. The reader should keep in mind that we have not defined (and we shall not in this paper) modules of partial groups, which should be the first step towards developing homological algebra for partial groups. The idea behind the proof of Theorem \ref{classext} is to construct the twisting function $\{\phi_n \colon \text{\bbfamily M}''_n \to \Gamma^{\ast} \leq \underline{\aut}_{n-1}(\text{\bbfamily M}')\}$ directly out of $\varepsilon$, by choosing liftings of the elements $\varepsilon[g]$ in $\mathrm{Aut}(\text{\bbfamily M}')$, and then proceeding to higher dimensions. Filling in the gaps in this idea would lead to ``group theoretical'' obstructions to the existence and uniqueness of extensions of partial groups, as done in \cite[Chapter IV]{MacLane} or \cite[Chapter IV]{Brown} for extensions of groups (more exactly, this way one would construct cocycles in the cochain complex for the simplicial set $\text{\bbfamily M}''$ with local coefficients in the abelian group $Z(\text{\bbfamily M}')$, which produce the desired obstructons). This is an outline of the process that the interested reader should follow. \begin{enumerate} \item Starting from $\varepsilon$, one may choose a representative $\Psi_g \in \mathrm{Aut}(\text{\bbfamily M}')$ for each $[g] \in \text{\bbfamily M}''_1$ (in particular, choose $\Psi_1 = \operatorname{Id}\nolimits$). \item The above choices are random, and so in general the equality $\Psi_g \circ \Psi_{h} = \Psi_{gh}$ does not hold. However, for each word $[g|h] \in \text{\bbfamily M}''_2$ the exact sequence of Theorem \ref{autX} (iii) implies the existence of some $\eta(g,h) \in N(\text{\bbfamily M})$ such that $$ \Psi_g \circ \Psi_{h} = c_{\eta(g,h)} \circ \Psi_{gh}. $$ Since $\Psi_1 = \operatorname{Id}\nolimits$, one may choose $\eta(g,1) = 1 = \eta(1,g)$ for all $[g] \in \text{\bbfamily M}''_1$. \item Using the above choices, one may define $\text{\bbfamily M}$ as in Proposition \ref{TCP1} and a multiplication using the formula (\ref{prodext}). This done, one has to check that this multiplication is associative (associativity only needs to be checked on the elements of $\text{\bbfamily L}''_3$), and this produces the class $[\kappa]$ of Theorem \ref{classext} (i). \item The vanishing of the class $[\kappa]$ in the previous step implies associativity of the product defined by the formula (\ref{prodext}). To check part (ii) of Theorem \ref{classext} from this group theoretical point of view, one just has to check that modifying the choices in steps (1) and (2) by a $2$-dimensional cocycle produces a different multiplication rule (and hence a different extension). \end{enumerate} \section{Extensions of localities}\label{isoext} We focus our study on extensions of saturated localities, our goal being to give conditions for such an extension to give rise to a new saturated locality. In order to give a clear introduction to this section, let $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ be (saturated) localities, and let $\varepsilon \colon \text{\bbfamily L}'' \to \operatorname{Out}\nolimits(\text{\bbfamily L}')$ be an outer action. Let also $$ \text{\bbfamily L}' \Right3{} X \Right3{\tau} \text{\bbfamily L}'' $$ be an extension of $(\text{\bbfamily L}', \text{\bbfamily L}'', \varepsilon)$. Ultimately, we want conditions for $X$ to be equivalent to the classifying space of a $p$-local finite group (up to $p$-completion). Given such an extension, one should not expect $X$ to be a locality in general, although we show some examples where this is the case. \subsection{Isotypical extension of localities} In order to achieve our goals for this section, we start with a rather more general setup, in which we do not require any locality to be saturated. This way we are able to prove some general results which we later specialize to saturated localities. Intuitively, it is necessary to put some conditions on such an extension for the locality structures to play any role. \begin{defi} Let $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ be localities. An extension of $\text{\bbfamily L}''$ by $\text{\bbfamily L}'$ is \emph{isotypical} if the following conditions hold: \begin{enumerate}[(i)] \item the action $\varepsilon \colon \text{\bbfamily L}'' \to \operatorname{Out}\nolimits(\text{\bbfamily L}')$ factors through $\operatorname{Out}\nolimits(\text{\bbfamily L}';S') \leq \operatorname{Out}\nolimits(\text{\bbfamily L}')$; and \item $\Delta'$ is $\mathrm{Aut}(\text{\bbfamily L}';S')$-invariant, i.e. $\Psi(P) \in \Delta'$ for all $P \in \Delta'$ and all $\Psi \in \mathrm{Aut}(\text{\bbfamily L}';S')$. \end{enumerate} \end{defi} Thus, roughly speaking an isotypical extension of $(\text{\bbfamily L}'', \Delta'', S'')$ by $(\text{\bbfamily L}', \Delta', S')$ is an $\underline{\aut}(\text{\bbfamily L}';S')$-bundle over $\text{\bbfamily L}''$, and with fibre $\text{\bbfamily L}'$. \begin{hyp}\label{hyp1} Fix an isotypical extension $\text{\bbfamily L}' \Right1{} \text{\bbfamily L} \Right1{\tau} \text{\bbfamily L}''$, where \begin{enumerate}[(a)] \item $(\text{\bbfamily L}', \Delta', S')$ is a locality, with associated fusion system $\mathcal{F}' = \mathcal{F}_{\Delta'}(\text{\bbfamily L}')$. \item $(\text{\bbfamily L}'', \Delta'', S'')$ is a locality, with associated fusion system $\mathcal{F}'' = \mathcal{F}_{\Delta''}(\text{\bbfamily L}'')$. \end{enumerate} The above extension is determined by some twisting function $\{\phi_n \colon \text{\bbfamily L}''_n \to (\underline{\aut})_{n-1}(\text{\bbfamily L}';S')\}$, which in turn is determined by the data $$ \{\Psi_g \in \mathrm{Aut}(\text{\bbfamily L}';S') \,\, \big| \,\, [g] \in \text{\bbfamily L}''_1\} \qquad \mbox{and} \qquad \{[\eta(g,h)] \in N_{\text{\bbfamily L}'}(S') \,\, \big| \,\, [g|h] \in \text{\bbfamily L}''_2\}, $$ satisfying the following conditions (see Lemma \ref{twistingn}) \begin{enumerate}[(1)] \item $\overline{\Psi_g} = \varepsilon[g]$ for all $[g] \in \text{\bbfamily L}''_1$; \item $\Psi_1 = \operatorname{Id}\nolimits$ and $\eta(1,h) = [(1,1)] = \eta(g,1)$ for all $[g], [h] \in \text{\bbfamily L}''_1$; \item $[\eta(g,h) \cdot \Psi_{gh}(x) \cdot \eta(g,h)^{-1}] = [(\Psi_g \circ \Psi_h)(x)]$ for all $[g|h] \in \text{\bbfamily L}''_2$ and all $[x] \in \text{\bbfamily L}'_1$; and \item $[\Psi_g(\eta(h,k)) \cdot \eta(g, hk)] = [\eta(g,h) \cdot \eta(gh, k)]$ for all $[g|h|k] \in \text{\bbfamily L}''_3$. \end{enumerate} We will consider these choices fixed, in case we have to perform explicit calculations with elements in $\text{\bbfamily L}$. Notice that the fusion systems $\mathcal{F}'$ and $\mathcal{F}''$ are not assumed to be saturated. \end{hyp} \begin{lmm}\label{propext1} The partial group $\text{\bbfamily L}$ contains a $p$-subgroup $S \leq \text{\bbfamily L}$ which makes the following diagram of extensions commutative $$ \xymatrix{ BS' \ar[rr]^{\iota} \ar[d]_{\operatorname{incl}\nolimits} & & BS \ar[rr]^{\tau} \ar[d]_{\operatorname{incl}\nolimits} & & BS'' \ar[d]^{\operatorname{incl}\nolimits} \\ \text{\bbfamily L}' \ar[rr]_{\iota} & & \text{\bbfamily L} \ar[rr]_{\tau} & & \text{\bbfamily L}'' } $$ In particular, $S$ is maximal in the poset of $p$-subgroups of $\text{\bbfamily L}$. \end{lmm} \begin{proof} Write $N' = N_{\text{\bbfamily L}'}(S')$ and $N'' = N_{\text{\bbfamily L}''}(S'')$ for short, which are finite groups since $S' \in \Delta'$ and $S'' \in \Delta''$, and let $N = \{[(x,g)] \in \text{\bbfamily L} \, | \, [x] \in N' \mbox{ and } [g] \in N''\}$. We claim that $N$ is a (finite) subgroup of $\text{\bbfamily L}$. To prove the claim we have to check that $[(x_1,g_1)|\ldots|(x_n,g_n)] \in \text{\bbfamily L}$ for every sequence $[(x_1,g_1)], \ldots, [(x_n,g_n)] \in N$. Since the subgroup $N' \leq \text{\bbfamily L}'$ is invariant under the action of $\mathrm{Aut}(\text{\bbfamily L}';S')$, it follows that $[x_1|\Psi_{g_1}(x_2)|\ldots|(\Psi_{g_1} \circ \ldots \circ \Psi_{g_{n-1}})(x_n)] \in BN' \leq \text{\bbfamily L}'$. Also, $[g_1|\ldots|g_n] \in BN'' \leq \text{\bbfamily L}''$, since $N''$ is a group. By Lemma \ref{alternativecond} this means that $[(x_1,g_1)|\ldots|(x_n,g_n)] \in \text{\bbfamily L}$, and thus $N'$ is a group. It is clear now that $N$ is an extension of $N''$ by $N'$, and there is a commutative diagram of extensions $$ \xymatrix{ BN' \ar[r] \ar[d] & BN \ar[r] \ar[d] & BN'' \ar[d] \\ \text{\bbfamily L}' \ar[r] & \text{\bbfamily L} \ar[r] & \text{\bbfamily L}'' \\ } $$ In particular, $N$ has Sylow $p$-subgroups, and we may choose $S \in \operatorname{Syl}\nolimits_p(N)$ completing the diagram in the statement. \end{proof} Fix a choice of a subgroup $S \leq \text{\bbfamily L}$ satisfying the properties described in Lemma \ref{propext1}. For a subgroup $P \leq S$, we use the following notation: $P' \stackrel{def} = P \cap S' \leq S'$ and $P'' \stackrel{def} = \tau(P) \leq S''$. Fix also the collection \begin{equation}\label{collectionS} \Delta = \{P \leq S \,\, \big| \,\, P' = P \cap S' \in \Delta' \mbox{ and } P'' = \tau(P) \in \Delta''\}. \end{equation} Notice that $\Delta$ depends heavily on the choices of $\Delta'$ and $\Delta''$ (and these choices are usually not unique!). \begin{rmk}\label{prodHi} Let $[(x,g)] \in \text{\bbfamily L}$, and let $L_{[(x,g)]} \leq S$ be the biggest subgroup of $S$ that is left conjugated by $[(x,g)]$ to a subgroup of $S$ (notice that we do not know whether $(\text{\bbfamily L}, \Delta, S)$ is a locality or not, and thus we cannot use the definition in (\ref{SwSu0})). This means that, for each $[(y,h)] \in L_{[(x,g)]}$, we have $u = [(x,g)|(y,h)|(x,g)^{-1}] \in \text{\bbfamily L}$ and $\Pi(u) \in S$. More specifically, we have $$ \begin{aligned} \Pi(u) & = \Pi\big[(x, g)|(y, h)|(\eta(g^{-1}, g)^{-1} \cdot \Psi_{g^{-1}}(x^{-1}), g^{-1})\big] = \\[4pt] & = \Pi\big[(x \cdot \Psi_{g}(y) \cdot \eta(g, h), g \cdot h)|(\eta(g^{-1}, g)^{-1} \cdot \Psi_{g^{-1}}(x^{-1}), g^{-1})\big] = \\[4pt] & = \big[(x \cdot \Psi_{g}(y) \cdot \eta(g, h) \cdot \Psi_{g h}(\eta(g^{-1}, g)^{-1}) \cdot \Psi_{g h}(\Psi_{g^{-1}}(x^{-1})) \cdot \eta(gh, g^{-1}), g \cdot h \cdot g^{-1}) \big] = \\[4pt] & = \big[(x \cdot \Psi_{g}(y) \cdot \eta(g, h) \cdot \eta(ghg^{-1}, g) \cdot (\9{ \eta(gh, g^{-1})^{-1}}((\Psi_{gh} \circ \Psi_{g^{-1}})(x^{-1}))), g \cdot h \cdot g^{-1})\big] = \\[4pt] & = \big[(x \cdot \Psi_{g}(y) \cdot \eta(g, h) \cdot \eta(ghg^{-1}, g) \cdot \Psi_{ghg^{-1}}(x^{-1}), g \cdot h \cdot g^{-1})\big], \end{aligned} $$ where the equality between lines three and four follows by an application of the cocycle formula (\ref{coboundary2}), and the equality between lines four and five follows from property (2) in Hypothesis \ref{hyp1}. In particular, if $[(y,h)] \in S'$, then $h = 1$ and the above formula implies that $$ \Pi[(x, g)|(y, 1)|(x, g)^{-1}] = [(x \cdot \Psi_{g}(y) \cdot x^{-1}, 1)]. $$ \end{rmk} We start by analyzing the triple $(\text{\bbfamily L}, \Delta, S)$. As we show below, this is not a locality in general, but it is rather close from being one. This requires the application of the formulae (\ref{prodext}), and the cocycle condition (\ref{coboundary2}), which we use without any further mention. Let $\mathbb{W}} %before it was \operatorname{W(\text{\bbfamily L}_1)$ be the free monoid on $\text{\bbfamily L}_1$. To simplify the notation, we denote the words in $\mathbb{W}} %before it was \operatorname{W(\text{\bbfamily L}_1)$ by $[(x_1, g_1)| \ldots| (x_n,g_n)]$. Let $\mathbb{D}} %before it was \operatorname{D_{\Delta}$ be the collection of words $\omega = [(x_1, g_1)| \ldots| (x_n,g_n)] \in \mathbb{W}} %before it was \operatorname{W(\text{\bbfamily L}_1)$ for which there exists $H_0, \ldots, H_n \in \Delta$ such that $\9{(x_i, g_i)}H_i = H_{i-1}$ for all $i = 1, \ldots, n$ (note that this is equivalent to the definition in \ref{opgroup}). \begin{prop}\label{propext3} The collection $\Delta$ defined in (\ref{collectionS}) satisfies the following properties: \begin{enumerate}[(i)] \item $S \in \Delta$; \item $(\text{\bbfamily L}, \Delta)$ satisfies condition (O2) of objective partial groups; \item there is an inclusion $\mathbb{D}} %before it was \operatorname{D_{\Delta} \subseteq \text{\bbfamily L}$. \end{enumerate} \end{prop} \begin{proof} Property (i) is immediate by definition of $S$ and $\Delta$. To prove property (ii), note that $\Delta$ is clearly closed by overgroups, and we have to show that if $K \in \Delta$ and $[(x,g)] \in \text{\bbfamily L}$ are such that $\9{(x,g)}K = H \leq S$, then $H \in \Delta$. By definition of $\Delta$, we need to check that $H' \in \Delta'$ and $H'' \in \Delta''$. Note that $H'' = [g] \cdot K'' \cdot [g^{-1}] \leq S''$, and thus $H'' \in \Delta''$ since $(\text{\bbfamily L}'', \Delta'', S'')$ is a locality. Regarding $H'$, the conjugation formula in Remark \ref{prodHi} implies that $$ H' = [x] \cdot \Psi_g(K') \cdot [x^{-1}]. $$ Since $K' \in \Delta'$ and every isotypical automorphism of $\text{\bbfamily L}'$ preserves $\Delta'$, it follows that $\Psi_g(K') \in \Delta'$, and it follows that $H' \in \Delta$ since $(\text{\bbfamily L}', \Delta', S')$ is a locality and $\Delta'$ is closed by conjugation. To prove property (iii), let $\omega = [(x_1, g_1)| \ldots| (x_n,g_n)] \in \mathbb{D}} %before it was \operatorname{D_{\Delta}$, via the sequence $H_0, \ldots, H_n \in \Delta$, so $\9{[(x_i,g_i)]}H_i = H_{i-1}$ for $i = 1, \ldots, n$. In particular, for each $i$ and each $[(y_i, h_i)] \in H_i$ we have $\omega_i = [(x_i, g_i)|(y_i, h_i)|(x_i, g_i)^{-1}] \in \text{\bbfamily L}$ and $\Pi(\omega_i) \in H_{i-1}$. By Lemma \ref{alternativecond}, in order to show that $\omega \in \text{\bbfamily L}$ we have to check that \begin{enumerate}[(1)] \item $\omega'' = [g_1|\ldots|g_n] \in \text{\bbfamily L}''$; and \item $\omega' = [x_1|\Psi_{g_1}(x_2)|(\Psi_{g_1} \circ \Psi_{g_2})(x_3)|\ldots |(\Psi_{g_1} \circ \ldots \Psi_{g_{n-1}})(x_n)] \in \text{\bbfamily L}'$. \end{enumerate} Since $(\text{\bbfamily L}'', \Delta'', S'')$ is a locality, we see that $\omega'' \in \text{\bbfamily L}''$ via the sequence $H_0'', \ldots, H_n'' \in \Delta''$. To check that $\omega' \in \text{\bbfamily L}'$, use the formula in Remark \ref{prodHi} above: we see that $\omega'$ conjugates the sequence $H_0', \Psi_{g_1}(H_1'), (\Psi_{g_1} \circ \Psi_{g_2})(H_2'), \ldots, (\Psi_{g_1} \circ \ldots \Psi_{g_n})(H_n') \in \Delta'$. Since $(\text{\bbfamily L}', \Delta', S')$ is a locality, it follows that $\omega' \in \text{\bbfamily L}'$. \end{proof} The partial group $\text{\bbfamily L}$ determines a locality as follows. Recall that $\mathbb{D}} %before it was \operatorname{D_{\Delta} \subseteq \text{\bbfamily L}$ by Proposition \ref{propext3}, where $\mathbb{D}} %before it was \operatorname{D_{\Delta}$ is the set of all words $\omega \in \mathbb{W}} %before it was \operatorname{W(\text{\bbfamily L}_1)$ that conjugate a sequence in $\Delta$. \begin{prop}\label{propext3-1} Set $\text{\bbfamily T} = \mathbb{D}} %before it was \operatorname{D_{\Delta}$. Then, the triple $(\text{\bbfamily T}, \Delta, S)$ is a locality. \end{prop} \begin{proof} It is clear that $S \leq \text{\bbfamily T}$. Let $\omega = [(x_1, g_1)|\ldots|(x_n,g_n)] \in \text{\bbfamily T}$. By definition of $\text{\bbfamily T}$, there is a sequence $H_0, \ldots, H_ n \in \Delta$ such that $\9{[(x_i,g_i)]}H_i = H_{i-1}$ for each $i = 1, \ldots, n$. Clearly, it follows that $\9{\Pi(\omega)}H_n = H_0$, so $\text{\bbfamily T}$ is closed by products, and we can see that $\text{\bbfamily T}$ is closed by inversion since we have $\9{[(x_i,g_i)]^{-1}}H_{i-1} = H_i$ for each $i = 1, \ldots, n$. This shows that $\text{\bbfamily T}$ is a partial group, with multiplication and inversion induced by those in $\text{\bbfamily L}$. Let us prove now that $(\text{\bbfamily T}, \Delta, S)$ is a locality. Since $S$ is maximal in $\text{\bbfamily L}$, it must be maximal in $\text{\bbfamily T}$ too. We have to check that $(\text{\bbfamily T}, \Delta)$ is an objective partial group, where $\Delta$ is the collection defined in (\ref{collectionS}). Note that $\Delta$ is closed by overgroups and conjugation in $\text{\bbfamily T}$ since the same holds with respect to $\text{\bbfamily L}$ by Proposition \ref{propext3} (ii). Thus, $(\text{\bbfamily T}, \Delta)$ satisfies condition (O2) of objective partial groups. Let $\mathbb{D}} %before it was \operatorname{D'_{\Delta} \subseteq \mathbb{W}} %before it was \operatorname{W(\text{\bbfamily T}_1)$ be the subset of all words $[(x_1,g_1)|\ldots|(x_n,g_n)]$ for which there exists some sequence $H_0, \ldots, H_ n \in \Delta$ such that $\9{[(x_i,g_i)]}H_i = H_{i-1}$ for each $i = 1, \ldots, n$. We have to check that $\mathbb{D}} %before it was \operatorname{D'_{\Delta} = \text{\bbfamily T}$, and this is immediate by definition of $\text{\bbfamily T}$. \end{proof} \begin{cor}\label{propext3-2} The subgroup $S' \leq S$ is strongly closed in the fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$. \end{cor} \begin{proof} This follows immediately from the conjugation formula in Remark \ref{prodHi}. \end{proof} The locality $(\text{\bbfamily T}, \Delta, S)$ will play an important role in the next subsections, where we analyze its relation to $\text{\bbfamily L}$. \subsection{Examples of isotypical extensions}\label{Sexpl} We now present some examples of isotypical extensions, all of which produce localities. These examples have already been studied in the context of $p$-local finite groups, in \cite{OV} and in \cite{BCGLO2} respectively. Among other reasons, we include these examples here to show that our results and constructions are independent from the aforementioned papers. Let us start by analyzing isotypical extensions where the fibre is a $p$-group. This situation was first studied in \cite{OV}(in the context of transporter systems), where the authors showed (among other results) that every extension of a transporter system by a $p$-group is again a transporter system, and the reader is referred to this paper for further details. \begin{expl}\label{explOV} Let $\text{\bbfamily L}'$ be a finite $p$-group. In other words, $\text{\bbfamily L}'_1 = S'$, and $\text{\bbfamily L}' = BS'$. Let $\Delta' = \{S'\}$. Then $(BS', \Delta', S')$ is a proper locality. In this example we show that an isotypical extension of a locality $(\text{\bbfamily L}'', \Delta'', S'')$ by $(BS', \Delta', S')$ always gives rise to a locality. More specifically, fix such an extension $BS' \to \text{\bbfamily L} \to \text{\bbfamily L}''$, and let $(\text{\bbfamily T}, \Delta, S)$ be the locality associated to the extension, as shown in Proposition \ref{propext3-1}. We show that $\text{\bbfamily T} = \text{\bbfamily L}$. By Propositions \ref{propext3} and \ref{propext3-1}, we only have to show that $\text{\bbfamily L} \subseteq \text{\bbfamily T} ( = \mathbb{D}} %before it was \operatorname{D_{\Delta})$. In other words, given $[(x_1, g_1)|\ldots|(x_n,g_n)] \in \text{\bbfamily L}$, we have to find a sequence of subgroups $H_0, \ldots, H_n \in \Delta$ such that $\9{[(x_i,g_i)]}H_i = H_{i-1}$ for all $i = 1, \ldots, n$. Since $(\text{\bbfamily L}'', \Delta'', S'')$ is a locality, we have $[g_1|\ldots|g_n] \in \text{\bbfamily L}''$ via a sequence $P_0'', \ldots, P_n'' \in \Delta''$, and now an easy calculation shows that it is enough to take $H_i$ to be the pull-back of $S \Right2{} S'' \Left2{} P_i''$ for $i = 0, \ldots, n$. Notice that the fusion system of any such extension need not be saturated. In \cite{OV} the authors give an example of an extension of a transporter system by a $p$-group whose associated fusion system is not saturated (see right after \cite[Proposition 5.8]{OV}), and this same example applies here. We will not analyze the question of saturation of these extensions here. Rather than that, we leave this for a later subsection. \end{expl} Next we consider isotypical extensions where the base is a finite group. These extensions were analyzed in \cite{BCGLO2} (in the context of $p$-local finite groups). Here, we consider a more general situation, in which no saturation is assumed. This example in particular will play an important role in the forthcoming subsections. \begin{expl}\label{particular1} Let $\text{\bbfamily L}''$ be a finite group, so $\text{\bbfamily L}_1'' = G$, and $\text{\bbfamily L}'' = BG$. Fix some $S'' \in \operatorname{Syl}\nolimits_p(G)$, and let $\Delta''$ be the collection of all subgroups of $S''$. Then $(BG, \Delta'', S'')$ is a locality (not necessarily proper). Let $(\text{\bbfamily L}', \Delta', S')$ be a locality, and fix an isotypical extension $\text{\bbfamily L}' \to \text{\bbfamily L} \to BG$. Again, let $(\text{\bbfamily T}, \Delta, S)$ be the locality associated to the extension, as in Proposition \ref{propext3-1}. We show that $\text{\bbfamily T} = \text{\bbfamily L}$. As happened in the previous examples, by Propositions \ref{propext3} and \ref{propext3-1} we only have to show that for every simplex $\omega = [(x_1,g_1)|\ldots|(x_n,g_n)] \in \text{\bbfamily L}$ there is some sequence $H_0, \ldots, H_n \in \Delta$ such that $\9{[(x_i,g_i)]}H_i = H_{i-1}$ for each $i = 1, \ldots, n$. By Proposition \ref{TCP1} and Lemma \ref{alternativecond}, we know that $\omega \in \text{\bbfamily L}$ if and only if \begin{enumerate}[(i)] \item $[g_1|\ldots|g_n] \in \text{\bbfamily L}''_n$; and\\[2pt] \item $\omega' = [x_1|\Psi_{g_1}(x_2)|(\Psi_{g_1} \circ \Psi_{g_2})(x_3)|\ldots|(\Psi_{g_1} \circ \ldots \circ \Psi_{g_{n-1}})(x_n)] \in \text{\bbfamily L}'_n$. \end{enumerate} Set $y_1 = x_1$ and $y_i = (\Psi_{g_1} \circ \ldots \Psi_{g_{i-1}})(x_i)$ for $i = 2, \ldots, n$ for short, so $\omega' = [y_1|\ldots|y_n]$. Since $(\text{\bbfamily L}', \Delta', S')$ is a locality, the word $\omega'$ conjugates some sequence of subgroups $K'_0, \ldots, K'_n \in \Delta'$. That is, $\9{[y_i]}(K_i') = K_{i-1}'$ for each $i = 1, \ldots, n$. Set $H'_0 = K'_0$ and $H'_i = (\Psi_{g_1} \circ \ldots \circ \Psi_{g_i})^{-1}(K'_i)$ for $i = 1, \ldots, n$. Then, $H'_i \in \Delta' \subseteq \Delta$ since every isotypical automorphism of $\text{\bbfamily L}'$ preserves $\Delta'$. Moreover, it follows that $\omega \in \mathbb{D}} %before it was \operatorname{D_{\Delta}$ since we have $\9{[(x_i,g_i)]}(H'_i) = H'_{i-1}$ for each $i$ (the reader can compare this with the conjugation formula in Remark \ref{prodHi}). \end{expl} We finish this subsection by studying saturation in the example above. We choose to do this in this section since this example will be crucial later on in this section. \begin{cor}\label{particular2} Let $G$ be a finite group, and let $\text{\bbfamily L}' \to \text{\bbfamily L} \to BG$ be an isotypical extension, where \begin{enumerate}[(i)] \item $(\text{\bbfamily L}', \Delta', S')$ is a saturated locality such that $\Delta'$ contains all the $\mathcal{F}'$-centric subgroups of $S'$; and \item $(BG, \Delta'', S'')$ is a locality, with $S'' \in \operatorname{Syl}\nolimits_p(G)$ and $\Delta'' = \{P'' \leq S''\}$. \end{enumerate} Let also $(\text{\bbfamily L}, \Delta, S)$ be the locality structure described in Example \ref{particular1}, and let $\mathcal{F} = \mathcal{F}_{\Delta}(\text{\bbfamily L})$ be the associated fusion category. Then, $\Delta$ contains all the $\mathcal{F}$-centric $\mathcal{F}$-radical subgroups, and in particular $\mathcal{F}$ is a saturated fusion system over $S$. \end{cor} \begin{proof} Suppose otherwise that $\Delta$ does not contain all the $\mathcal{F}$-centric $\mathcal{F}$-radical subgroups of $S$, and let $P \notin \Delta$ be an $\mathcal{F}$-centric $\mathcal{F}$-radical subgroup of $S$. By definition of $\Delta$, this means that $P' = P \cap S' \notin \Delta'$, so in particular $P'$ is not $\mathcal{F}'$-centric. We can choose $P$ to be of maximal order among those $\mathcal{F}$-centric $\mathcal{F}$-radical subgroups not in $\Delta$. Thus we may assume as well that the saturation axioms hold in $\mathcal{F}$ for all subgroups $R \leq S$ such that $|P| < |R|$. First we prove the following claim \begin{itemize} \item[(\textasteriskcentered)] There is some $Q \in P^{\mathcal{F}}$ such that $Q'$ is fully $\mathcal{F}'$-normalized. \end{itemize} Clearly, we may assume that $P'$ is not fully $\mathcal{F}'$-normalized (in particular $P' \lneqq S'$), since otherwise there is nothing to show. Set $P_0' = P'$, and let $P_1' \leq S'$ be $\mathcal{F}'$-conjugate to $P_0'$ and fully $\mathcal{F}'$-normalized. Let also $\rho \in \operatorname{Hom}\nolimits_{\mathcal{F}'}(N_{S'}(P_0'), N_{S'}(P_1'))$ be such that $\rho(P_0') = P_1'$. Since $P_0' \lneqq S'$, we also have $P_0' \lneqq N_{S'}(P_0')$, and the saturation axioms in $\mathcal{F}$ hold for $N_{S'}(P_0')$ and $N_{S'}(P_1')$. Set now $R_0' = N_{S'}(P_0')$ and $K_0 = \{f \in \mathrm{Aut}(R_0') \,\, | \,\, f(P_0') = P_0'\}$, and recall from \cite[Appendix \S A]{BLO2} the notation $$ N_S^{K_0}(R_0') = \{x \in N_{S'}(R_0') \,\, | \,\, c_x \in K_0\}. $$ Let also $R_1' = \rho(R_0') \leq N_{S'}(P_1')$ and $K_1 = \{\rho \circ f \circ \rho^{-1} \,\, | \,\, f \in K_0\}$. Finally, let $R_2' \leq S'$ and $\gamma \in \operatorname{Iso}\nolimits_{\mathcal{F}}(R_0', R_2')$ be such that $R_2'$ is fully $K_2$-normalized in $\mathcal{F}$, where $$ K_2 = \{\gamma \circ f \circ \gamma^{-1} \,\, | \,\, f \in K_0\}. $$ Set also $P_2' = \gamma(P_0')$. By \cite[Proposition A.2 (b)]{BLO2} there exist $\chi, \chi' \in \mathrm{Aut}_{\mathcal{F}}^{K_2}(R_2')$ and morphisms $$ \alpha \in \operatorname{Hom}\nolimits_{\mathcal{F}}(N_S^{K_0}(R_0'), N_S^{K_2}(R_2')) \qquad \beta \in \operatorname{Hom}\nolimits_{\mathcal{F}}(N_S^{K_1}(R_1'), N_S^{K_2}(R_2')) $$ such that $\alpha|_{R_0'} = \chi \circ \gamma$ and $\beta|_{R_1'} = \chi' \circ \gamma \circ \rho^{-1}$. We claim that there is a sequence of inequalities $$ |N_{S'}(P_0')| \lneqq |N_{S'}^{K_1}(R_1')| \leq |N_{S'}^{K_2}(R_2')| \leq |N_{S'}(P_2'')|. $$ Indeed, since $P_0'$ is not fully $\mathcal{F}'$-normalized, we have $R_1' = \rho(N_{S'}(P_0')) \lneqq N_{S'}(P_1')$, and thus $$ R_1' \lneqq N_{N_{S'}(P_1')}(R_1') = N_{S'}^{K_1}(R_1'). $$ This proves the leftmost inequality. The middle inequality holds immediately since $\beta$ restricts to an inclusion of $N_{S'}^{K_1}(R_1')$ into $N_{S'}^{K_2}(R_2')$. Finally, the rightmost inequality holds since every element in $N_{S'}^{K_2}(R_2')$ normalizes $P_2'$ by definition. Set $Q = \alpha(P)$, so in particular $Q' = P_2'$, and we have $|N_{S'}(P')| < |N_{S'}(Q')|$. If $Q'$ is not fully $\mathcal{F}'$-normalized, we can iterate the process, until we find some $Q \in P^{\mathcal{F}}$ such that $Q'$ is fully $\mathcal{F}'$-normalized. This proves the claim (\textasteriskcentered). Suppose now that $P$ is such that $P'$ is fully $\mathcal{F}'$-centralized, and let $\mathrm{Aut}^0_{\mathcal{F}}(P) \leq \mathrm{Aut}_{\mathcal{F}}(P)$ be the subgroup of automorphisms which induce the identity on $P'$ and $P''$. This is a normal subgroup of $\mathrm{Aut}_{\mathcal{F}}(P)$, and it is also a $p$-group by \cite[Lemma 1.15]{BCGLO2}. Since $P$ is $\mathcal{F}$-radical, it follows that $$ \mathrm{Aut}^0_{\mathcal{F}}(P) \leq \operatorname{Inn}\nolimits(P). $$ Now, $P$ acts on $C_{S'}(P')$ since $P$ normalizes $P'$, and thus $P/P'$ acts on $C_{S'}(P')/Z(P')$. If the coset $[(z,1)] \cdot Z(P') \in C_{S'}(P')/Z(P')$ is fixed by the action of $P/P'$, then $c_{(z,1)} \in \mathrm{Aut}^0_{\mathcal{F}}(P) \leq \operatorname{Inn}\nolimits(P)$. Thus, $\Pi[(z,1)|(x,g)] \in C_S(P)$ for some $[(x,g)] \in P$. Since $P$ is $\mathcal{F}$-centric, this implies that $\Pi[(z,1)|(x,g)] \in Z(P) \leq P$, and hence $$ [(z,1)] \in P \cap C_{S'}(P') = P \cap S' \cap C_S(P') = P' \cap C_S(P') = Z(P'). $$ This means that the action of $P/P'$ on $C_{S'}(P')/Z(P')$ only fixes the trivial element, and since all groups involved are $p$-groups, this implies that $C_{S'}(P') = Z(P')$. Since $P'$ is fully $\mathcal{F}'$-normalized, this means that $P'$ is $\mathcal{F}'$-centric, contradicting the assumption that $P' \notin \Delta'$. \end{proof} \begin{rmk} Combining Example \ref{particular1} and Corollary \ref{particular2}, we see that any extension of a finite group by a saturated locality is, up to $p$-completion, the classifying space of a $p$-local finite group. The reader may compare this with \cite[Theorem A]{BLO6} for $p$-local finite groups. Note also that our results do not require $(\text{\bbfamily L}', \Delta', S')$ to be a proper locality, just as long as $\Delta'$ contains all the centrics. \end{rmk} \subsection{Further properties of isotypical extensions}\label{Sfurther} We have seen earlier in this section how an isotypical extension gives rise to a locality (Proposition \ref{propext3-1}). The purpose of this subsection is to study some further properties of this locality associated to an isotypical extension. This subsection contains a series of technical results, and the reader can skip it in a first reading. Fix an isotypical extension $$ \text{\bbfamily L}' \Right3{} \text{\bbfamily L} \Right3{\tau} \text{\bbfamily L}'', $$ where $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ are localities, as done in Hypothesis \ref{hyp1}. Let also $(\text{\bbfamily T}, \Delta, S)$ be the locality associated to the above extension. \begin{lmm}\label{aux-1} Let $H'' \leq \text{\bbfamily L}''$ be a subgroup satisfying that $H'' \cap S'' \in \operatorname{Syl}\nolimits_p(H'')$. Set also \begin{enumerate}[(i)] \item $\text{\bbfamily L}(H'') \stackrel{def} = \{[(x,g)] \in \text{\bbfamily L} \, | \, [g] \in H''\}$; \item $S(H'') \stackrel{def} = \text{\bbfamily L}(H'') \cap S$; and \item $\Delta(H'') \stackrel{def} = \{P \leq S(H'') \, | \, P \cap S' \in \Delta'\}$. \end{enumerate} Then, the triple $(\text{\bbfamily L}(H''), \Delta(H''), S(H''))$ is a locality. \end{lmm} \begin{proof} By definition of $\text{\bbfamily L}(H'')$ there is an isotypical extension $\text{\bbfamily L}' \Right1{} \text{\bbfamily L}(H'') \Right1{\tau} BH''$, where by abuse of notation $\tau$ denotes the restriction of $\tau \colon \text{\bbfamily L} \to \text{\bbfamily L}''$ to $\text{\bbfamily L}(H'')$. The statement follows by Example \ref{particular1}. \end{proof} In particular, if $P'' \in \Delta''$ is fully normalized in $\mathcal{F}''$ and $H'' = N_{\text{\bbfamily L}''}(P'')$, then it follows that $H'' \cap S'' = N_{S''}(P'') \in \operatorname{Syl}\nolimits_p(N_{\text{\bbfamily L}''}(P''))$, the triple $(\text{\bbfamily L}(H''), \Delta(H''), S(H''))$ is a locality, with $S(H'') \leq S$. Furthermore, if $P \leq S$ is such that $\tau(P) = P''$, then we have $N_{\text{\bbfamily L}}(P) = N_{\text{\bbfamily L}(H'')}(P)$: \begin{itemize} \item $N_{\text{\bbfamily L}}(P) \leq N_{\text{\bbfamily L}(H'')}(P)$, since the projection map $\tau \colon \text{\bbfamily L} \to \text{\bbfamily L}''$ sends $N_{\text{\bbfamily L}}(P)$ to a subgroup of $N_{\text{\bbfamily L}''}(P'')$; and \item $N_{\text{\bbfamily L}(H'')}(P) = \text{\bbfamily L}(H'') \cap N_{\text{\bbfamily L}}(P) \leq N_{\text{\bbfamily L}}(P)$. \end{itemize} Recall that a \emph{section} of $\tau \colon \text{\bbfamily L} \to \text{\bbfamily L}''$ is a map (of sets) $\sigma \colon \text{\bbfamily L}'' \to \text{\bbfamily L}$ such that $\tau \circ \sigma = \operatorname{Id}\nolimits_{\text{\bbfamily L}''}$. The following two lemmas deal with some particular sections of $\tau$. \begin{lmm}\label{aux0} The section $\sigma_0 \colon \text{\bbfamily L}'' \to \text{\bbfamily L}$ defined by $[g] \mapsto [(1,g)]$ satisfies the following properties. \begin{enumerate}[(i)] \item For each $[g] \in \text{\bbfamily L}''$, left conjugation by $\sigma_0(g)$ induces an element of $\mathrm{Aut}(\text{\bbfamily L}';S')$. \item If $[g] \in \text{\bbfamily L}''$ and $H'', K'' \leq S''$ are such that $\9{[g]}(K'') = H''$, then left conjugation by $\sigma_0(g)$ induces an isomorphism of partial groups form $\text{\bbfamily L}(K'')$ to $\text{\bbfamily L}(H'')$. \item If $[g_1|\ldots|g_n] \in \text{\bbfamily L}''$, then $[\sigma_0(g_1)|\ldots|\sigma_0(g_n)] \in \text{\bbfamily L}$. \end{enumerate} \end{lmm} \begin{proof} To prove parts (i) and (ii), we show that, for each $\omega = [(y_1,h_1)|\ldots|(y_n,h_n)] \in \text{\bbfamily L}(K'')$, we have $$ [(1,g)|(y_1,h_1)|(1,g)^{-1}|(1,g)|(y_2,h_2)|(1,g)^{-1}|\ldots|(1,g)|(y_n,h_n)|(1,g)^{-1}] \in \text{\bbfamily L}. $$ The conjugation formula of \ref{prodHi} implies that conjugation by $\sigma_0(g)$ induces an automorphism of $\text{\bbfamily L}'$, as well an isomorphism of partial groups from $\text{\bbfamily L}(K'')$ to $\text{\bbfamily L}(H'')$. The conjugation formula of \ref{prodHi} also implies that conjugation by $\sigma_0(g)$ induces an automorphism of $S'$, since the extension is isotypical. Set $\eta = \eta(g^{-1},g) \in N_{\text{\bbfamily L}'}(S')$ for short, so $[(1,g)^{-1}] = [(\eta^{-1}, g^{-1})]$. Then, by Lemma \ref{alternativecond}, it is enough to show that the following conditions hold: \begin{enumerate}[(1)] \item $[g^{-1}|h_1|g|g^{-1}|h_2|g|\ldots |g^{-1}|h_n|g] \in \text{\bbfamily L}''$; and \item $[1|a_1|b_1|1|a_2|b_2|\ldots|1|a_n|b_n] \in \text{\bbfamily L}'$, where $a_1 = \Psi_g(y_1)$ and $b_1 = (\Psi_g \circ \Psi_{h_1})(\eta^{-1})$, and $$ \begin{array}{l} a_i = (\Psi_{g} \circ \Psi_{h_1} \circ \Psi_{g^{-1}} \circ \ldots \circ \Psi_{g} \circ \Psi_{h_{i-1}} \circ \Psi_{g^{-1}} \circ \Psi_{g})(y_i) \\[4pt] b_i = (\Psi_{g} \circ \Psi_{h_1} \circ \Psi_{g^{-1}} \circ \ldots \circ \Psi_{g} \circ \Psi_{h_i})(\eta^{-1}) \end{array} $$ for $i = 2, \ldots, n$. \end{enumerate} Condition (1) follows immediately since $H'' = \9{[g]}(K'')$ by assumption. To show that condition (2) also holds, notice that by definition the element $[\eta] \in N_{\text{\bbfamily L}}(S)$ defines a homotopy from $\Psi_g^{-1}$ to $\Psi_{g^{-1}}$. Recall from Lemma \ref{homotopies} that this is equivalent to $$ [\Psi_{g^{-1}}(x) \cdot \eta] = [\eta \cdot \Psi_g^{-1}(x)] $$ for all $[x] \in \text{\bbfamily L}'$. Furthermore, since $[\eta] \in N_{\text{\bbfamily L}}(S)$, it follows that $\Psi_{g^{-1}}[x] = [\eta \cdot \Psi_{g^{-1}}(x) \cdot \eta^{-1}]$. Equivalently, for all $[y] \in \text{\bbfamily L}'$ we have $$ (\Psi_{g^{-1}} \circ \Psi_g)[y] = [\eta \cdot y \cdot \eta^{-1}]. $$ It is easy to see now that condition (2) above holds if and only if $$ [\Psi_g(y_1)|(\Psi_g \circ \Psi_{h_1})(y_2)|\ldots|(\Psi_g \circ \Psi_{h_1} \circ \ldots \circ \Psi_{h_{n-1}})(y_n)] \in \text{\bbfamily L}'. $$ Since $\omega \in \text{\bbfamily L}$, it follows that $[y_1|\Psi_{h_2}(y_2)|\ldots|(\Psi_{h_1} \circ \ldots \circ \Psi_{h_{n-1}})(y_n)] \in \text{\bbfamily L}'$ and the above condition holds. Finally, we prove property (iii). We have to show that $[\sigma_0(g)|\ldots|\sigma_0(g_n)] \in \text{\bbfamily L}$ for each $[g_1|\ldots|g_n] \in \text{\bbfamily L}''$. By Proposition \ref{TCP1} and Lemma \ref{alternativecond}, part (iii) holds if the following conditions are satisfied: $[g_1|\ldots|g_n] \in \text{\bbfamily L}''$ and $[1|1|\ldots|1] \in \text{\bbfamily L}'$. Clearly, both conditions hold, and thus part (iii) follows. \end{proof} The section $\sigma_0$ has the disadvantage that in general it does not take values in $\text{\bbfamily T}$. Thus, we now show that there is a section with similar properties and which, in addition, factors through $\text{\bbfamily T}$. \begin{lmm}\label{aux2} There is a section $\sigma \colon \text{\bbfamily L}'' \to \text{\bbfamily L}$ satisfying the following properties: \begin{enumerate}[(i)] \item $\sigma(g) \in \text{\bbfamily T}$ for all $[g] \in \text{\bbfamily L}''$; \item For each $[g] \in \text{\bbfamily L}''$, left conjugation by $\sigma(g)$ induces an element of $\mathrm{Aut}(\text{\bbfamily L}';S')$. \item If $[g] \in \text{\bbfamily L}''$ and $H'', K'' \leq S''$ are such that $\9{[g]}(K'') = H''$, then left conjugation by $\sigma(g)$ induces an isomorphism of partial groups form $\text{\bbfamily L}(K'')$ to $\text{\bbfamily L}(H'')$. \item If $[g_1|\ldots|g_n] \in \text{\bbfamily L}''$, then $[\sigma(g_1)|\ldots|\sigma(g_n)] \in \text{\bbfamily L}$. \end{enumerate} Furthermore, we can choose the above so that $\sigma(1) = [(1,1)]$. \end{lmm} \begin{proof} The proof is divided into several steps for the reader's convenience. \textbf{Step 1.} Definition of $\sigma$ and properties (i) and (iv). Fix some $[g] \in \text{\bbfamily L}''$, and let $P'' = L_{[g]}$ and $Q'' = R_{[g]}$, as in (\ref{SwSu0}). In particular, note that $P'', Q'' \in \Delta''$, by \cite[Lemma 2.14]{Chermak}. By Lemma \ref{aux0}, conjugation by $[(1,g)] \in \text{\bbfamily L}$ defines an isomorphism of partial groups $\text{\bbfamily L}(P'') \to \text{\bbfamily L}(Q'')$ by the formula $[(y,h)] \mapsto [(1,g)\cdot (y,h) \cdot (1,g)^{-1}]$. However, in general we have $$ X \stackrel{def} = \9{[(1,g)]}(S(P'')) \neq S(Q'') $$ (note that $X$ is a subgroup of $\text{\bbfamily L}(Q'')$). Since $(\text{\bbfamily L}(Q''), \Delta(Q''), S(Q''))$ is a locality, there is some $[(y,h)] \in \text{\bbfamily L}(Q'')$ such that $\9{[(y,h)]}X \leq S(Q'')$, and thus $\9{[(y,h)]}X = S(Q'')$ since $|S(P'')| = |X| = |S(Q'')|$. By Lemma \ref{alternativecond}, we have $[(y,h)|(1,g)] \in \text{\bbfamily L}$, and thus $$ [(y \cdot \eta(h,g), h \cdot g)] = \Pi[(y,h)|(1,g)] \in \text{\bbfamily T}, $$ since the above element conjugates the subgroup $S(P'')$ to $S(Q'')$, and these are elements of $\Delta$. In particular, $[h] \in Q''$, since $\tau(\text{\bbfamily L}(Q'')) = Q''$ by definition. Let $[(z,h)] \in S(Q'') \leq S$ be a preimage of $[h]$. Then, $$ [(z,h)^{-1}|(y \cdot \eta(h,g), h \cdot g)] \in \text{\bbfamily T} $$ since $(\text{\bbfamily T}, \Delta, S)$ is a locality. Set $\sigma(g) \stackrel{def} = \Pi[(z,h)^{-1}|(y \cdot \eta(g,h), h \cdot g)] \in \text{\bbfamily T}$. Note that in the case of $1 \in \text{\bbfamily L}''$, conjugation by $[(1,1)]$ already satisfies the required conditions, so we can choose $\sigma(1)$ to be $[(1,1)]$. By definition property (i) holds, and property (iv) follows easily too. Indeed, if $[g_1|\ldots|g_n] \in \text{\bbfamily L}''$, via a sequence $P_0'', \ldots, P_n'' \in \Delta''$, then the word $\omega = [\sigma(g_1)|\ldots|\sigma(g_n)]$ conjugates the sequence $S(P_0''), \ldots, S(P_n'') \in \Delta$, and thus $\omega \in \text{\bbfamily T}$. \textbf{Step 2.} Property (iii). Fix some $[g] \in \text{\bbfamily L}''$ as above, and let $[(1,g)]$, $[(y,h)]$ and $[(z,h)^{-1}]$ be the elements used in Step 1 to define $\sigma(g)$. Notice that left conjugation by any of these three elements must restrict to an automorphism of $S'$. Indeed, \begin{enumerate}[(1)] \item for $[(1,g)]$, it follows from Lemma \ref{aux0}; \item for $[(y,h)]$, it follows because both conjugation by $[(1,g)]$ and by $\Pi[(y,h)|(1,g)]$ do; and \item for $[(z,h)^{-1}]$, it follows because this is an element of $S(Q'') \leq S$. \end{enumerate} Thus, conjugation by $\sigma(g)$ also restricts to an automorphism of $S'$. We have to check that restriction to $\text{\bbfamily L}'$ also produces an automorphism. For $[(1,g)]$ and $[(z,h)^{-1}]$ this is clear, either by Lemma \ref{aux0}, in the case of $[(1,g)]$, or because $[(z,h)^{-1}] \in S$. It remains to check that conjugation by $[(y,h)]$ induces an automorphism of $\text{\bbfamily L}'$. Let $\omega_1 = [u_1|\ldots|u_n] \in \text{\bbfamily L}'$, via the sequence $P_0', \ldots, P_n' \in \Delta'$, and let $\varphi_g \in \mathrm{Aut}(\text{\bbfamily L}';S')$ be the automorphism induced by left conjugation by $[(1,g)]$. Then, $\omega_2 \stackrel{def} = \varphi_g(\omega_1) \in \text{\bbfamily L}'$ via the sequence $\varphi_g(P_0'), \ldots \varphi_g(P_n') \in \Delta'$. Set for short $\omega_2 = [v_1|\ldots|v_n]$, and $Q_i' = \varphi_g(P_i')$ for $i = 0, \ldots, n$. Recall that $(\text{\bbfamily L}(Q''), \Delta(Q''), S(Q''))$ is a locality, and that $\Delta' \subseteq \Delta(Q'')$ by definition. Since conjugation by $[(y,h)]$ restricts to an automorphism of $S'$, we have $R_i' \stackrel{def} = \9{[(y,h)]}(Q_i') \in \Delta'$, for $i = 0, \ldots, n$, and it follows that $$ [(y,h)|(v_1,1)|(y,h)^{-1}|(y,h)|(v_2,1)|(y,h)^{-1}|\ldots|(y,h)|(v_n,1)|(y,h)^{-1}] \in \text{\bbfamily L}(Q''), $$ via the sequence $R_0', Q_0', Q_1', R_1', Q_1', Q_2', \ldots, Q_n', R_n' \in \Delta'$. The conjugation formula of Remark \ref{prodHi} now implies that this induces an automorphism of $\text{\bbfamily L}'$. \textbf{Step 3.} Property (ii). Again, fix some $[g] \in \text{\bbfamily L}''$, and suppose that $\9{[g]}(K'') = H''$ for some $H'', K'' \leq S''$. Let also $[(1,g)]$, $[(y,h)]$ and $[(z,h)^{-1}]$ be as in previous steps of the proof. By Lemma \ref{aux0}, conjugation by $[(1,g)]$ induces an isomorphism from $\text{\bbfamily L}(K'')$ to $\text{\bbfamily L}(H'')$, and conjugation by $[(z,h)^{-1}] \in S(H'')$ clearly induces an automorphism of $\text{\bbfamily L}(H'')$. Thus, to prove property (iii), it is enough to show that conjugation by $[(y,h)] \in \text{\bbfamily L}(H'')$ also induces an automorphism of $\text{\bbfamily L}(H'')$. Recall that $(\text{\bbfamily L}(H''), \Delta(H''), S(H''))$ is a locality by Lemma \ref{aux-1}. Let $[(u_1, k_1)|\ldots |(u_n, k_n)] \in \text{\bbfamily L}(H'')$, via some sequence $P_0, \ldots, P_n \in \Delta(H'')$. By definition, $$ \Delta(H'') = \{R \leq S(H'') \, \, | \, \, R \cap S' \in \Delta'\}. $$ This means that $\Delta' \subseteq \Delta(H'')$, and that we may assume that $P_0, \ldots, P_n \in \Delta'$ (if $P_i \notin \Delta'$, we can replace $P_i$ by $P_i \cap S' \in \Delta'$). Set $V_i = \9{[(y,h)]}U_i$, for $i = 0, \ldots, n$, and note that $V_i \in \Delta'$ by Step 2, since conjugation by $[(y,h)]$ induces an automorphism of $S'$, and $U_i \leq S'$. It follows that $$ [(y,h)|(u_1,k_1)|(y,h)^{-1}|(y,h)|(u_2, k_2)|(y,h)^{-1}|\ldots|(y,h)|(u_n,k_n)|(y,h)^{-1}] \in \text{\bbfamily L}(H''), $$ via the sequence $V_0, U_0, U_1, V_1, U_1, U_2, V_2, \ldots, U_n, V_n$. Property (ii) follows easily now. \end{proof} \begin{lmm}\label{aux1} The subgroup $S$ is a Sylow $p$-subgroup of $\text{\bbfamily L}$: if $H \leq \text{\bbfamily L}$ is a $p$-group, then $H$ is conjugate in $\text{\bbfamily L}$ to a subgroup of $S$. \end{lmm} \begin{proof} Let $H \leq \text{\bbfamily L}$ be a $p$-subgroup. Then $H''$ is a $p$-subgroup of $\text{\bbfamily L}''$, and it is conjugate to a subgroup of $S''$ by \cite[Proposition 2.21 (b)]{Chermak} since $(\text{\bbfamily L}'', \Delta'',S'')$ is a locality. Suppose first that $H'' \leq S''$. In this case the pull-back $\text{\bbfamily L}(S'')$ is a locality with Sylow $p$-subgroup $S$ and $H \leq \text{\bbfamily L}(S'')$, and the statement follows by \cite[Proposition 2.21 (b)]{Chermak}. Suppose now that $H''$ is not a subgroup of $S''$, and let $[g] \in \text{\bbfamily L}''$ be such that $\9{[g]}(H'') = K'' \leq S''$. By \cite[Proposition 2.21 (a)]{Chermak}, the subgroup $H''$ normalizes some $Q'' \in \Delta''$, and this means that we can choose $[g] \in N_{\text{\bbfamily L}''}(Q'')$ so that $K'' \leq N_{S''}(Q'')$. By Lemma \ref{aux0} the element $[(1,g)] \in \text{\bbfamily L}$ induces an isomorphism of partial groups from $\text{\bbfamily L}(H'')$ to $\text{\bbfamily L}(K'')$, and in particular the subgroup $H$ is sent to a $p$-subgroup $K \leq \text{\bbfamily L}(K'')$. To finish the proof, notice that $(\text{\bbfamily L}(K''), \Delta(K''), S(K''))$ is a locality by Example \ref{particular1}, and thus by \cite[Proposition 2.21 (b)]{Chermak} $K$ is conjugate in $\text{\bbfamily L}(K'')$ to a subgroup of $S(K'') \leq S$. \end{proof} \subsection{Isotypical extensions and saturated localities}\label{isosat} Finally, we study isotypical extensions of saturated localities. More specifically, given an isotypical extension $\text{\bbfamily L}' \to \text{\bbfamily L} \to \text{\bbfamily L}''$, with $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ saturated localities, we want sufficient conditions for $\text{\bbfamily L}$ to be equivalent to the classifying space of a $p$-local finite group after $p$-completion. Theorem \ref{good1} below motivates our approach to this question. \begin{thm}\label{good1} Let $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ be saturated localities, let $\text{\bbfamily L}' \Right1{} \text{\bbfamily L} \Right1{\tau} \text{\bbfamily L}''$ be an isotypical extension, and let $(\text{\bbfamily T}, \Delta, S)$ be the locality described in Proposition \ref{propext3-1}, with associated fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$. Suppose in addition that the following conditions hold: \begin{enumerate}[(a)] \item $\text{\bbfamily T}$ contains $\text{\bbfamily L}'$ as a partial normal subgroup; and \item $\Delta$ contains all the $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-centric $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-radical subgroups of $S$. \end{enumerate} Then the following holds. \begin{enumerate}[(i)] \item $(\text{\bbfamily T}, \Delta, S)$ is a saturated locality. \item The inclusion $\text{\bbfamily T} \subseteq \text{\bbfamily L}$ induces an equivalence after $p$-completion. \item $\mathcal{F}'$ is a normal subsystem of $\mathcal{F}_{\Delta}(\text{\bbfamily T})$. \end{enumerate} In particular, after $p$-completion $\text{\bbfamily L}$ is equivalent to the classifying space of a $p$-local finite group, and $\mathcal{F}_{\Delta}(\text{\bbfamily T}) = \mathcal{F}_S(\text{\bbfamily L})$. \end{thm} \begin{proof} By definition, $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ is $\Delta$-generated and $\Delta$-saturated. Thus, saturation of $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ follows immediately from \cite[Theorem A]{BCGLO1} or \cite[Proposition 3.6]{OV}. The rest of the proof is divided into steps for the reader's convenience. \textbf{Step 1.} The $p$-completed space $|\text{\bbfamily T}|^{\wedge}_p$ is equivalent to the classifying space of a $p$-local finite group. Let $\mathcal{L}$ be the unique centric linking system associated to the saturated fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$. We show that $|\text{\bbfamily T}|^{\wedge}_p \simeq |\mathcal{L}|^{\wedge}_p$. Let $\mathcal{H} = \Delta \cap \mathcal{F}_{\Delta}(\text{\bbfamily T})^c$. By definition the set $\mathcal{H}$ contains all the $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-centric $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-radical subgroups of $S$. Set also, \begin{itemize} \item $\mathcal{T} = \mathcal{T}_{\Delta}(\text{\bbfamily T})$, the transporter category associated to $(\text{\bbfamily T}, \Delta, S)$; \item $\mathcal{T}_{\mathcal{H}} \subseteq \mathcal{T}$, the full subcategory with object set $\mathcal{H}$; \item $\mathcal{L}$, the centric linking system associated to the saturated fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$; \item $\mathcal{L}_{\mathcal{H}} \subseteq \mathcal{L}$, the full subcategory with object set $\mathcal{H}$. \end{itemize} Then there is a zigzag $$ |\text{\bbfamily T}| \Left2{\operatorname{proj}\nolimits^{\mathcal{T}}_{\text{\bbfamily T}}} |\mathcal{T}| \Left2{\operatorname{incl}\nolimits_{\mathcal{T}}} |\mathcal{T}_{\mathcal{H}}| \Right2{\operatorname{proj}\nolimits_{\mathcal{L}}} |\mathcal{L}_{\mathcal{H}}| \Right2{\operatorname{incl}\nolimits_{\mathcal{L}}} |\mathcal{L}|, $$ where the map $|\text{\bbfamily T}| \Left1{\operatorname{proj}\nolimits^{\mathcal{T}}_{\text{\bbfamily T}}} |\mathcal{T}|$ is a weak equivalence by Theorem \ref{equivnerves}, and all the other maps are equivalences after $p$-completion by \cite[Proposition 4.6]{OV}. \textbf{Step 2.} Proof of part (ii). The proof follows \cite[Theorem 5.1]{Diaz}, with some small modifications. Consider the commutative diagram of extensions \begin{equation}\label{diag43} \xymatrix{ BS' \ar[r] \ar[d] & BS \ar[r] \ar[d] & BS'' \ar[d] \\ \text{\bbfamily L}' \ar[r] & \text{\bbfamily L} \ar[r] & \text{\bbfamily L}'' } \end{equation} from Lemma \ref{propext1}. Each row has an associated mod $p$ Lyndon-Hochschild-Serre spectral sequence, whose second pages are $$ E_{2,S}^{r,s} = H^r(S'; H^s(S''; {\mathbb F}_p)) \qquad \mbox{and} \qquad E_{2, \text{\bbfamily L}}^{r,s} = H^r(\text{\bbfamily L}''; H^s(\text{\bbfamily L}'; {\mathbb F}_p)), $$ and converging to $H^{\ast}(S; {\mathbb F}_p)$ and $H^{\ast}(\text{\bbfamily L}; {\mathbb F}_p)$, respectively. Consider also the fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ over $S$, and recall that $S' \leq S$ is a strongly $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-closed subgroup by Corollary \ref{propext3-2}. Thus, by \cite[Theorem 1.1]{Diaz} there is a spectral sequence with second page $$ E_{2, \text{\bbfamily T}}^{r,s} = H^r(S/S'; H^s(S'; {\mathbb F}_p))^{\mathcal{F}_{\Delta}(\text{\bbfamily T})} = H^r(S''; H^s(S'; {\mathbb F}_p))^{\mathcal{F}_{\Delta}(\text{\bbfamily T})} $$ and converging to $H^{r+s}(\mathcal{F}_{\Delta}(\text{\bbfamily T}); {\mathbb F}_p)$. By part (i), $\text{\bbfamily T}$ is mod $p$ equivalent to the classifying space of a $p$-local finite group, and thus by \cite[Theorem 5.8]{BLO2} there is an isomorphism $$ H^{\ast}(\text{\bbfamily T}; {\mathbb F}_p) \cong H^{\ast}(\mathcal{F}_{\Delta}(\text{\bbfamily T}); {\mathbb F}_p). $$ By the same arguments of the proof of \cite[Theorem 5.1]{Diaz}, there is a cohomological Mackey functor $(A,B) \colon \mathcal{F}_{\Delta}(\text{\bbfamily T}) \to CCh^2({\mathbb Z}_{(p)})$, which produces morphisms of spectral sequences $$ \xymatrix@C=3cm{ H^r(\text{\bbfamily L}''; H^s(\text{\bbfamily L}';{\mathbb F}_p)) \ar@/^2pc/[rr]^{H^{r,s}(A)(\iota)} & & H^r(S''; H^s(S'; {\mathbb F}_p)) \ar@/^2pc/[ll]^{H^{r,s}(B)(\iota)} } $$ where $H^{r,s}(A)(\iota)$ coincides with the restriction morphism induced by diagram (\ref{diag43}). The isomorphism between $E_{2,\text{\bbfamily L}}^{\ast,\ast}$ and $E_{2, \text{\bbfamily T}}^{\ast, \ast}$ follows now by the same arguments of \cite{Diaz}. To finish the proof, this isomorphism of spectral sequences implies an isomorphism of the $\infty$-pages, and thus there is an isomorphism $H^{\ast}(\text{\bbfamily L}; {\mathbb F}_p) \cong H^{\ast}(\text{\bbfamily T}; {\mathbb F}_p)$, which is induced by the inclusion $\text{\bbfamily T} \to \text{\bbfamily L}$. \textbf{Step 3.} The equality $\mathcal{F}_{\Delta}(\text{\bbfamily T}) = \mathcal{F}_S(\text{\bbfamily L})$. Set for short $\mathcal{F} = \mathcal{F}_S(\text{\bbfamily L})$. By part (i) and Step 2 we know that the $p$-completion of $\text{\bbfamily L}$ is equivalent to the classifying space of a $p$-local finite group. Consider the commutative triangle $$ \xymatrix{ & BS \ar[rd]^{\gamma} \ar[ld]_{\gamma'} & \\ |\text{\bbfamily L}| \ar[rr]_{(-)^{\wedge}_p} & & |\text{\bbfamily L}|^{\wedge}_p } $$ and consider the topological construction introduced in \cite[Section 7]{BLO2}. Given a $p$-group $R$, this construction assigns a fusion system $\mathcal{E}(\mu)$ to each map $\mu \colon BR \to X$, as follows. For each $P, Q \leq R$, $$ \operatorname{Hom}\nolimits_{\mathcal{E}(\mu)}(P,Q) = \{f \in \operatorname{Inj}\nolimits(P,Q) \, | \, \mu|_{BP} \simeq \mu|_{BQ} \circ Bf\}, $$ where $\operatorname{Inj}\nolimits(P,Q)$ is the set of injective group homomorphism from $P$ to $Q$. In the particular case where $X$ is the classifying space of a $p$-local finite group and $\mu \colon BR \to X$ is the inclusion of its Sylow $p$-subgroup, the authors prove in \cite[Proposition 7.3]{BLO2} that $\mathcal{E}(\mu)$ is (isomorphic to) the fusion system of the original $p$-local finite group. Applying the topological construction to the triangle above, we get the following sequence of inclusions and isomorphisms $$ \mathcal{F}_{\Delta}(\text{\bbfamily T}) \subseteq \mathcal{F} \subseteq \mathcal{E}(\gamma') \subseteq \mathcal{E}(\gamma) \cong \mathcal{F}_{\Delta}(\text{\bbfamily T}). $$ More specifically, from left to right, the first inclusion is given by definition of $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ and $\mathcal{F}$; the second inclusion follows from the topological construction, since clearly any conjugation by an element of $\text{\bbfamily L}$ will induce an morphism in $\mathcal{E}(\gamma')$; the third inclusion is given again by the topological construction; and the isomorphism follows from \cite[Proposition 7.3]{BLO2}, together with part (ii). \textbf{Step 4.} Proof of part (iii). By Step 3, it is enough to show that the fusion systems $\mathcal{F}' \subseteq \mathcal{F}$ satisfy conditions (N1)-(N4) in Definition \ref{normalF}. By hypothesis the fusion system $\mathcal{F}'$ is saturated since $(\text{\bbfamily L}', \Delta', S')$ is a proper locality, and condition (N1) holds. Condition (N2) also holds easily: $\text{\bbfamily L}'$ is a partial normal subgroup of $\text{\bbfamily L}$, and thus $S' = S \cap \text{\bbfamily L}'$ is strongly $\mathcal{F}$-closed. To show that condition (N3) holds, let $P' \leq Q' \leq S'$ and $\gamma$ be as in Definition \ref{normalF}. By definition, the morphism $\gamma$ is the left conjugation morphism induced by some word $[(x_1,g_1)|\ldots|(x_n,g_n)] \in \mathbb{W}} %before it was \operatorname{W(\text{\bbfamily L}_1)$, so that $$ \9{[(x_i,g_i)]}(\ldots \9{[(x_{n-1}, g_{n-1})]}(\9{[(x_n,g_n)]}Q')) \leq S $$ for all $i = 1, \ldots, n$. In particular, it is enough to check the case $n = 1$. That is, $[(x,g)] \in \text{\bbfamily L}$ such that ${[(x,g)]}Q' \leq S'$. By the conjugation formula in Remark \ref{prodHi}, we have $$ \Pi[(x,g)|(y,1)|(x,g)^{-1}] = [(x \cdot \Psi_g(y) \cdot x^{-1}, 1)] $$ for all $[(y,1)] \in Q'$. Thus, $\gamma = \alpha \circ \Psi_g$, where $\alpha$ is the left conjugation morphism induced by $[(x, 1)]$. Clearly, there are bijections $$ \xymatrix@R=1mm{ \operatorname{Hom}\nolimits_{\mathcal{F}'}(P',Q') \ar[rr]^{\cong} & & \operatorname{Hom}\nolimits_{\mathcal{F}'}(\Psi_g(P'), \Psi_g(Q')) \ar[rr]^{\cong} & & \operatorname{Hom}\nolimits_{\mathcal{F}'}(\gamma(P'), \gamma(Q'))\\ f \ar@{|->}[rr] & & \Psi_g \circ f \circ \Psi_g^{-1} & & \\ & & f' \ar@{|->}[rr] & & \alpha \circ f' \circ \alpha^{-1} } $$ and condition (N3) follows. Finally, let us show that condition (N4) holds. Let $f \in \mathrm{Aut}_{\mathcal{F}'}(S')$, and let $[x] \in N_{\text{\bbfamily L}'}(S')$ be such that $f$ is the left conjugation automorphism induced by $[x]$. Then, for each element $[(z,g)] \in C_S(S')$, we have $[(x,1)|(z,g)|(x,1)^{-1}|(z,g)^{-1}] \in \text{\bbfamily L}$, and $$ \alpha = \Pi[(x,1)|(z,g)|(x,1)^{-1}|(z,g)^{-1}] = \Pi[(x,1)|(z \cdot \Psi_g(x^{-1}) \cdot z^{-1},1)] \in S'. $$ Notice that the conjugation actions on $S'$ of the elements $[x]$ and $[z \cdot \Psi_g(x^{-1}) \cdot z^{-1}]$ are the same since $[(z,g)]$ centralizes $S'$, and hence $\alpha \in C_{S'}(S') = Z(S')$. \end{proof} \begin{rmk} Given a good isotypical extension $\text{\bbfamily L}' \to \text{\bbfamily L} \to \text{\bbfamily L}''$, the associated locality $(\text{\bbfamily T}, \Delta, S)$ described above need not be proper. For example, consider the split extension $\text{\bbfamily L}' \to \text{\bbfamily L}' \times \text{\bbfamily L}'' \to \text{\bbfamily L}''$. In this case, $\text{\bbfamily T} = \text{\bbfamily L}' \times \text{\bbfamily L}''$, and $(\text{\bbfamily T}, \Delta, S)$ is proper if and only if both $\text{\bbfamily L}'$ and $\text{\bbfamily L}''$ are proper, which is not necessarily the case. \end{rmk} \begin{defi}\label{defigood} Let $(\text{\bbfamily L}', \Delta', S')$ and $(\text{\bbfamily L}'', \Delta'', S'')$ be saturated localities, let $\text{\bbfamily L}' \Right1{} \text{\bbfamily L} \Right1{\tau} \text{\bbfamily L}''$ be an isotypical extension, and let $(\text{\bbfamily T}, \Delta, S)$ be the locality described in Proposition \ref{propext3-1}, with associated fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$. The above extension is \emph{good} if the following conditions hold: \begin{enumerate}[(i)] \item $\text{\bbfamily T}$ contains $\text{\bbfamily L}'$ as a partial normal subgroup; and \item $\Delta$ contains all the $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-centric $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-radical subgroups of $S$. \end{enumerate} \end{defi} \begin{rmk} Let $(\text{\bbfamily L}', \Delta', S')$, $(\text{\bbfamily L}'', \Delta'', S'')$ be saturated localities, and let $\varepsilon \colon \text{\bbfamily L}'' \to \operatorname{Out}\nolimits(\text{\bbfamily L}';S')$ be an outer action. Assuming that some extension of $(\text{\bbfamily L}', \text{\bbfamily L}'', \varepsilon)$ is good, it is not clear whether all the extensions of $(\text{\bbfamily L}', \text{\bbfamily L}'', \varepsilon)$ are good or not. \end{rmk} The rest of this section is devoted to present sufficient (but not necessary) conditions for an isotypical extension $\text{\bbfamily L}' \to \text{\bbfamily L} \to \text{\bbfamily L}''$ to be good. Given such an extension, let $(\text{\bbfamily T}, \Delta, S)$ be the locality described in Proposition \ref{propext3-1}. Note that in general $\text{\bbfamily T}$ does not contain $\text{\bbfamily L}'$ as a partial subgroup, and as a consequence the fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ may not contain $\mathcal{F}'$ as a subsystem. The concept of \emph{rigid} extensions is thus introduced to deal with condition (i) in Definition \ref{defigood}. Regarding condition (ii) in \ref{defigood}, our analysis follows the steps of \cite{OV}, where the authors study extensions of transporter systems by $p$-groups. This way we introduce \emph{admissible} extensions, generalizing the same concept introduced in \cite[Definition 5.10]{OV}. The results in the previous subsections, and in particular Corollary \ref{particular2}, impose some mild restrictions to our approach, which we summarize as follows. \begin{hyp}\label{hyp3} Fix an isotypical extension $\text{\bbfamily L}' \Right1{} \text{\bbfamily L} \Right1{\tau} \text{\bbfamily L}''$, where \begin{enumerate}[(a)] \item $(\text{\bbfamily L}', \Delta', S')$ is a saturated locality such that $\Delta'$ contains all $\mathcal{F}'$-centric subgroups. \item $(\text{\bbfamily L}'', \Delta'', S'')$ is a saturated locality. \end{enumerate} The twisting function that determines the above extension is assumed to satisfy the same properties (1)-(4) as listed in Hypothesis \ref{hyp1}. Also, the following notation will be tacitly used throughout the rest of this section. \begin{enumerate}[(i)] \item $S \leq \text{\bbfamily L}$ and $\Delta$ are as described in Lemma \ref{propext1} and (\ref{collectionS}) respectively. \item $\mathcal{F}$ is the fusion system over $S$ whose morphisms are generated by all the conjugations among subgroups of $S$ induced by elements of $\text{\bbfamily L}$. \item $(\text{\bbfamily T}, \Delta, S)$ is the locality described in Proposition \ref{propext3-1}, with fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$. \end{enumerate} \end{hyp} \begin{lmm}\label{propext5-2} For all $P, Q \in \Delta$ there is an equality $\operatorname{Hom}\nolimits_{\mathcal{F}_{\Delta}(\text{\bbfamily T})}(P,Q) = \operatorname{Hom}\nolimits_{\mathcal{F}}(P,Q)$. \end{lmm} \begin{proof} By definition, $\mathcal{F}_{\Delta}(\text{\bbfamily T}) \subseteq \mathcal{F}$. Fix $P, Q \in \Delta$, and let $\omega = [(x_1, g_1)|\ldots|(x_n,g_n)] \in \mathbb{W}} %before it was \operatorname{W(\text{\bbfamily L}_1)$ be such that $\9{\omega}P \leq Q$ (so that $\omega$ induces a morphism in $\operatorname{Hom}\nolimits_{\mathcal{F}}(P,Q)$). Since $P, Q \in \Delta$, it follows that $\omega \in \text{\bbfamily T}$ by definition, and the statement follows. \end{proof} \begin{prop}\label{aux3} Each $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-conjugacy class of elements of $\Delta$ contains some element $P$ such that $P'$ is fully $\mathcal{F}'$-normalized and $P''$ is fully $\mathcal{F}''$-normalized. \end{prop} \begin{proof} Recall from Lemma \ref{propext5-2} that $\operatorname{Hom}\nolimits_{\mathcal{F}_{\Delta}(\text{\bbfamily T})}(P,Q) = \operatorname{Hom}\nolimits_{\mathcal{F}}(P,Q)$ for all $P, Q \in \Delta$. First we show that we may assume $P''$ to be fully $\mathcal{F}''$-normalized. Suppose otherwise that $P''$ is not fully $\mathcal{F}''$-normalized. Since $\mathcal{F}''$ is saturated, there exists some morphism $f'' \colon P'' \to R''$ such that $R''$ is fully $\mathcal{F}''$-normalized. Since $\mathcal{F}'' = \mathcal{F}_{\Delta''}(\text{\bbfamily L}'')$ and $P'' \in \Delta''$, there exists some $[g] \in \text{\bbfamily L}''$ such that $f''$ is the left conjugation homomorphism induced by $[g]$. Let $\sigma(g) \in \text{\bbfamily L}$ be as in Corollary \ref{aux2}. Then, $R = \9{\sigma(g)}P$ is such that $\tau(R) = R''$ is fully normalized in $\mathcal{F}''$. Suppose for simplicity that $P$ already satisfies that $P''$ is fully normalized in $\mathcal{F}''$. Consider the locality $(\text{\bbfamily L}(H''), \Delta(H''), S(H''))$, where $H'' = N_{\text{\bbfamily L}''}(P'')$. Note that the associated fusion system $\mathcal{F}(H'')$ is saturated by Corollary \ref{particular2}. If $P'$ is not fully $\mathcal{F}'$-normalized, then there are some subgroup $R' \leq S(H'')$ and some morphism $f \in \operatorname{Hom}\nolimits_{\mathcal{F}(H'')}(N_{S(H'')}(P'), N_{S(H'')}(R'))$ such that $f(P') = R'$, where $R'$ is chosen to be fully $\mathcal{F}(H'')$-normalized. In particular, $R'$ is fully $\mathcal{F}'$-normalized because $S' \leq S(H'')$ is strongly $\mathcal{F}(H'')$-closed. Notice that $P \leq N_{S(H'')}(P')$ by construction, and thus $R \stackrel{def} = f(P) \leq S(H'') \leq S$ is $\mathcal{F}$-conjugate to $P$ and $R'$ is fully $\mathcal{F}'$-normalized. Furthermore, $R'' = P''$ by construction, and $P''$ was already assumed to be fully $\mathcal{F}''$-normalized by the first part of the proof. \end{proof} We are now ready to introduce rigid and admissible extensions. Before we do so, let us motivate the definition of admissible extension. The following is a (partial) generalization of \cite[Lemma 5.9]{OV}. \begin{prop}\label{aux4} Set $S_1'' = \operatorname{Ker}\nolimits(S'' \Right2{\operatorname{incl}\nolimits} \text{\bbfamily L}'' \Right2{\varepsilon} \operatorname{Out}\nolimits(\text{\bbfamily L}';S') \Right2{} \operatorname{Out}\nolimits_{_{\textup{fus}}}(S'))$. Then, for each $P \in \Delta$ that is $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-centric $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-radical, the following holds. \begin{enumerate}[(i)] \item $P'$ is $\mathcal{F}'$-centric; and \item $C_{S_1''}(P'') \leq P''$. \end{enumerate} \end{prop} \begin{proof} By Lemma \ref{aux3} we may assume that both $P'$ and $P''$ are fully normalized in the corresponding fusion systems. Let us prove first that $P'$ is $\mathcal{F}'$-centric. Suppose otherwise that $P'$ is not $\mathcal{F}'$-centric, and let $K = P \cdot C_{S'}(P')$. By hypothesis, $P \lneqq K$ and hence $P \lneqq N_K(P)$, and $P' \lneqq N_K(P) \cap S'$. Since $P$ is $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-centric and the elements in $N_K(P)$ induce the identity both on $P'$ and $P''$ (modulo an inner automorphism of $P$), we have $$ \{1\} \neq N_K(P)/P \leq \operatorname{Out}\nolimits_S(P) \cap O_p(\operatorname{Out}\nolimits_{\mathcal{F}_{\Delta}(\text{\bbfamily T})}(P)), $$ contradicting the hypothesis that $P$ is $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-radical. Finally we prove the second part of the statement. Again, we proceed by contradiction, so assume that $C_{S_1''}(P'') \not \leq P''$. For a subgroup $Q' \leq S'$ set $$ K(Q') = \{[(x,g)] \in S \,\, | \,\, [(x,g)] \in C_S(Q') \mbox{ and } [g] \in C_{S''}(P'')\}. $$ We claim that $K(P') \not \leq P$. Indeed, if $K(P') \leq P$ then $\tau(K(P')) \leq P''$. However, by definition we have $$ K(S') \leq K(P') \qquad \mbox{and} \qquad \tau(K(S')) = C_{S_1''}(P''). $$ Since $C_{S_1''}(P'') \not \leq P''$ it follows that $K(P') \not \leq P$. Next we claim that $K(P') \cap P \lneqq K(P') \cap N_S(P)$. Suppose otherwise that we have $K(P') \cap P = K(P') \cap N_S(P)$, and let $J(P) \leq N_S(P')$ be the subgroup generated by $P$ and $K(P')$ (note that by definition $K(P') \leq N_S(P')$). By assumption, $P \lneqq J(P)$, and thus $P \lneqq N_{J(P)}(P)$. Now, by definition, for each $\alpha \in N_{J(P)}(P)$ there is some $\beta \in P$ such that $$ (c_{\alpha})|_{P'} = (c_{\beta})|_{P'} \qquad \mbox{and} \qquad (c_{\tau(\alpha)})|_{P''} = (c_{\tau(\beta)})|_{P''}. $$ This means that if $\alpha \notin P$, then conjugation by $\beta^{-1} \cdot \alpha \in N_{J(P)}(P) \setminus P$ induces the identity on both $P'$ and $P''$, which contradicts the original hypothesis that $K(P') \cap P = K(P') \cap N_S(P)$. Thus we have $K(P') \cap P \lneqq K(P') \cap N_S(P)$. Since $P$ is assumed to be $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-centric, we have $$ \{1\} \neq (K(P') \cap N_S(P)) \cdot P / P \leq \operatorname{Out}\nolimits_S(P) \cap O_p(\operatorname{Out}\nolimits_{\mathcal{F}_{\Delta}(\text{\bbfamily T})}(P)), $$ which contradicts the hypothesis that $P$ is $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-radical. \end{proof} \begin{defi}\label{rigidext} Let $\text{\bbfamily L}' \Right1{} \text{\bbfamily L} \Right1{\tau} \text{\bbfamily L}''$ be the isotypical extension fixed in Hypothesis \ref{hyp3}, with associated outer action $\varepsilon \colon \text{\bbfamily L}'' \to \operatorname{Out}\nolimits(\text{\bbfamily L}';S')$. \begin{enumerate}[(i)] \item The above extension is \emph{rigid} if $S_0'' \stackrel{def} = \operatorname{Ker}\nolimits(S'' \Right1{\operatorname{incl}\nolimits} \text{\bbfamily L}'' \Right1{\varepsilon} \operatorname{Out}\nolimits(\text{\bbfamily L}';S')) \in \Delta''$. \item The above extension is \emph{adimissible} if, upon setting $$ S_1'' \stackrel{def} = \operatorname{Ker}\nolimits(S'' \Right2{\operatorname{incl}\nolimits} \text{\bbfamily L}'' \Right2{\varepsilon} \operatorname{Out}\nolimits(\text{\bbfamily L}';S') \Right2{} \operatorname{Out}\nolimits_{_{\textup{fus}}}(S')), $$ the following condition holds: if $P'' \leq S''$ is fully $\mathcal{F}''$-centralized and $C_{S_1''}(P'') \leq P''$, then $P'' \in \Delta''$. \end{enumerate} \end{defi} \begin{rmk}\label{perfect1} We have some observations to make about the above definition. \begin{enumerate}[(i)] \item It may seem that rigidity is a very strong condition to impose on an extension. Consider for example the situation where the action $\varepsilon$ is \emph{faithful} (i.e., $\operatorname{Ker}\nolimits(\varepsilon) = \{1\}$). Rigidity implies in this case that the trivial subgroup of $S''$ must be an object in $\Delta''$, which forces $\text{\bbfamily L}''$ to be a group (with $\text{\bbfamily L}'' = \mathbb{W}} %before it was \operatorname{W(\text{\bbfamily L}''_1)$). Notice that in this case $\text{\bbfamily L}''$ is essentially acting on $\text{\bbfamily L}'$ as an actual group, via the subgroup of $\operatorname{Out}\nolimits(\text{\bbfamily L}';S')$ generated by the image of $\varepsilon$. Thus, the idea behind rigidity is that is a locality is acting as a group, it should be a group. \item Let $S_0'', S_1'' \leq S''$ be as above. By definition, these two subgroups are strongly $\mathcal{F}''$-closed, and $S_0'' \leq S_1''$. Furthermore, this inclusion is an equality for all odd primes by \cite[Theorem C]{Oliver}. Thus, every admissible extension is rigid for all odd primes. Whether the same is true for $p = 2$ remains an open question. \item The extensions considered in Corollary \ref{particular2} are always rigid and admissible, since in this case $\Delta''$ is the collection of all subgroups of $S''$. \item Let $(\text{\bbfamily L}', \Delta', S')$, $(\text{\bbfamily L}'', \Delta'', S'')$ and $\varepsilon \colon \text{\bbfamily L}'' \to \operatorname{Out}\nolimits(\text{\bbfamily L}';S')$ be as in Hypothesis \ref{hyp3}. If an extension of this data is rigid (respectively admissible), then so is any other extension of this data, just by definition of rigid (respectively admissible) extensions. \end{enumerate} \end{rmk} \begin{thm}\label{propext6} Let $\text{\bbfamily L}' \Right1{} \text{\bbfamily L} \Right1{\tau} \text{\bbfamily L}''$ be the isotypical extension fixed in Hypothesis \ref{hyp3}. Then the following holds. \begin{enumerate}[(i)] \item If the extension is rigid, then $\text{\bbfamily L}'$ is a partial normal subgroup of $\text{\bbfamily T}$, and $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ contains $\mathcal{F}'$ as a subsystem. \item If the extension is admissible, then the fusion system $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ is saturated. \end{enumerate} In particular, if the extension is both rigid and admissible, then it is a good extension. \end{thm} \begin{proof} Clearly, if the extension is both rigid and admissible, then it is good, so there is nothing to prove in this case. Suppose first that the extension is rigid. Let $C_S(\text{\bbfamily L}') = \{[(x,g)] \in S \,\, | \,\, \forall [y] \in \text{\bbfamily L}', \, \omega_y =[(x,g)|(y,1)|(x,g)^{-1}] \in \text{\bbfamily L} \mbox{ and } \Pi(\omega_y) = [(y,1)]\}$. Clearly, this is a subgroup of $S$. Furthermore, it satisfies the following condition: for each $P' \in \Delta'$, we have $P' \cdot C_S(\text{\bbfamily L}') \in \Delta$ since $$ (P' \cdot C_S(\text{\bbfamily L}')) \cap S' \geq P' \qquad \mbox{and} \qquad \tau(P' \cdot C_S(\text{\bbfamily L}')) = S_0''. $$ Thus, if $[x_1|\ldots|x_n] \in \text{\bbfamily L}'_n$ via some $P_0', \ldots, P_n' \in \Delta'$, then $[(x_1,1)|\ldots|(x_n,1)] \in \text{\bbfamily T}$ via the sequence $P_0, \ldots, P_n \in \Delta$, where $P_i = P_i' \cdot C_S(\text{\bbfamily L}')$. This shows that $\text{\bbfamily L}' \subseteq \text{\bbfamily T}$. That $\text{\bbfamily L}'$ is a partial subgroup of $\text{\bbfamily T}$ follows by the description of the simplices of $\text{\bbfamily L}'$ as pairs $[(x,1)]$, and normality follows because $\text{\bbfamily L}'$ is normal in $\text{\bbfamily L}$. The inclusion $\mathcal{F}' \subseteq \mathcal{F}_{\Delta}(\text{\bbfamily T})$ follows easily. Suppose now that the extension is admissible. By definition, $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ is $\Delta$-generated and $\Delta$-saturated. Since $\text{\bbfamily L}$ is an admissible extension it follows from Proposition \ref{aux4} that $\Delta$ contains all the $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-centric $\mathcal{F}_{\Delta}(\text{\bbfamily T})$-radical subgroups, and hence by \cite[Theorem A]{BCGLO1} or \cite[Proposition 3.6]{OV} it follows that $\mathcal{F}_{\Delta}(\text{\bbfamily T})$ is saturated. \end{proof} \begin{cor}\label{propext6-1} Let $(\text{\bbfamily L}', \Delta', S')$ be a saturated locality such that $\Delta'$ contains all the centric subgroups, let $(\text{\bbfamily L}'', \Delta'', S'')$ be a saturated locality such that $\Delta''$ contains all the centric subgroups, and let $\varepsilon \colon \text{\bbfamily L}'' \to \operatorname{Out}\nolimits(\text{\bbfamily L}';S')$ be an outer action. If $\varepsilon$ is the trivial morphism, then every extension of $(\text{\bbfamily L}', \text{\bbfamily L}'', \varepsilon)$ is good. \end{cor} \begin{proof} If $\varepsilon \colon \text{\bbfamily L}'' \to \operatorname{Out}\nolimits(\text{\bbfamily L}';S')$ is trivial, then any extension of $(\text{\bbfamily L}', \text{\bbfamily L}'', \varepsilon)$ is clearly rigid and admissible, and thus by Theorem \ref{propext6} the extension is good. \end{proof} \section{Applications}\label{Sapp} In this section we study some situations related to isotypical extensions of localities. We start by relating extensions of finite groups to isotypical extensions of localities. \begin{expl}\label{Expl1} Let $K \Right1{} G \Right1{\tau} Q$ be an extension of finite groups, and let $p$ be a prime. Fix Sylow $p$-subgroups $$ S_K \in \operatorname{Syl}\nolimits_p(K) \qquad S_G \in \operatorname{Syl}\nolimits_p(G) \qquad S_Q \in \operatorname{Syl}\nolimits_p(Q) $$ so that the above extension of groups restricts to an extension $S_K \to S_G \to S_Q$. Set also $\mathcal{F}_K = \mathcal{F}_{S_K}(K)$, $\mathcal{F}_G = \mathcal{F}_{S_G}(G)$ and $\mathcal{F}_Q = \mathcal{F}_{S_Q}(Q)$. Finally, let $(\text{\bbfamily L}_K, \Delta_K, S_K)$ be the proper locality associated to $K$, where $\Delta_K$ is the collection of centric subgroups in $\mathcal{F}_K$. An easy computation shows that $Z(K) \cong Z(\text{\bbfamily L}_K) \times Z'(K)$, where $Z'(K) = O_{p'}(Z(K))$. Furthermore, there is a natural group homomorphism $\operatorname{Out}\nolimits(K) \to \operatorname{Out}\nolimits((BK)^{\wedge}_p) \cong \operatorname{Out}\nolimits(\text{\bbfamily L}_K;S_K)$. Thus, there is a natural map $$ \underline{\aut}(BK) \Right3{\Omega} \underline{\aut}((BK)^{\wedge}_p) \cong \underline{\aut}(\text{\bbfamily L}_K;S_K). $$ The group extension $K \to G \to Q$ is classified by a map $BQ \to B \underline{\aut}(BK)$, and composition with $\Omega$ yields a map $BQ \to \underline{\aut}(\text{\bbfamily L}_K;S_K)$ which in turn determines an isotypical extension $$ \text{\bbfamily L}_K \Right2{} \text{\bbfamily L} \Right2{} BQ. $$ Moreover, this is a good extension in the sense of \ref{defigood} (here, $Q$ is seen as a locality $(BQ, \Delta_Q, S_Q)$, where $\Delta_Q$ is the collection of all subgroups of $S_Q$). Consider now the following modification. The classifying map $BQ \to B\underline{\aut}(\text{\bbfamily L}_K;S_K)$ induces an outer action $$ \alpha \colon Q \Right2{} \operatorname{Out}\nolimits(\text{\bbfamily L}_K;S_K). $$ Given such an action, let $\Delta_Q$ be the smallest collection of subgroups of $S_Q$ that satisfies the following conditions: \begin{enumerate}[(1)] \item it is closed by $\mathcal{F}_Q$-conjugation and overgroups; \item it contains every $\mathcal{F}_Q$-centric $\mathcal{F}_Q$-radical subgroup of $S_Q$; and \item the action $\alpha$ is both rigid and admissible. \end{enumerate} Let also $(\text{\bbfamily L}_Q, \Delta_Q, S_Q)$ be the locality associated to $Q$ with $N_{\text{\bbfamily L}_Q}(X, Y) = N_Q(X, Y)$ for each $X, Y \in \Gamma_Q$. This is indeed a locality by \cite[Example 2.10]{Chermak}, and there is an obvious monomorphism of partial groups $\iota \colon \text{\bbfamily L}_Q \to BQ$. Moreover, a group extension $K \to H \to Q$ with the above outer action produces a map $$ \text{\bbfamily L}_Q \Right2{\iota} BQ \Right2{} B\underline{\aut}(BK) \Right2{\Omega} B\underline{\aut}((BK)^{\wedge}_p) \cong B\underline{\aut}(\text{\bbfamily L}_K;S_K), $$ where the middle arrow is the classifying map of the group extension. Note that the outer action associated to $\text{\bbfamily L}_Q \to B\underline{\aut}(\text{\bbfamily L}_K;S_K)$ is the composition $\alpha' \colon \text{\bbfamily L}_Q \Right1{\iota} Q \Right1{\alpha} \operatorname{Out}\nolimits(\text{\bbfamily L}_K;S_K)$, and thus it is rigid and admissible by hypothesis. Thus, this determines a good extension $$ \text{\bbfamily L}_K \Right2{} \text{\bbfamily L}_H \Right2{} \text{\bbfamily L}_Q, $$ where $|\text{\bbfamily L}_H|^{\wedge}_p \simeq (BH)^{\wedge}_p$. Let $\alpha'$ and $(\text{\bbfamily L}_Q, \Delta_Q, S_Q)$ be as above. In general, it is not clear whether a map $\text{\bbfamily L}_Q \to B\underline{\aut}(\text{\bbfamily L}_K)$ (which classifies a good extension of localities) determines a group extension $K \to H \to Q$, since it depends on the following lifting/extension problem $$ \xymatrix@C=3cm{ BQ \ar@{.>}[r] & B\underline{\aut}(BK) \ar[d]^{\Omega} \\ \text{\bbfamily L}_Q \ar[u]^{\iota} \ar[r] & B\underline{\aut}(\text{\bbfamily L}_K;S_K) } $$ \end{expl} Next, we relate certain fibrations involving $p$-local finite groups to isotypical extensions of localities. The following is a generalization of \cite[Proposition 7.1]{BLO6}. \begin{prop}\label{fibrationfb} Let $\mathcal{G} = (S, \FF, \LL)$ be a $p$-local finite group and let $(\text{\bbfamily L}, \Delta, S)$ be its associated proper locality. Then, for each saturated locality $(\overline{\text{\bbfamily L}}, \overline{\Delta}, \overline{S})$ there is a bijection from the set of equivalence classes of fibre bundles over $\overline{\text{\bbfamily L}}$ with fibre $\text{\bbfamily L}$ and structure group $N\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)$ to the set of equivalence classes of fibrations over $\overline{\text{\bbfamily L}}$ with fibre homotopy equivalent to $B\mathcal{G}$: a bijection which sends the class of a fibre bundle to the equivalence class of its fibrewise $p$-competion. \end{prop} \begin{proof} By \cite[Theorem IV.5.6]{BGM}, there is a bijection between the set of equivalence classes of fibrations over $|\overline{\text{\bbfamily L}}|$ with fibre $B\mathcal{G}$ and the set $[|\overline{\text{\bbfamily L}}|, B\underline{\aut}(B\mathcal{G})]_{\ast}$ of homotopy classes of pointed maps. Similarly, there is a bijection between the set of equivalence classes of $|\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)|$-bundles over $\overline{\text{\bbfamily L}}$ with fibre $\text{\bbfamily L}$ and the set $[\overline{\text{\bbfamily L}}, B\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)]_{\ast}$ of homotopy classes of pointed maps. By Corollary \ref{autloc2} the natural map $$ \Lambda \colon |\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)| \Right4{} \underline{\aut}(\text{\bbfamily L}) \Right4{} \underline{\aut}(B\mathcal{G}), $$ where the leftmost arrow is an inclusion of simplicial sets (see Lemma \ref{autloc0}) and the rightmost arrow is induced by $p$-completion, is a homotopy equivalence. It follows that the map $\Phi \colon [\overline{\text{\bbfamily L}}, B\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)]_{\ast} \Right6{B\Lambda \circ -} [|\overline{\text{\bbfamily L}}|, B\underline{\aut}(B\mathcal{G})]_{\ast}$ that sends the class of an $|\mathcal{A}ut} %%%{\EuR{Aut}(\text{\bbfamily L};S)|$-bundle to the class of its fibrewise $p$-completion is a bijection. \end{proof} Part of the proof for the following result was communicated by R. Levi. \begin{thm}\label{app2} Let $F \to X \to B$ be a fibration where both $B$ and $F$ are homotopy equivalent to classifying spaces of $p$-local finite groups. Then, $X$ is homotopy equivalent to the classifying space of a $p$-local finite group. Moreover, there exist proper localities $(\text{\bbfamily L}_F, \Delta_F, S_F)$ and $(\text{\bbfamily L}_B, \Delta_B, S_B)$, and a commutative diagram of fibre bundles $$ \xymatrix{ F \ar[r] & X \ar[r] & B \\ |\text{\bbfamily L}_F| \ar[u] \ar[r] & |\text{\bbfamily L}| \ar[r] \ar[u] & |\text{\bbfamily L}_B| \ar[u] } $$ where the bottom row is (the realization of) a good extension and all the vertical arrows are equivalences after $p$-completion. \end{thm} \begin{proof} Let $(\text{\bbfamily L}_F, \Delta_F, S_F)$ be the proper locality associated to the $p$-local finite group for $F$, so $|\text{\bbfamily L}_F|^{\wedge}_p \simeq F$. For each linking system $\mathcal{L}_B$ with $|\mathcal{L}_B|^{\wedge}_p \simeq B$ (we assume that $\operatorname{Ob}\nolimits(\mathcal{L}_B)$ contains all the centric radicals), let $(\text{\bbfamily L}_B, \Delta_B, S_B)$ be the proper locality associated to $\mathcal{L}_B$. By Theorem \ref{equivnerves} there is an equivalence $|\text{\bbfamily L}_B|^{\wedge}_p \simeq B$, and thus there is a commutative diagram \begin{equation}\label{diagfibr} \xymatrix{ F \ar[r] \ar@{=}[d] & X \ar[r] & B \\ F \ar[r] & X_0 \ar[u] \ar[r] & |\text{\bbfamily L}_B| \ar[u] \\ |\text{\bbfamily L}_F| \ar[r] \ar[u] & |\text{\bbfamily L}| \ar[r] \ar[u] & |\text{\bbfamily L}_B| \ar@{=}[u] \\ } \end{equation} where each row is a fibre bundle. The middle row is obtained from the top row by pulling back along the completion map $|\text{\bbfamily L}_B| \to B$, and the bottom row is obtained form the middle row by Proposition \ref{fibrationfb}. In particular, the classifying map for $\text{\bbfamily L}_F \to \text{\bbfamily L} \to \text{\bbfamily L}_B$ (and thus the associated twisting function) is given by the composition $$ \alpha \colon |\text{\bbfamily L}_B| \Right2{} B \Right2{} B\underline{\aut}(F) \cong B\underline{\aut}(\text{\bbfamily L}_F;S_F). $$ By comparing the Serre spectral sequences associated to each of the fibre bundles in (\ref{diagfibr}) it follows that $\text{\bbfamily L}$ is homotopy equivalent to $X$ after $p$-completion. However, this still does not imply that $X$ is the classifying space of a $p$-local finite group. We consider three cases: when $B$ is $2$-connected, when $B$ is $1$-connected, and the general case. Each case is done in a separate step. \textbf{Step 1.} Suppose first that $B$ is $2$-connected. By \cite[Theorem 8.1]{BLO2}, we have $\pi_i(B\underline{\aut}(F)) = 0$ for all $i \geq 3$, and thus the map $B \to B\underline{\aut}(F)$ is nulhomotopic. As a consequence, we have $$ X \simeq F \times B \qquad \mbox{and} \qquad \text{\bbfamily L} \cong \text{\bbfamily L}_F \times \text{\bbfamily L}_B. $$ Clearly, the extension $\text{\bbfamily L}_F \to \text{\bbfamily L} \to \text{\bbfamily L}_B$ is good in the sense of \ref{defigood}, and $X$ is equivalent to the classifying space of a $p$-local finite group. Note also that in this case the choice of the locality $(\text{\bbfamily L}_B, \Delta_B, S_B)$ is irrelevant, as long as $\Delta_B$ contains all the centric radicals and $|\text{\bbfamily L}_B|^{\wedge}_p \simeq B$. \textbf{Step 2.} Suppose now that $B$ is $1$-connected. Set $A = H_2(B, {\mathbb Z}^{\wedge}_p)$, which is a finite abelian $p$-group, and consider the commutative diagram of fibration sequences \begin{equation}\label{diag34} \xymatrix{ & K(A, 1) \ar@{=}[r] \ar[d] & K(A,1) \ar[d] \\ F \ar@{=}[d] \ar[r] & Y \ar[r] \ar[d] & D \ar[d] \\ F \ar[r] & X \ar[r] \ar[d] & B \ar[d] \\ & K(A,2) \ar@{=}[r] & K(A,2) } \end{equation} From now on we abbreviate $K(A, 1) \simeq BA$. By construction, $D$ is the $2$-connected cover of $B$. To see that $D$ is also homotopy equivalent to the classifying space of a $p$-local finite group, consider the fibration $BA \to D \to B$. By definition, this is a central extension in the sense of \cite{BCGLO2}, and thus $D$ is homotopy equivalent the classifying space of a $p$-local finite group by \cite[Theorem E]{BCGLO2}. Step 1 applies to show that $Y \simeq F \times D$ is homotopy equivalent to the classifying space of a $p$-local finite group. Finally, we see that $X$ is equivalent to the classifying space of a $p$-local finite group since it corresponds to the (central) quotient of the $p$-local finite group associated to $Y$ by the subgroup $A$. For each space $Z$ in the two middle rows of the above diagram, let $S_Z$ denote the Sylow $p$-subgroup of the corresponding $p$-local finite group. These $p$-groups can be chosen so that there is a commutative diagram of group extensions $$ \xymatrix{ & A \ar@{=}[r] \ar[d] & A \ar[d] \\ S_F \ar[r] \ar@{=}[d] & S_Y \ar[r] \ar[d] & S_D \ar[d] \\ S_F \ar[r] & S_X \ar[r] & S_B } $$ Let $(\text{\bbfamily L}_D, \Delta_D, S_D)$ be the proper locality associated to $D$, where $\Delta_D$ is the collection of quasicentric subgroups that contain the subgroup $A \leq S_D$. Let also $\Delta_B$ be the collection of subgroups of $S_B$ of the form $PA/A$ for $P \in \Delta_D$, and let $(\text{\bbfamily L}_B, \Delta_B, S_B)$ be the proper locality associated to $B$ with object set $\Delta_B$. Notice that $\Delta_B$ is the collection of all quasicentric subgroups by \cite[Lemma 6.4]{BCGLO2}. By first pulling back along the completion map $|\text{\bbfamily L}_B| \to B$ and then applying Lemma \ref{fibrationfb} in (\ref{diag34}), we produce a commutative diagram of isotypical extensions $$ \xymatrix{ & BA \ar@{=}[r] \ar[d] & BA \ar[d] \\ \text{\bbfamily L}_F \ar@{=}[d] \ar[r] & \text{\bbfamily L}_Y \ar[r] \ar[d] & \text{\bbfamily L}_D \ar[d] \\ \text{\bbfamily L}_F \ar[r] & \text{\bbfamily L} \ar[r] & \text{\bbfamily L}_B } $$ By Corollary \ref{propext6-1}, the rightmost column is a good extension in the sense of \ref{defigood}, since the associated outer action is trivial; and so is the middle row, by Step 1. Note also that there is a commutative diagram of morphisms of partial groups $$ \xymatrix{ \text{\bbfamily L}_D \ar[d] \ar[rd]^{\varepsilon_D} & \\ \text{\bbfamily L}_B \ar[r]_{\varepsilon} & \operatorname{Out}\nolimits(\text{\bbfamily L}_F;S_F) } $$ where $\varepsilon \colon \text{\bbfamily L}_B \to \operatorname{Out}\nolimits(\text{\bbfamily L}_F;S_F)$ and $\varepsilon_D \colon \text{\bbfamily L}_D \to \operatorname{Out}\nolimits(\text{\bbfamily L}_F;S_F)$ denote the corresponding outer actions. Since $D$ is $2$-connected, it follows by Step 1 that $\varepsilon_D$ is the trivial map, and thus $\varepsilon$ is also the trivial map (since $\text{\bbfamily L}_D \to \text{\bbfamily L}_B$ is surjective). Thus, the extension $\text{\bbfamily L}_F \to \text{\bbfamily L} \to \text{\bbfamily L}_B$ is good by Corollary \ref{propext6-1} (note that $\Delta_B$ contains all the centrics). \textbf{Step 3.} The general case. There is a commutative diagram of fibrations $$ \xymatrix{ F \ar@{=}[d] \ar[r] & W \ar[r] \ar[d] & C \ar[d] \\ F \ar[r] & X \ar[r] \ar[d] & B \ar[d] \\ & B\pi_1(B) \ar@{=}[r] & B \pi_1(B) } $$ where $\pi_1(B)$ is a finite $p$-group by \cite[Proposition 1.12]{BLO2}, since $B$ is the classifying space of a $p$-local finite group. Note that $W \to X$ and $C \to B$ are (regular) covering spaces, and thus both $C$ and $X$ are equivalent to classifying spaces of $p$-local finite groups by \cite[Theorem A]{BLO6}. Since all the spaces involved are homotopy equivalent to classifying spaces of $p$-local finite groups, the above diagram induces a commutative diagram of group extensions $$ \xymatrix{ S_F \ar[r] \ar@{=}[d] & S_W \ar[r]^{\tau_W} \ar[d] & S_C \ar[d] \\ S_F \ar[r] & S_X \ar[r]_{\tau} & S_B } $$ where $S_Z$ denotes the Sylow $p$-subgroup for the $p$-local finite group associated to the space $Z$. Even if the $p$-local finite group associated to $Z$ is only unique up to isomorphism, we can still choose Sylow $p$-subgroups as above to make the diagram commutative, and we assume these choices fixed. Consider the following. \begin{enumerate}[(1)] \item $\Delta_C$ is the collection of all quasicentric subgroups of $S_C$ with respect to the $p$-local finite group associated to $C$. \item $\Delta_B = \{P \leq S_B \, | \, P \cap S_C \in \Delta_C\}$. \item $\Delta_F$ is the collection of all centric subgroups of $S_F$ with respect to the $p$-local finite group associated to $F$. \item $\Delta_W = \{P \leq S_W \, | \, P \cap S_F \in \Delta_F \mbox{ and } \tau_W(P) \in \Delta_C\}$. \item $\Delta_X = \{P \leq S_X \, | \, P \cap S_W \in \Delta_W\}$. \end{enumerate} We claim that each of the above collections of subgroups contains all the centric radical subgroups with respect to the corresponding $p$-local finite group. \begin{enumerate}[(a)] \item Let $(\text{\bbfamily L}_C, \Delta_C, S_C)$ be the proper locality associated to $C$. By Lemma \ref{fibrationfb} there is an isotypical extension $\text{\bbfamily L}_C \Right2{} \text{\bbfamily L}_B \Right2{} B\pi_1(B)$, which is rigid and admissible by Remark \ref{perfect1} (iii) (and thus it is good by Theorem \ref{propext6}). In particular $\Delta_B$ contains all the centric radical subgroups of $S_B$ with respect to the $p$-local finite group associated to $B$. \item The fibration $F \to W \to C$ induces an isotypical extension $\text{\bbfamily L}_F \Right2{} \text{\bbfamily L}_W \Right2{} \text{\bbfamily L}_C$, which is good by Step 2. As a consequence, $\Delta_W$ contains all the centric radical subgroups of $S_W$ with respect to the $p$-local finite group associated to $W$. \item Let $(\4{\text{\bbfamily L}}_W, \Delta_W, S_W)$ be the proper locality associated to $W$, with $\Delta_W$ as above. By Lemma \ref{fibrationfb} there is an isotypical extension $\4{\text{\bbfamily L}}_W \Right2{} \text{\bbfamily L}_X \Right2{} B\pi_1(B)$, which again is rigid and admissible by Remark \ref{perfect1} (iii) (and thus good by Theorem \ref{propext6}). In particular this implies that the collection $\Delta_X$ contains all the centric radical subgroups of $S_X$ with respect to the $p$-local finite group associated to $X$. \end{enumerate} Finally, consider the fibration $F \to X \to B$. By first pulling back along the $p$-completion map $|\text{\bbfamily L}_B| \to B$, and then applying Lemma \ref{fibrationfb}, we obtain an extension $$ \text{\bbfamily L}_F \Right2{} \text{\bbfamily L} \Right2{\tau} \text{\bbfamily L}_B. $$ Let $S_X$ be as above, and set $$ \Delta = \{P \leq S_X \, | \, P \cap S_F \in \Delta_F \mbox{ and } \tau(P) \in \Delta_B\}. $$ We claim that the above extension is good in the sense of \ref{defigood}. To show this, we check that this extension is rigid, and that $\Delta$ contains all the centric radical subgroups of $S_X$ with respect to the $p$-local finite group associated to $X$. By Step 2, the outer action $\varepsilon_C \colon \text{\bbfamily L}_C \Right2{} \operatorname{Out}\nolimits(\text{\bbfamily L}_F;S_F)$ is trivial. Furthermore, it factors through the outer action $\varepsilon \colon \text{\bbfamily L}_B \to \operatorname{Out}\nolimits(\text{\bbfamily L}_F;S_F)$ associated to the extension $\text{\bbfamily L}_F \to \text{\bbfamily L} \to \text{\bbfamily L}_B$ above, which implies that $$ S_C \leq \operatorname{Ker}\nolimits(S_B \Right2{} \text{\bbfamily L}_B \Right2{} \operatorname{Out}\nolimits(\text{\bbfamily L}_F;S_F)). $$ On the other hand, $S_C \in \Delta_B$ by definition, and thus the extension $\text{\bbfamily L}_F \to \text{\bbfamily L} \to \text{\bbfamily L}_B$ is rigid, since $\Delta_B$ is closed by overgroups. To show that $\Delta$ contains all the centric radical subgroups of $S_X$ with respect to the $p$-local finite group associated to $X$, we prove that $\Delta = \Delta_X$ above. Indeed, let $P \in \Delta_X$. Then, \begin{itemize} \item $P \cap S_W \in \Delta_W$, which implies that that $P \cap S_F = (P \cap S_W) \cap S_F \in \Delta_F$; and \item $\tau(P) \cap S_C = \tau_W(P \cap S_W) \in \Delta_C$, and thus $P \in \Delta$. \end{itemize} Conversely, let $P \in \Delta$. Then, \begin{itemize} \item $(P \cap S_W) \cap S_F = (P \cap S_F) \cap S_W = P \cap S_F \in \Delta_F$; and \item $\tau_W(P \cap S_W) = \tau(P) \cap S_C \in \Delta_C$, since $\tau(P) \in \Delta_B$. Thus $P \in \Delta_X$. \end{itemize} We already showed above that $\Delta_X$ contains all the centric radical subgroups, and thus the extension $\text{\bbfamily L}_F \to \text{\bbfamily L} \to \text{\bbfamily L}_B$ is good and satisfies the properties required in the statement. \end{proof}
{ "redpajama_set_name": "RedPajamaArXiv" }
9,426
{"url":"https:\/\/repository.kaust.edu.sa\/handle\/10754\/665535.1?show=full","text":"### Notice\n\n dc.contributor.author Boffi, Daniele dc.contributor.author Gardini, Francesca dc.contributor.author Gastaldi, Lucia dc.date.accessioned 2020-10-12T12:24:48Z dc.date.available 2020-10-12T12:24:48Z dc.date.issued 2020-01-05 dc.identifier.uri http:\/\/hdl.handle.net\/10754\/665535.1 dc.description.abstract We discuss the solution of eigenvalue problems associated with partial differential equations that can be written in the generalized form $\\m{A}x=\\lambda\\m{B}x$, where the matrices $\\m{A}$ and\/or $\\m{B}$ may depend on a scalar parameter. Parameter dependent matrices occur frequently when stabilized formulations are used for the numerical approximation of partial differential equations. With the help of classical numerical examples we show that the presence of one (or both) parameters can produce unexpected results. dc.description.sponsorship The authors are members of INdAM Research group GNCS and their research is supported by PRIN\/MIUR. The research of the first and third authors is partially supported by IMATI\/CNR. dc.publisher arXiv dc.relation.url https:\/\/arxiv.org\/pdf\/2001.01304 dc.rights Archived with thanks to arXiv dc.title Approximation of PDE eigenvalue problems involving parameter dependent matrices dc.type Preprint dc.contributor.department King Abdullah University of Science and Technology (KAUST), Saudi Arabia dc.eprint.version Pre-print dc.contributor.institution Dipartimento di Matematica \u201cF. Casorati\u201d, Universita di Pavia, Italy dc.contributor.institution Department of Mathematics and System Analysis, Aalto University, Finland dc.contributor.institution DICATAM, Universita di Brescia, Italy dc.identifier.arxivid 2001.01304 kaust.person Boffi, Daniele refterms.dateFOA 2020-10-12T12:27:43Z\n\ufeff\n\n### Files in this item\n\nName:\nPreprintV2.pdf\nSize:\n4.949Mb\nFormat:\nPDF\nDescription:\nPreprint File Version 2\n\n### This item appears in the following Collection(s)\n\nVersionItemEditorDateSummary\n\n*Selected version","date":"2021-10-23 20:21:21","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.7195722460746765, \"perplexity\": 4032.8683354002414}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-43\/segments\/1634323585768.3\/warc\/CC-MAIN-20211023193319-20211023223319-00253.warc.gz\"}"}
null
null
Lunch and RMPA (Rocky Mountain Print Alliance) Exhibition at the Vee Bar Guest Ranch (arrive apx. 12:30 pm) …followed by time for conversation and relaxation. Options will include time at the river, hot tub, archery, hay ride and additional charges for firing range or horse riding. We will reconvene in the afternoon for a panel discussion with RMPA members, followed by a barbeque dinner and fireside conversation under the stars. Return to Laramie around 8pm. *lunch, dinner, and transportation are included in the "Further West" conference fees. Limited rooms are available at the Vee Bar guest ranch for conference members who would like to stay Saturday night. The Vee Bar guest ranch is located about thirty minutes west of the conference site and about fifteen minutes from the Laramie Airport.
{ "redpajama_set_name": "RedPajamaC4" }
5,493
Q: Não lista dados do banco corretamente na View asp.net Os dados foram inserido no banco, mas na View não mostra um dos campo. Eu verifiquei no SQL Server e está tudo certo, mas o campo nome retorna vazio na view public ActionResult Index() { List<MovimentacaoVM> lispedido; using (Db db = new Db()) { lispedido = db.Movimentacao.ToArray() .OrderBy(x => x.MovimentacaoId) .Select(x => new MovimentacaoVM(x)).ToList(); } return View(lispedido); } Código da view: @model IEnumerable<PraticaNtoN.Models.MovimentacaoVM> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Criar") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.ProdutoNome) </th> <th> @Html.DisplayNameFor(model => model.ClienteNome) </th> <th> @Html.DisplayNameFor(model => model.DataCriacao) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.ProdutoNome) </td> <td> @Html.DisplayFor(modelItem => item.ClienteNome) </td> <td> @Html.DisplayFor(modelItem => item.DataCriacao) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.MovimentacaoId }) | @Html.ActionLink("Details", "Details", new { id=item.MovimentacaoId }) | @Html.ActionLink("Delete", "Delete", new { id=item.MovimentacaoId }) </td> </tr> } </table> Método MovimentacaoVM public MovimentacaoVM(Movimentacao row) { MovimentacaoId = row.MovimentacaoId; ClienteId = row.ClienteId; DataCriacao = row.DataCriacao; ProdutoId = row.ProdutoId; ProdutoNome = row.ClienteNome; ProdutoNome = row.ProdutoNome; } A: Primeiramente uma dica: não faça a ordernação dos dados em memória a não ser que tenha um motivo para isto. Claro que isso não é uma receita que você deva seguir cegamente, mas na maioria das vezes delegar a ordenação para o banco de dados é muito mais performático. Você pode ver mais detalhes sobre isto em: Em que momento o Entity Framework executa a query de um IQueryable? public ActionResult Index() { List<MovimentacaoVM> lispedido; using (Db db = new Db()) { lispedido = db.Movimentacao.OrderBy(x => x.MovimentacaoId) //Remova o ToArray() .Select(x => new MovimentacaoVM(x)).ToList(); } return View(lispedido); } Segundo, seu erro é bem simples. Veja o método MovimentacaoVM, que é o método que faz a seleção dos itens public MovimentacaoVM(Movimentacao row) { MovimentacaoId = row.MovimentacaoId; ClienteId = row.ClienteId; DataCriacao = row.DataCriacao; ProdutoId = row.ProdutoId; //ProdutoNome = row.ClienteNome; // <----- Isso está errado ClienteNome = row.ClienteNome; // <------- Deveria ser isto ProdutoNome = row.ProdutoNome; }
{ "redpajama_set_name": "RedPajamaStackExchange" }
6,443
Вахтанг Беридзе: Беридзе, Вахтанг Вуколович (1914—2000) — грузинский советский искусствовед. Беридзе, Вахтанг Ираклиевич (род. 1980) — российский актёр, шоумен, продюсер, теле- и радиоведущий. См. также Улица Вахтанга Беридзе
{ "redpajama_set_name": "RedPajamaWikipedia" }
5,357
{"url":"https:\/\/en.academic.ru\/dic.nsf\/enwiki\/4229776","text":"# Euclidean distance matrix\n\n\ufeff\nEuclidean distance matrix\n\nIn mathematics, a Euclidean distance matrix is an \"n\u00d7n\" matrix representing the spacing of a set of \"n\" points in Euclidean space. If \"A\" is a Euclidean distance matrix and the points are defined on \"m\"-dimensional space, then the elements of \"A\" are given by\n\n:\n\nwhere ||.||2 denotes the 2-norm on Rm.\n\nProperties\n\nSimply put, the element \"aij\" describes the square of the distance between the \"i\" th and \"j\" th points in the set. By the properties of the 2-norm (or indeed, Euclidean distance in general), the matrix \"A\" has the following properties.\n\n* All elements on the diagonal of \"A\" are zero (i.e. is it a hollow matrix).\n* The trace of \"A\" is zero (by the above property).\n* \"A\" is symmetric (i.e. \"aij\" = \"aji\").\n* \"aij\"1\/2 is less than or equal to \"aik\"1\/2 + \"akj\"1\/2 (by the triangle inequality)\n* $a_\\left\\{ij\\right\\}ge 0$\n\nReferences\n\n*; chapter 4.\n*\n\nWikimedia Foundation. 2010.\n\n### Look at other dictionaries:\n\n\u2022 Matrix - \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u043d\u0430 \u0410\u043a\u0430\u0434\u0435\u043c\u0438\u043a\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0439 \u043f\u0440\u043e\u043c\u043e\u043a\u043e\u0434 Pharmacosmetica \u0438\u043b\u0438 \u0432\u044b\u0433\u043e\u0434\u043d\u043e matrix \u043a\u0443\u043f\u0438\u0442\u044c \u0441\u043e \u0441\u043a\u0438\u0434\u043a\u043e\u0439 \u043d\u0430 \u0440\u0430\u0441\u043f\u0440\u043e\u0434\u0430\u0436\u0435 \u0432 Pharmacosmetica\n\n\u2022 Distance matrix \u2014 In mathematics, computer science and graph theory, a distance matrix is a matrix (two dimensional array) containing the distances, taken pairwise, of a set of points. This matrix will have a size of N\u00d7N where N is the number of points, nodes or\u2026 \u2026 \u00a0 Wikipedia\n\n\u2022 Distance matrices in phylogeny \u2014 Distance matrices are used in phylogeny as non parametric distance methods were originally applied to phenetic data using a matrix of pairwise distances. These distances are then reconciled to produce a tree (a phylogram, with informative branch\u2026 \u2026 \u00a0 Wikipedia\n\n\u2022 Euclidean plane isometry \u2014 In geometry, a Euclidean plane isometry is an isometry of the Euclidean plane, or more informally, a way of transforming the plane that preserves geometrical properties such as length. There are four types: translations, rotations, reflections,\u2026 \u2026 \u00a0 Wikipedia\n\n\u2022 Distance \u2014 This article is about distance in the mathematical or physical sense. For other senses of the term, see distance (disambiguation). Proximity redirects here. For the 2001 film, see Proximity (film). Distance (or farness) is a numerical description \u2026 \u00a0 Wikipedia\n\n\u2022 Distance correlation \u2014 In statistics and in probability theory, distance correlation is a measure of statistical dependence between two random variables or two random vectors of arbitrary, not necessarily equal dimension. Its important property is that this measure of\u2026 \u2026 \u00a0 Wikipedia\n\n\u2022 Euclidean vector \u2014 This article is about the vectors mainly used in physics and engineering to represent directed quantities. For mathematical vectors in general, see Vector (mathematics and physics). For other uses, see vector. Illustration of a vector \u2026 \u00a0 Wikipedia\n\n\u2022 Euclidean group \u2014 In mathematics, the Euclidean group E ( n ), sometimes called ISO( n ) or similar, is the symmetry group of n dimensional Euclidean space. Its elements, the isometries associated with the Euclidean metric, are called Euclidean moves.These groups\u2026 \u2026 \u00a0 Wikipedia\n\n\u2022 Euclidean subspace \u2014 In linear algebra, an Euclidean subspace (or subspace of R n ) is a set of vectors that is closed under addition and scalar multiplication. Geometrically, a subspace is a flat in n dimensional Euclidean space that passes through the origin.\u2026 \u2026 \u00a0 Wikipedia\n\n\u2022 Matrix (mathematics) \u2014 Specific elements of a matrix are often denoted by a variable with two subscripts. For instance, a2,1 represents the element at the second row and first column of a matrix A. In mathematics, a matrix (plural matrices, or less commonly matrixes)\u2026 \u2026 \u00a0 Wikipedia\n\n\u2022 Hollow matrix \u2014 In mathematics, a hollow matrix may refer to one of several related classes of matrix.parseA hollow matrix may be one with few non zero entries: that is, a sparse matrix [cite book | author=Pierre Mass\u00e9 | title=Optimal Investment Decisions: Rules \u2026 \u00a0 Wikipedia","date":"2020-08-09 03:43:13","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 1, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.8905826210975647, \"perplexity\": 1694.5463780532484}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2020-34\/segments\/1596439738380.22\/warc\/CC-MAIN-20200809013812-20200809043812-00539.warc.gz\"}"}
null
null
\section{Introduction.} Markov Decision Process (MDP) are widely used to model sequential decision-making problems under uncertainty. The goal is to find a policy that maximizes the infinite horizon discounted reward, for a (fixed) \textit{discount factor} $\lambda \in (0,1)$. Several algorithms have been studied in the literature, including LP formulation, policy iteration (\cite{howard-1960},\cite{Ye}), or value iteration (VI); we refer the reader to \cite{Puterman} and \cite{Bertsekas} for extensive reviews of MDPs. However, none of these algorithms scale well when $\lambda$ is close to $1$, which is the case in many applications where the effective horizon is large. In particular, the number of iterations before convergence scales as $1/(1-\lambda).$ Moreover, each iteration of VI becomes computationally expensive when the numbers of states and actions of our MDPs become large. The goal in this paper is to design algorithms to solve MDPs that are scalable and more efficient than current approaches. Several faster algorithms have been proposed in this direction in the literature. The most widespread are the \textit{Gauss-Seidel} and \textit{Jacobi} value iteration algorithms, which iteratively apply operators that are variations of the Bellman operator (see Section 6.3.3 in~\cite{Puterman}). The authors in \cite{herzberg-1994}, \cite{herzberg-1996} propose iterative algorithms based on one-step and $k$-step look-ahead, while \cite{shlakhter-2010} compose the Bellman operator with a projection. We would like to note that even though these algorithms can be proved to converge at linear rate at least as fast as VI, the exact convergence rate is not known. \subsection{Our Contributions.} Our main contributions are as follows. \vspace{2mm} \paragraph{Connection between Gradient Descent and Value Iteration.} We present a fundamental analogy between gradient descent (GD) and value iteration (VI). In particular, for the bellman operator $T$ in value iteration, we consider $\bm{v} - T(\bm{v})$ as the gradient of some function at $\bm{v} \in \mathbb{R}^{n}$. Therefore, the {\em gradient} of this function vanishes at the fixed-point of $T$. We extend this analogy and propose an iterative algorithm, \textit{Relaxed Value Iteration} (\ref{alg:R-VI}). We choose some fixed step sizes conditions based on our analogy and prove convergence at a linear rate that surprisingly matches the convergence and step sizes of gradient descent. \paragraph{Accelerated Value Iteration.} Our main contribution is to present an accelerated algorithm for value iteration. Our algorithm relies upon the idea of Nesterov's acceleration in convex optimization and choosing the step sizes appropriately. While we borrow ideas from convex optimization, the proofs for convergence of gradient descent algorithms can not be directly extended to our setting, since the Bellman operator is neither smooth nor convex. We provide insights on the dynamics of Accelerated Value Iteration (Algorithm \ref{alg:AVI}). In particular, we show that our algorithm is a composition of carefully chosen affine maps (possibly different in each iteration) and relate the convergence to the joint-spectral radius of this family of affine maps. While our convergence guarantees do not extend to Algorithm \ref{alg:AVI} our numerical experiments show that it exhibits strong empirical performances, outperforming by up to one order of magnitude the current state-of-the-art approaches. \paragraph{Lower-bound on convergence rate of first-order algorithms.} We present a family of hard instances of MDPs where the transient convergence of value iteration is a lower bound on the convergence rate of a large class of algorithms (including Algorithm \ref{alg:AVI}) when the number of iterations is smaller than the number of states. This is a key difference with smooth, convex optimization, where Nesterov's accelerated gradient descent is known to converge faster than gradient descent, while attaining the optimal convergence rate over the class of all smooth, convex functions. \paragraph{Accelerated and Momentum Value Computation.} We also present an accelerated and a momentum algorithm for computing the value vector of a given policy (Accelerated Value Computation, Algorithm \ref{alg:AVC} and Momentum Value Computation, \ref{alg:MVC}) and we show theoretical convergence guarantees. In particular, when the Markov chain induced by a policy $\pi$ is \textit{irreducible} and \textit{reversible}, Algorithm \ref{alg:AVC} and Algorithm \ref{alg:MVC} compute the value vector of $\pi$ at a significantly faster rate than current approaches. Their running time scale as $1/\sqrt{1-\lambda}$, a significant improvement compared to $1/(1-\lambda)$ as in the current approaches. Our numerical experiments show that Algorithm \ref{alg:AVC} and Algorithm \ref{alg:MVC} achieve significant speedup compared to current state-of-the-art approaches, both when the states and actions spaces become large, as well as when the discount factor $\lambda$ approaches $1$. \subsection{Related Work.} Several variants of value iteration have been considered in the literature, based on changing the update operators, either with alternate Bellman operators (such as \textit{Gauss-Seidel} and \textit{Jacobi} value iteration algorithms, see Section 6.3.3 in~\cite{Puterman})), or \textit{Anderson mixing} to speed up empirically the convergence of value iteration (see \cite{ref-a}, \cite{ref-c}). \cite{hendrickx-2019} consider acceleration but for the case of $\alpha$-averaged operators instead of Bellman operators. In contrast here, we propose to change the value iteration to incorporate the idea of acceleration based on our analogy between value iteration and gradient descent and insights from accelerated algorithms for convex optimization. MDPs have been studied extensively in the literature from an optimization perspective. In particular, analogous to our connection between gradient descent and value iteration, \cite{Puterman-PI} show that policy iteration can be reformulated as a variant of the Newton's algorithm in convex optimization. \cite{approx-newton-methods-MDP} and \cite{ref-e} consider approximate Newton's algorithm for policy search. \cite{protasov-PI} show that a variant of policy iteration has a global linear convergence rate, and a quadratic convergence rate when the current estimate is close enough to the optimal solution analogous to the convergence behavior of the Newton's algorithm (see \cite{boyd-2004}). The connection between Newton's algorithm and policy iteration has been extended to the case of stochastic games (\cite{ref-d}). Moreover, \cite{operator-approach} draw a connection between the optimal value vector of a two-player stochastic game and a policy iteration algorithm for optimizing the max-min joint spectral radius of two sets of matrices. While these works also draw a formal connection between MDP algorithms and convex optimization, they do not suggest any modification of policy iteration based on this analogy. Our main contribution in this paper is to propose a new accelerated value iteration algorithm based on insights from first-order algorithms in convex optimization. \section{Preliminaries on MDP.}\label{sec:MDP} A Markov Decision Process (MDP) is given by a tuple $(\mathbb{S},\mathbb{A},\bm{P},\bm{r},\bm{p}_{0},\lambda)$, where $\mathbb{S}$ is the set of states and $\mathbb{A}$ is the state of actions. Let $|\mathbb{S}|=n < + \infty, |\mathbb{A}|=A < + \infty.$ We call $\bm{P} \in \mathbb{R}^{n \times A \times n}$ the transition kernel, $\bm{r} \in \mathbb{R}^{n \times A}$ the state-action reward, $\bm{p}_{0} \in \mathbb{R}^{n}_{+}$ the initial state distribution, and $\lambda \in (0,1)$ the discount factor. A \textit{policy} $\pi \in \mathbb{R}^{n \times A}_{+}$ maps each state to a probability distribution over the set of actions $\mathbb{A}$. For each policy $\pi$ and transition kernel $\bm{P}$, one can associate a \textit{value vector} in $\mathbb{R}^{n}$, defined as \[v^{\pi}_{i} = E^{\pi, \boldsymbol{P}} \left[ \sum_{t=0}^{\infty} \lambda^{t}r_{i_{t}a_{t}} \; \bigg| \; i_{0} = i \right], \forall \; i \in \mathbb{S},\] where $(i_{t},a_{t})$ is the state-action pair visited at time $t$. The goal of the decision-maker is to compute a policy $\pi^{*}$ that maximizes the expected discounted reward, defined as $R(\pi) = \bm{p}_{0}^{\top} \bm{v}^{\pi}.$ Given a policy $\pi$, we define the reward vector $\bm{r}_{\pi} \in \mathbb{R}^{n}$ as \[r_{\pi,i} = \sum_{a=1}^{A} \pi_{ia}r_{ia}, \forall \; i \in \mathbb{S}.\] The policy $\pi$ defines a Markov chain on $\mathbb{S}$, whose transition matrix is $ \bm{L}_{\pi} \in \mathbb{R}^{n \times n}$ defined as \[ L_{\pi,ij} = \sum_{a=1}^{A} \pi_{ia}P_{iaj}, \forall \; (i,j) \in \mathbb{S} \times \mathbb{S}.\] As we mention earlier, several algorithms to compute an optimal policy have been studied, including value iteration, policy iteration and linear programming based algorithms. We refer the reader to \cite{Puterman} and \cite{Bertsekas} for a detailed discussion. Since our iterative algorithms use value iteration as a basic step, let us introduce it more specifically. Define the \textit{Bellman operator} $T: \mathbb{R}^{n} \rightarrow \mathbb{R}^{n}$, where for $\bm{v} \in \mathbb{R}^{n}$, \begin{equation}\label{eq:T_max-def} T(\bm{v})_{i} = \max_{a \in \mathbb{A}} \{ r_{ia} + \lambda \cdot \bm{P}_{ia}^{\top}\bm{v} \}, \forall \; i \in \mathbb{S}. \end{equation} The operator $T$ is an order-preserving contraction of $\left(\mathbb{R}^{n},\| \cdot \|_{\infty} \right)$, where for any vector $\bm{v},\bm{w} \in \mathbb{R}^{n}$, we have $ \bm{v} \leq \bm{w} \Rightarrow T(\bm{v}) \leq T(\bm{w}),$ and $\| T(\bm{v}) - T(\bm{w}) \|_{\infty} \leq \lambda \cdot \| \bm{v} - \bm{w}\|_{\infty}.$ The value iteration (VI) algorithm is defined as follow: \begin{equation}\label{alg:VI}\tag{VI} \bm{v}_{0} \in \mathbb{R}^{n}, \bm{v}_{s+1} = T(\bm{v}_{s}), \forall \; s \geq 0. \end{equation} Following \cite{Puterman}, Chapter 6.3, the value vector $\bm{v}^{*}$ of the optimal policy $\pi^{*}$ is the unique fixed point of the operator $T$, and for any $s \geq 0,$ we have $ \| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \leq \lambda^{s} \| \bm{v}_{0} - \bm{v}^{*} \|_{\infty}$. Moreover, we know that \begin{equation}\label{eq:eps-approx-policy} \| \bm{v}_{s} - \bm{v}_{s+1} \|_{\infty} \leq \epsilon (1-\lambda) (2 \lambda)^{-1} \Rightarrow \| \bm{v}^{\pi_{s}} - \bm{v}^{*} \|_{\infty} \leq \epsilon, \end{equation} where $\bm{v}^{\pi_{s}}$ is the value vector of $\pi_{s}$, the policy attaining the maximum in each row of $T(\bm{v}_{s}).$ An $\epsilon$-optimal policy is a policy $\pi$ such that $\| \bm{v}^{\pi} - \bm{v}^{*} \|_{\infty} \leq \epsilon.$ By choosing the policy attaining the maximum on each row of $T(\bm{v}_{s})$ as in \eqref{eq:T_max-def}, one can recover an $\epsilon$-optimal policy after a number of iterations in \begin{equation}\label{eq:rate-VI-eps-pol} \mathcal{O} \left( n^{2} \cdot A \cdot \dfrac{1}{1-\lambda} \log\left(\dfrac{1}{\epsilon \cdot (1-\lambda)}\right) \right). \end{equation} Therefore, we know that (i) $\lim_{s \rightarrow \infty} \bm{v}_{s} = \bm{v}^{*}$, (ii) $\bm{v}_{s} = \bm{v}^{*} + \mathcal{O}\left( \lambda^{s} \right)$ and (iii) each iteration requires a number of operations in the order of $n^{2} \cdot A,$ while the number of iterations before convergence grows as $1/(1-\lambda)$. Algorithm \ref{alg:VI} does not scale well when $\lambda$ is close to $1$, which is of interest in many applications. We also consider the problem of computing the value vector $\bm{v}^{\pi}$ of a policy $\pi$. The operator associated with a policy $\pi$, $T_{\pi}:\mathbb{R}^{n} \rightarrow \mathbb{R}^{n}$, is defined as \begin{equation}\label{eq:T_pi} T_{\pi}(\bm{v})_{i} = \sum_{a=1}^{A} \pi_{ia}\left(r_{ia} + \lambda \bm{P}_{ia}^{\top}\bm{v}\right), \forall \; i \in \mathbb{S}. \end{equation} The sequence of vectors $\left(T_{\pi}^{s}(\bm{v}_{0})\right)_{s \geq 0}$ converges to $\bm{v}^{\pi}$ with a geometric rate of $\lambda$, for any initial vector $\bm{v}_{0}$~\cite{Puterman}. Therefore, one can compute an $\epsilon$-approximation of the value vector $\bm{v}^{\pi}$ in a number of iterations in \eqref{eq:rate-VI-eps-pol}, using the following Value Computation (VC) algorithm: \begin{equation}\label{alg:VC}\tag{VC} \bm{v}_{0} \in \mathbb{R}^{n}, \bm{v}_{s+1} = T_{\pi}(\bm{v}_{s}), \forall \; s \geq 0. \end{equation} Finally, we also need the notion of \textit{reversible} Markov chain. We have the following definition. \begin{definition}\label{def:reversible} A Markov chain associated with an irreducible transition matrix $\bm{L}$ and a unique stationary distribution $\bm{\nu}$ is \textit{reversible} if and only if it satisfies the following detailed balance equation: \[ \nu_{i} L_{ij} = \nu_{j} L_{ji}, \forall \; (i,j) \in \mathbb{S} \times \mathbb{S}.\] \end{definition} \section{Value Iteration and Gradient Descent.}\label{sec:VI-GD} In this section we present a connection between value iteration and gradient descent. Let us first recall the main results on gradient descent. For a given differentiable function $f: \mathbb{R}^{n} \rightarrow \mathbb{R}$ and a sequence of non-negative scalars $(\alpha_{s})_{s \geq 0}$, the gradient descent algorithm (Algorithm \ref{alg:GD}) is described as: \begin{equation}\label{alg:GD}\tag{GD} \bm{v}_{0} \in \mathbb{R}^{n}, \bm{v}_{s+1} = \bm{v}_{s}-\alpha_{s} \nabla f (\bm{v}_{s}), \forall \; s \geq 0. \end{equation} If additionally the function $f$ is $\mu$-strongly convex and $L$-Lipschitz continuous ($L>\mu >0)$, the sequence $(\bm{v}_{s})_{s \geq 0}$ produced by \ref{alg:GD} does converge at a linear rate to $\bm{v}_{f}$ the minimizer of $f$ as soon as $\alpha_{s} = \alpha \in (0,2/L), \forall \; s \geq 0$ (see Chapter 2.1.5 in \cite{nesterov-book}). Moreover, we obtain an optimal rate with the fixed-step size $\alpha= 2/(L+\mu)$ for which, for $\kappa=L/\mu$, \[ \| \bm{v}_{s} - \bm{v}_{f} \|_{2}^{2} = \mathcal{O} \left( \left( \left( \kappa - 1 \right) / \left(\kappa + 1 \right) \right)^{s} \right).\] In order to compute an optimal policy $\pi^{*}$, we want to compute the vector $\bm{v}^{*}$, the unique solution of $\bm{v}^{*} - T(\bm{v}^{*})=\bm{0}$. We can treat the vector $\bm{v} - T(\bm{v})=\left( \bm{I} - T \right)(\bm{v})$ as the gradient of some function $\mathbb{R}^{n} \rightarrow \mathbb{R}^{n}$, applied to the vector $\bm{v}$, and we are looking for a vector $\bm{v}^{*}$ at which this gradient vanishes, i.e., for which $\| \bm{v}^{*} - T(\bm{v}^{*}) \|_{\infty} = 0.$ Note that since the operator $T$ is a piecewise affine map (as a maximum of affine maps, see Equation \eqref{eq:T_max-def}), the operator $\bm{I} - T$ is not necessarily differentiable. Inspired by this analogy, we consider the following algorithm, defined for any sequence of scalar $(\alpha_{s})_{s \geq 0}$. \begin{equation}\label{alg:R-VI}\tag{R-VI} \boxed{ \bm{v}_{0} \in \mathbb{R}^{n}, \bm{v}_{s+1} = \bm{v}_{s}-\alpha_{s} \left( \bm{v}_{s}- T(\bm{v}_{s}) \right), \forall \; s \geq 0.} \end{equation} We would like to note that this idea was also considered in \cite{relax-VI-2} and \cite{relax-VI-1} where the authors refer to it as \textit{relaxation}. Therefore, we refer to Algorithm \ref{alg:R-VI} as \textit{Relaxed Value Iteration} (R-VI). However, no convergence guarantee or formal connection to \ref{alg:GD} was provided. Additionally, Algorithm \ref{alg:R-VI} is reminiscent to Krasnoselskii-Mann (KM) iteration in non-expansive operator theory (see Chapter 6 in \cite{chidume-2009}): when $\alpha_{s} \in (0,1), \forall \; s \geq 0$ and $T$ is a non-expansive operator ($\lambda \leq 1$), Algorithm \ref{alg:R-VI} is known to converge to one of the fixed points of $T$, but no rate is provided (see \cite{krasnoselskii-1955} and Chapter 5 in \cite{bauschke-2011}). Note that in the case of a non-expansive operator, this convergence result excludes the case $\alpha =1$, which recovers the original value iteration (Algorithm \ref{alg:VI}). We present the following extension to the result for non-expansive operators. \begin{proposition}\label{prop:VI-step size} Consider $\left( \bm{v}_{s} \right)_{s \geq 0}$ the iterates of \ref{alg:R-VI} and $\bm{v}^{*}$ the unique fixed point of the Bellman operator $T$. \begin{enumerate} \item Let the step sizes in Algorithm \ref{alg:R-VI} be $\alpha_{s} = \alpha \in (0,2/(1+\lambda)), \forall \; s \geq 0.$ Then \[\| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \leq \| \bm{v}_{0} - \bm{v}^{*} \|_{\infty} \cdot ( \lambda \cdot \alpha + | 1- \alpha |)^{s} , \forall \; s \geq 0.\] The optimal rate is $\lambda$, attained when $\alpha=1$. \item Let $(\alpha_{s})_{s \geq 0}$ be a sequence of non-negative scalars such that \\ $ \sum_{n=0}^{+\infty} \alpha_{n} = + \infty, \lim_{n \rightarrow +\infty} \alpha_{n} = 0.$ Then \[\| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \leq \| \bm{v}_{0} - \bm{v}^{*} \|_{\infty} \cdot \mathcal{O} \left( \exp \left( - \sum_{\ell = 0}^{s} \alpha_{\ell} \right) \right) , \forall \; s \geq 0.\] \end{enumerate} \end{proposition} \begin{proof} \begin{enumerate} \item Let $\alpha \in \mathbb{R}_{+}$ and $s \geq 0.$ We have \begin{align} \| \bm{v}_{s+1} - \bm{v}^{*} \|_{\infty} & = \| (1-\alpha)\bm{v}_{s} +\alpha T(\bm{v}_{s}) - \bm{v}^{*} \|_{\infty} \nonumber \\ & = \| (1-\alpha)(\bm{v}_{s} - \bm{v}^{*} ) + \alpha ( T(\bm{v}_{s}) - \bm{v}^{*} ) \|_{\infty} \nonumber \\ & \leq \| (1-\alpha)(\bm{v}_{s} - \bm{v}^{*} )\|_{\infty} + \alpha \cdot \| T(\bm{v}_{s}) - \bm{v}^{*} \|_{\infty} \label{eq:proof-R-VI} \\ & \leq | 1 -\alpha | \cdot \|\bm{v}_{s} - \bm{v}^{*} \|_{\infty} + \alpha \cdot \| T(\bm{v}_{s}) - T(\bm{v}^{*}) \|_{\infty} \label{eq:proof-VI-2} \\ & \leq | 1 -\alpha | \cdot \|\bm{v}_{s} -\bm{v}^{*} \|_{\infty} + \alpha \cdot \lambda \cdot \| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \label{eq:proof-VI-3}\\ & \leq ( \lambda \cdot \alpha + | 1- \alpha |) \cdot \| \bm{v}_{s} - \bm{v}^{*} \|_{\infty}, \end{align} where \eqref{eq:proof-R-VI} follows from triangle inequality, \eqref{eq:proof-VI-2} follows from $\bm{v}^{*} = T(\bm{v}^{*})$, and \eqref{eq:proof-VI-3} follows from the Bellman operator being a contraction with factor $\lambda$. We can therefore conclude that \[ \| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \leq ( \lambda \cdot \alpha + | 1- \alpha |)^{s} \cdot \| \bm{v}_{0} - \bm{v}^{*} \|_{\infty}, \forall \; s \geq 0. \] Now we can see that the function $ \alpha \mapsto ( \lambda \cdot \alpha + | 1- \alpha |)$ remains strictly smaller than $1$ only for $\alpha \in (0,2/(1+\lambda)),$ and attains its minimum, $\lambda$, for $\alpha =1$. \item Since $\lim_{s \rightarrow \infty} \alpha_{s} = 0$, there exists an integer $s_{0} \in \mathbb{N}$ such that $\alpha_{s_{0}} \leq 1, \forall \; s \geq s_{0}.$ The same reasoning as above gives \[ \| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \leq \left( \prod_{\ell=s_{0}}^{s-1} ( 1 - (1-\lambda)\alpha_{\ell})) \right) \cdot \| \bm{v}_{s_{0}} - \bm{v}^{*} \|_{\infty}, \forall \; s \geq s_{0}. \] Finally, \[\prod_{\ell=s_{0}}^{s-1} ( 1 - (1-\lambda)\alpha_{\ell})) = \mathcal{O} \left( \exp \left( - \sum_{\ell = s_{0}}^{s} \alpha_{\ell} \right) \right)=\mathcal{O} \left( \exp \left( - \sum_{\ell = 0}^{s} \alpha_{\ell} \right) \right).\] \end{enumerate} \end{proof} The following remarks are in order. \begin{remark} Note that in \eqref{eq:proof-R-VI} we use triangle inequality, then in \eqref{eq:proof-VI-3} we use the contracting property of the operator $T$. Triangle inequality is tight if and only if the vectors involved are proportional with a non-negative coefficient of proportionality, while we a priori do not know when the inequality $\| T(\bm{v}) - T(\bm{w}) \|_{\infty} \leq \lambda \cdot \| \bm{v} - \bm{w}\|_{\infty}$ is tight. It could be of interest to study under which conditions the rate of Proposition \ref{prop:VI-step size} is tight and if it could be improved in the case of Bellman operator $T$ \eqref{eq:T_max-def}, as suggested by our numerical experiments in Section \ref{sec:simu}. \end{remark} \begin{remark} We would like to note that Proposition \ref{prop:VI-step size} holds for any operator that is a contraction for $\| \cdot \|_{\infty}$. Therefore, it can also be applied to compute the value vector of a policy $\bm{v}^{\pi}$, which is the fixed point of $T_{\pi}$ \eqref{eq:T_pi}. Other contracting operators of interest include Boltzmann operator as a softmax operator (see \cite{boltzman-1}), log-sum-exp operators (see \cite{log-sum-exp}), and robust Bellman operators for Robust MDPs (see \cite{Iyengar},\cite{Kuhn}, \cite{GGC}). \end{remark} We discuss here the choice of the upper bound $2/(1+\lambda)$ for the step size. Let us consider $F$ a contraction operator with factor $\lambda$. From the triangle inequality we have, for any vectors $\bm{v},\bm{w} \in \mathbb{R}^{n},$ \begin{align} (1-\lambda) \cdot \| \bm{v} - \bm{w} \|_{\infty} & \leq \| (\bm{I} - F)(\bm{v}) - (\bm{I} - F)(\bm{w}) \|_{\infty}, \label{eq:mu-infty} \\ \| (\bm{I} - F)(\bm{v}) - (\bm{I} - F)(\bm{w}) \|_{\infty} & \leq (1+\lambda) \cdot \| \bm{v} - \bm{w} \|_{\infty}. \label{eq:L-infty} \end{align} Note that \eqref{eq:mu-infty}-\eqref{eq:L-infty} are the analogous of the following inequalities for differentiable, $\mu$-strongly convex, $L$-Lipschitz continuous function $f: \mathbb{R}^{n} \rightarrow \mathbb{R}$: for all vectors $\bm{v},\bm{w} \in \mathbb{R}^{n},$ \begin{align} \mu \cdot \| \bm{v} - \bm{w} \|_{2} & \leq \| \nabla f(\bm{v}) - \nabla f (\bm{w}) \|_{2}, \label{eq:mu-2} \\ \| \nabla f(\bm{v}) - \nabla f (\bm{w}) \|_{2} & \leq L \cdot \| \bm{v} - \bm{w} \|_{2}. \label{eq:L-2} \end{align} Therefore, when $F=T$, this strengthens our interpretation of $\bm{I} - T$ as $\nabla f$, with $\| \cdot \|_{\infty}$ (instead of $\| \cdot \|_{2}$) and $\mu = 1- \lambda, L=1+\lambda.$ Moreover, in Proposition \ref{prop:VI-step size}, we note that the maximum fixed step size guaranteeing convergence is $2/(1+\lambda)=2/L$, and that the optimal rate is $\lambda=(1+\lambda - (1 -\lambda))/(1+\lambda + 1 - \lambda) = (L-\mu)/(L + \mu)$, attained for $\alpha=1=2 / (1 + \lambda + 1 - \lambda) = 2 / (L + \mu).$ Therefore, the properties of \ref{alg:GD} for a function satisfying \eqref{eq:mu-2}-\eqref{eq:L-2} do translate for Algorithm \ref{alg:R-VI} applied for a Bellman operator $F=T$ satisfying \eqref{eq:mu-infty}-\eqref{eq:L-infty}. Similarly, Proposition \ref{prop:VI-step size} is reminiscent to the following conditions of convergence for gradient descent with varying step size: $ \sum_{n=0}^{+\infty} \alpha_{n} = + \infty, \sum_{n=0}^{+\infty} \alpha_{n}^{2} < + \infty. $ We would like to emphasize that the convergence proof for \ref{alg:GD} does not readily extend to Algorithm \ref{alg:R-VI}. In particular, there is a fundamental difference between $\| \cdot\|_{\infty}$ and $\| \cdot \|_{2}$, since $\| \cdot \|_{2}$ is naturally related to the scalar product of $\mathbb{R}^{n}$, i.e., $\| \bm{v} \|_{2}^{2} = \bm{v}^{\top}\bm{v}$, whereas this is not the case for $\| \cdot \|_{\infty}.$ Therefore, we can not rely on scalar products and Taylor expansions of first order to prove our convergence results. Moreover, if one were to infer some new constants $\mu,L$ for \eqref{eq:mu-2}-\eqref{eq:L-2} from \eqref{eq:mu-infty}-\eqref{eq:L-infty} and the equivalence of norms in finite dimension, one would obtain (in general) $\mu = (1-\lambda)/\sqrt{n},L=\sqrt{n}(1+\lambda)$, essentially loosing a factor of $n$ as regards to the convergence rate guarantee of Algorithm \ref{alg:R-VI}. \section{Accelerated and Momentum Fixed Point Iteration.}\label{sec:Acc_fix_point_comp} \subsection{Accelerated Algorithm.} In this section, we build upon the connection between iterations of contraction mappings and \ref{alg:GD} to present an accelerated algorithm for computing the fixed point of a contraction mapping $F$. As we detailed in the previous section, one can consider the operator $\left( \bm{I} - F \right)$ to be the gradient of some function. The goal is to find $\bm{v}^{*} \in \mathbb{R}^{n}$ where the `gradient' vanishes, i.e., where $\bm{v}^{*} = F \left( \bm{v}^{*} \right)$. Accelerated Gradient Descent (A-GD, \cite{nesterov-1983} and \cite{nesterov-book}) has been extended to popular iterative methods such as FISTA (\cite{fista}) and F-ADMM (\cite{fadmm}). Building upon our analogy between gradient descent and value iteration, we extend A-GD to an accelerated iterative algorithm for computing $\bm{v}^{*}$, the unique fixed point of the contraction $F$. In particular, for any sequences of scalar $(\alpha_{s})_{s \geq 0}$ and $(\gamma_{s})_{s \geq 0} \in \mathbb{R}^{\mathbb{N}}$, for any contraction $F:\mathbb{R}^{n} \rightarrow \mathbb{R}^{n}$, we propose the following algorithm. \begin{equation}\label{alg:AFP} \boxed{ \bm{v}_{0},\bm{v}_{1} \in \mathbb{R}^{n}, \begin{cases} \bm{h}_{s}=\bm{v}_{s}+\gamma_{s}\cdot \left( \bm{v}_{s}-\bm{v}_{s-1} \right), \\ \bm{v}_{s+1} \gets \bm{h}_{s}-\alpha_{s} \left( \bm{h}_{s}- F \left( \bm{h}_{s} \right) \right) \end{cases}, \forall \; s \geq 1.} \end{equation} When $F=T$ the Bellman operator \eqref{eq:T_max-def} for computing an optimal policy, we consider Accelerated Value Iteration (A-VI): \begin{equation}\label{alg:AVI}\tag{A-VI} \bm{v}_{0},\bm{v}_{1} \in \mathbb{R}^{n}, \begin{cases} \bm{h}_{s}=\bm{v}_{s}+\gamma_{s}\cdot \left( \bm{v}_{s}-\bm{v}_{s-1} \right), \\ \bm{v}_{s+1} \gets \bm{h}_{s}-\alpha_{s} \left( \bm{h}_{s}- T \left( \bm{h}_{s} \right) \right) \end{cases}, \forall \; s \geq 1. \end{equation} When $F=T_{\pi}$ the operator \eqref{eq:T_pi} for computing the value vector for the policy $\pi$, we consider Accelerated Value Computation (\ref{alg:AVC}): \begin{equation}\label{alg:AVC}\tag{A-VC} \bm{v}_{0},\bm{v}_{1} \in \mathbb{R}^{n}, \begin{cases} \bm{h}_{s}=\bm{v}_{s}+\gamma_{s}\cdot \left( \bm{v}_{s}-\bm{v}_{s-1} \right), \\ \bm{v}_{s+1} \gets \bm{h}_{s}-\alpha_{s} \left( \bm{h}_{s}- T_{\pi} \left( \bm{h}_{s} \right) \right) \end{cases}, \forall \; s \geq 1. \end{equation} \paragraph{Choice of constant step sizes.} We based our choice of step sizes on our connection between value iteration and gradient descent. In particular, \cite{nesterov-book} (Algorithm 2.2.11) chooses $\alpha=1/L,\gamma = (\sqrt{L}-\sqrt{\mu})/(\sqrt{L}+\sqrt{\mu})$. From our analogy between \ref{alg:VI} and \ref{alg:GD}, and from \eqref{eq:mu-infty}-\eqref{eq:L-infty} and \eqref{eq:mu-2}-\eqref{eq:L-2}, we have $\mu= (1- \lambda), L=(1+ \lambda),$ which corresponds to our first choice of fixed step sizes of \begin{equation}\label{eq:tuning-1} \alpha_{s} = \alpha = 1/(1+\lambda), \gamma_{s} = \gamma = \left(1-\sqrt{1- \lambda^{2}}\right)/\lambda, \forall s \; \geq 1. \end{equation} In smooth convex optimization, it can be challenging to estimate the value of the Lipschitz-constant $L$ (respectively, of the strong-convexity constant $\mu$), thereby making it difficult to find the optimal step sizes. \cite{estimation-L} and \cite{estimation-mu} propose backtracking schemes to evaluate optimal step sizes. In contrast, for our algorithm, the Lipschitz-constant is replaced by $(1+\lambda)$ (respectively, the strong-convexity parameter is replaced by $(1-\lambda)$), and it is the discount factor $\lambda$ that needs to be evaluated. The value of the discount factor can be seen as a choice of the decision-maker, depending on the impact of future rewards, i.e., depending on the effective time horizon. \subsection{Momentum Algorithm.} In this section, we present a Momentum Fixed Point iteration algorithm. Momentum Gradient Descent is a popular method to improve the convergence of Algorithm \ref{alg:GD} (\citet{polyak-1964}, \citet{heavyball-2015}). For any sequences of scalars $(\alpha_{s})_{s \geq 0}$ and $(\beta_{s})_{s \geq 0} \in \mathbb{R}^{\mathbb{N}}$, for any contraction $F:\mathbb{R}^{n} \rightarrow \mathbb{R}^{n}$, we propose the following algorithm. \begin{equation}\label{alg:MFP}\tag{M-FP} \boxed{ \bm{v}_{0},\bm{v}_{1} \in \mathbb{R}^{n}, \bm{v}_{s+1} =\bm{v}_{s}-\alpha_{s} \left( \bm{v}_{s}- F \left( \bm{v}_{s} \right) \right) + \beta_{s}\cdot \left( \bm{v}_{s}-\bm{v}_{s-1} \right) , \forall \; s \geq 1.} \end{equation} When $F=T_{\pi}$ the operator \eqref{eq:T_pi} for computing the value vector for the policy $\pi$, we call this algorithm \textit{Momentum Value Computation} (\ref{alg:MVC}). When $F=T$ the Bellman operator \eqref{eq:T_max-def} for computing an optimal policy, we call this algorithm \textit{Momentum Value Iteration} (\ref{alg:MVI}). \begin{equation}\label{alg:MVC}\tag{M-VC} \bm{v}_{0},\bm{v}_{1} \in \mathbb{R}^{n}, \bm{v}_{s+1} =\bm{v}_{s}-\alpha_{s} \left( \bm{v}_{s}-T_{\pi} \left( \bm{v}_{s} \right) \right) + \beta_{s}\cdot \left( \bm{v}_{s}-\bm{v}_{s-1} \right) , \forall \; s \geq 1. \end{equation} \begin{equation}\label{alg:MVI}\tag{M-VI} \bm{v}_{0},\bm{v}_{1} \in \mathbb{R}^{n}, \bm{v}_{s+1} =\bm{v}_{s}-\alpha_{s} \left( \bm{v}_{s}-T \left( \bm{v}_{s} \right)\right) + \beta_{s}\cdot \left( \bm{v}_{s}-\bm{v}_{s-1} \right) , \forall \; s \geq 1. \end{equation} \paragraph{Choice of constant step sizes.} We choose step sizes based on our connection between convex optimization and fixed point iterations. The authors in \citet{polyak-1964} and \citet{heavyball-2015} show that if a smooth, strongly convex function is twice differentiable, the optimal choice of constant for Momentum GD is $\alpha=4/(\sqrt{L} + \sqrt{\mu})^{2},\beta = (\sqrt{L}-\sqrt{\mu})^{2}/(\sqrt{L}+\sqrt{\mu})^{2}$. We use $\mu= (1- \lambda), L=(1+ \lambda)$ based on our analogy between \ref{alg:VI} and \ref{alg:GD}, and from \eqref{eq:mu-infty}-\eqref{eq:L-infty} and \eqref{eq:mu-2}-\eqref{eq:L-2}. Therefore, we consider the following choice of step sizes. \begin{equation}\label{eq:tuning-MVC-1} \begin{aligned} \forall \; s \geq 1, \alpha_{s}=\alpha & =2/(1+\sqrt{1-\lambda^{2}}), \\ \gamma_{s}=\gamma & =(1-\sqrt{1-\lambda^{2}})/(1+\sqrt{1-\lambda^{2}}). \end{aligned} \end{equation} \section{Analysis of Accelerated and Momentum Value Computation.}\label{sec:analysis_MAVC} \subsection{Analysis of Accelerated Value Computation.}\label{sec:analysis_AVC} In this section we provide a theoretical convergence rate for Algorithm \ref{alg:AVC} and investigate its numerical performance. \subsubsection{Convergence rate.} Consider an MDP and a policy $\pi$. Recall that a classical fixed point iteration scheme such as Algorithm \ref{alg:VC} converges as $O(\lambda^{s})$ after $s$ iterations. We show that Algorithm \ref{alg:AVC} returns the value vector $\bm{v}^{\pi}$ significantly faster, if the Markov chain defined by the policy $\pi$ is irreducible and reversible (see Definition \ref{def:reversible}). The irreducibility condition is very general and to ensures that the Markov chain has a unique stationary distribution. The reversibility assumption is a fairly common assumption in the MDP literature, particularly for applications to Reinforcement Learning (\cite{revers-1}, \cite{revers-2}), Markov Chain Monte Carlo methods (\cite{revers-3}, \cite{revers-4}), queuing control (\cite{queue-1}, \cite{queue-2}, \cite{queue-3}) and random walks on graph (\cite{revers-book}, \cite{rd-walk-1}, \cite{rd-walk-2}). In particular, we have the following theorem. \begin{theorem}\label{th:AVI-value-computation} Consider an MDP and a policy $\pi$ which defines an irreducible, reversible Markov chain on the set of states $\mathbb{S}$. Consider $(\bm{v}_{s})_{s \geq 0}$ the sequence of iterates of Algorithm \ref{alg:AVC} with step sizes \eqref{eq:tuning-1}. Then $(\bm{v}_{s})_{s \geq 0}$ converges to $\bm{v}^{\pi}$. Moreover, for any $ \eta>0 $, for $\kappa = (1+\lambda)/(1-\lambda)$, \[\bm{v}_{s} = \bm{v}^{\pi} + o\left( \left(1- \sqrt{\dfrac{1}{\kappa}} + \eta \right)^{s}\right), \forall \; s \geq 0.\] \end{theorem} We first analyze the structure of the iterations in Algorithm \ref{alg:AVC}. Let $\bm{I} \in \mathbb{R}^{n \times n}$ be the identity matrix and $ \bm{B}_{\pi} \in \mathbb{R}^{2n \times 2n}$ defined as \begin{equation}\label{eq:def-B-pi} \bm{B}_{\pi} = \left[ {\begin{array}{cc} (1-\sqrt{1/\kappa} ) \left( \bm{I} +\bm{L}_{\pi}\right) &- (1-\sqrt{1/\kappa})^{2}/2\left( \bm{I} + \bm{L}_{\pi} \right) \\ \bm{I} & \bm{0} \end{array} } \right]. \end{equation} \begin{lemma}\label{lem:LTV-AVC} Let $\bm{x}^{\pi} = (\bm{v}^{\pi},\bm{v}^{\pi}) \in \mathbb{R}^{2 n},\bm{x}_{s} = (\bm{v}_{s},\bm{v}_{s-1}) \in \mathbb{R}^{2 n}$. Then $$\bm{x}_{s} = \bm{x}^{\pi}+ \bm{B}_{\pi}^{s-1}\left(\bm{x}_{0}-\bm{x}^{\pi}\right), \forall \; s \geq 1.$$ \end{lemma} \begin{proof} Let $(\bm{v}_{s})_{s \geq 0}$ be the sequence of iterates of Algorithm \ref{alg:AVC}. We have \begin{align*} \bm{v}_{s+1} & = (1-\alpha) \bm{h}_{s} + \alpha T_{\pi}(\bm{h}_{s}) \\ &= (1-\alpha)(1+\gamma)\bm{v}_{s} - (1- \alpha) \gamma \bm{v}_{s-1} + \alpha (1+\gamma) \lambda \bm{L}_{\pi}\bm{v}_{s} - \alpha \gamma \lambda \bm{L}_{\pi}\bm{v}_{s-1} + \alpha \bm{r}_{\pi} \\ & = \left( (1-\alpha)(1+\gamma) \bm{I} + \alpha (1+\gamma)\lambda \bm{L}_{\pi} \right) \bm{v}_{s} - \left( (1-\alpha)\gamma \bm{I} + \alpha \gamma \lambda \bm{L}_{\pi} \right) \bm{v}_{s-1} + \alpha \bm{r}_{\pi}. \end{align*} Recall that $\alpha = 1/(1+\lambda),\gamma = (1-\sqrt{1-\lambda^{2}})/\lambda$ and that $\kappa = (1+\lambda)/(1-\lambda).$ Then \begin{align*} 1 + 1 / \kappa - 2 \alpha& = 0, \\ (1-\alpha)(1+\gamma) = \alpha \lambda (1+\gamma ) & = 1 - \sqrt{1 / \kappa}, \\ \alpha \gamma \lambda = (1-\alpha)\gamma = \alpha - \sqrt{1 / \kappa} & = \dfrac{1}{2} \left(1 - \sqrt{1 / \kappa}\right)^{2}. \end{align*} Therefore, for $\bm{b}_{\pi} = \left(\bm{r}_{\pi},\bm{r}_{\pi} \right)$, \begin{equation}\label{eq:rec-x-AVC} \bm{x}_{s+1} = \bm{B}_{\pi}\bm{x}_{s} + \bm{b}_{\pi}. \end{equation} Note that $\bm{x}^{\pi}=\bm{B}_{\pi}\bm{x}^{\pi}+\bm{b}_{\pi}$. Therefore, for $s \geq 0$, $$ \bm{x}_{s+1} - \bm{x}^{\pi} = \bm{B}_{\pi}\bm{x}_{s}+\bm{b}_{\pi} - \bm{B}_{\pi}\bm{x}^{\pi}-\bm{b}_{\pi} = \bm{B}_{\pi}\left( \bm{x}_{s}-\bm{x}^{\pi}\right).$$ From this we conclude \[\bm{x}_{s} = \bm{x}^{\pi}+ \bm{B}_{\pi}^{s-1}\left(\bm{x}_{0}-\bm{x}^{\pi}\right), \forall \; s \geq 1.\] \end{proof} In the next lemma we bound the spectral radius of $\bm{B}_{\pi}$. \begin{lemma}\label{lem:radius} Consider a policy $\pi$ which defines an irreducible, reversible Markov chain on the set of states $\mathbb{S}$. Then we have \[\rho(\bm{B}_{\pi}) = 1 - \sqrt{1/\kappa}.\] \end{lemma} \begin{proof}To any eigenvalue $\mu$ of $\bm{L}_{\pi}$ correspond (at most) two eigenvalues of $\bm{B}_{\pi}$, satisfying the following equation in $\omega$: \begin{equation}\label{eq:sec-order-nu-2} \omega^{2} - (\mu+1)(1-\sqrt{1 / \kappa})\omega + \dfrac{1}{2} (\mu+1)(1 - \sqrt{1 / \kappa})^{2} = 0. \end{equation} The discriminant of \eqref{eq:sec-order-nu-2} is $\Delta = (\mu^{2}-1) \cdot (1-\sqrt{1 / \kappa})^{2},$ which leads to the expression of the roots of \eqref{eq:sec-order-nu-2}: \begin{align} \omega^{+}(\mu) & = (1-\sqrt{1 / \kappa}) \cdot \dfrac{1}{2} \cdot \left( \mu+1 + \sqrt{\mu^{2}-1} \right),\label{eq:w_plus}\\ \omega^{-}(\mu) & = (1-\sqrt{1 / \kappa}) \cdot \dfrac{1}{2} \cdot \left( \mu+1 - \sqrt{\mu^{2}-1} \right). \label{eq:w_minus} \end{align} Remember that $ \mu \in \mathbb{C}, | \mu | \leq 1$ since $\bm{L}_{\pi}$ is a stochastic matrix. Now $Sp(\bm{L}_{\pi}) \subset \mathbb{R}$ since the Markov chain defined by $\pi$ is reversible (Section 3.3 in \cite{revers-book}). For $\mu \in [-1,1]$, \[ \dfrac{1}{2} | \mu+1 + \sqrt{\mu^{2}-1} | = \dfrac{1}{2} \sqrt{(\mu+1)^{2} + \left( \sqrt{1-\mu^{2}} \right)^{2} } = \dfrac{1}{2} \sqrt{2} \cdot \sqrt{1 + \mu} \leq 1, \] Similarly, for $ \mu \in [-1,1],$ we have \[ \dfrac{1}{2} | \mu+1 - \sqrt{\mu^{2}-1} | \leq 1. \] Therefore, the leading eigenvalue of $\bm{B}_{\pi}$ is attained for $\mu=1$, which leads to $\Delta=0$, and a unique solution $\omega^{*} = 1- \sqrt{1 / \kappa}.$ \end{proof} \begin{remark} We would like to note that the reversibility of the Markov chain associated with $\pi$ is only a \textit{sufficient} condition for the spectral radius of $\bm{B}_{\pi}$ to be equal to $1- \sqrt{1/\kappa}$, but not necessary. In particular, another sufficient condition is $Sp(\bm{L}_{\pi}) \subset \mathbb{R}$. \end{remark} We are now ready to prove Theorem \ref{th:AVI-value-computation}. \begin{proof}[Proof of Theorem \ref{th:AVI-value-computation}] From Lemma \ref{lem:LTV-AVC}, we can write $$\bm{x}_{s} = \bm{x}^{\pi}+ \bm{B}_{\pi}^{s-1}\left(\bm{x}_{0}-\bm{x}^{\pi}\right), \forall \; s \geq 1.$$ We have assumed that $\pi$ defines an irreducible, reversible Markov chain on the set of states $\mathbb{S}$. From Lemma \ref{lem:radius} we conclude that $\rho(\bm{B}_{\pi}) = 1 -\sqrt{1/\kappa}<1$. This implies that for any $\eta >0$, we have \[\lim_{s \rightarrow + \infty}\dfrac{1}{\left(1 -\sqrt{1/\kappa} + \eta \right)^{s}} \cdot \bm{B}_{\pi}^{s}\left(\bm{x}_{0}-\bm{x}^{\pi}\right) = 0.\] We can therefore conclude that for any $\eta >0$, \[\bm{v}_{s} = \bm{v}^{\pi} + o\left(\left(1 -\sqrt{1/\kappa} + \eta \right)^{s}\right), \forall \; s \geq 0.\] \end{proof} Therefore, we prove theoretical guarantees for the convergence of Algorithm \ref{alg:AVC}, under the assumption that the associated Markov chain is irreducible and reversible. In this case, Algorithm \ref{alg:AVC} converges geometrically at a rate of $1-\sqrt{1/\kappa}$, which coincidentally also corresponds to the known convergence rate for Nesterov's acceleration in the case of a strongly convex function (\cite{nesterov-book}, Algorithm 2.2.11). Note that $1-\sqrt{1/\kappa}=1-\sqrt{(1-\lambda)/(1+\lambda)}$ is always smaller than $\lambda$, the known convergence rate for Algorithm \ref{alg:VC}, since \[ \lambda = 1 - \sqrt{1 / \kappa}+ \dfrac{\sqrt{1-\lambda} \cdot \left( 1-\sqrt{1-\lambda^{2}} \right) }{\sqrt{1+\lambda}}.\] When $\lambda$ approaches $1$, the difference in computation time between an algorithm with a convergence rate of $1-\sqrt{(1-\lambda)/(1+\lambda)}$ and an algorithm with a convergence rate of $\lambda$ increases significantly (see our simulations in Section \ref{sec:simu}). In particular, from Theorem \ref{th:AVI-value-computation} and the stopping criterion \eqref{eq:eps-approx-policy}, we can conclude that Algorithm \ref{alg:AVC} returns an $\epsilon$-approximation of $\bm{v}^{\pi}$ in a number of iterations in \[\mathcal{O} \left( n^{2} \cdot A \cdot \dfrac{1}{\sqrt{1-\lambda}}\cdot \log\left(\dfrac{1}{\epsilon \cdot (1-\lambda)}\right) \right),\] which is significantly faster than \eqref{eq:rate-VI-eps-pol}, the convergence rate of Algorithm \ref{alg:VC}, for $\lambda$ approaching $1$. \subsubsection{Discussion on the irreducibility and reversibility assumption.}\label{sec:disc-reversibility} We provide here an example of an MDP instance and a policy which do not define a reversible Markov chain and where Algorithm \ref{alg:AVC} may diverge. Consider an MDP with $n$ states where $n$ is even and one action for all states. The (only) transition matrix is defining a cycle, i.e., $L_{i,i+1}=1$ for $s \in \{1,...,n-1\}$ and $L_{n,1}=1.$ The eigenvalues of the transition matrix are the $n-th$ roots of $1$ in $\mathbb{C}$. For example, for $n=4$, the transition matrix $\bm{L}$ and its eigenspectrum are given by \begin{equation}\label{eq:L-counter-ex} \bm{L}= \left[ {\begin{array}{cccc} 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 &0 & 0 & 1 \\ 1 & 0 & 0 & 0 \\ \end{array} } \right], \; Sp(\bm{L}) = \{ 1,-1,i,-i\}. \end{equation} Now from \eqref{eq:w_plus}-\eqref{eq:w_minus}, we know that the spectral radius of the associated $\bm{B}_{\pi}$ is strictly higher than $1$ and therefore Algorithm \ref{alg:AVC} may diverge, since for $\mu=i \in Sp(\bm{L})$ we have \[ \dfrac{1}{2}| \mu+1 + \sqrt{\mu^{2}-1} | = | i + 1 + \sqrt{i^{2}-1}| =\dfrac{1}{2}| i + 1 + \sqrt{-2} | = \dfrac{1}{2}\sqrt{4 + 2 \sqrt{2}} >1. \] \subsection{Analysis of Momentum Value Computation.}\label{sec:analysis-MVC} In this section we provide a theoretical convergence rate for Algorithm \ref{alg:MFP} with $F=T_{\pi}$ with the constants \eqref{eq:tuning-MVC-1}. We present a detailed proof in Appendix \ref{app:proof-section-MVC}. \begin{theorem}\label{th:MVC-1} Consider an MDP and a policy $\pi$ which defines an irreducible, reversible Markov chain on the set of states $\mathbb{S}$. Consider $(\bm{v}_{s})_{s \geq 0}$ the sequence of iterates of Algorithm \ref{alg:MVC} with step sizes \eqref{eq:tuning-MVC-1}. Then $(\bm{v}_{s})_{s \geq 0}$ converges to $\bm{v}^{\pi}$. Moreover, for any $ \eta>0 $, \[\bm{v}_{s} =\bm{v}^{\pi} + o \left( \left( \dfrac{1-\sqrt{\kappa}}{1+\sqrt{\kappa}} + \eta \right)^{s} \right), \forall \; s \geq 0.\] \end{theorem} In the case where the associated Markov chain is irreducible and reversible, Algorithm \ref{alg:MVC} converges geometrically at a rate of $(1-\sqrt{\kappa})/(1+\sqrt{\kappa})$. This rate coincides with the known convergence rate for Momentum Gradient Descent in the case of a twice differentiable, strongly convex function \citet{heavyball-2015}. We would like to note that we consider $(\bm{I}-T_{\pi})$ as the gradient of a function and that $\bm{v} \mapsto (\bm{I} - T_{\pi})(\bm{v})$ is itself a differentiable function. Moreover, $(1-\sqrt{\kappa})/(1+\sqrt{\kappa})$ is always smaller than $\lambda$, the known convergence rate for Algorithm \ref{alg:VC}. Our simulations shows that the difference in computation time between Algorithm \ref{alg:MVC} and Algorithm \ref{alg:VC} increases significantly when $\lambda$ approaches $1$ (see Section \ref{sec:simu}). Using the stopping criterion \eqref{eq:eps-approx-policy}, we can conclude that Algorithm \ref{alg:MVC} with constants \eqref{eq:tuning-MVC-1} returns an $\epsilon$-approximation of $\bm{v}^{\pi}$ in a number of operations in \[\mathcal{O} \left( n^{2} \cdot A \cdot \dfrac{1}{\sqrt{1-\lambda}}\cdot \log\left(\dfrac{1}{\epsilon \cdot (1-\lambda)}\right) \right).\] As for \ref{alg:AVC}, this is significantly faster than \eqref{eq:rate-VI-eps-pol}, the convergence rate of Algorithm \ref{alg:VC}, for $\lambda$ approaching $1$. \paragraph{Comparison with Accelerated Value Computation.} Accelerated Value Computation converges linearly to $\bm{v}^{\pi}$ with a rate of $1-\sqrt{\kappa}$. Therefore, Momentum Value Computation with constants \eqref{eq:tuning-MVC-1} has slightly better convergence guarantees than Accelerated VC, namely a rate of $(1-\sqrt{\kappa})/(1+\sqrt{\kappa})$, a situation similar to the case of convex optimization \citet{heavyball-2015}. \paragraph{Irreducibility and Reversibility Assumption.} We show in Section \ref{sec:analysis_AVC} that on a non-reversible MDP instance, Algorithm \ref{alg:AVC} may diverge. For the same choice of non-reversible MDP instance, Algorithm \ref{alg:MVC} may also diverge. This highlights the key role of reversibility assumption in the convergence of Theorem \ref{th:MVC-1}. We present the detail about the divergence of \ref{alg:MVC} on this MDP instance in Appendix \ref{app:proof-section-MVC}. \section{Analysis of Accelerated and Momentum Value Iteration.}\label{sec:analysis_MAVI} \subsection{Analysis of Accelerated Value Iteration.}\label{sec:analysis_AVI} In this section we present our analysis of Algorithm \ref{alg:AVI}. While for \ref{alg:AVI} we are not able to give a theoretical convergence rate analogous to \ref{alg:AVC}, we highlight the challenges in the analysis, including a lower-bound on the performance of any \textit{first-order} algorithm for solving MDPs. On the positive side, we present empirical results to highlight the significant speedups of Algorithm \ref{alg:AVI} compared to the state-of-the-art approaches over an extensive set of MDP instances. \subsubsection{Structure of the iterations.} The Bellman operator $T$ is a piecewise affine operator. Therefore, at any step $s \geq 1$, the iterate $\bm{v}_{s+1}$ is some affine function (which may change from iteration to iteration) of $\mathbb{R}^{2 n}$ applied to $\bm{x}_{s}=(\bm{v}_{s},\bm{v}_{s-1})$. This leads to the following proposition, which gives a Linear Time-Varying (LTV) dynamical system formulation for the evolution of the sequence $(\bm{v}_{s})_{s \geq 0}$ (for literature on LTVs, see \cite{klamka-1963}, \cite{vladimirov-2000}, and Section 1.3 in \cite{jungers-book}). In particular, we have the following proposition. We give a detailed proof in Appendix \ref{app:prop-B-pi-IRU}. \begin{proposition}\label{prop:B-pi-IRU} Let $\bm{x}^{*} = \left( \bm{v}^{*},\bm{v}^{*} \right) \in \mathbb{R}^{2n}$, where $\bm{v}^{*}$ is the value vector of the optimal policy, and let $\bm{x}_{s} = \left( \bm{v}_{s},\bm{v}_{s-1}\right) \in \mathbb{R}^{2n}, s \geq 1.$ There exists a sequence of policies $(\hat{\pi}_{s})_{s \geq 0}$ such that \begin{equation}\label{eq:LTV-AVI} \bm{x}_{s} = \bm{x}^{*} + \bm{B}_{\hat{\pi}_{s-1}} \cdot ... \cdot \bm{B}_{\hat{\pi}_{0}}(\bm{x}_{0}-\bm{x}^{*}), \forall \; s \geq 1. \end{equation} \end{proposition} The dynamical system \eqref{eq:LTV-AVI} is said to be \textit{stable} if $(\bm{x}_{s})_{s \geq 0}$ converges to $\bm{0}$ for \textit{any} sequence of policies $(\hat{\pi}_{\ell})_{\ell \geq 0}$ and for any initial condition $\bm{x}_{0}$. Proposition \ref{prop:B-pi-IRU} highlights the key role played by the spectral radius of each matrix $\bm{B}_{\pi}$ and the \textit{joint spectral radius} of the set $\mathcal{B} = \{ \bm{B}_{\pi} \; | \; \pi \in \Pi \}$. The joint spectral radius of the set $\mathcal{B}$ is defined (among other equivalent definitions) as \[ \rho(\mathcal{B}) = \limsup_{s \rightarrow \infty} \max \left\lbrace \rho \left(\bm{B}_{\pi_{s}} \cdot ... \cdot \bm{B}_{\pi_{1}} \right)^{1/s} \; | \; \pi_{1},...,\pi_{s} \in \Pi \right\rbrace. \] In particular, the sequence $(\bm{x}_{s})_{s \geq 0}$ is stable if and only if $\rho(\mathcal{B}) <1$ (Corollary 1.1 in \cite{jungers-book}). The authors in \cite{blondel-NP-hard} show that it is NP-hard to approximate the joint spectral radius for general set of matrices. The computation of $\rho(\mathcal{E})$ is known to be tractable for some special cases of set of matrices $\mathcal{E}$. In particular, if all the matrices in $\mathcal{E}$ are normal, or commonly triangularizable (Section 2.3.2 in \cite{jungers-book}), or row-wise nonnegative matrices (\cite{blondel-IRU}), it holds that \[\rho(\mathcal{E})=\max_{\bm{E} \in \mathcal{E}} \rho(\bm{E}).\] This highlights the role of the spectral radius of each of the matrix $\bm{B}_{\pi}$. Therefore, one approach to study the convergence of Algorithm \ref{alg:AVI} would be to show a bound on the joint spectral radius of the set $\mathcal{B}$, the set of affine operators driving the dynamics of \eqref{eq:LTV-AVI}. However, without any assumption, it may not hold that $\rho(\mathcal{B}) < 1$ (see Section \ref{sec:disc-reversibility}). Even if we assume that the Markov chain associated with each policy $\pi$ is irreducible and reversible, we would only have $\rho(\bm{B}_{\pi})<1$, for all $\pi$ (see Lemma \ref{lem:radius}). However, this does not imply that $\rho(\mathcal{B})<1$ (see Example 1.1 in~\cite{jungers-book}). While such a bound on the joint spectral radius is sufficient to prove convergence of Algorithm \ref{alg:AVI} for the Bellman operator $T$, it may not be a \textit{necessary} condition to prove the convergence of the sequence $(\bm{v}_{s})_{s \geq 0}$. In particular, there may be some more structure in the sequence of policies $(\hat{\pi}_{s})_{s \geq 0}$ of Proposition \ref{prop:B-pi-IRU}. We would like to note that our algorithm converges at a significantly faster rate than the classical approaches for all instances in our numerical study, for a large class of MDP instances (see Section \ref{sec:simu}). It is an interesting open question to study the theoretical convergence of Algorithm \ref{alg:AVI}. \begin{remark} A similar analysis as for Proposition \ref{prop:B-pi-IRU} shows that the dynamics of the iterates of Momentum Value Iteration can also be modeled as a LTV dynamical system. However, we notice in our numerical study (Section \ref{sec:simu}) that \ref{alg:MVI} may diverge on some of the instances that we considered. We would like to note that this is also the case in convex optimization, where \cite{heavyball-2015} give an example of an instance where momentum gradient descent may diverge when the objective function is only differentiable once. \end{remark} \subsection{A family of hard MDP instances.} In light of the limitations of Algorithm \ref{alg:AVI} and \ref{alg:MVI}, we present a lower-bound on the class of `first-order' iterative algorithms for MDP. We first recall the analogous results for convex optimization. In optimization, a \textit{first-order algorithm} minimizing a differentiable, $\mu$-strongly convex, $L$-Lipschitz function $f: \mathbb{R}^{n} \rightarrow \mathbb{R}$ satisfies the following condition on the sequence of iterates $(\bm{x}_{s})_{s \geq 0}$: $ \bm{x}_{s+1} \in\bm{x}_{0} + span \{ \nabla f (\bm{x}_{0}),...,\nabla f (\bm{x}_{s}) \}, \forall \; s \geq 0.$ \cite{nesterov-book} provides lower-bounds on the convergence rate of any first-order algorithm on the class of smooth, convex functions and on the class of smooth, strongly-convex functions. In particular, we recall the results for lower-bounds of first-order algorithms in smooth convex optimization. \begin{theorem}[Th. 2.1.7, \cite{nesterov-book}] For any $\bm{x}_{0} \in \mathbb{R}^{n}$ and any step \\ $s \in \{0,..., (1/2)\cdot (n-1)\}$, there exists a convex, $L$-Lipschitz continuous function $f$ such that for any sequence of iterates $(\bm{x}_{s})_{s \geq 0}$ satisfying \[ \bm{x}_{s+1} \in \bm{x}_{0} + span \{ \nabla f (\bm{x}_{0}),...,\nabla f (\bm{x}_{s}) \}, \forall \; s \geq 0,\] the following lower bounds hold: \begin{align*} f(\bm{x}_{s}) - \inf_{\bm{x} \in \mathbb{R}^{n}} f(\bm{x}) & \geq \dfrac{3 L \| \bm{x}_{0} - \bm{x}^{*} \|_{2}^{2}}{32 \cdot (s+1)^{2}}, \\ \| \bm{x}_{s} - \bm{x}^{*} \|^{2}_{2} & \geq \dfrac{1}{8} \cdot \| \bm{x}_{0} - \bm{x}^{*} \|^{2}_{2}. \end{align*} \end{theorem} Note the key condition that the number of step $s$ is smaller than $(1/2)\cdot (n-1)$. Therefore, in finite dimension, some first-order algorithms may have a faster convergence rate than $\mathcal{O} \left(1/s^{2}\right)$, \textit{after} the first $(1/2)\cdot (n-1)$ iterations. In order to remove this condition, \cite{nesterov-book} considers $n = + \infty$, i.e., considers the space $\mathbb{R}^{\mathbb{N}}$ of infinite sequences of scalars, and proves the following lower-bound for smooth, strongly-convex functions. \begin{theorem}[Th. 2.1.13, \cite{nesterov-book}] For any $\bm{x}_{0} \in \mathbb{R}^{n}$ and any step $s \geq 0$, there exists a $\mu$-strongly convex, $L$-Lipschitz continuous function $f$ such that for any sequence of iterates $(\bm{x}_{s})_{s \geq 0}$ satisfying $$ \bm{x}_{s+1} \in \bm{x}_{0} + span \{ \nabla f (\bm{x}_{0}),...,\nabla f (\bm{x}_{s}) \}, \forall \; s \geq 0,$$ the following lower bounds hold : \begin{align*} f(\bm{x}_{s}) - \inf_{\bm{x} \in \mathbb{R}^{\mathbb{N}}} f(\bm{x}) & \geq \dfrac{\mu}{2} \cdot \left( \dfrac{\sqrt{L/ \mu}-1}{\sqrt{L/ \mu}+1} \right)^{2 s} \cdot \| \bm{x}_{0} - \bm{x}^{*} \|^{2}_{2}, \\ \| \bm{x}_{s} - \bm{x}^{*} \|^{2}_{2} & \geq \left( \dfrac{\sqrt{L/ \mu}-1}{\sqrt{L/ \mu}+1} \right)^{2 s} \cdot \| \bm{x}_{0} - \bm{x}^{*} \|^{2}_{2}. \end{align*} \end{theorem} Therefore, Nesterov's A-GD achieves the optimal rate of convergence over the class of smooth, convex functions, as well as over the class of smooth, strongly-convex functions. The proof relies on designing a hard instance. Additionally, \cite{nesterov-book} proves that the rates of convergence of A-GD match these lower-bounds and therefore that A-GD attains the optimal rate of convergence for these two classes of functions. Given our interpretation of $\left( \bm{I} -T \right)(\bm{v})$ as a gradient, in our MDP setting we consider \textit{first-order algorithm} as any iterative method where the sequence of iterates $(\bm{v}_{s})_{s \geq 0}$ satisfies $ \bm{v}_{0}=\bm{0}, \bm{v}_{s+1} \in span \{\bm{v}_{0},...,\bm{v}_{s}, T(\bm{v}_{0}), ... T(\bm{v}_{s}) \}, s \geq 0.$ We prove the following theorem. \begin{theorem}\label{th:hard-instance} There exists an MDP instance $(\mathbb{S},\mathbb{A},\bm{P},\bm{r},\bm{p}_{0},\lambda)$ such that for any sequence of iterates satisfying \[ \bm{v}_{0}=\bm{0}, \bm{v}_{s+1} \in span \{\bm{v}_{0},...,\bm{v}_{s}, T(\bm{v}_{0}), ... T(\bm{v}_{s}) \}, s \geq 0,\] the following lower bound holds for any step $s \in \{1,...,n-1\}$: \[\| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \geq \dfrac{\lambda^{s}}{1+\lambda}.\] \end{theorem} \begin{proof} Let us consider the following MDP. The discount factor is any $\lambda \in (0,1)$, there are $n $ states and one action. The rewards are such that $r_{1}=1$ and $r_{i}=0$ for all other states $i$. The state $1$ is absorbing and for $i \geq 2$, there is a deterministic transition from $i$ to $i-1$. \begin{figure}[H] \centering \includegraphics[scale=0.25]{MDP_hard.png} \caption{An MDP where there are $n$ states and one action. The state $1$ is absorbing, $r_{1}=1$ and there is no reward in any other state. The arrows represent deterministic transitions.} \label{fig:hard_instance} \end{figure} It is easy to see that the (optimal) value vector is $v^{*}_{i}=\lambda^{i-1}/(1-\lambda), i \in \mathbb{S}.$ Let us consider a sequence of vectors $(\bm{v}_{s})_{s \geq 0}$ such that $\bm{v}_{0}=\bm{0}$ and \[\bm{v}_{s} \in span \{ \bm{v}_{0}, ..., \bm{v}_{s-1}, T(\bm{v}_{0}), ... T(\bm{v}_{s-1}) \}, s \geq 0.\] We prove by recursion that for all $s \geq 0, i \in \mathbb{S}$, we have $v_{s,i}=0$ if $i \geq s+1.$ This is true for $s=0$ because $\bm{v}_{0}=\bm{0}$. Let us assume that this is true for $v_{0},...,v_{s-1}$. Then given the definition of $T$ as in \eqref{eq:T_max-def} and the fact that $r_{i}=0$ for $i \geq 2$ in the MDP of Figure \ref{fig:hard_instance}, we have $T(\bm{v}_{t})_{i} = 0$ if $i \geq t+2$, for all $t \leq s-1$. Therefore, from $ \bm{v}_{s} \in span \{ \bm{v}_{0}, ..., \bm{v}_{s-1}, T(\bm{v}_{0}), ... T(\bm{v}_{s-1}) \}$ we see that $v_{s,i} = 0,$ for $i \geq s+1$, and we proved our recursion. The state $1$ is the only state where the decision-maker earns a reward; note that we essentially proved that any first-order algorithm takes at least $s-1$ steps to back-propagate the reward from state $1$ towards a state $1 \leq s \leq n$. Now we have, for $1 \leq s \leq n-1$, \begin{align} \| \bm{v}_{s} - T(\bm{v}_{s}) \|_{\infty} & = \| \bm{v}_{s} - T(\bm{v}_{s}) - (\bm{v}^{*} - T(\bm{v}^{*})) \|_{\infty} \label{ineq:1} \\ & \geq (1-\lambda) \| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \label{ineq:2} \\ & \geq (1-\lambda) \max_{ 1 \leq i \leq n} |v_{s,i} - v^{*}_{i} | \nonumber \\ & \geq (1-\lambda) \max_{ s+1 \leq i \leq n} |v_{s,i} - v^{*}_{i} | \nonumber \\ & \geq (1-\lambda) \max_{ s+1 \leq i \leq n} | v^{*}_{i}| \label{ineq:3} \\ & \geq (1-\lambda) \max_{ s+1 \leq i \leq n} \dfrac{\lambda^{i-1}}{1-\lambda} \nonumber \\ & \geq \lambda^{s}, \nonumber \end{align} where \eqref{ineq:1} follows from $\bm{v}^{*} = T(\bm{v}^{*})$, \eqref{ineq:2} follows from \eqref{eq:mu-infty} and \eqref{ineq:2}, and \eqref{ineq:3} follows from $v_{s,i}=0$ for $i \geq s+1$. We can conclude since triangle inequality gives $\| \bm{v}_{s} - \bm{v}^{*} \|_{\infty} \geq (1/(1+\lambda)) \cdot \| \bm{v}_{s} - T(\bm{v}_{s}) \|_{\infty}.$ \end{proof} Note that Algorithm \ref{alg:AVI} is a first-order iterative algorithm for MDP. This implies that in general, Algorithm \ref{alg:AVI} may not perform better than \ref{alg:VI} in intermediate steps, \textit{before} the $n$-th iteration. In particular, we would like to note that this hard MDP instance is not irreducible. We illustrate this for our hard MDP instance in Figure \ref{fig:hard_instance_errors}. We notice that \ref{alg:VI} and \ref{alg:R-VI} converge linearly with a rate close to $\lambda$ (as we prove in Proposition \ref{prop:VI-step size}). However, Algorithm \ref{alg:AVI} starts to converge faster than \ref{alg:VI} only after (at least) $n$ iterations. This suggests that if one wants to compute an $\epsilon$-optimal policy for a large $\epsilon$ in a high-dimensional MDP with an analogous structure as our hard MDP instance, \ref{alg:VI} might be a faster algorithm for this particular instance. \begin{figure}[H] \centering \includegraphics[scale=0.5]{hard_instance_one_plot} \caption{We focus on the hard MDP instance of Figure \ref{fig:hard_instance}. We present the logarithm of the error $\| \bm{v}_{s} - \bm{v}^{*} \|_{\infty}$ for iterates of \ref{alg:VI}, Algorithm \ref{alg:R-VI} for $\alpha=0.9$ and $\alpha=1.1$ (R-VI-(0.9) and R-VI-(1.1)), Algorithm \ref{alg:AVI} with the tuning \eqref{eq:tuning-1} (A-V-1I), Algorithm \ref{alg:AVI} with the more aggressive tuning $\alpha_{s}=\alpha=1,\gamma_{s}=\gamma=\left(1-\sqrt{1-\lambda}\right)^{2}/\lambda, \forall \; s \geq 1$, corresponding to $L=1, \mu=1-\lambda$. We also include $(\lambda^{s})_{s \geq 0}$, the rate of convergence of \ref{alg:VI}, for reference.} \label{fig:hard_instance_errors} \end{figure} Finally, note that Algorithm \ref{alg:AVI} need not to be a \textit{descent algorithm}, i.e., it does not necessarily produce estimates that result in a monotonically decreasing objective function. The objective value might increase for a few periods, before significantly decreasing afterward (see Figure \ref{fig:hard_instance_errors}). This is analogous to \textit{oscillations} for accelerated gradient descent (see for instance Figure 1 in \cite{oscillation-2015} for a detailed study of the oscillation effect of A-GD). \section{Numerical study.}\label{sec:simu} We now present our numerical experiments which highlight the strong empirical performances of our algorithms. \paragraph{Experimental setup: Garnet MDP} The simulations are performed on a laptop with 2.2 GHz Intel Core i7 and 8 GB of RAM. We generate Garnet MDPs (\citet{garnet}), which are an abstract class of MDPs parametrized by a branching factor $n_{branch}$, equal to the number of reachable next states from each state-action pair $(i,a)$. We consider $n_{branch}=0.8$ in our simulations. We draw the rewards parameters at random uniformly in $[0,100]$. All the simulations are averages of the running-times to obtain an $\epsilon$-approximation of the value vector $\bm{v}^{\pi}$ of a random policy (Figure \ref{fig:value-computation}) or an $\epsilon$-approximation of the optimal value vector (Figure \ref{fig:policy-computation}), over 10 samples of random Garnet MDP instances. In order to obtain an $\epsilon$-approximation, we use the stopping condition $\| \bm{v}_{s+1} - \bm{v}_{s} \|_{\infty} \leq \epsilon \cdot (1-\lambda) \cdot (2 \lambda)^{-1}$ (Chapter 6.3 in \citet{Puterman}). We choose $\epsilon=1$. We initialize the algorithms with $\bm{v}_{0}=\bm{0}$ and, for \ref{alg:MVC} and \ref{alg:AVC}, $\bm{v}_{1}=T_{\pi} \left( \bm{v}_{0} \right)$, and for \ref{alg:AVI} and \ref{alg:MVI}, $\bm{v}_{1}=T \left( \bm{v}_{0} \right).$ \paragraph{Empirical performances for Value Computation} \begin{figure*}[h] \centering \includegraphics[width=.43\linewidth]{Value_Computation_Large_Lambda_large_instance_one_figure.pdf} \includegraphics[width=.43\linewidth]{Value_Computation_Large_Lambda_small_instance_one_figure.pdf} \caption{Value Computation. Logarithm of the running time of \ref{alg:VC}, \ref{alg:AVC} and \ref{alg:MVC} to obtain an $\epsilon$-approximation of the value vector of a random policy, for $\epsilon = 1$, for $n=150,A=100$ (left-hand side) and $n=50,A=30$ (right-hand side).} \label{fig:value-computation} \end{figure*} \begin{figure*}[h] \centering \includegraphics[width=.43\linewidth]{Policy_Computation_Large_Lambda_large_instance_one_figure.pdf} \includegraphics[width=.43\linewidth]{Policy_Computation_Large_Lambda_large_instance_one_figure.pdf} \caption{Policy Computation. Logarithm of the running time of \ref{alg:VI}, GS-VI, \ref{alg:R-VI} ($\alpha=0.9$ and $\alpha=1.1$) and A-VI, to obtain an $\epsilon$-approximation of the optimal value vector, for $\epsilon = 1$, for $n=150,A=100$ (left-hand side) and $n=50,A=30$ (right-hand side).} \label{fig:policy-computation} \end{figure*} We compare \ref{alg:AVC} and \ref{alg:MVC} with \ref{alg:VC}, the baseline method for computing the value vector $\bm{v}^{\pi}$ of a policy $\pi$. We present the results in Figure \ref{fig:value-computation} for large ($(n,A)=(150,100)$) and small instance ($(n,A)=(50,30)$) and different discount factors. Note that the axis for running time is in logarithmic scale. We notice that \ref{alg:MVC} and \ref{alg:AVC} both significantly outperform the classical approach \ref{alg:VC}. For large instance M-VC slightly outperforms \ref{alg:AVC}, which is coherent with our theoretical bounds (Theorem \ref{th:AVI-value-computation}, Theorem \ref{th:MVC-1}). For small instance \ref{alg:MVC} is slightly outperformed by \ref{alg:AVC} as $\lambda \rightarrow 1$. \paragraph{Empirical performances for Policy Computation} We present in Figure \ref{fig:policy-computation} our comparisons of the performance of Accelerated Value Iteration with state-of-the-art iterative approaches. We do not consider Momentum Value Iteration since we observed that it may not always converge. We also consider Gauss-Seidel Value Iteration (GS-VI), a popular asynchronous variant of \ref{alg:VI} \citet{Puterman}. where $(\bm{v}_{s})_{s \geq 0}$ is computed as $\bm{v}_{0} \in \mathbb{R}^{n},$ and for $i \in \mathbb{S}, s \geq 0,$ $ v_{s+1,i} = \max_{a \in \mathbb{A}} r_{ia} + \lambda \cdot \sum_{j=1}^{i-1} P_{iaj}v_{s+1,j} + \lambda \cdot \sum_{j=i}^{n} P_{iaj}v_{s,j}.$ We notice that Algorithm A-VI significantly outperforms the other approaches, by more than one order of magnitude when $\lambda$ approaches $1$. We also notice that Algorithm \ref{alg:R-VI} outperforms \ref{alg:VI} for $\alpha=1.1$ but not for $\alpha=0.9$, which highlights the importance of the choice of step size in Algorithm \ref{alg:R-VI}. \paragraph{Divergence of Momentum Value Iteration} In our simulations we observe that Algorithm \ref{alg:MVI} might diverge for the natural choice of step sizes for twice differentiable functions, i.e. for tuning \eqref{eq:tuning-MVC-1}. This is analogous to the situation in convex optimization, where the optimal choice of parameters for $f$ a twice differentiable function might lead to a non-converging sequence for a function with a piece-wise linear gradient, i.e. when $f$ is only differentiable once (\citet{heavyball-2015}). We would like to note that $ \bm{v} \mapsto (\bm{I} - T)(\bm{v})$ is a piece-wise linear function. Even though we do not have a theoretical bound for A-VI, we would like to note that it converges on all our test instances. \section{Conclusion.} In this paper we present a fundamental connection between gradient descent and value iteration and build upon this analogy and ideas from Nesterov's acceleration to present an accelerated value iteration algorithm for MDP. We prove a significantly faster convergence rate for the computation of a value vector, including a novel momentum algorithm for value computation, and highlight the faster empirical performances of our algorithms. We also present a lower-bound on the convergence rate of any first-order iterative method for solving MDP. For the case of computing an optimal value vector, even though we do not have a theoretical convergence rate, our algorithm \ref{alg:AVI} exhibits significantly better empirical performances compared to state-of-the-art iterative algorithms. Analyzing the theoretical convergence rate for Algorithm \ref{alg:AVI} is an interesting open question. \small \bibliographystyle{plainnat}
{ "redpajama_set_name": "RedPajamaArXiv" }
4,704
Have you ever lied—even once? Ever used God's name as a cuss word? Those who are right with God will spend eternity with Him in heaven. Those who die in their sin will be punished for eternity in hell. (Romans 14:10-12, John 5:24, & Psalms 9:17). If God judged you today, according to what you have done, would you be innocent or guilty? If you are guilty before a just God, should you go to heaven or hell? Because God is a good judge, sin can't be swept under the rug. Whenever we sin, God says that justice must be done. We deserve to pay for our sin. Jesus Christ's death satisfied the demands of God's justice and allows God to forgive and save those who place their faith in Him. The Bible says the that even our best attempts of being "good" are like filthy rags to God. We are completely incapable of earning God's grace. When you work for someone, they owe you a wage. Unlike a gift, which is freely given and never owed. God's grace is a gift, freely given from the overflow of His love and goodness. You can't work for it. Admit that you have broken God's laws and deserve to be punished. And that you are totally incapable of saving yourself and are destined for hell. Acknowledge Jesus as Lord. This means that, with God's help, you must turn your heart away from wrong things (sin) and turn your heart toward God, deciding to surrender your heart to Him and submitting to His will. Instead of being "the lord" of your own life, you decide to submit to the Lordship of Jesus Christ. Believe that Jesus, God's son, died on the cross and rose again, taking the punishment you deserve for your sins. This belief, or faith, comes from a deep confidence within your heart: choosing to place all of your trust in Jesus alone for salvation, that He is the only way to God. WHAT HAPPENS WHEN I BELIEVE?
{ "redpajama_set_name": "RedPajamaC4" }
9,254
A Transzfogarasi út (románul Drumul Transfăgărășan), másként 7C jelzésű országút (Drumul Național 7C) a Fogarasi-havasok központi részén keresztül észak-déli irányban köti össze Alsóárpás és Curtea de Argeș településeket. Az 1970-es években építették, 90 km hosszú. 2042 m magasságig vezet fel, majd egy alagúton halad át a főgerinc alatt. Összesen 830 hídja, 27 viaduktja, valamint 5 alagútja van. Az út lavinaveszély miatt csak nyáron van nyitva. A hóviszonyoktól függően októberben vagy novemberben lezárják és csak június elején, közepén nyitják meg újra. Az út honlapján olvasható információ szerint a hivatalos nyitvatartás július 1-től november 30-ig tart. Története Nicolae Ceaușescu román diktátor katonai szállítási útvonalnak építtette, mert az 1968-as prágai tavasz után attól tartott, hogy a Szovjetunió Romániát is megszállhatja. Az Argeș megyei pártbizottság azt javasolta, hogy Ceaușescuról nevezzék el az utat (Drumul Transfăgărășan Nicolae Ceaușescu), de ezt maga Ceaușescu – aki akkor még nem honosította meg személyi kultuszát – határozottan elutasította. Építése 1969 végén kezdődött; katonák dolgoztak rajta, és hivatalos adatok szerint az építkezés alatt 40 ember veszítette életét különféle balesetekben. Az utat 1974. szeptember 20-án nyitották meg, de a munkálatok egészen 1980-ig folytatódtak. Turizmus Az út lenyűgöző szépségű tájon vezet keresztül, elhalad a Bilea-vízesés telep, a Bilea-tó és a mesterséges Vidraru-tó mellett. A Transzfogarasi út elkészülte megkönnyítette a hegység megközelítését, ezért az 1970-es évek óta nagyon sok turista érkezik. A nagy turistaforgalom együtt jár a környezetre káros hatások növekedésével. Képek Jegyzetek Források Nagy Balázs: "A Kárpátok magashegyi útjai". A Földgömb, 2008/7. szám, 36-41. oldal További információk Az építés története Képek A Transzfogarasi út interaktív térképe A Top Gear tv-sorozat romániai kiruccanásának 6 részes videója (Az utolsó rész a Transzfogarasi úton készült) Képgaléria Az út honlapja (románul) Fórum, információk az út pillanatnyi állapotáról Fogarasi-havasok Románia főútjai
{ "redpajama_set_name": "RedPajamaWikipedia" }
2,954
{"url":"https:\/\/forum.allaboutcircuits.com\/threads\/one-gram.7550\/","text":"# one Gram\n\n#### Voltboy\n\nJoined Jan 10, 2007\n197\nOne gram is the absolute weight of a volume of pure water equal to the cube of the hundredth part of a metre, and at the temperature of melting ice (4\u00b0C). That's 1 milliliter of pure water at 4\u00b0C.\nWhy does it have to be at 4\u00b0C, if 1ml of pure water at 4\u00b0C still will be 1ml of pure water at 5\u00b0C, and will have the same mass (because its still 1ml or pure water).\n\n#### Elektronster\n\nJoined Oct 19, 2007\n2\nWater changes volume as it warms up or cools down. At 4\u00b0 C (actually, 3.98\u00b0 C) pure water is at its densest state, when one milliliter equals exactly one gram. Water any warmer or cooler than 3.98\u00b0 C is not as dense, so one milliliter of pure water would exhibit less mass than exactly one gram.\n\n#### Papabravo\n\nJoined Feb 24, 2006\n15,462\nSo the answer is that the sum of the masses of the water atoms is the same but the volume of those atoms changes as a function of temperature. To get the standard gram you have to have the right number of water molecules, each having a mass that can be computed from the atomic weight and Avagodro's number, occupying a volume of one cubic centimeter.\n\nIn short one cubic centimeter of water at 4 degrees C with the right number of atoms will have a mass of 1 gram. If you change the temperature, the number of atoms stays the same, the mass stays the same, but the volume is no longer 1 cubic centimeter so that situation is no good for a standard.\n\n#### Voltboy\n\nJoined Jan 10, 2007\n197\nThanks guys.\n\n#### recca02\n\nJoined Apr 2, 2007\n1,214\nwhat about pressure isnt that defined for density?\ni think density also changes with pressure (though negligibly with liquid and even lesser with solids)\n\n#### Papabravo\n\nJoined Feb 24, 2006\n15,462\nwhat about pressure isnt that defined for density?\ni think density also changes with pressure (though negligibly with liquid and even lesser with solids)\nI don't think so. Density is mass per unit volume. Pressure has units of force per unit area. By NSL force has units of mass times distance per second squared. This leaves mass per distance times seconds squared. I can't see any relation between density and pressure, at least with respect to a cubic centimeter of water sitting on a table in a room a 4 degrees C.\n\n#### recca02\n\nJoined Apr 2, 2007\n1,214\nunits aside, pressure greatly influences density. so much so that at criticle point the density of steam and water become equal (though this time the temperature equals boiling point).\n\nthe critical pressure is at abt 221 bars or thereabout.\nand temp abt 374 deg centigrade(not sure).\n\nlet me elaborate a little.\neven solids have something called bulk modulus.\nthere is a change in volume for a pressure applied.\nmass does not change with pressure.\nthus density shud change.what say?\n\n#### Voltboy\n\nJoined Jan 10, 2007\n197\nyea.. I think you're right\n\n#### Papabravo\n\nJoined Feb 24, 2006\n15,462\nHardly a significant effect on a solid or a liquid at 1 atm( ~ 1000 mB). How many angels can dance on the head of a pin? If I go from 960 mB during Hurricane Katrina to 1020 mB on a beautifal fall day in Michigan what is the change in volume of my cubic centimeter of water? Assume the temperature is a constant 68 degrees F.\n\n#### recca02\n\nJoined Apr 2, 2007\n1,214\ntrue,\nlike i said before the compressibility of fluid is ideally zero,\nbut for a standard definition pressure like STP should be mentioned since pressure also changes boiling and freezing points.in any case is the above definition accurate?\ndoes the density fo water exactly equal 1000 Kg\/cu.m\n\n#### GS3\n\nJoined Sep 21, 2007\n408\nOne gram is the absolute weight of a volume of pure water equal to the cube of the hundredth part of a metre, and at the temperature of melting ice (4\u00b0C). That's 1 milliliter of pure water at 4\u00b0C.\nWhy does it have to be at 4\u00b0C, if 1ml of pure water at 4\u00b0C still will be 1ml of pure water at 5\u00b0C, and will have the same mass (because its still 1ml or pure water).\nThe gram *was* originally defined like that but no longer.\nhttp:\/\/en.wikipedia.org\/wiki\/Kilogram\n\nThe kilogram is defined as being equal to the mass of the International Prototype Kilogram (IPK), which is almost exactly equal to the mass of one liter of water.\n...\nOn 7 April 1795, the gram was decreed in France to be equal to \u0093the absolute weight of a volume of pure water equal to a cube of one hundredth of a meter, and to the temperature of the melting ice.\u0094[5] The regulation of trade and commerce required a practical reference standard in addition to the definition based on fundamental physical properties. Accordingly, a provisional kilogram standard was made as a single-piece, metallic reference standard one thousand times more massive than the gram.\n\nIn addition to this provisional kilogram standard, work was commissioned to determine precisely how massive a cubic decimeter (now defined as one liter) of water is. Although the decreed definition of the kilogram specified water at 0 \u00b0C \u0097 a highly stable temperature point \u0097 the scientists chose to redefine the standard and perform their measurements at the most stable density point: the temperature at which water reaches maximum density, which was measured at the time as 4 \u00b0C.[6] They concluded that one cubic decimeter of water at its maximum density was equal to 99.92072% of the mass of the provisional kilogram made earlier that year.[7] Four years later in 1799, an all-platinum prototype kilogram, the Kilogramme des Archive (Kilogram of the Archives), was fabricated with the objective that it would equal, as close as was scientifically feasible for the day, the mass of a cubic decimeter of water at 4 \u00b0C. The kilogram was defined to be equal to the mass of the Kilogram of the Archives and this standard stood for the next ninety years.\n\nSince 1889, the SI system defines the magnitude of the kilogram to be equal to the mass of the International Prototype Kilogram \u0097 often referred to in the professional metrology world as the \u0093IPK\u0094. The IPK is made of an alloy of 90% platinum and 10% iridium (by weight) and is machined into a right-circular cylinder (height = diameter) of 39.17 mm to minimize its surface area.\n...\nThe kilogram underpins the entire SI system of measurement as it is currently defined and structured, so its stability is crucial. For instance, the newton \u0097 the SI unit of force \u0097 is defined as the force necessary to accelerate the kilogram by one meter per second\u00b2. Accordingly, if the mass of the IPK were to change slightly, so too must the newton by a proportional degree so that the acceleration remains at precisely one meter\/second\u00b2. In turn, the pascal \u0097 the SI unit of pressure \u0097 is defined in terms of the newton. This chain of dependency follows to all the electrical units. For instance, the joule, which is the electrical and mechanical unit of energy, is defined as the energy expended when a force of one newton acts through one meter. The ampere is also defined relative to the kilogram. With two of the primary units of electricity thus defined in terms of the kilogram, so too follow all the rest, including the watt, volt, ohm, coulomb, farad, and weber.\n\nClearly, having the magnitude of many of the units comprising the SI system of measurement ultimately defined by the mass of a 128-year-old piece of metal is a tenuous state of affairs.\nVery interesting article.","date":"2021-04-13 05:00:17","metadata":"{\"extraction_info\": {\"found_math\": false, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.8025656342506409, \"perplexity\": 1145.3750645805055}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-17\/segments\/1618038072082.26\/warc\/CC-MAIN-20210413031741-20210413061741-00341.warc.gz\"}"}
null
null
Q: Filtering table record based on time availability in SQL Server I have one table tblAvailability in which I have two column StartTime time and EndTime time. There I set StartTime=7 AM and EndTime=10. Now I have filter in front end which send time range like 6 TO 10 OR 7:30 TO 10 like this. I wrote the SQL query like below. Where CONVERT(varchar, StartTime, 108) >= CONVERT(varchar, @startTime, 108) AND CONVERT(varchar, EndTime, 108) <= CONVERT(varchar, @endTime, 108) Now I would like to filter out rows based on start and end time range, means would like to get all records table whose start and end time ranges between selected time range. A: As mentioned in the comments above, you are not clear whether you are using time of date or date and time. Can you please post more information. You should be aware that date types and ranges in SQL Server can differ to a client language such as C# (although you don't mention your client language). For example, if you are using SQL Server "datetime" you can restrict the client date range in C# by using the appropriate type, e.g. System.Data.SqlDbType.DateTime You say you have written a query you want to use as to filter some data, which I assume you run within SQL Server. Assume using C# as the client, an efficient way of returning data is to write a View in SQL Server and add this to an Entity Framework model. To query this data at the client, use LinqSQL which will convert your client code into SQL and runs surprisingly efficiently. var filteredData = (from i in _db.vw_SomeData where i.StartDate >= fromDate && i.EndDate < toDate select i).ToList() Be careful of your data endpoints (inclusive and exclusive values). If you use SQL Server datetime and you want all times within a day, then I use (date >= today and date < tomorrow) which is guaranteed to work. trying to test against the last second of the day with a "less than or equals" won't work where there is a time between the last second and midnight. To sum up, comparing date and or time is best performed natively for those types. Only where some of the comparison data is a string should you convert one to the other. The only easily sortable and comparable date and time is yyyymmdd and HHmmss
{ "redpajama_set_name": "RedPajamaStackExchange" }
9,538
Woman's face burned with alkaline solution in store attack Apr. 6, 2013 03:00 pm JST Apr. 8, 2013 | 07:55 am JST A woman was attacked with a strong alkaline liquid in a store at a train station in Tokyo's Ota Ward on Friday night. According to police, the 19-year-old woman was working at a confectionery store at JR Omori Station at around 7 p.m. when she was attacked from behind by an assailant who threw a clear liquid into her face, TBS reported. She was quoted by police as saying she was unable to see the assailant. Police on Saturday arrested the assailant who was an ex-boyfriend of the woman. Police say the woman sustained burns to her face and back in the attack, thought to have been caused by a strong alkaline agent that was detected in the liquid. © Japan Today kimuzukashiiiii Apr. 6, 2013 03:44 pm JST That is absolutely terrifying, especially if there was no motive. Were there no witnesses? If it was at work, surely there would be security cameras? For a woman, to be scarred like this is a horrible thing to have to live with, even if her face is eventually unscarred. I hope she makes a complete recovery, poor girl. This is scary even if she knew the attacker. Way too many attacks just this week. Jilted boyfriend for sure! Or, should that be, boy fiend? OrangeXenon54 I really don't understand these "acid attacks" in Asia. Where do you even buy that stuff?? Here's hoping that she has a full recovery and that they catch the man responsible. timeon Orange, it was alkaline. You can buy at any store an alkaline solution for clogged drainage "pipeman"), that's what the guy probably used. I hope her eyes are ok, alkaline is very dangerous for the eyes. whoa, hope the psychos are not taking a page outta the pakistanis Very sad hope she will recover soon. House Atreides There was also a recent acid attack on Sergei Filin, the artistic director of the Bolshoi. I hope they have video of the assailant. The sooner he or she is caught the better. I wouldn't rule out the attacker being a woman though. There have been a number of incidents where a woman has attacked another woman with acid. hereforever For those of you who are not familiar with that station, it is packed at 7pm on a Friday. Why no one helped catch the loser is beyond me. Dukeleto Shame, what a terrible thing to do to anyone. This person who did this is a coward of the nth degree. Poor girl I hope she makes a full recovery and is not mentally scarred by the ordeal. I hope the police catch this guy and really throw the book at him. tokyo-star cmon, Ive had fallings out with exes, but just let them be ffs. This is going too far. hereforever: "For those of you who are not familiar with that station, it is packed at 7pm on a Friday. Why no one helped catch the loser is beyond me." It's Japan. Sure, they'll all talk about it to the media and say how horrible it was, but to actually do something about it is rare, here. There ARE some occasions where people do, and I hope if they cannot step forward at least all the anti-crime cameras were actually on. Poor woman.... what a horrible thing. I pray the police catch the guy. April has literally had every day a stabbing, axe attack, or some other horrific crime. Be careful, people. Where do you even buy that stuff? In any supermarket. Most cleaning products are dangerous when used in an improper way. That's like kitchen knives. We can always ban weapons and restrict access to concentrated products to industry, but there will always be things the weirdos can use. I just hope the poor lady recovers somehow - physically and mentally. Sadly there is a very real chance her life is effectively destroyed. This cowardly, violent maniac must be caught soon, and locked away for the term of his natural life. I also hope there are not a spate of copycat attacks: this form of extreme violence toward women is usually only seen in India and Islamic culture. Japan does not need more problems. Viviana Guadagno Apr. 7, 2013 12:24 am JST in Japan ????? It's sad ! I would not make the assumption about the gender of the assailant. gyroman These cowardly attacks are way too common in India. And like cos pointed out, this stuff is daily use, easily available. However, unlike India I hope the assailants are found and hope they have to part with what they've taken of the poor lady's life which is for the rest *of their lives nigelboy Reality versus TV. The assailant poured a liquid over the victim. I seriously doubt anybody around knew exactly what the liquid was. In any case, it appears based on other reports that it's likely the work of her ex-boyfriend. Extra Virgin Palm Oil attacked from behind by an assailant who threw a clear liquid into her face.< For those of you who are not familiar with that station, it is packed at 7pm on a Friday. Why no one helped catch the loser is beyond me.< Call in the detectives! Shumatsu_Samurai I really don't understand these "acid attacks" in Asia. Where do you even buy that stuff?? There was an acid attack in the UK not so long ago. And as Cos said, you can buy liquids that will burn skin from the supermarket. Triumvere Oh god, not here too. i don't know about u guys but japan is really getting worse, well, in general the whole world is getting worse :(. don't take things for granted. be happy where u r at, what u got. i know i am. anyways for a women this really sucks i feel for her, i really hope those burn marks aren't so bad. but yeah these liquid type attacks are THE WORST i tear up for the victim all the time when i read em online or in the newspaper. so called safe japan lol no where in the whole world is it safe. so i really hate it when people say oh japan is safest place. come on no it isn't. the whole world is not a safe. hope they catch this bastard 602miko poor girl! hope she can recover soon this might bring her a in bigger trauma. Kokashi Scary. That is the sort of story one is used to hearing from Pakistan and Afghanistan. But in Japan? I hope they catch the creep soon. This happens in the entire world. It must have caught it on video, because the article now says they've arrested the assailant who was an ex-boyfriend of the victim. I don't care how much of a biyaitch the girl might have been, there's no action that warrants this kind of response.
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
6,364
from __future__ import unicode_literals import datetime import hashlib import random import re from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ObjectDoesNotExist from django.core.mail import EmailMultiAlternatives from django.db import models, transaction from django.template import TemplateDoesNotExist from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from django.utils.timezone import now as datetime_now from django.utils import six from .users import UserModel, UserModelString SHA1_RE = re.compile('^[a-f0-9]{40}$') def send_email(addresses_to, ctx_dict, subject_template, body_template, body_html_template): """ Function that sends an email """ subject = ( getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') + render_to_string( subject_template, ctx_dict) ) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) from_email = getattr(settings, 'REGISTRATION_DEFAULT_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL) message_txt = render_to_string(body_template, ctx_dict) email_message = EmailMultiAlternatives(subject, message_txt, from_email, addresses_to) if getattr(settings, 'REGISTRATION_EMAIL_HTML', True): try: message_html = render_to_string( body_html_template, ctx_dict) except TemplateDoesNotExist: pass else: email_message.attach_alternative(message_html, 'text/html') email_message.send() class RegistrationManager(models.Manager): """ Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts. """ def _activate(self, profile, get_profile): """ Activate the ``RegistrationProfile`` given as argument. User is able to login, as ``is_active`` is set to ``True`` """ user = profile.user user.is_active = True profile.activated = True with transaction.atomic(): user.save() profile.save() if get_profile: return profile else: return user def activate_user(self, activation_key, get_profile=False): """ Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``User``. If the key is valid but the ``User`` is inactive, return ``False``. To prevent reactivation of an account which has been deactivated by site administrators, ``RegistrationProfile.activated`` is set to ``True`` after successful activation. """ # Make sure the key we're trying conforms to the pattern of a # SHA1 hash; if it doesn't, no point trying to look it up in # the database. if SHA1_RE.search(activation_key): try: profile = self.get(activation_key=activation_key) except self.model.DoesNotExist: # This is an actual activation failure as the activation # key does not exist. It is *not* the scenario where an # already activated User reuses an activation key. return False if profile.activated: # The User has already activated and is trying to activate # again. If the User is active, return the User. Else, # return False as the User has been deactivated by a site # administrator. if profile.user.is_active: return profile.user else: return False if not profile.activation_key_expired(): return self._activate(profile, get_profile) return False def create_inactive_user(self, site, new_user=None, send_email=True, request=None, profile_info={}, **user_info): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. Additionally, if email is sent and ``request`` is supplied, it will be passed to the email template. """ if new_user is None: password = user_info.pop('password') new_user = UserModel()(**user_info) new_user.set_password(password) new_user.is_active = False # Since we calculate the RegistrationProfile expiration from this date, # we want to ensure that it is current new_user.date_joined = datetime_now() with transaction.atomic(): new_user.save() registration_profile = self.create_profile( new_user, **profile_info) if send_email: registration_profile.send_activation_email(site, request) return new_user def create_profile(self, user, **profile_info): """ Create a ``RegistrationProfile`` for a given ``User``, and return the ``RegistrationProfile``. The activation key for the ``RegistrationProfile`` will be a SHA1 hash, generated from a combination of the ``User``'s pk and a random salt. """ profile = self.model(user=user, **profile_info) if 'activation_key' not in profile_info: profile.create_new_activation_key(save=False) profile.save() return profile def resend_activation_mail(self, email, site, request=None): """ Resets activation key for the user and resends activation email. """ try: profile = self.get(user__email=email) except ObjectDoesNotExist: return False # TODO: Catch multiple objects returned exception? if profile.activated or profile.activation_key_expired(): return False profile.create_new_activation_key() profile.send_activation_email(site, request) return True def delete_expired_users(self): """ Remove expired instances of ``RegistrationProfile`` and their associated ``User``s. Accounts to be deleted are identified by searching for instances of ``RegistrationProfile`` with expired activation keys, and then checking to see if their associated ``User`` instances have the field ``is_active`` set to ``False``; any ``User`` who is both inactive and has an expired activation key will be deleted. It is recommended that this method be executed regularly as part of your routine site maintenance; this application provides a custom management command which will call this method, accessible as ``manage.py cleanupregistration``. Regularly clearing out accounts which have never been activated serves two useful purposes: 1. It alleviates the ocasional need to reset a ``RegistrationProfile`` and/or re-send an activation email when a user does not receive or does not act upon the initial activation email; since the account will be deleted, the user will be able to simply re-register and receive a new activation key. 2. It prevents the possibility of a malicious user registering one or more accounts and never activating them (thus denying the use of those usernames to anyone else); since those accounts will be deleted, the usernames will become available for use again. If you have a troublesome ``User`` and wish to disable their account while keeping it in the database, simply delete the associated ``RegistrationProfile``; an inactive ``User`` which does not have an associated ``RegistrationProfile`` will not be deleted. """ for profile in self.all(): try: if profile.activation_key_expired(): user = profile.user if not user.is_active: profile.delete() user.delete() except UserModel().DoesNotExist: profile.delete() @python_2_unicode_compatible class RegistrationProfile(models.Model): """ A simple profile which stores an activation key for use during user account registration. Generally, you will not want to interact directly with instances of this model; the provided manager includes methods for creating and activating new accounts, as well as for cleaning out accounts which have never been activated. While it is possible to use this model as the value of the ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do so. This model's sole purpose is to store data temporarily during account registration and activation. """ user = models.OneToOneField( UserModelString(), on_delete=models.CASCADE, verbose_name=_('user'), ) activation_key = models.CharField(_('activation key'), max_length=40) activated = models.BooleanField(default=False) objects = RegistrationManager() class Meta: verbose_name = _('registration profile') verbose_name_plural = _('registration profiles') def __str__(self): return "Registration information for %s" % self.user def create_new_activation_key(self, save=True): """ Create a new activation key for the user """ salt = hashlib.sha1(six.text_type(random.random()) .encode('ascii')).hexdigest()[:5] salt = salt.encode('ascii') user_pk = str(self.user.pk) if isinstance(user_pk, six.text_type): user_pk = user_pk.encode('utf-8') self.activation_key = hashlib.sha1(salt + user_pk).hexdigest() if save: self.save() return self.activation_key def activation_key_expired(self): """ Determine whether this ``RegistrationProfile``'s activation key has expired, returning a boolean -- ``True`` if the key has expired. Key expiration is determined by a two-step process: 1. If the user has already activated, ``self.activated`` will be ``True``. Re-activating is not permitted, and so this method returns ``True`` in this case. 2. Otherwise, the date the user signed up is incremented by the number of days specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of days after signup during which a user is allowed to activate their account); if the result is less than or equal to the current date, the key has expired and this method returns ``True``. """ expiration_date = datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS) return (self.activated or (self.user.date_joined + expiration_date <= datetime_now())) activation_key_expired.boolean = True def send_activation_email(self, site, request=None): """ Send an activation email to the user associated with this ``RegistrationProfile``. The activation email will use the following templates, which can be overriden by setting ACTIVATION_EMAIL_SUBJECT, ACTIVATION_EMAIL_BODY, and ACTIVATION_EMAIL_HTML appropriately: ``registration/activation_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/activation_email.txt`` This template will be used for the text body of the email. ``registration/activation_email.html`` This template will be used for the html body of the email. These templates will each receive the following context variables: ``user`` The new user account ``activation_key`` The activation key for the new account. ``expiration_days`` The number of days remaining during which the account may be activated. ``site`` An object representing the site on which the user registered; depending on whether ``django.contrib.sites`` is installed, this may be an instance of either ``django.contrib.sites.models.Site`` (if the sites application is installed) or ``django.contrib.sites.requests.RequestSite`` (if not). Consult the documentation for the Django sites framework for details regarding these objects' interfaces. ``request`` Optional Django's ``HttpRequest`` object from view. If supplied will be passed to the template for better flexibility via ``RequestContext``. """ activation_email_subject = getattr(settings, 'ACTIVATION_EMAIL_SUBJECT', 'registration/activation_email_subject.txt') activation_email_body = getattr(settings, 'ACTIVATION_EMAIL_BODY', 'registration/activation_email.txt') activation_email_html = getattr(settings, 'ACTIVATION_EMAIL_HTML', 'registration/activation_email.html') ctx_dict = { 'user': self.user, 'activation_key': self.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': site, } subject = (getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') + render_to_string( activation_email_subject, ctx_dict, request=request)) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) from_email = getattr(settings, 'REGISTRATION_DEFAULT_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL) message_txt = render_to_string(activation_email_body, ctx_dict, request=request) email_message = EmailMultiAlternatives(subject, message_txt, from_email, [self.user.email]) if getattr(settings, 'REGISTRATION_EMAIL_HTML', True): try: message_html = render_to_string( activation_email_html, ctx_dict, request=request) except TemplateDoesNotExist: pass else: email_message.attach_alternative(message_html, 'text/html') email_message.send() class SupervisedRegistrationManager(RegistrationManager): def _activate(self, profile, get_profile): """ Activate the ``SupervisedRegistrationProfile`` given as argument. Send an email to the site administrators to approve the user. User is not able to login yet, as ``is_active`` is not yet ``True`` """ if not profile.user.is_active and not profile.activated: site = Site.objects.get_current() self.send_admin_approve_email(profile.user, site) # do not set ``User.is_active`` as True. This will be set # when a site administrator approves this account. profile.activated = True profile.save() if get_profile: return profile else: return profile.user def admin_approve_user(self, profile_id, site, get_profile=False, request=None): """ Approve the ``SupervisedRegistrationProfile`` object with the given ``profile_id``. If the id is valid, return the ``User`` after approving. If the id is not valid, return ``False``. If the id is valid but the ``User`` is already active, return ``User``. If the id is valid but the ``SupervisedRegistrationProfile`` object is not activated, return ``False``. """ try: profile = SupervisedRegistrationProfile.objects.get(id=profile_id) if profile.activated: if profile.user.is_active: return profile.user # If the user has not activated their profile the admin should # not be able to approve his account (at least not following # this process) if profile.activated: profile.user.is_active = True else: return False profile.user.save() profile.send_admin_approve_complete_email(site, request) if get_profile: return profile else: return profile.user except self.model.DoesNotExist: return False def send_admin_approve_email(self, user, site, request=None): """ Send an approval email to the site administrators to approve this user. The approval email will use the following templates, which can be overriden by setting APPROVAL_EMAIL_SUBJECT, APPROVAL_EMAIL_BODY, and APPROVAL_EMAIL_HTML appropriately: ``registration/admin_approve_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/admin_approve_email.txt`` This template will be used for the text body of the email. ``registration/admin_approve_email.html`` This template will be used for the html body of the email. These templates will each receive the following context variables: ``user`` The new user account ``profile_id`` The id of the associated``SupervisedRegistrationProfile`` object. ``site`` An object representing the site on which the user registered; depending on whether ``django.contrib.sites`` is installed, this may be an instance of either ``django.contrib.sites.models.Site`` (if the sites application is installed) or ``django.contrib.sites.requests.RequestSite`` (if not). Consult the documentation for the Django sites framework for details regarding these objects' interfaces. ``request`` Optional Django's ``HttpRequest`` object from view. If supplied will be passed to the template for better flexibility via ``RequestContext``. """ admin_approve_email_subject = getattr( settings, 'ADMIN_APPROVAL_EMAIL_SUBJECT', 'registration/admin_approve_email_subject.txt' ) admin_approve_email_body = getattr( settings, 'ADMIN_APPROVAL_EMAIL_BODY', 'registration/admin_approve_email.txt' ) admin_approve_email_html = getattr( settings, 'ADMIN_APPROVAL_EMAIL_HTML', 'registration/admin_approve_email.html' ) ctx_dict = { 'user': user, 'profile_id': user.registrationprofile.id, 'site': site, } admins = getattr(settings, 'ADMINS', None) if not admins: raise ImproperlyConfigured( 'Using the admin_approval registration backend' ' requires at least one admin in settings.ADMINS') admins = [admin[1] for admin in admins] send_email( admins, ctx_dict, admin_approve_email_subject, admin_approve_email_body, admin_approve_email_html ) class SupervisedRegistrationProfile(RegistrationProfile): # Same model as ``RegistrationProfile``, just a different # Manager to implement the extra functionality required # in admin approval objects = SupervisedRegistrationManager() def send_admin_approve_complete_email(self, site, request=None): """ Send an "approval is complete" email to the user associated with this ``SupervisedRegistrationProfile``. The email will use the following templates, which can be overriden by settings APPROVAL_COMPLETE_EMAIL_SUBJECT, APPROVAL_COMPLETE_EMAIL_BODY, and APPROVAL_COMPLETE_EMAIL_HTML appropriately: ``registration/admin_approve_complete_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/admin_approve_complete_email.txt`` This template will be used for the text body of the email. ``registration/admin_approve_complete_email.html`` This template will be used for the text body of the email. These templates will each receive the following context variables: ``user`` The new user account ``site`` An object representing the site on which the user registered; depending on whether ``django.contrib.sites`` is installed, this may be an instance of either ``django.contrib.sites.models.Site`` (if the sites application is installed) or ``django.contrib.sites.requests.RequestSite`` (if not). Consult the documentation for the Django sites framework for details regarding these objects' interfaces. ``request`` Optional Django's ``HttpRequest`` object from view. If supplied will be passed to the template for better flexibility via ``RequestContext``. """ admin_approve_complete_email_subject = getattr( settings, 'APPROVAL_COMPLETE_EMAIL_SUBJECT', 'registration/admin_approve_complete_email_subject.txt') admin_approve_complete_email_body = getattr( settings, 'APPROVAL_COMPLETE_EMAIL_BODY', 'registration/admin_approve_complete_email.txt') admin_approve_complete_email_html = getattr( settings, 'APPROVAL_COMPLETE_EMAIL_HTML', 'registration/admin_approve_complete_email.html') ctx_dict = { 'user': self.user.username, 'site': site, } send_email( [self.user.email], ctx_dict, admin_approve_complete_email_subject, admin_approve_complete_email_body, admin_approve_complete_email_html )
{ "redpajama_set_name": "RedPajamaGithub" }
6,922
Your straw hat, gone modern. A 3 1/2" shaped brim helps you keep comfortable under the sun and look stylish when wearing. 100% Poly-straw, internal drawstring adjusts fit, packs flat, handwash cold, Made in China.
{ "redpajama_set_name": "RedPajamaC4" }
795
Proclama de París es la denominación de la proclamación que se fijó en los muros de la ciudad de París en la mañana del día 1 de abril de 1814 (escrita a las tres de la tarde del 31 de marzo), el día siguiente a la entrada en la ciudad de las tropas de la Sexta Coalición vencedoras en la batalla de París, encabezadas por el zar Alejandro I de Rusia. Iba firmada por el propio zar, aunque se supone que fue redactada o al menos inspirada por Charles-Marcel Talleyrand, príncipe de Périgord, cercano a Alejandro en esos días. Se le atribuye una gran importancia histórica porque condicionó todas las posteriores decisiones de los aliados; destacadamente, el Tratado de París (30 de mayo de 1814). No obstante, los representantes de tales potencias no estuvieron satisfechos con la proclama, especialmente el canciller austríaco Klemens von Metternich (quien por otra parte detestaba al zar Alejandro), y el inglés Robert Stewart, vizconde de Castlereagh (plenipotenciario de Su Majestad Británica en el Congreso de Viena), que acusaron veladamente al autócrata ruso de haber concedido demasiado a los franceses; pero al considerarse como hechos consumados y palabra de rey, no pudieron revertir la decisión. En cuanto a los rusos, quedaron impactados por el contraste entre la libertad consentida para un país vencido y el propio régimen zarista, lo que determinó la evolución política de muchos oficiales (decembristas). Notas Enlaces externos DECLARATION/ LES Armées des Puissances alliées ont occupé la capitale de la France. Les Souverains alliés/ accueillent le voeu de la Nation française. ... A Paris de l'Imprimerie Royale Avril 1814 (Musée Carnavalet, Histoire de Paris) Restauración francesa Guerras napoleónicas
{ "redpajama_set_name": "RedPajamaWikipedia" }
8,060
Walt Disney Television – jednostka zależna The Walt Disney Company operująca jako segment biznesowy General Entertainment Networks. W latach 1996–2004 funkcjonowała pod nazwą ABC Group, a później jako Disney–ABC Television Group. W jej skład wchodzą studia produkcji telewizyjnej i amerykańskie stacje telewizyjne Disneya. Dywizja zarządza również 50% udziałów A&E Television Networks. Historia Walt Disney Television and Telecommunications (1994 – 1996) Walt Disney Television and Telecommunications zostało utworzone w 1994, aby wyłączyć produkcję telewizyjną i stacje telewizyjne z Walt Disney Studios. Dywizja została rozwiązana w 1996 roku po zakończeniu transakcji z Capital Cities/ABC Inc., a część jej jednostek powróciła do Walt Disney Studios. ABC Group (1996 – 2004) W 1995 roku The Walt Disney Company zakupiło Capital Cities/ABC Inc. Rok później holding został wprowadzony w struktury Disneya jako ABC Group. Wśród aktywów zakupionych znalazły się: ABC Television Network Group, CC/ABC Broadcasting Group (ABC Radio Network, osiem stacji telewizyjnych i 21 radiowych), ABC Cable and International Broadcast Group, CC/ABC Publishing Group i CC/ABC Multimedia Group. Cable and International Broadcast Group zawierało 80% udziałów ESPN, Inc., jak i współudziały w A&E Television Networks (37.5%), Lifetime Television (50%) oraz międzynarodowe aktywa. Wśród nich udziały w Tele-München w Niemczech, Hamster Productions we Francji, Scandinavian Broadcasting System w Luksemburgu. ESPN posiadało również udziały Eurosport w Anglii, TV Sport we Francji i The Japan Sports Channel. Publishing Group zawierała Fairchild Publications i Chilton Publications oraz wiele tytułów gazet. Część udziałów w wydawnictwach i międzynarodowych holdingach Disney zaczął sprzedawać od 1997 roku. Disney–ABC Television Group (2004 – 2019) W 2004 roku The Walt Disney Company poinformowało o restrukturyzacji Disney Media Networks, wskutek której powstało Disney–ABC Television Group z Anne Sweeney jako dyrektorem grupy wspólnie z George'em Bodenheimerem z ESPN. W 2007 roku marka Touchstone Television została przemianowana na ABC Television Studio. W 2009 roku ABC Entertainment i ABC Studios zostały połączone w jedną jednostkę ABC Entertainment Group. W tym samym roku uruchomiono stację Live Well Network. W 2012 roku przejęto kontrolę operacyjną nad kanałem Soapnet, która działała do końca 2013 roku. Na początku 2016 roku zmieniono nazwę stacji ABC Family na Freeform. Walt Disney Television (2019 –) W październiku 2018 roku The Walt Disney Company poinformowało o restrukturyzacji firmy w związku z zakupem aktywów 21st Century Fox. Dywizja zmieniła nazwę na Walt Disney Television. W 2019 roku transakcja została sfinalizowana, wskutek czego 20th Century Fox Television, Fox Television Animation i Fox 21 Television Studios znalazły się w strukturze dywizji i stały się jednostkami Disney Television Studios, razem z ABC Studios i ABC Signature Studios. W sierpniu 2020 roku podczas kolejnej restrukturyzacji obie marki zostały połączone w jedną tworząc ABC Signature. Nastąpił wtedy również rebranding studiów przejętych przez Disneya rok wcześniej. 20th Century Fox Television zmieniono na 20th Television. Reaktywowano też markę Touchstone Television, która zastąpiła Fox 21 Television Studios. 1 grudnia tego samego roku zadecydowano o zamknięciu Touchstone Television, a produkcje tego studia zostały przejęte przez 20th Television Na początku zmieniono nazwę Live Well Network na Localish. Struktura Przypisy Linki zewnętrzne wdtvpress.com/ – oficjalna strona Walt Disney Television Amerykańskie przedsiębiorstwa mediowe Przedsiębiorstwa z siedzibą w Burbanku
{ "redpajama_set_name": "RedPajamaWikipedia" }
4,661
import random def orchard(fruitbox_strategy): raven = 0 fruits = 4 * [10] while sum(fruits) > 0 and raven < 9: n = random.randint(0,5) if n == 5: raven = raven+1 elif n == 4: fruitbox_strategy(fruits) fruitbox_strategy(fruits) elif fruits[n] > 0: fruits[n] = fruits[n]-1 return raven < 9 def decrease_max(fruits): mi, mv = 0,0 for i, v in enumerate(fruits): if v > mv: mi,mv = i,v fruits[mi] = mv-1 def decrease_min(fruits): mi, mv = 0, 11 for i, v in enumerate(fruits): if v < mv and v > 0: mi,mv = i,v if mv < 11: fruits[mi] = mv-1 def decrease_random(fruits): mi = random.randint(0,3) v = fruits[mi] if v > 0: fruits[mi] = v-1 elif sum(fruits) > 0: decrease_random(fruits) ## http://en.wikipedia.org/wiki/Monte_Carlo_method def monte_carlo_simulation(game, count): won = 0 for _ in range(count): if game(): won = won + 1 return (won*100) /count def simulate_orchard_best(count): return monte_carlo_simulation(lambda:orchard(decrease_max), count) def simulate_orchard_worst(count): return monte_carlo_simulation(lambda:orchard(decrease_min), count) def simulate_orchard_random(count): return monte_carlo_simulation(lambda:orchard(decrease_random), count) print('Winning rates of 10 runs of the best strategy with 50 games: \n%s' % ([str(simulate_orchard_best(50)) + '%' for _ in range(10)])) print('Winning rates of 10 runs of the best strategy with 1000 games: \n%s' % ([str(simulate_orchard_best(1000)) + '%' for _ in range(10)])) print('Winning rates of 10 runs of the worst strategy with 50 games: \n%s' % ([str(simulate_orchard_worst(50)) + '%' for _ in range(10)])) print('Winning rates of 10 runs of the worst strategy with 1000 games: \n%s' % [str(simulate_orchard_worst(1000)) + '%' for _ in range(10)]) print('Winning rates of 10 runs of the random strategy with 50 games: \n%s' % ([str(simulate_orchard_random(50)) + '%' for _ in range(10)])) print('Winning rates of 10 runs of the random strategy with 1000 games: \n%s' % [str(simulate_orchard_random(1000)) + '%' for _ in range(10)])
{ "redpajama_set_name": "RedPajamaGithub" }
3,963
\section{Introduction} 4U1323-619 is a dipping low-mass x-ray binary detected by {\it Uhuru} and {\it Ariel V} \citep{forman78,warwick81}. It exhibits X-ray bursts and irregular intensity dips repeating every 2.94~h. Dips discovered in EXOSAT data \citep{parmar89} lasting typically $~30$~per~cent of the orbital cycle, and the lack of X-ray eclipses are indicative that the binary plane is viewed at inclination $i = 60-80\degr$ \citep{frank87}. Such dipping behaviour is explained by periodic obscurations of the central X-ray emitting region by a structure located in the outer regions of the disc \citep{white82}. High interstellar matter column density ($N_H\sim4 \times 10^{22}$~cm$^{-2}$) derived from X-ray spectral models \citep{parmar89} suggests that this source possesses significant extinction of the order of $A_V\sim18$~mag and, thus, cannot be observed at optical wavelengths. \citet{smale95} attempted to find its IR counterpart subject to much lower extinction and reported a candidate which demonstrated some variability of the IR flux (though at a low significance level). Similarly to other sources, the dipping activity in 4U1323-619 attracted attention of researchers as a laboratory for studying the accretion disc corona \citep{balucinska99,boirin05,church05}. These studies and other recent observational efforts produced new data available for this source in archives of X-ray missions and the European Southern Observatory (ESO). We have noticed a significant positional discrepancy between the {\it Einstein} coordinates of 4U1323-619 and its more recent {\it XMM} and {\it Chandra} observations. Having found the IR archival data for 4U1323-619 by the means of the Virtual Observatory, we decided to re-examine the IR candidate discovered by \citet{smale95}. \section{Observations and results} \subsection{X-ray observations} We have analysed {\it Chandra} observations performed on Sep 25, 2003 with a total exposure time about 40~ksec. The observations were aimed at high energy resolution spectroscopy and the telescope was equipped with gratings. Detectors were operating in the so-called Continuous-Clocking (CC) mode, when the information in one spatial direction is lost. Therefore we have determined the source coordinates mainly in one direction (with the nominal {\it Chandra} localisation accuracy $\sim 0.6$~arcsec at 90~per~cent confidence). Orientation of the effective position ``strip'' depends on the orientation of the telescope during the observations. We represent the {\it Chandra} localisation by a wide ellipse in Fig.~\ref{error_boxes}. The centre of the ellipse is at RA(J2000)=201.65397~deg, Dec(J2000)=-62.135403~deg, its positional angle is 156.6~deg, the ellipse is $\sim 0.6$~arcsec wide in one direction and effectively infinitely long in another. In Fig.~\ref{error_boxes}, we have limited the size by arbitrarily adopting a length of 5~arcsec. {\it XMM-Newton} observed the source position two times, on Aug 17, 2001 and Jan 29, 2003, the observations spanning 26 ksec and 51 ksec, respectively. Data of the {\it XMM-Newton} EPIC-MOS cameras were analysed using the standard tasks of the {\it Science Analysis Software (SAS) v9.0.0}. Unfortunately, the source is sufficiently bright to have a non-negligible effect on the {\it XMM}/EPIC-MOS imaging capability because of pile-up. This depresses the brightness of central pixels, degrading the localisation accuracy, in spite of the possibility of cross-calibrating the absolute astrometry of {\it XMM} using optical sources within its field of view. Therefore, we would like to adopt some conservative uncertainty radius of the source position $\sim 3$~arcsec approximately corresponding to 90~per~cent confidence, which without pile-up might have been significantly improved. The source position was determined to be RA(J2000)=201.654870~deg, Dec(J2000)=-62.135985~deg. \subsection{IR observations} The infrared data analysed in this work were obtained on May 18, 2005 between 03:40 and 04:01 UT using the SOFI infrared spectrometer and imaging camera \citep{moorwood98} at the ESO 3.6m NTT telescope under programme ID 075.D-0529(A). All scientific and calibration data were retrieved through the publicly available ESO observational archive\footnote{http://archive.eso.org}. The scientific data contain 21 three second exposures, each taken in Small Field imaging mode with pixel scale 0.144~arcsec~pix$^{-1}$ and seeing $\sim$1.1~arcsec. Due to the specific nature of IR observations, i.e. a rapidly changing background and the techniques used to determine this, the reduction procedure is quite different from optical imaging observations. To get the data ready for scientific analysis we, therefore, used tools and recipes provided by ESO: {\it GASGANO v2.3.0} for data organisation tasks and the SOFI data reduction recipes from the {\it Common Pipeline Library v5.0.0} to correct for bias, flat field and frame jittering. After co-adding 21 reduced co-aligned frames (see Fig.~\ref{error_boxes}), we performed aperture photometry measurements with the {\it SExtractor} software \citep{bertin96} and calibrated instrumental magnitudes using 2MASS $K_s$ photometry of field stars. Our photometric errors therefore include calibration dependency uncertainties of 0.10~mag. The astrometric solution was obtained in the 2MASS reference frame with the {\it SCAMP} software \citep{bertin06} and had 0.2~arcsec calibration uncertainty. Infrared measurements of all sources of interest in the 4U1323-619 field are listed in Tab.~\ref{sources_params}. \begin{figure*} \includegraphics[width=\textwidth]{4u1323_error_boxes.ps} \caption{The co-added $K_s$ image of the 4U1323-619 field constructed from 21 individual three second exposures after reduction and correction for frame jittering. {\it Einstein}, {\it Chandra}, and {\it XMM} positional uncertainties are overplotted. North is up, East is left. Measured sources are designated by capital letters; see the text for details.} \label{error_boxes} \end{figure*} \begin{table} \caption{Positions and $K_s$ magnitudes of the sources from Fig.~\ref{error_boxes}. The astrometric uncertainty is 0.2~arcsec for all objects. Source B is the proposed new IR counterpart for 4U1323-619, marked boldface.} \label{sources_params} \begin{tabular}{lcccc} \hline Source & RA (J2000) & Dec (J2000) & $K_s$ \\ \hline A & 13:26:37.22 & -62 08 07.7 & $18.56 \pm 0.23$ \\ {\bf B} & {\bf 13:26:36.98} & {\bf -62:08:09.0} & $\bmath{18.12 \pm 0.20}$ \\ C & 13:26:36.25 & -62:08:10.1 & $17.87 \pm 0.18$ \\ \hline \end{tabular} \end{table} \subsection{Results} We overplotted positional uncertainties obtained from the {\it XMM} and {\it Chandra} data on the combined IR image (see Fig.~\ref{error_boxes}), together with the {\it Einstein} error circle which, following \citet{smale95}, is centred at the X-ray position of Source D from \citet{parmar89}, as measured by {\it Einstein} HRI: $\alpha_{J2000} = 13^h26^m36.08^s,~\delta_{J2000} = -62\degr08\arcmin10.2\arcsec,~R = 2.5$~arcsec (90~per~cent confidence). In Fig.~\ref{error_boxes} we designated sources of the interest by a capital letters and measured their magnitudes and the astrometric positions which are given in Tab.~\ref{sources_params}. The single object within the {\it Einstein} error circle (source C in this work) was proposed by \citet{smale95} as the IR counterpart of 4U1323-619 and can now be ruled out. This mis-identification was probably caused by the underestimation of the position uncertainty radius for the source, which is quite faint for {\it Einstein}/HRI. We propose the only source visible inside {\it Chandra} and {\it XMM} positional errors intersection down to a limiting magnitude $K_s \sim 19.4$~mag ($3\sigma$ upper limit), source B, as a new counterpart for 4U1323-619. \section{Discussion} We obtained simple estimations of optical luminosity of the accretion disc illuminated by the central isotropic spherical X-ray source with a 0.1-10~keV luminosity $L_X \sim 5.2 \times 10^{36}$~erg~s$^{-1}$ \citep{boirin05} assuming for convenience that its radius is $\sim {\rm few}\times10 R_g$ which means that it is relatively small comparing to the accretion disc size. While it is known that the source has varied in luminosity over a 20 year period \citep{balucinska09} and an interpolation to the date of the IR observations gives $\simeq 2.5$ times smaller luminosity, we leave mentioned $L_X$ value because the bolometric luminosity is expected to be the same factor higher. Given a system period $P=2.94$~h and assuming a compact object to be a neutron star with $M_X = 1.4M_\odot$, one can estimate the mass of the secondary component from the mass-radius relation for main sequence stars and the constraint that the star fills its Roche lobe of size \citep{eggleton83}: \begin{equation} \label{eq_radius} r/a = 0.49 \frac{q^{2/3}}{0.6 q^{2/3} + \ln(1 + q^{1/3})} \end{equation} where $q = M_{opt}/M_X$ and $a$ is the semi-major axis of the binary. This simple estimate gives $M_{opt} \simeq 0.25M_\odot$ and enables us to determine the accretion disc size using \citet{paczynski77}: $r_{out} \simeq 0.51a = 0.62R_\odot$ for $\mu = M_{opt} / (M_{opt} + M_X) = 0.15$. The effective temperature of an accretion disc with a height $z_0 \propto r^n$ illuminated by a point source in its centre is approximated by \citep{shakura73}: \begin{equation} \label{eq_temp} \sigma T_{eff}^4 = \eta \frac{L_X}{4 \pi r^2} \cos \theta = \eta \frac{L_X}{4 \pi r^2} (n - 1) \frac{z_0}{r} \end{equation} where $\eta$ is the absorbed fraction of the radiation impinging on the disc surface assumed to be $\sim 0.5$. Let us consider the situation when the illumination does not change much the structure of a standard $\alpha-$disc. We therefore adopt standard $\alpha$-disc parameters, $n = 9/8, z_0/r_{out} \simeq 0.05$, giving a temperature $T_{eff,~out} = 10500$~K at the outer disc radius $r_{out}$. The observed flux (from a single side of the accretion disc as visible from Earth) at frequency $\nu = 1.4 \times 10^{14}$~Hz for the $K_s$ filter is close to the Rayleigh-Jeans range and can be estimated as follows: \begin{equation} \label{eq_flux} Q_\nu = \frac{64}{49} \pi \cos i \frac{2 \nu^2 kT_{eff,~out} r^2_{out}}{c^2 d^2 f} e^{-\tau_\nu} \end{equation} Here the factor $64/49$ accounts for the $T_{eff}(r) \propto r^{-15/32}$ dependency in the standard accretion disc, and $f \simeq 1.3$ compensates for a non Rayleigh-Jeans law for a given $h\nu/kT_{eff,~out} = 0.58$ ratio. Moreover, the observed flux is obviously decreased by the interstellar extinction with optical depth $\tau_\nu$. Taking a moderate orbital plane inclination angle $i = 70\degr$, a source distance $d = 10$~kpc, and a typical extinction $A_{K_s} \simeq 2.0$~mag ($\tau_\nu \simeq 1.84$) derived from the 3D galactic extinction map in this direction \citep{marshall06}, gives $Q_\nu = 2.1 \times 10^{-29}$~erg~cm$^{-2}$~s$^{-1}$~Hz$^{-1}$ which is an order of magnitude less than the observed flux $(3.1\dots4.5) \times 10^{-28}$~erg~cm$^{-2}$~s$^{-1}$~Hz$^{-1}$ translated from the measured magnitude $K_s=18.12 \pm 0.20$~mag and its uncertainty using zeropoints from \citet{cohen03}. We also estimated the observed flux in another limiting case for an illuminated disc with constant temperature along the $z$ coordinate (isothermal disc). Following equation (A5) from \citet{vrtilek90} with the same set of the system parameters used above, one gets $T_{eff,~out} = 10000$~K. Use of $T_{eff}(r) \propto r^{-3/7}$ in integrating across the disc for isothermal model gives a factor of $14/11$ instead of $64/49$ in Eq.~\ref{eq_flux} and the observed flux $Q_\nu$ becomes a factor of 0.9 smaller than in the first case, considering also slightly different $T_{eff,~out}$. There are several possible explanations for this discrepancy between the observed and predicted fluxes. The existence of a hot ($2 \times 10^6$~K) atmosphere above the outer regions of a disc \citep{jimenez02} can increase the observed flux at a given frequency $\nu = 1.4 \times 10^{14}$~Hz by a factor of $1.3\dots1.7$ if we naively consider the effect of increased $z_0/r_{out} \simeq 0.2$ ratio on Eq.~\ref{eq_temp}--\ref{eq_flux}. In such a hot atmosphere, the scattering of X-ray photons on free electrons with consequent penetration to sub-photosphere layers and thermalization takes place. This increases disc illumination and hence brightens the optical emission. Also we assumed in the beginning the compact nature of the central X-ray source while it is now known that there exists extended accretion disc corona with the radius $\simeq 30 000$~km for adopted $L_X$ \citep{church04,balucinska09}. This changes the illumination geometry of the outer regions of a disc, namely $\cos \theta \simeq z_0/r$ in Eq.~\ref{eq_temp}, and thus increases $T_{eff,~out}$ and $Q_\nu$ by a factor of $(n - 1)^{-1/4} \simeq 1.7$, correspondingly. Placing the object to the distance of 4--5~kpc instead of 10~kpc suggested by \citet{parmar89} on the basis of observed bursts being sub-Eddington would account for all inconsistency of predicted vs. observed fluxes because of significantly reduced extinction in this direction and the fact that $Q_\nu$ scales with distance as $d^{-3/2}$ for a fixed X-ray flux (which follows immediately from Eq.~\ref{eq_temp}--\ref{eq_flux} since $Q_\nu \propto T_{eff,~out}/d^2 \propto L_X^{1/4}/d^2$ while itself $L_X \propto d^2$ for the mentioned condition). We therefore might get $Q_\nu = 2.0 \times 10^{-28}$~erg~cm$^{-2}$~s$^{-1}$~Hz$^{-1}$ in this case. There is also a possibility of existence of a $\sim2-3$~mag fainter object inside the combined {\it XMM} and {\it Chandra} error box which could be the actual counterpart of 4U1323-619, but this cannot be ruled out on the basis of existing archival data and requires dedicated high spatial resolution X-ray observations and deeper phase-resolved follow-up IR observations, probably with adaptive optics in order to reduce field contamination by the source B. Discovery of the 2.94~h variability period in the IR source would allow to finally identify the 4U1323-619 counterpart. \section{Conclusions} On the basis of examination of archival ESO NTT data within the area of overlap of {\it XMM} and {\it Chandra} error regions, we have identified a probable candidate for the IR counterpart of 4U1323-619. Its observed $K_s$ magnitude significantly differs from that predicted by a simple analytical model of an accretion disc illuminated by a hot central spherical corona with a parameter set available in the literature. While putting the object to 4--5~kpc instead of assumed 10~kpc would explain the discrepancy, we encourage high spatial accuracy X-ray observations (e.g. using {\it Chandra}/HRC) and deeper phase-resolved follow-up observations inside the resulting error box listed here. \section*{Acknowledgments} The authors thank Pavel Shtykovskiy for his help in {\it XMM} data analysis and our referee, Mike Church, for his prompt and clear report which helped to improve this letter. This research is based on observations made with ESO 3.6m NTT telescope at the La Silla under programme ID 075.D-0529(A) and has made use of the VizieR catalogue access tool, CDS, Strasbourg, France. IZ and NS were supported by the Russian Foundation for Basic Research, grant 09-02-00032. \bibliographystyle{mn2e}
{ "redpajama_set_name": "RedPajamaArXiv" }
4,030
Guitarist, vocalist, songwriter Michael "Iron Man" Burks died in Atlanta on Sunday, May 6, 2012. He was 54 years old. He was returning from a tour of Europe and collapsed at Hartsfield-Jackson Atlanta International Airport. He was rushed to South Fulton Medical Center where he could not be revived. The preliminary diagnosis for cause of death was a heart attack. More information will follow as it becomes available. Michael "Iron Man" Burks earned his moniker by his hours-long, intensely physical performances, fearsome guitar attack, and tough, smoky vocals. He also earned it by the thousands of miles he personally logged behind the wheel of his touring van. Burks was a true modern blues hero whose music was driven by an intense, blue collar work ethic that had won him well-deserved national and international recognition. His instantly identifiable guitar sound and his live charisma earned him four Blues Music Award nominations. He won the 2004 Living Blues magazine Critics' Award for Best Guitarist. Burks received a nomination for the 2012 Blues Music Award for Best Guitarist. Born in Milwaukee in 1957, Burks grew up immersed in the blues, and learned to play guitar at an early age. His family moved to Camden, Arkansas in the early 1970s. There, Burks and his siblings helped their father build the Bradley Ferry Country Club — a 300-seat juke joint. By this time Michael was fronting his own band as well as backing several of the blues and R&B greats that passed through town. Burks left music to raise a family and returned to performing blues in the 1990s. After self-releasing his first CD in 1997, Burks signed with Chicago's Alligator Records in 2001 and released three critically acclaimed albums. GuitarOne named his debut album, Make It Rain, one of the Top 200 greatest guitar recordings of all time. He has toured the world, headlining blues festivals, concert halls and clubs. His status as an Arkansas musical hero was confirmed by his receipt of the prestigious Sonny Payne Award for Blues Excellence in 2006, presented by the Delta Cultural Center, and by his multiple headlining appearances at The Arkansas Blues & Heritage Festival. Burks had just finished recording his fourth Alligator CD, which is due for release at the end of July 2012. Ook de vaste rubrieken komen langs, zoals De BlaBlaBlog van Theo Verriet; De Platenkeuze van Rob Ricard; Wat gaan we eten en de Donderslag Muziekagenda. Om 18:00 is Rastabarry er weer met zijn reggaeklanken. Rob de Greeuw besteedt in de Indy501 aandacht aan de 10 meest bijzondere voetbalstadions ter wereld. Ook kun je weer stemmen op een Live or Life artiest. Geef jij Alpha Blondy of Richard Buckner zendtijd? Laat het weten via studio@radio501.nl. Verder komt Maartje Brandt van Park Schouwburg nog langs met informatie over een aantal mooie theatertips. Klokslag 22.00 is het weer tijd voor jouw wekelijkse portie hiphop in Geluid Uit De Bunker met GW Style.
{ "redpajama_set_name": "RedPajamaC4" }
92
Abrogation (von lateinisch abrogatio "Aufhebung", "Widerruf") steht für: Abrogation (Islam), die Aufhebung einer normativen Bestimmung des Korans oder der Sunna durch eine andere, zeitlich nachfolgende Bestimmung aus Koran oder Sunna Abrogation (Kanonisches Recht), die vollständige Aufhebung einer Rechtsnorm im kanonischen Kirchenrecht Abrogation (Band), eine deutsche Melodic-Death-Metal-Band aus Magdeburg Siehe auch: Derogation Obrogation
{ "redpajama_set_name": "RedPajamaWikipedia" }
850
Мемориал энергетикам – героям Великой Отечественной войны находится в Туле. Открыт 19 сентября 2020 г. Расположен на Юге Тулы, в районе Ивановских дач, пос. Менделеевский, ул. Льва Толстого. Занимает 1 гектар. Он посвящен не только энергетикам-фронтовикам, но и тем, кто работал в тылу. История создания Памятник построен по инициативе главы «Россетей» Павла Ливинского и губернатора Тульской области Алексея Дюмина. Оплачивало строительство ПАО «Россети». Проект памятника был выбран сотрудниками предприятия на онлайн-голосовании, в котором участвовало 16 467 человек. Строительство началось в 2019 году как подготовка к празднованию 75-летия Победы. Внешний вид монумента Состоит из 5 площадок - по одной на каждый год Великой Отечественной войны - на каждой из которых расположена стела. На стелах высечены имена 72 героев-энергетиков. Среди них имена энергетиков «Россети Урал», награжденных орденами Отечественной войны первой и второй степеней, кавалеров ордена Славы и ордена Красной Звезды. Это Анатолий Нехонов, Петр Захаров и Хайкул Крамник. В центре — обелиск в виде вышки высоковольтной линии электропередач, высота которой — 1418 см. Столько дней шла война.. Обелиск выполнен из марочной латуни на стальном каркасе. К нему ведет аллея. Обелиск увенчан изображением ордена Победы — высшей награды Великой Отечественной войны. В комплекс также входит Вечный огонь, в Тулу пламя привезли из Москвы. Его зажгли от Вечного огня у Могилы Неизвестного Солдата. Примечания Памятники героям Памятники Тулы Памятники труженикам тыла Энергетика Тульской области Энергетики России
{ "redpajama_set_name": "RedPajamaWikipedia" }
4,337
package org.onehippo.forge.exdocpicker.impl.folder; import java.io.Serializable; import javax.jcr.RepositoryException; import org.apache.commons.lang.StringUtils; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.ResourceReference; import org.hippoecm.addon.workflow.StdWorkflow; import org.hippoecm.addon.workflow.WorkflowDescriptorModel; import org.hippoecm.frontend.dialog.AbstractDialog; import org.hippoecm.frontend.dialog.IDialogFactory; import org.hippoecm.frontend.dialog.IDialogService; import org.hippoecm.frontend.model.JcrNodeModel; import org.hippoecm.frontend.plugin.IPluginContext; import org.hippoecm.frontend.plugin.config.IPluginConfig; import org.hippoecm.frontend.service.render.RenderPlugin; import org.hippoecm.repository.api.WorkflowDescriptor; import org.hippoecm.repository.standardworkflow.FolderWorkflow; import org.onehippo.forge.exdocpicker.api.ExternalDocumentCollection; import org.onehippo.forge.exdocpicker.api.ExternalDocumentServiceContext; import org.onehippo.forge.exdocpicker.api.ExternalDocumentServiceFacade; import org.onehippo.forge.exdocpicker.api.PluginConstants; import org.onehippo.forge.exdocpicker.impl.SimpleExternalDocumentServiceContext; import org.onehippo.forge.exdocpicker.impl.field.TextSearchExternalDocumentFieldBrowserDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExternalDocumentFolderActionWorkflowMenuItemPlugin extends RenderPlugin<WorkflowDescriptor> { private static final long serialVersionUID = 1L; private static Logger log = LoggerFactory.getLogger(ExternalDocumentFolderActionWorkflowMenuItemPlugin.class); private WorkflowDescriptorModel folderWorkflowModel; private JcrNodeModel folderNodeModel; private ExternalDocumentServiceFacade<Serializable> exdocService; private ExternalDocumentCollection<Serializable> curDocCollection; private ExternalDocumentServiceContext extDocServiceContext; public ExternalDocumentFolderActionWorkflowMenuItemPlugin(IPluginContext context, IPluginConfig config) { super(context, config); folderWorkflowModel = (WorkflowDescriptorModel) getModel(); try { folderNodeModel = new JcrNodeModel(folderWorkflowModel.getNode()); } catch (RepositoryException e) { throw new IllegalStateException("Folder node is not resolvable.", e); } setExternalDocumentServiceFacade((ExternalDocumentServiceFacade<Serializable>) createExternalDocumentService()); setExternalDocumentServiceContext( new SimpleExternalDocumentServiceContext(this, config, context, folderNodeModel)); add(new StdWorkflow<FolderWorkflow>("menuItem", getMenuItemLabelModel(), folderWorkflowModel) { private static final long serialVersionUID = 1L; @Override protected ResourceReference getIcon() { return getMenuItemIconResourceReference(); } @Override protected String execute(FolderWorkflow workflow) throws Exception { final IDialogService dialogService = getDialogService(); if (!dialogService.isShowingDialog()) { final IDialogFactory dialogFactory = createDialogFactory(); dialogService.show(dialogFactory.createDialog()); } return null; } }); } protected IModel<String> getMenuItemLabelModel() { String menuItemLabel = getPluginConfig().getString("exdocfield.menu.label", PluginConstants.DEFAULT_FIELD_CAPTION); String menuItemLabelKey = menuItemLabel; return new StringResourceModel(menuItemLabelKey, this, null).setDefaultValue(menuItemLabel); } protected ResourceReference getMenuItemIconResourceReference() { String menuItemIcon = getPluginConfig().getString("exdocfield.menu.icon"); if (StringUtils.isBlank(menuItemIcon)) { return null; } else { return new PackageResourceReference(ExternalDocumentFolderActionWorkflowMenuItemPlugin.class, menuItemIcon); } } protected IModel<String> getDialogTitleModel() { String dialogTitle = getPluginConfig().getString("exdocfield.dialog.title"); if (StringUtils.isBlank(dialogTitle)) { return getMenuItemLabelModel(); } else { String dialogTitleKey = dialogTitle; return new StringResourceModel(dialogTitleKey, this, null).setDefaultValue(dialogTitle); } } /** * Creates a dialog factory to create a picker dialog. * @return a dialog factory to create a picker dialog */ protected IDialogFactory createDialogFactory() { return new IDialogFactory() { private static final long serialVersionUID = 1L; public AbstractDialog<ExternalDocumentCollection<Serializable>> createDialog() { return createDialogInstance(); } }; } /** * Creates a picker dialog with which user can select external documents. * @return a picker dialog with which user can select external documents */ protected AbstractDialog<ExternalDocumentCollection<Serializable>> createDialogInstance() { return new TextSearchExternalDocumentFieldBrowserDialog(getDialogTitleModel(), getExternalDocumentServiceContext(), getExternalDocumentServiceFacade(), new Model<ExternalDocumentCollection<Serializable>>(getCurrentExternalDocumentCollection())); } /** * Creates a new {@link ExternalDocumentServiceFacade} instance. * By default, this method reads the plugin configuration by the name, {@link PluginConstants#PARAM_EXTERNAL_DOCUMENT_SERVICE_FACADE}, * and instantiated an object by the FQCN configuration parameter. * @return a new {@link ExternalDocumentServiceFacade} instance */ protected ExternalDocumentServiceFacade<? extends Serializable> createExternalDocumentService() { ExternalDocumentServiceFacade<? extends Serializable> service = null; String serviceFacadeClassName = null; try { serviceFacadeClassName = getPluginConfig() .getString(PluginConstants.PARAM_EXTERNAL_DOCUMENT_SERVICE_FACADE); Class<? extends ExternalDocumentServiceFacade> serviceClass = (Class<? extends ExternalDocumentServiceFacade>) Class .forName(serviceFacadeClassName); service = serviceClass.newInstance(); } catch (Exception e) { log.error("Failed to create external document service facade from class name, '{}'.", serviceFacadeClassName, e); } return service; } /** * Returns the {@link ExternalDocumentServiceFacade} instance used by this plugin instance. * @return the {@link ExternalDocumentServiceFacade} instance used by this plugin instance */ protected ExternalDocumentServiceFacade<Serializable> getExternalDocumentServiceFacade() { return exdocService; } /** * Sets the {@link ExternalDocumentServiceFacade} instance used by this plugin instance. * @param exdocService the {@link ExternalDocumentServiceFacade} instance used by this plugin instance */ protected void setExternalDocumentServiceFacade(ExternalDocumentServiceFacade<Serializable> exdocService) { this.exdocService = exdocService; } /** * Returns the collection of the currently-selected external documents in the document. * @return the collection of the currently-selected external documents in the document */ protected ExternalDocumentCollection<Serializable> getCurrentExternalDocumentCollection() { if (curDocCollection == null) { curDocCollection = getExternalDocumentServiceFacade() .getFieldExternalDocuments(getExternalDocumentServiceContext()); } return curDocCollection; } /** * Sets the collection of the currently-selected external documents in the document. * @param curDocCollection the collection of the currently-selected external documents in the document */ protected void setCurrentExternalDocumentCollection(ExternalDocumentCollection<Serializable> curDocCollection) { this.curDocCollection = curDocCollection; } /** * Returns the {@link ExternalDocumentServiceContext} instance. * @return the {@link ExternalDocumentServiceContext} instance */ protected ExternalDocumentServiceContext getExternalDocumentServiceContext() { return extDocServiceContext; } /** * Sets the {@link ExternalDocumentServiceContext} instance. * @param extDocServiceContext the {@link ExternalDocumentServiceContext} instance */ protected void setExternalDocumentServiceContext(ExternalDocumentServiceContext extDocServiceContext) { this.extDocServiceContext = extDocServiceContext; } }
{ "redpajama_set_name": "RedPajamaGithub" }
2,273
Han Kyoo-hee (; March 29, 1944 – December 18, 2014) is a South Korean voice actor. He joined the Munhwa Broadcasting Corporation's voice acting division in 1964. Roles Broadcasting TV 24 (TV series) (Season 2, replacing John Terry, Korea TV Edition, MBC) Akazukin Chacha (Korea TV Edition, MBC) Alps Sound (MBC) Bakusou Kyoudai Let's & Go!! WGP (Korea TV Edition, SBS) Buffy the Vampire Slayer (replacing Anthony Head, Korea TV Edition, MBC) Captain Tailer (Korea TV Edition, SBS) CSI: Crime Scene Investigation (replacing Marc Vann, Korea TV Edition, MBC) Dragon Ball (Korea TV Edition, SBS) Escaflowne (Korea TV Edition, SBS) Frog Wangnooni (SBS) Great Gunder (Korea TV Edition, SBS) Hekcle Jeckle (Korea TV Edition, MBC) K-Cops (Korea TV Edition, MBC) Pigeon Chorus (MBC) Super SWAT (MBC) See also Munhwa Broadcasting Corporation MBC Voice Acting Division External links MBC Voice Acting Division Han Kyoo Hee Blog (in Korean) South Korean male voice actors 1944 births 2014 deaths
{ "redpajama_set_name": "RedPajamaWikipedia" }
2,698
\section*{Acknowledgements} This research is partly supported by the Agence Nationale de la Recherche through the Misgepop project. Both last authors are affiliated with CREST, Paris. Parts of this paper were written by the last author in the Isaac Newton Institute, Cambridge, whose peaceful and stimulating environment was deeply appreciated. Helpful comments from the editorial board of {\em Biometrika} and from O.~Capp\'e are gratefully acknowledged.
{ "redpajama_set_name": "RedPajamaArXiv" }
3,038
The BBQ sauce is a sauce used as a seasoning, commonly applied on grilled meat in barbecue mode, however it is great to accompany the seconds and contours. It was probably invented between the 19th and 20th centuries in the USA by European settlers. Tomatoes, spirit vinegar, sugar, modified corn starch, molasses, sea salt, aromas, spices, colors: caramel, onion powder, garlic powder, mustard flour (contains milk, soy, mustard).
{ "redpajama_set_name": "RedPajamaC4" }
9,617
\section{Introduction} Let $\skp{}{}$ be an inner product on the space of polynomials $\mathbb{R}[x]$. By the Gram-Schmidt process we may obtain a basis $E_0,E_1,\dots$ of $\mathbb{R}[x]$ orthogonal with respect to $\skp{}{}$. This basis, which we call a Gram-Schmidt basis, has the defining property that $E_n$ is of degree $n$ and is orthogonal to the space $V_{n-1}\subset \mathbb{R}[x]$ of polynomials of degree at most $n-1$. In the most relevant cases the inner product has the form \[ \skp{f}{g} = \int_I f(x)g(x) w(x) dx, \] where $I\subset \mathbb{R}$ is a (possibly unbounded) interval, and $w(x)$ is an integrable almost everywhere positive weight function on $I$ for which all moments exist. The classical orthogonal polynomials provide examples of Gram-Schmidt bases, which are in addition solutions of a polynomial differential equation $Lf=\lambda f$. Concretely, for a bounded interval $I=(-1,1)$ and $w(x)=(1-x)^\alpha(1+x)^\beta$ one obtains the Jacobi polynomials, with $Lf=(1-x^2)f''+(\beta-\alpha-(\alpha+\beta+2)x)f'$. For a semi-bounded interval $I=(0,\infty)$ and $w(x)=x^\alpha e^{-x}$ one obtains the (associated) Laguerre polynomials, with $Lf=xf''+(\alpha+1-x)f'$. For $I=(-\infty, \infty)$, $w(x)=e^{-x^2/2}$ one obtains the Hermite polynomials, with $Lf=f''-2xf'$. In this paper we consider the generalization of the Gram-Schmidt process to $k\geq 1$ inner products \begin{equation}\label{equ:innerprodj} \skp{f}{g}_j = \int_{I_j} f(x)g(x) w_j(x) dx, \end{equation} where $j=1,\dots, k$ and $I_1,\dots ,I_k \subset \mathbb{R}$ are disjoint intervals and the $w_j$ are integrable, almost everywhere positive weight functions, for which all moments exist. In this situation it is not immediately obvious how to generalize the defining property $E_n\in V_{n-1}^\perp$ of the Gram-Schmidt basis. It turns out that a good generalization is what we call a \emph{jointly orthogonal system}. To define it let us introduce the following notation. We denote by $V_n\subset \mathbb{R}[x]$ the space of polynomials of degree at most $n$. Let $V^k=S^k\mathbb{R}[x]$ be the space of symmetric polynomials in $k$ variables. Let $V_n^k=S^kV_n\subset V^k$ be the subspace of polynomials for which the degreee in each variable does not exceed $n$. For a polynomial $p\in \mathbb{R}[x]$ we let \begin{equation}\label{equ:prtimes} p^{(r)} := \underbrace{p\otimes \cdots \otimes p}_{r \times} \in V^r. \end{equation} In particular we set $p^{(0)}:=1\in V^0\cong\mathbb{R}$. We call symmetric polynomials of the form $p^{(r)}$ \emph{rank one tensors}. Assuming that the intervals $I_1,\dots, I_k$ are ordered from left to right we define an inner product $\skp{}{}$ on $V^k$ as follows: \begin{multline}\label{equ:kipro} \skp{f}{g} = \idotsint_{I_1\times \cdots \times I_k} f(x_1,\dots, x_k)g(x_1,\dots, x_k) \\ w_1(x_1)\cdots w_k(x_k) \prod_{1\leq i<i'\leq k}(x_{i'}-x_i) dx_1\cdots dx_k. \end{multline} Note in particular that the Vandermonde factor is always positive by the assumption on disjointness and orderedness on the intervals. Finally, we define $k$ inner products $\skp{}{}_{(1)},\dots,\skp{}{}_{(k)}$ on $V^{k-1}$ such that \begin{multline}\label{equ:k1ipro} \skp{f}{g}_{(j)} = \idotsint_{I_1\times \cdots \hat I_j \cdots \times I_k} f(x_1,\dots, \hat x_j, \dots, x_k)g(x_1,\dots,\hat x_j, \dots, x_k) \\ w_1(x_1)\cdots \hat w_j(x_j) \cdots w_k(x_k) \prod_{\substack{1\leq i<i'\leq k\\ i,i'\neq j }}(x_{i'}-x_i) dx_1\cdots \widehat{dx_j} \cdots dx_k. \end{multline} where a hat denotes omission. \begin{defi}\label{def:jointorthog} A jointly orthogonal system of degree $n$ with respect to inner products $\skp{}{}_1,\dots, \skp{}{}_k$ ($k\geq 2$) as above is a family of polynomials $\{E_\alpha\}_\alpha$ of degree $n$ in one variable such that the family $\{E_\alpha^{(k-1)}\}_\alpha$ is a basis of $V_n^{k-1}$ orthogonal with respect to each of the inner products $\skp{}{}_{(1)},\dots,\skp{}{}_{(k)}$. \end{defi} Note that for $k=2$ a jointly orthogonal system of degree $n$ is just a basis of $V_n$ that is simultaneously orthogonal with respect to the two inner products $\skp{}{}_1,\skp{}{}_2$. Our main result is the following. \begin{thm}\label{thm:main} Let $\skp{}{}_1,\dots ,\skp{}{}_k$ be inner products on $\mathbb{R}[x]$ of the form \eqref{equ:innerprodj} for disjoint intervals $I_1,\dots, I_k$. Then for every $n=0,1,\dots$ a jointly orthogonal system of degree $n$ with respect to these inner products exists, and it is unique up to rescaling and permutation of its members. \end{thm} The following result relates the notion of joint orthogonality to the Gram-Schmidt property. \begin{prop}\label{prop:firstsecondid} A family of polynomials $\{E_\alpha\}_\alpha$ is a jointly orthogonal system of degree $n$ with respect to inner products $\skp{}{}_1,\dots, \skp{}{}_k$ as above if and only if the family of polynomials $\{E_\alpha^{(k)}\}_\alpha$ forms an orthogonal basis of $(V_{n-1}^k)^\perp\subset V_n^k$, where the orthogonal complement is taken with respect to the inner product $\skp{}{}$ as in \eqref{equ:kipro}. \end{prop} In the literature, jointly orthogonal systems arise as solutions to many well studied polynomial differential equations. For example, for $k=2$ it is well known that the Lam\' e polynomials form jointly orthogonal systems. In this case the two intervals $I_1,I_2$ are bounded. The Ince polynomials form jointly orthogonal systems, with one of the intervals being unbounded. The polynomials arising in the doubly unbounded case have no special name to our knowledge but were studied by Turbiner, see also section \ref{sec:sexticpotential}. For $k>2$ the known examples are provided by the Heine-Stieltjes polynomials or certain higher Heine-Stieltjes polynomials \cite{shapiro}. \begin{rem} Note that the uniqueness part of Theorem \ref{thm:main} allows to define each of these classical families of polynomials purely in terms of their orthogonality properties, without reference to any differential equation. \end{rem} \subsection*{Structure of the paper} In sections \ref{sec:examples} and \ref{sec:examples2} we will discuss several classical examples of jointly orthogonal systems given by solutions of polynomial differential equations. In section \ref{sec:jointorthog} we discuss some immediate properties of jointly orthogonal systems. In particular, we will prove the forward implication of Proposition \ref{prop:firstsecondid}. In section \ref{sec:multieig} we show that the problem of finding a jointly orthogonal system can be restated as a multiparameter eigenvalue problem. Its solutions exist and are unique, hence Theorem \ref{thm:main} follows. Finally section \ref{sec:gramschmidt} discusses our version of the Gram-Schmidt algorithm, which we call the rank 1 Gram-Schmidt algorithm. A uniqueness result therein will show the reverse implication of Proposition \ref{prop:firstsecondid}. For most of the proofs it will be convenient to work in a slightly more general setting than discussed in the introduction. Essentially, we allow general inner products, replacing the condition of disjointness of the intervals by a more abstract definiteness condition. The relevant definitions can be found in section \ref{sec:jointorthogdef}. \subsection*{Acknowledgements} We are grateful to Alexander Veselov for useful comments and instructive discussions on the subject of this paper. \section{Examples: Jointly orthogonal polynomials for two inner products}\label{sec:examples} Let us consider the case of two inner products, i.e., $k=2$. A jointly orthogonal system of degree $n$ is just a basis of $V_n$ simultaneously othogonal with respect to both inner products. \subsection{Heun and Lam\'e polynomials} Let $Q(x)=(x-e_1)(x-e_2)(x-e_3)$, be a monic polynomial of degree $3$ with distinct real roots $e_1<e_2<e_3$ and $P(x)$ a polynomial of degree $2$ such that $a_i:=P(e_i)/Q'(e_i)>0$. Set \[ w_1(x)=w_2(x)=w(x)=\prod_{i=1}^3|x-e_i|^{a_i-1},\quad I_1=(e_1,e_2),\quad I_2=(e_2,e_3). \] The Heun differential operator, cf.~\cite{Erdelyetal}, \begin{align*} L_n&=Q(x)\frac{d^2}{dx^2}+P(x)\frac{d}{dx}-n(n-1+a_1+a_2+a_3)x \\ &=Q(x)\left(\frac{d^2}{dx^2}+\sum_{i=1}^3\frac{a_i}{x-e_i}\frac{d}{dx}\right)-n(n-1+a_1+a_2+a_3)x \end{align*} preserves $V_n$ and is self-adjoint with respect to both inner products. The latter property follows by integration by parts by using the relation \begin{equation}\label{e-logder} \frac{w'(x)}{w(x)}=\frac{P(x)-Q'(x)}{Q(x)}. \end{equation} Indeed this identity implies that \[ \int_a^bL_nf(x)g(x)\,dx=\int_a^bf(x)L_ng(x)dx+(f'g-fg')Qw|_{a}^{b} \] and since \begin{equation}\label{e-boundary} \lim_{x\to x_0} Q(x)w(x)=0, \text{ for all endpoints $x_0$ of the intervals $I_1,I_2$,} \end{equation} $L_n$ is selfadjoint for both inner products. Thus the jointly orthogonal polynomials $E_{\alpha,n}$, $\alpha=1,\dots,n+1$, of degree $n$ are the polynomial eigenvectors of the Heun differential operators. Lam\'e polynomials arise in the special cases where $a_i\in\{1/2,3/2\}$. By definition they are solutions of the Lam\'e differential equation \[ Q(x)y''(x)+\frac12 Q'(x)y-\frac14(\nu(\nu+1)x+\lambda)y=0, \] with $Q$ as above, of the form \begin{equation}\label{e-Lamepol} y(x)=\prod_{i=1}^3(x-e_i)^{\epsilon_i/2}p(x) \end{equation} with $p(x)$ a polynomial and $\epsilon_i\in\{0,1\}$. If $\epsilon_1=\epsilon_2=\epsilon_3=0$ the Lam\'e equation is the eigenvalue problem for the Heun operator $L_n$ with parameters $n=\nu/2,a_i=\frac12$, $i=1,2,3$. The other cases can be related to this case: let $\epsilon\in\{0,1\}^3$ and $L_n^{(\epsilon)}$ denote the Heun operator with parameters $n$, $a_i=\frac12+\epsilon_i$. Then we have the identity \[ \prod_{i=1}^3(x-e_i)^{-\epsilon_i/2}\circ L_{n}^{(000)}\circ\prod_{i=1}^3(x-e_i)^{\epsilon_i/2}=L_{n-(\epsilon_1+\epsilon_2+\epsilon_3)/2}^{(\epsilon)}+c, \] for some multiple of the identity $c$. Solutions of the Lam\'e equation of the form \eqref{e-Lamepol} with $1+\epsilon_1+\epsilon_2+\epsilon_3=k$ are called Lam\'e polynomials of degree $\nu$ of the $k$-th species. The parameter $\nu$ dictates the behaviour at infinity of solutions and so the degree $n$ of $p$: \[ \nu = 2n+\epsilon_1+\epsilon_2+\epsilon_3. \] Let $E_{\alpha,n}^{(\epsilon)}, \alpha=1,\dots,n+1$ be the jointly orthogonal polynomials of degree $n$ with parameters $a_i=\epsilon_i+1/2$. Then for even $\nu=2m\geq0$, there are Lam\'e polynomials of the first species $ E_{\alpha,m}^{(000)}, \alpha=1,\dots,m+1, $ and of the third species \[ (x-e_1)^{\frac12}(x-e_2)^{\frac12} E_{\alpha,m-1}^{(110)},\; (x-e_1)^{\frac12}(x-e_3)^{\frac12} E_{\alpha,m-1}^{(101)},\; (x-e_2)^{\frac12}(x-e_3)^{\frac12} E_{\alpha,m-1}^{(011)}, \] $\alpha=1,\dots,m$. For odd $\nu=2m+1\geq0$, there are Lam\'e polynomials of the fourth species \[ (x-e_1)^{\frac12}(x-e_2)^{\frac12}(x-e_3)^{\frac12}E_{\alpha,m-1}^{(111)}, \] and of the second species \[ (x-e_1)^{\frac12}E_{\alpha,m}^{(100)}, \;(x-e_1)^{\frac12}E_{\alpha,m}^{(010)}, \;(x-e_1)^{\frac12}E_{\alpha,m}^{(001)}. \] In both cases there is a total of $2\nu+1$ Lam\'e polynomials of degree $\nu$. The Heun differential equation $L_ny=\lambda y$ is a Fuchsian differential equation with four singular points $(e_1,e_2,e_3,\infty)$ on the Riemann spheres. The next examples are confluent versions where singular points merge at infinity. \subsection{Whittaker--Hill equation and Ince polynomials} Let $\alpha<0, a>0$, \[ w(x)=e^{2\alpha x}|1-x|^{a_1-1}|1+x|^{a_2-1}, \quad I_1=(-1,1),\quad I_2=(1,\infty) \] For $a_i=\frac12,\frac32$, the jointly orthogonal polynomials are related to solutions of the {\em Whittaker--Hill equation}, see \cite{Whittaker, Ince, Arscott,NIST, HemeryVeselov}, \[ -\psi''(\theta)-(A\cos(2\theta)+B\cos(4\theta))\psi(\theta)=\lambda\psi(\theta) \] in trigonometric polynomials. Let us explain the relation. The differential operator \[ L_n=(x^2-1)\frac{d^2}{dx^2}+(a_1(x+1)+a_2(x-1)+2\alpha(x^2-1))\frac d{dx}-2n\alpha x \] clearly preserves the space of polynomials of degree $\leq n$. It is self-adjoint for both inner products as its coefficients $Q(x)=x^2-1$ and $P(x)=a_1(x+1)+a_2(x-1)+2\alpha(x^2-1)$ obey the relations \eqref{e-logder}, \eqref{e-boundary}. The change of variables $x=\cos(2\theta)$ transforms $L_n$ to the differential operator \[ \tilde L_n=-\frac14\frac {d^2}{d\theta^2}+ \left(-\alpha\sin(2\theta)+\frac{a_1+a_2-1}2\cot(2\theta)+\frac{a_1-a_2}{2\sin(2\theta)}\right) \frac d{d\theta}-2n\alpha\cos(2\theta). \] Let $a_1,a_2\in\{\frac12,\frac32\}$ and set $\epsilon_i=a_i-\frac12\in\{0,1\}$. Let \[ \varphi(\theta)=\sin(\theta)^{\epsilon_1}\cos(\theta)^{\epsilon_2}e^{\alpha\cos(2\theta)}. \] Then $H_\nu=\varphi\circ 4\tilde L_n\circ \varphi^{-1}=H_\nu+c$ is the Whittaker--Hill differential operator \[ H_\nu=-\frac {d^2}{d\theta^2}-4\alpha\nu\cos(2\theta)-2\alpha^2\cos(4\theta), \] with parameter $\nu=2n+1+\epsilon_1+\epsilon_2$, up to an additive constant $c=2\alpha^2+4(\epsilon_2-\epsilon_1)\alpha-(\epsilon_1+\epsilon_2)^2$. It follows that the jointly orthogonal polynomials $E^{(\epsilon_1\epsilon_2)}_{1,n},\dots,E^{(\epsilon_1\epsilon_2)}_{n+1,n}$ for $a_i=\epsilon_i+\frac12\in\{\frac12,\frac32\}$ yield eigenfunctions of $H_\nu$ of the form \begin{equation}\label{e-Ince} \psi_\alpha^{(\epsilon_1\epsilon_2)}(\theta)= \sin(\theta)^{\epsilon_1} \cos(\theta)^{\epsilon_2} E_{\alpha,n}^{(\epsilon_1\epsilon_2)} (\cos(2\theta))e^{\alpha\cos(2\theta)}, \quad \nu=2n+1+\epsilon_1+\epsilon_2. \end{equation} Altogether we get for each positive integer $\nu$ a basis of the space of eigenfunctions of $H_\nu$ of the form \[ p(\theta)e^{\alpha\cos(2\theta)}, \qquad p\in \mathit{TP}_{\nu-1}=\mathbb R[\cos(\theta),\sin(\theta)]_{\leq \nu-1}, \] the space of trigonometric polynomials of degree $\leq \nu-1$. If $\nu$ is even, the trigonometric polynomials are \[ \sin(\theta)E^{(10)}_{\alpha,\nu/2-1}(\cos(2\theta)),\; \cos(\theta)E^{(01)}_{\alpha,\nu/2-1}(\cos(2\theta)),\quad \alpha=1,\dots,\nu/2, \] and they form a basis of the subspace of $\mathit{TP}_{\nu-1}$ of $\pi$-antiperiodic polynomials, i.e., obeying $p(\theta+\pi)=-p(\theta)$. If $\nu$ is odd they are \begin{align*} E^{(00)}_{\alpha,(\nu-1)/2}(\cos(2\theta)),\quad \alpha=1,\dots,(\nu+1)/2, \\ \sin(\theta)\cos(\theta)E^{(11)}_{\alpha,(\nu-3)/2}(\cos(2\theta)),\quad \alpha=1,\dots,(\nu-1)/2, \end{align*} and they are a basis of the subspace of $\pi$-periodic polynomials in $\mathit{TP}_{\nu+1}$. The trigonometric polynomials arising this way are called Ince polynomials. They are a solutions of the differential equation \[ p''+4\alpha\sin(2\theta)p'+(4(\nu-1)\alpha\cos(2\theta)+\lambda)p=0 \] for different values of the spectral parameter $\lambda$. \subsection{Eigenfunctions of Schr\"odinger operators with sextic potential}\label{sec:sexticpotential} Let $\ell>-1$, \[ w(x)=|x|^{\ell+1/2} e^{-x^2/2}dx,\quad I_1=(-\infty,0),\quad I_2=(0,\infty). \] The differential operator \[ L=-2x\frac{d^2}{dx^2}+(2x^2-2\ell-3)\frac d{dx}-2nx \] preserves polynomials of degree $\leq n$ and is self-adjoint for both inner products, since its coefficients $Q(x)=-2x$ and $P(x)=2x^2-2\ell-3$ obey \eqref{e-logder} and \eqref{e-boundary}. After the change of variables $x=r^2$, $L$ becomes \[ \tilde L=-\frac12 \frac {d^2}{dr^2}+\left(r^3-\frac{\ell+1}{r}\right)\frac d{dr}-2n r^2 \] This operator is related by conjugation by \[ \varphi(r)=r^{\ell+1}e^{-r^4/4} \] to the radial Schr\"odinger operator with sextic potential \[ H=-\varphi\circ 2\tilde L\circ\varphi^{-1} =-\frac{d^2}{dr^2}+r^6-\nu r^2+\frac{\ell(\ell+1)}{r^2}, \] with $\nu=4n+5+2\ell$, introduced by Turbiner \cite{Turbiner} in his theory of quasi-exactly solvable systems and is a special case of the family of monodromy free Schr\"odinger operators with sextic growth \cite{GibbonsVeselov}. It follows that the simultaneous orthogonal polynomials $E_1,\dots,E_{n+1}$ give a basis \[ \psi_\alpha(r)=r^{\ell+1}e^{-r^4/4}E_\alpha(r^2) \] of eigenfunctions of $H$ in \[ W_n=\{r^{\ell+1}e^{-r^4/4}p(r^2),\, p\in V_n\}. \] The simultaneous orthogonality translates to the condition that these eigenfunctions are characterized as being jointly orthogonal for the two inner products on $W_n$: \[ \int_0^\infty f(r)g(r)dr,\qquad e^{-i\pi(\ell+1)} \int_0^\infty f\left(e^{i\pi/2}r\right) g\left(e^{i\pi/2}r\right)dr. \] \section{Examples for higher $k$: Heine-Stieltjes polynomials}\label{sec:examples2} Consider the differential equation \begin{equation}\label{equ:HS} \prod_{i=0}^k(x-e_i) y'' + \sum_{j=0}^k m_j \prod_{\substack{i=0 \\ i\neq j}}^k(x-e_i)y' + V(x) y = 0. \end{equation} Here the unknowns are $y$ and the degree $k-1$ polynomial $V(x)$ (the van Vleck polynomial), which generalizes the eigenvalue $\lambda$ in the previous examples. The Heine-Stieltjes polynomials are the polynomial solutions $y$ of the above equation. For each van Vleck polynomial $V$ there is at most one polynomial solution $y$. Furthermore note that for Heine-Stieltjes polynomials of degree $n$ the leading coefficient of the van Vleck polynomial must necessarily be $-n(n-1+\sum_j m_j)$ We assume in the following that the roots $e_i$ are real and ordered, $e_0<e_1<\cdots <e_k$, and that $m_0,\dots, m_k>0$. The differential operator \[ L= \prod_{i=0}^k(x-e_i) \frac{d^2}{dx^2} + \sum_{j=0}^k m_j \prod_{\substack{i=0 \\ i\neq j}}^k(x-e_i)\frac{d}{dx} \] is self-adjoint with respect to the $k$ inner products \[ \skp{f}{g}_j = \int_{e_{j-1}}^{e_j} f(x)g(x) w(x) dx \] where \[ w(x)= \prod_{i=0}^k |x-e_i|^{m_j-1}. \] There is a well-known orthogonality relation satisfied by Heine-Stieltjes polynomials, found by Germanski \cite{germanski} and rediscovered by Volkmer \cite{volkmer}: \begin{equation} \label{equ:HSortho} \skp{E_\alpha^{(k)}}{E_\beta^{(k)}} = 0 \end{equation} where $E_\alpha, E_\beta$ are two distinct (i.e., non-proportional) Heine-Stieltjes polynomials and the inner product is the inner product \eqref{equ:kipro} on $V^k$. To see \eqref{equ:HSortho}, note that \[ \skp{E_\alpha}{(V_\alpha - V_\beta) E_\beta}_j =\skp{E_\alpha}{ L E_\beta}_j - \skp{L E_\alpha}{ E_\beta}_j =0 \] where $V_\alpha$, $V_\beta$ are the (necessarily distinct) van Vleck polynomials corresponding to $E_\alpha, E_\beta$. It follows that the matrix \[ \begin{pmatrix} \skp{E_\alpha}{E_\beta}_1 & \cdots & \skp{E_\alpha}{E_\beta}_k \\ \vdots & \ddots & \vdots \\ \skp{E_\alpha}{x^{k-1} E_\beta}_1 & \cdots & \skp{E_\alpha}{x^{k-1}E_\beta}_k \end{pmatrix} \] annihilates the coefficient vector of $V_\alpha - V_\beta$. Hence the determinant of the above matrix is zero. This is easily calculated to be the statement \eqref{equ:HSortho}. Note furthermore that if $E_\alpha, E_\beta$ are both of degree $n$, then $V_\alpha - V_\beta$ is of degree $\leq k-1$ since the leading coefficients of the van Vleck polynomials are necessarily the same. Hence the matrix \[ \begin{pmatrix} \skp{E_\alpha}{E_\beta}_1 & \cdots & \skp{E_\alpha}{E_\beta}_k \\ \vdots & \ddots & \vdots \\ \skp{E_\alpha}{x^{k-2} E_\beta}_1 & \cdots & \skp{E_\alpha}{x^{k-2}E_\beta}_k \end{pmatrix} \] must be rank deficient and hence all its $k$ minors vanish. The vanishing of the $j$-th minor is easily checked to be equivalent to the condition \[ \skp{E_\alpha^{(k-1)}}{E_\beta^{(k-1)}}_{(j)} = 0 \] where $\skp{}{}_{(j)}$ is the scalar product \eqref{equ:k1ipro} on $V^{k-1}$. It is furthermore well known that the Heine-Stieltjes differential equation has $N={ n+k-1 \choose k-1 }$ polynomial solutions of degree $n$, in one-to-one correspondence with the $N$ ways of distributing the $n$ roots of $y$ among the $k$ intervals $(e_{j-1},e_j)$ \cite{Stieltjes}. It follows that the Heine-Stieltjes polynomials of degree $n$ form a jointly orthogonal system of degree $n$ according to Definition \ref{def:jointorthog}. \section{Jointly orthogonal systems}\label{sec:jointorthog} \subsection{Definitions}\label{sec:jointorthogdef} As in the introduction we denote the space of symmetric polynomials in $k$ variables by $V^k$ and let $V_n^k \subset V^k$ be the space of symmetric polynomials of degree at most $n$ in any variable. For example $x_1^3x_2^2+x_2^3x_1^2\in V_3^2$, while $x_1^4x_2+x_2^4x_1\notin V_3^2$. Suppose we are given $k$ inner products $\skp{}{}_1,\dots, \skp{}{}_k$ on the space of polynomials $\mathbb{R}[x]$. We suppose throughout this paper and without further mention the following condition: \vskip .3cm {\bf Standing Assumption:} The operator of multiplication by $x$ is self-adjoint for all scalar products on $\mathbb{R}[x]$ considered. \vskip .3cm The $k$ inner products on $\mathbb{R}[x]$ can be used to define an symmetric bilinear form $\skp{}{}$ on $V^k$ such that \begin{equation} \label{equ:bilink} \skp{p^{(k)}}{q^{(k)}} = \det \begin{pmatrix} \skp{p}{q}_1 & \cdots & \skp{p}{q}_k \\ \skp{p}{xq}_1 & \cdots & \skp{p}{xq}_k \\ \vdots & \ddots & \vdots \\ \skp{p}{x^{k-1}q}_1 & \cdots & \skp{p}{x^{k-1}q}_k \end{pmatrix} \end{equation} for all $p,q\in \mathbb{R}[x]$, where we used again the notation \eqref{equ:prtimes}. Depending on the inner products $\skp{}{}_j$, this bilinear form may or not be definite. We will generally assume the following condition. \vskip .3cm {\bf Definiteness Condition 1:} For all non-zero $p\in \mathbb{R}[x]$: $\skp{p^{(k)}}{p^{(k)}}\neq 0$. \vskip .3cm \begin{rem} Note that by renumbering the scalar products $\skp{}{}_j$ we may change the sign of $\skp{}{}$, so we might as well ask that $\skp{p^{(k)}}{p^{(k)}}>0$ in the above condition. \end{rem} Similarly, we define $k$ symmetric bilinear forms $\skp{}{}_{(1)}, \dots, \skp{}{}_{(k)}$ on $V^{k-1}$ such that \begin{multline}\label{equ:bilink1} \skp{p^{(k-1)}}{q^{(k-1)}}_{(j)} = \\ \det \begin{pmatrix} \skp{p}{q}_1 & \cdots & \skp{p}{q}_{j-1} & \skp{p}{q}_{j+1} & \cdots & \skp{p}{q}_k \\ \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ \skp{p}{x^{k-2}q}_1 & \cdots & \skp{p}{x^{k-2}q}_{j-1} &\skp{p}{x^{k-2}q}_{j+1} & \cdots & \skp{p}{x^{k-2}q}_k \end{pmatrix} \end{multline} for all $p,q\in \mathbb{R}[x]$. These bilinear forms again may or may not be definite. However, for some results below we will assume the following condition: \vskip .3cm {\bf Definiteness Condition 2:} For all non-zero $p\in \mathbb{R}[x]$ and all $j=1,\dots,k$: $\skp{p^{(k-1)}}{p^{(k-1)}}_j\neq 0$. \vskip .3cm Assuming that Definiteness Conditions 1 and 2 are satisfied, we extend Definition \ref{def:jointorthog} of jointly orthogonal systems verbatim to this more general setting. \begin{ex} Scalar products $\skp{}{}_j$ as in \eqref{equ:innerprodj} for disjoint intervals $I_1,\dots ,I_k$ satisfy the Definiteness Conditions 1 and 2. To see this, note that the bilinear form \eqref{equ:bilink} takes on the form \begin{equation}\label{equ:kproduct} \langle f,f \rangle = \idotsint |f(x_1, \dots , x_k)|^2 \prod_{1\leq i< j\leq k}(x_i-x_j) \prod_{j=1}^k w_j(x_j) dx_j \end{equation} where $f\in \mathbb{R}[x_1,\dots, x_k]$, using the Vandermonde formula. Since the intervals are disjoint, the Vandermonde factor is non-zero and has a definite sign, while all other terms are non-negative. Hence Definiteness Condition 1 holds. By an analogous argument, Definiteness Condition 2 also holds. \end{ex} \subsection{Properties}\label{sec:properties} \begin{lemma}\label{lem:firstimpliessecond} Let $\{E_\alpha\}_\alpha$ be a jointly orthogonal system of degree $n$ with respect to the inner products $\skp{}{}_1,\dots,\skp{}{}_k$. Then the symmetric polynomials $E_\alpha^{(k)}$ are orthogonal (with respect to the bilinear form \eqref{equ:bilink}) to all symmetric polynomials $Q\in V_{n-1}^k\subset V_n^k$. \end{lemma} \begin{proof} Note that for any polynomial $p$ of degree at most $n$ and for all $i,j\in \{1,\dots,k\}$, \[ \sum_\alpha \frac{\langle E_\alpha^{(k-1)} ,p^{(k-1)} \rangle_{(i)}}{\langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(i)}} E_\alpha^{(k-1)} =p^{(k-1)} = \sum_\alpha \frac{\langle E_\alpha^{(k-1)} ,p^{(k-1)} \rangle_{(j)}}{\langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(j)}} E_\alpha^{(k-1)}. \] Hence \begin{equation}\label{equ:coeffequal} \frac{\langle E_\alpha^{(k-1)} ,p^{(k-1)} \rangle_{(i)}}{\langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(i)}} = \frac{\langle E_\alpha^{(k-1)} ,p^{(k-1)} \rangle_{(j)}}{\langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(j)}} \end{equation} for any polynomial $p$ of degree $\leq n$ and any $\alpha$. Our goal is to show that for any $Q\in V_{n-1}^k$ and any $\alpha$ \[ \skp{E_\alpha}{Q}=0. \] Since the rank one tensors span $V_{n-1}^k$ it suffices to show the above equation for $Q$ of the form $q^{(k)}$, where $q$ is a polynomial of degree at most $n-1$. We will distinguish two cases: (i) Suppose $\langle E_\alpha^{(k-1)} ,q^{(k-1)} \rangle_{(1)}=0$. Then by \eqref{equ:coeffequal}, $\langle E_\alpha^{(k-1)} ,q^{(k-1)} \rangle_{(i)}=0$ for all $i$. Hence \[ \langle E_\alpha^{(k)} ,q^{(k)} \rangle = \sum_{i=1}^k (-1)^{i+k} \langle E_\alpha ,x^{k-1} q \rangle_{i} \langle E_\alpha^{(k-1)} ,q^{(k-1)} \rangle_{(i)} = 0, \] expanding the determinant \eqref{equ:bilink} with respect to the last row. (ii) Suppose $\langle E_\alpha^{(k-1)} ,q^{(k-1)} \rangle_{(1)}\neq 0$. Expand the determinant \eqref{equ:bilink} with respect to the first row and compute \begin{align*} \langle E_\alpha^{(k)} ,q^{(k)} \rangle &= \sum_{i=1}^k (-1)^{i+1} \langle E_\alpha ,q \rangle_{i} \langle E_\alpha^{(k-1)} ,(xq)^{(k-1)} \rangle_{(i)} \\ &= \sum_{i=1}^k (-1)^{i+1} \langle E_\alpha ,q \rangle_{i} \langle E_\alpha^{(k-1)} ,(xq)^{(k-1)} \rangle_{(1)} \frac{\langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(i)}}{\langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(1)}} \\ &= \frac{\langle E_\alpha^{(k-1)} ,(xq)^{(k-1)} \rangle_{(1)}}{\langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(1)}} \sum_{i=1}^k (-1)^{i+1} \langle E_\alpha ,q \rangle_{i} \langle E_\alpha^{(k-1)} ,E_\alpha^{(k-1)} \rangle_{(i)} \\ &= \frac{\langle E_\alpha^{(k-1)} ,(xq)^{(k-1)} \rangle_{(1)}}{\langle E_\alpha^{(k-1)} ,q^{(k-1)} \rangle_{(1)}} \sum_{i=1}^k (-1)^{i+1} \langle E_\alpha ,q \rangle_{i} \langle E_\alpha^{(k-1)} ,q^{(k-1)} \rangle_{(i)} \\ &=0. \end{align*} Here we used \eqref{equ:coeffequal} twice, once for for $p=xq$ (this is possible since $q$ is of degree $\leq n-1$) and once for $p=q$. The last equality is true since the left hand side is a determinant of a matrix with two equal rows. \end{proof} An important feature of a jointly orthogonal system $E_\alpha$ is that it defines a family of orthogonal symmetric polynomials in $V_{n}^{k}$. \begin{lemma}\label{lem:northog} Let $\{E_\alpha\}_\alpha$ be a family of polynomials such that the $E_\alpha^{(k-1)}$ form a jointly orthogonal basis of $V_{n}^{k-1}$ for the inner products $\skp{}{}_{(i)}$, $i=1,\dots,k$. Then the vectors \[ E^{(k)}_\alpha \in V_{n}^{k} \] are pairwise orthogonal with respect to \eqref{equ:bilink}. \end{lemma} \begin{proof} As in \cite{germanski, volkmer} define, for each fixed pair $\alpha\neq \beta$, the $k\times k$ matrices \[ M_{\alpha\beta} = ( \langle x^{i-1} E_\alpha ,E_\beta \rangle_{j} )_{ij}. \] Orthogonality of the $E^{(k)}_\alpha$ is the statement that \[ \det M_{\alpha\beta}=\langle E_\alpha^{(k)} ,E_\beta^{(k)} \rangle=0. \] Let $M_{\alpha\beta}^j$ be the minor obtained by deleting the $k$-th row and the $j$-th column. Joint orthogonality is the statement that \[ \det M_{\alpha\beta}^j=\langle E_\alpha^{(k-1)} ,E_\beta^{(k-1)} \rangle_{(j)}=0 \] for $j=1,2,\dots, k$. Clearly, by expanding $\det M_{\alpha\beta}$ along the $k$-th row the statement of the Lemma follows. \end{proof} \begin{rem} Note that if we are given jointly orthogonal systems for each degree $n=0,1,\dots$, the symmetric polynomials $E_\alpha^{(k)}$ form an orthogonal basis of the space of symmetric polynomials $V^k$. By Theorem \ref{thm:main} this basis is canonical, i.e., uniquely defined (up to rescaling) and independent of arbitrary choices. This is in contrast to other methods of obtaining an orthogonal basis of $V^k$, for example by applying the Gram-Schmidt algorithm to an arbitrary non-orthogonal basis. \end{rem} \section{Joint orthogonality and multiparameter eigenvalue problems }\label{sec:multieig} \subsection{Symmetric rectangular multiparameter eigenvalue problems}\label{sec:symmmultpar} \hfill \\ Let $A_1,\dots, A_k$ be complex $(m+k-2)\times m$ matrices. A rectangular multiparameter eigenvalue problem is the equation \begin{equation} \label{equ:smultpar} \sum_{i=1}^k \lambda_i A_i v = 0 \end{equation} in complex unknowns $(\lambda_1,\dots, \lambda_k)\neq 0$ (the multiparameter eigenvalue, defined up to a multiplicative constant) and $0\neq v\in \mathbb{C}^n$ (the eigenvector). Eqn. \eqref{equ:smultpar} is overdetermined and may have solutions or not. Define the $m\times m$ matrix $A_{ij}$, $1\leq i \leq k$, $1\leq j \leq k-1$, as the submatrix of $A_i$ composed of the rows $j,\dots, j+m-1$. We call the rectangular multiparameter eigenvalue problem \emph{symmetric} if all matrices $A_{ij}$ are real and symmetric. \begin{rem} For $k>2$ the matrices $A_i$ appearing in a symmetric rectangular multiparameter eigenvalue problem are necessarily Hankel matrices. \end{rem} Similar to \eqref{equ:bilink1} define the $k$-vector valued sesquilinear form $\mu$ on $S^{k-1}\mathbb{C}^n$ such that \[ \mu(\underbrace{u\otimes \cdots \otimes u}_{k-1\times},\underbrace{v\otimes \cdots \otimes v}_{k-1\times}) := \vec{\det} (\bar u^T A_{ji} v )_{ij}. \] Here the vector valued determinant $\vec{\det}$ of a $(k-1)\times k$ matrix is the $k$-vector of its minors of size $k-1$, taken with alternating signs. If for all non-zero $v\in \mathbb{C}^n$: $\mu(v^{\otimes k-1},v^{\otimes k-1})\neq 0$ one calls the mutiparameter eigenvalue problem locally definite. In the following, we will say that two multiparameter eigenvalues are \emph{distinct} if they are not collinear. We will say that a multiparameter eigenvalue is \emph{real} if some non-zero multiple is real. \begin{prop}\label{prop:eigval} Suppose $v$ is an eigenvector of a symmetric and locally definite rectangular multiparameter eigenvalue problem. Then the corresponding multiparameter eigenvalue is $\lambda=\mu(v^{\otimes k-1},v^{\otimes k-1})$ and is real. Suppose $u$ is another eigenvector corresponding to the eigenvalue $\lambda'$ which is distinct from $\lambda$. Then \[ \mu(u^{\otimes k-1},v^{\otimes k-1})=0 \] In addition all multiparameter eigenvectors may be taken real. \end{prop} \begin{proof} It is an easy verification, using Cramer's rule. \end{proof} For $k=2$ and $A_1$ the identity matrix, the proposition reduces to well known statements of elementary linear algebra. \begin{rem} We use here the notation ``rectangular multiparameter eigenvalue problem'' to distinguish it from a multiparameter eigenvalue problem in the sense of \cite{volkmer}. A rectangular multiparameter eigenvalue problem determines a multiparameter eigenvalue problem in the sense of loc. cit., and eigenvalues in our sense are eigenvalues in the sense of loc. cit. Since we only consider multiparameter eigenvalue problems that are rectangular in this paper, we will sometimes drop the adjective rectangular, abusing notation slightly. \end{rem} \begin{rem} A more general definition of symmetry of a rectangular multiparameter eigenvalue problem is provided in Appendix \ref{sec:symmmultpar2}. \end{rem} \subsection{The relation to joint orthogonality} One motivation for Definition \ref{def:jointorthog} is the following Theorem. \begin{thm}\label{thm:multieig} Assume inner products $\skp{}{}_1,\dots \skp{}{}_k$ on $\mathbb{R}[x]$ are given that satisfy the Definiteness Conditions 1 and 2. Then the following two conditions are equivalent for a family $\{E_\alpha\}_{\alpha=1,\dots, N}$ of degree $\leq n$ polynomials, with $N={ n+k-1\choose k-1 }=\mathrm{dim} V_n^{k-1}$. \begin{itemize} \item $\{E_\alpha\}_\alpha$ is a jointly orthogonal system of degree $n$ with respect to the inner products given. \item The $E_\alpha$ are solutions to the symmetric rectangular multiparameter eigenvalue problem \begin{equation} \label{equ:eigval} \sum_{j=1}^k \Ket{E_\alpha}_j \lambda_{\alpha, j} =0 \end{equation} for \emph{distinct} non-zero eigenvectors $\lambda_\alpha=(\lambda_{\alpha,1},\dots , \lambda_{\alpha,k})$, where $\Ket{E_\alpha}_j$ is the linear form $v\mapsto \skp{v}{E_\alpha}_j$ on the space of polynomials of degree $\leq n+k-2$. \end{itemize} In fact, all such $\lambda_\alpha$ are multiples of \begin{equation} \label{equ:eigvalexpl} \left( \skp{E_\alpha^{(k-1)}}{E_\alpha^{(k-1)}}_{(1)}, \dots,(-1)^{j-1} \skp{E_\alpha^{(k-1)}}{E_\alpha^{(k-1)}}_{(j)} ,\dots, (-1)^{k-1} \skp{E_\alpha^{(k-1)}}{E_\alpha^{(k-1)}}_{(k)} \right). \end{equation} \end{thm} \begin{rem} In the usual monomial basis of the space of polynomials \eqref{equ:eigval} becomes a symmetric multiparameter eigenvalue problem of the form \eqref{equ:smultpar}. Here $m=n+1$ and $A_j$ is the matrix of the linear operator \[ V_n \to V_{n+k-2}^* \] sending $v\in V_n$ to $\ket{v}_j\in V_{n+k-2}^*$. \end{rem} \begin{cor}\label{cor:HSeig} The Heine-Stieltjes polynomials are solutions to the rectangular multiparameter eigenvalue problem above for distinct eigenvalues. \end{cor} \begin{proof}[Proof of the Theorem] Suppose first that the $E_\alpha$ solve the eigenvalue problem with respect to distinct eigenvalues. Then by Proposition \ref{prop:eigval} the eigenvalues are obtained by \eqref{equ:eigvalexpl} and the $E_\alpha^{(k-1)}$ form an orthogonal basis of $V_n^{k-1}$ with respect to each of the bilinear forms $\skp{}{}_{(j)}$. For the other direction, note that for all $p\in V_n$ \begin{align*} 0 &= \sum_{j=1}^k (-1)^{j-1} \skp{ p }{E_\alpha}_j \skp{ p^{(k-1)} }{E_\alpha^{(k-1)}}_{(j)} \\&= \frac{ \skp{ p^{(k-1)} }{E_\alpha^{(k-1)}}_{(1)} }{\skp{E_\alpha^{(k-1)}}{E_\alpha^{(k-1)}}_{(1)}} \sum_{j=1}^k (-1)^{j-1} \skp{ p }{E_\alpha}_j \skp{E_\alpha^{(k-1)}}{E_\alpha^{(k-1)}}_{(j)}. \end{align*} The first equation is the vanishing of a determinant with two equal rows, and for the second equation we used \eqref{equ:coeffequal}. Note that the right hand side is a product of a polynomial in (the coefficients of) $p$ and a linear function in $p$. If the product vanishes for all $p$, then one of the factors has to vanish identically. It can not be the first, since this factor is 1 for $p=E_\alpha$. Hence \[ \sum_{j=1}^k (-1)^{j-1} \skp{ p }{E_\alpha}_j \skp{E_\alpha^{(k-1)}}{E_\alpha^{(k-1)}}_{(j)} =0 \] for all polynomials $p$ of degree at most $n$. Hence the left hand side of \eqref{equ:eigval} is zero on all polynomials of degree $\leq n$. Next, evaluate the left hand side of \eqref{equ:eigval} on $x^r E_\alpha$, $r=0,\dots, k-2$. \[ \sum_{j=1}^k (-1)^{j-1} \skp{E_\alpha}{x^r E_\alpha}_j \skp{E_\alpha^{(k-1)}}{E_\alpha^{(k-1)}}_{(j)}. \] This is however the determinant of a matrix with two equal rows and hence zero. Summarizing, we have shown that the left hand side of \eqref{equ:eigval} vanishes on all polynomials of degrees $\leq n+k-2$. Hence the $E_\alpha$ are indeed multiparameter eigenvectors. It remains to be shown that the corresponding eigenvalues are distinct. So suppose to the contrary that two members of the family both are eigenvectors for some eigenvalue $(\lambda_1,\dots, \lambda_k)$. Since the members of the family are non-collinear by assumption, the kernel of $\sum_{j=1}^k\lambda_j A_j$ has dimension $\geq 2$. It follows that there is polynomial of degree $<n$ in the kernel, say $v$. But then we may replace \[ \skp{v}{x^r v}_1= -\sum_{j=2}^k \frac{\lambda_k}{\lambda_1} \skp{v}{x^r v}_j \] in the determinant defining $\skp{v^{(k)}}{v^{(k)}}$, see \eqref{equ:bilink}. The determinant of a matrix with linearly dependent columns vanishes, and hence arrive at a contradiction to Definiteness Condition 1. Here we used that $\lambda_1\neq 0$, which follows from \eqref{equ:eigvalexpl} and Definiteness Condition 2. Alternatively, since $\lambda \neq 0$ we may as well suppose that $\lambda_1\neq 0$. \end{proof} \subsection{Existence of solutions, and the proof of Theorem \ref{thm:main}} \begin{thm} Assume we are given $k$ inner products on the space of polynomials such that Definiteness Conditions 1 and 2 hold. Then for every $n$ the eigenvalue problem \eqref{equ:eigval} has ${ n+k-1 \choose k-1 }$ distinct solutions $(\lambda_1,\dots, \lambda_k)\in \mathbb{P}^{k-1}$. In particular it follows that there is a (unique up to rescaling) set of ${ n+k-1 \choose k-1 }$ multiparameter eigenvectors $E_\alpha$ that form a jointly orthogonal basis in the sense of Definition \ref{def:jointorthog}. \end{thm} \begin{proof} First let us show that there are $N:={ n+k-1 \choose k-1 }$ solutions, counted with multiplicity. For this we can use Shapiro's lemma, see Appendix \ref{sec:shapiro}. Indeed, note that by the Definiteness Condition 2, there can be no eigenvalue $\lambda = (\lambda_1,\dots, \lambda_k)$ which has a zero component, and in particular none that has $\lambda_1=0$. It follows that $\lambda_2A_2+\dots+\lambda_k A_k$ is rank deficient iff all $\lambda_2=\lambda_3=\cdots=\lambda_k=0$. Hence the condition in Shapiro's Lemma is satisfied. Hence there are $N$ solutions counted with multiplicity. It remains to show that there are no solutions of multiplicity $>1$. First note that the kernel of $\sum_{j=1}^k\lambda_j A_j$ cannot have dimension $\geq 2$. Otherwise, we can arrive at contradiction to Definiteness Condition 1 as in the proof of Theorem \ref{thm:multieig}. It remains to be shown that if $\lambda$ is an eigenvalue of multiplicity $\geq 2$, then the corresponding eigenspace is of dimension $\geq 2$. The set of $A_j$'s for which there are multiple eigenvalues is Zariski closed, and there is a point in the complement by Corollary \ref{cor:HSeig}, or alternatively by the explicit computation of Appendix \ref{sec:exmultipar}. Hence we may always perturb the eigenvalue problem so as to lift the degeneracies of eigenvalues, so say we set $A_j^\epsilon= A_j+\epsilon B_j$. Then there are eigenvectors $v_\epsilon,w_\epsilon$ to the distinct perturbed eigenvalues, continuously depending on $\epsilon>0$, such that $v^{(k)}_\epsilon$, $w^{(k)}_\epsilon$ are orthogonal. To disregard the arbitrary multiplicative factor, we also consider the corresponding one-dimensional eigenspaces $V_\epsilon,W_\epsilon\in \mathbb{P}^{n-1}$, which are uniquely defined. By compactness, they have to have limit points (as $\epsilon\to 0$), and there must be at least two different limit points by orthogonality of $V_\epsilon,W_\epsilon$. Suppose $v, w\neq 0$ are vectors in these limit points (subspaces). Then by continuity $\sum_j \lambda_j^\epsilon A_j^\epsilon$ must annihilate both $v$ and $w$ at $\epsilon=0$. Hence the kernel is at least $2$-dimensional. \end{proof} \section{Orthogonal symmetric polynomials and the rank 1 Gram-Schmidt algorithm}\label{sec:gramschmidt} In this section we show that the two conditions of Definition \ref{def:jointorthog} are slightly stronger than necessary to guarantee uniqueness. \begin{prop}\label{prop:rank1unique} Assume an inner product on the space of symmetric polynomials $V^k$ is given. Suppose we are given two families of polynomials $\{E_\alpha\}_\alpha$, $\{E_\alpha'\}_\alpha$ with $E_\alpha, E_\alpha'\in V_n$, such that the families $\{E_\alpha^{(k)}\}_\alpha$ and $\{(E_\alpha')^{(k)}\}_\alpha$ both form bases of $(V_{n-1}^{k})^\perp\subset V_n^k$. Then the two families are identical, up to rescaling and permutation of its members. \end{prop} The proof will be given in the subsequent section. \begin{rem} It follows that the rank 1 basis of $(V_{n-1}^k)^\perp$ in this case is essentially the set of rank one, norm one tensors in $(V_{n-1}^k)^\perp$. ``Essentially'' here means that if $v$ is of rank one and norm one, so is $-v$ of course, so we must pick one of $v$ or $-v$ for the basis. In particular, the jointly orthogonal system in the sense of Definition \ref{def:jointorthog} is essentially the set of polynomials $v\in V_n$ such that $v^{(r)}\in (V_{n-1}^k)^\perp$. \end{rem} The following algorithm can hence be used to determine the (essentially unique) jointly orthogonal systems of each degree. \vskip .3cm {\bf Rank 1 Gram-Schmidt Algorithm:} \begin{enumerate} \item Initialization: A jointly orthogonal system of degree 0 is given by the constant polynomial $E_{0,1}:=1\in V_0$. Set $n=1$. \item Solve the system of homogeneous polynomial equations \[ \skp{v^{(k)}}{E_{n-1,\alpha}^{(k)}}=0 \] for $v\in V_n$ where $\alpha=1,2,\dots , { n+k-2 \choose k-1 }$. Assuming that the inner product is of the form \eqref{equ:bilink} and assuming Definiteness Conditions 1 and 2 one finds ${ n+k-1 \choose k-1 }$ solutions up to rescaling. They become the jointly orthogonal system $\{E_{n,\alpha}\}_\alpha$ of degree $n$. \item Increase $n$ and go to step 2. \end{enumerate} \vskip .3cm \subsection{Proof of Proposition \ref{prop:rank1unique}} \begin{rem}\label{rem:basis} Note that a (non-orthogonal) basis of $V^k_n$ may be given by the monomial symmetric polynomials $m_\mu$ where $\mu=(\mu_1,\dots, \mu_k)$, $n\geq \mu_1\geq \mu_2 \geq \cdots \geq \mu_k \geq 0$ is a multiindex. Counting such multiindices, one sees that \[ \dim V_n^k = \begin{pmatrix} n+k \\ k \end{pmatrix}. \] It follows that \[ \dim (V_{n-1}^k)^\perp = \begin{pmatrix} n+k \\ k \end{pmatrix} - \begin{pmatrix} n+k-1 \\ k \end{pmatrix} = \begin{pmatrix} n+k-1 \\ k-1 \end{pmatrix} = \dim V^{k-1}_n. \] Explicitly, a map $V^{k-1}_n\to (V^k_{n-1})^\perp$ may be defined as the composition $V^{k-1}_n\to V^k_n \to (V^k_{n-1})^\perp$ where the first arrow sends \[ m_{\mu_1, \dots, \mu_{k-1}} \mapsto m_{n, \mu_1, \dots, \mu_{k-1}} \] and the second is the orthogonal projection. An explicit isomorphism in the other direction $(V^k_{n-1})^\perp\to V^{k-1}_n$ is given by the operator $\frac{\partial^n}{\partial x_k^n}$. In particular, the images of the elements $E_\alpha^{(k)}$ of a rank one basis under this operator are non-zero multiples of \[ E_\alpha^{(k-1)} = E_\alpha(x_1)E_\alpha(x_2)\cdots E_\alpha(x_{k-1}). \] Hence it follows that the $E_\alpha^{(k-1)}$ form a basis of $V^{k-1}_n$. \end{rem} \begin{proof}[Proof of Proposition \ref{prop:rank1unique}] Suppose there is some degree $n$ polynomial $p\in \mathbb{C}[x]$ such that $p^{(k)}:= p(x_1)\cdots p(x_k)$ is in $(V^k_{n-1})^\perp$. We want to show that $p^{(k)}$ is a multiple of some $E_\alpha^{(k)}$. Since the $E_\alpha^{(k)}$ form a basis, we may write \[ p^{(k)} = \sum_\alpha \lambda_\alpha E_\alpha^{(k)} \] for some constants $\lambda_\alpha$. Let $a_1,\dots, a_r$ be the roots of $p$, with multiplicities $m_1,\dots, m_r$. Let $\mathit{ev}_{x_k=a}$ be the operator of evaluation at $x_k=a$ and apply the operators \[ \mathit{ev}_{x_k=a_i} \frac{\partial^j}{\partial x_k^j} \] on both sides of the above equation for $i=1,2,\dots, r$, $j=0,1,\dots, m_r-1$. We obtain $n$ equations of the form \[ 0 = \sum_\alpha \lambda_\alpha c_{\alpha ij} E_\alpha^{(k-1)}. \] for some constants $c_{\alpha ij}$ which are zero iff $E_\alpha$ has a root $a_i$ with multiplicity not equal to $j$. Since by Remark \ref{rem:basis} above the $E_\alpha^{(k-1)}$ are elements of a basis and hence linearly independent, we must have $\lambda_\alpha c_{\alpha ij}=0$ for each $\alpha, i, j$. Hence $\lambda_\alpha=0$ unless $E_\alpha$ has the same roots, with the same multiplicities, as $p$. But then $p\propto E_\alpha$. \end{proof} Note that by Theorem \ref{thm:main} the Rank 1 Gram-Schmidt algorithm will succeed in finding the jointly orthogonal systems if the inner product on $V^k$ has the form \eqref{equ:bilink} and Definiteness Conditions 1 and 2 are satisfied. For a general inner product however, the algorithm might fail, as the following example shows. \begin{ex} For a general inner product on $V^k$ a rank 1 basis may or may not exist. As an example, consider the $n=1$, $k=2$ case. Polynomials in this case may be identified with $2\times 2$ symmetric matrices. Fix a basis $e_1=x_1x_2$, $e_2=x_1+x_2$, $e_3=1$. Consider the inner product \begin{align*} \langle e_1 , e_1 \rangle &= \langle e_3 , e_3 \rangle = 1 & \langle e_2 , e_2 \rangle &= \lambda \\ \langle e_1 , e_2 \rangle &= \langle e_2 , e_3 \rangle = 0 & \langle e_1 , e_3 \rangle &= -\epsilon^2 \end{align*} where $\lambda>0$, $0\leq \epsilon<1$. The rank 1 vectors in the orthogonal complement of $e_3$ are $e_1\pm \epsilon e_2 + \epsilon^2 e_3$. So in particular, there may be either 2 or only one, depending on $\epsilon$. Furthermore, these two vectors are orthogonal iff \[ 1-\epsilon^4 - \lambda \epsilon^2 = 0, \] so while generically the vectors are not orthogonal, for a specific value of $\lambda$ they are. \end{ex} \subsection{Proof of Proposition \ref{prop:firstsecondid}} The forward implication of Proposition \ref{prop:firstsecondid} is the content of Lemmas \ref{lem:firstimpliessecond} and \ref{lem:northog} of section \ref{sec:properties}. For the reverse implication note that the by Proposition \ref{prop:rank1unique} the condition of Proposition \ref{prop:firstsecondid} determines the family $\{E_\alpha\}_\alpha$ uniquely up to rescaling and permutation, if such a family exists. However, by Theorem \ref{thm:main} and the forward implication we know that at least one such family exists, namely a jointly orthogonal system. Hence, by uniqueness, the family $\{E_\alpha\}_\alpha$ must be a jointly orthogonal system. \hfill \qed
{ "redpajama_set_name": "RedPajamaArXiv" }
483
{"url":"https:\/\/turbomachinery.asmedigitalcollection.asme.org\/electrochemical\/article-abstract\/4\/4\/474\/451262\/Investigation-of-Atomistic-Scale-Transport?redirectedFrom=fulltext","text":"This paper studies the transport phenomena inside the electrolyte of proton exchange membrane fuel cells (PEMFCs) using atomistic simulation techniques. The investigated material of the electrolyte is $Nafion\u00ae$, which is the most widely adapted polymer membrane in low-temperature fuel cells. The molecular dynamics simulation system includes part of the Nafion structure, numerous water molecules, and the transporting cations. The cations are assumed to be hydroxoniums $(H3O+)$, which are a hydrogen proton combined with a water molecule. Simulation results indicated that the electrostatic energy dominated the other potential energies in the total internal energy analysis. Clusters of water molecules tend to move toward the sulfonic acid group in the Nafion fragment, where the hydrophilic\/hydrophobic characteristics can be observed. The transport phenomena of hydroxoniums are classified into two categories\u2014continuous migration and noncontinuous hopping. The self-diffusion coefficients of the hydroxoniums and the water molecules in the membrane were evaluated to be $3.476\u00d710\u22125cm2\u2215s$ and $4.993\u00d710\u22125cm2\u2215s$ respectively, based on the Einstein relation. The calculated self-diffusion coefficients are of the same order of magnitude as the experimental results, which indicates this atomistic simulation is reaching more and more practical in engineering analysis.\n\n1.\nUSDOE\n, 2004,\nFuel Cell Handbook\n, 7th ed.,\nU.S. Department of Energy\n, Morgantown, WV.\n2.\nEnnari\n,\nJ.\n,\nElomaa\n,\nM.\n,\nNeelov\n,\nI.\n, and\nSundholm\n,\nF.\n, 2000, \u201c\nModeling of Water-Free and Water Containing Solid Polyelectrolytes\n,\u201d\nPolymer\n0032-3861,\n41\n(\n3\n), pp.\n985\n990\n.\n3.\nJinnouchi\n,\nR.\n, and\nOkazaki\n,\nK.\n, 2003, \u201c\nMolecular Dynamics Study of Transport Phenomena in Perfluorosulfonate Ionomer Membranes for Polymer Electrolyte Fuel Cells\n,\u201d\nJ. Electrochem. Soc.\n0013-4651,\n150\n(\n1\n), pp.\nE66\nE73\n.\n4.\nElliott\n,\nJ. A.\n,\nHanna\n,\nS.\n,\nElliot\n,\nA. M. S.\n, and\nCooley\n,\nG. E.\n, 1999, \u201c\nAtomistic Simulation and Molecular Dynamics of Model Systems for Perfluorinated Ionomer Membranes\n,\u201d\nPhys. Chem. Chem. Phys.\n1463-9076,\n1\n(\n20\n), pp.\n4855\n4863\n.\n5.\nVishnyakov\n,\nA.\n, and\nNeimark\n,\nA. V.\n, 2000, \u201c\nMolecular Dynamics Simulation of Nafion Oligomer Salvation in Equimolar Methanol-Water Mixture\n,\u201d\nJ. Phys. Chem. B\n1089-5647,\n105\n(\n32\n), pp.\n7830\n7834\n.\n6.\nJang\n,\nS. S.\n,\nMolinero\n,\nV.\n,\nCagin\n,\nT.\n, and\nGoddard\n, III\nW. A.\n, 2004, \u201c\nNanophase-Segregation and Transport in Nafion 117 From Molecular Dynamics Simulation: Effect of Monomeric Sequence\n,\u201d\nJ. Phys. Chem. B\n1089-5647,\n108\n(\n10\n), pp.\n3149\n3157\n.\n7.\nHypercube\n, 2002,\nHyperChem Reference Manual\n.\n8.\nBerendsen\n,\nH. J. C.\n,\nGrigera\n,\nJ. R.\n, and\nStraatsma\n,\nT. P.\n, 1987, \u201c\nThe Missing Term in Effective Pair Potentials\n,\u201d\nJ. Phys. Chem.\n0022-3654,\n91\n(\n24\n), pp.\n6269\n6271\n.\n9.\nAllen\n,\nM. P.\n, and\nTildesley\n,\nD. J.\n, 1987,\nComputer Simulation of Liquids\n,\nClarendon\n, Oxford.\n10.\nMayo\n,\nS. L.\n,\nOlfason\n,\nB. D.\n, and\nGoddard\n,\nW. A.\n, 1990, \u201c\nDREIDING: A Generic Force Field for Molecular Simulations\n,\u201d\nJ. Phys. Chem.\n0022-3654,\n94\n(\n24\n), pp.\n8897\n8909\n.\n11.\nSmith\n,\nW.\n,\nLeslie\n,\nM.\n, and\nForester\n,\nT. R.\n, 2003,\nThe DLPOLY2 User Manual\n,\nCCLRC\n, Daresbury Laboratory.\n12.\nBerendsen\n,\nH. J. C.\n,\nPostma\n,\nJ. P. M.\n,\nvan Gunsteren\n,\nW.\n,\nDiNola\n,\nA.\n, and\nHaak\n,\nJ. R.\n, 1984, \u201c\nMolecular Dynamics With Coupling to an External Bath\n,\u201d\nJ. Chem. Phys.\n0021-9606,\n81\n(\n8\n), pp.\n3684\n3690\n.\n13.\nVerlet\n,\nL.\n, 1967, \u201c\nComputer \u2018Experiment\u2019 on Classical Fluids. I. Thermodynamical Properties of Lennard-Jones Molecules\n,\u201d\nPhys. Rev.\n0031-899X,\n159\n, pp.\n98\n10\n.\n14.\nRyckaert\n,\nJ. P.\n,\nCiccotti\n,\nG.\n, and\nBerendsen\n,\nH. J. C.\n, 1977, \u201c\nNumerical Integration of the Cartesian Equations of Motion of a System With Constraints: Molecular Dynamics of n-Alkanes\n,\u201d\nJ. Comput. Phys.\n0021-9991,\n23\n, pp.\n327\n341\n.\n15.\nLaaksonen\n,\nL.\n, 1992, \u201c\nA Graphics Program for the Analysis and Display of Molecular Dynamics Trajectories\n,\u201d\nJ. Mol. Graphics\n0263-7855,\n10\n, pp.\n33\n34\n.\n16.\nKreuer\n,\nK. D.\n, 1997, \u201c\nOn the Development of Proton Conducting Materials for Technological Applications\n,\u201d\nSolid State Ionics\n0167-2738,\n97\n, pp.\n1\n15\n.","date":"2023-02-05 14:41:13","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 4, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.6951801180839539, \"perplexity\": 12948.867423887128}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2023-06\/segments\/1674764500255.78\/warc\/CC-MAIN-20230205130241-20230205160241-00573.warc.gz\"}"}
null
null
\section{Introduction} In this paper we consider some properties of the harmonic gauge fixing condition in the context of Linearized Massive Gravity (LMG) theory \cite{Rubakov:2008nh,Hinterbichler:2011tt,deRham:2014zqa}. The harmonic gauge is adopted in Linearized Gravity (LG) indipendently whether the theory is massive or not, but LMG in the harmonic gauge displays some interesting physical properties which we would like to focus on in this Letter. Of course, in gauge field theory the observables, or, more in general, any physical claim, should not depend on the gauge choice, but in certain gauges some physical properties might be more apparent than in others. We believe that this is the case for the harmonic gauge in LMG. The theory of LG is obtained as a perturbation of General Relativity (GR) around an arbitrary background metric $g^{(0)}_{\mu \nu}$ \cite{Carroll:2004st}. For the scope of this paper we will consider a Minkowskian background, i.e. $g^{(0)}_{\mu \nu} = \eta_{\mu \nu} =$ diag $(-1,1,1,1)$, so that the whole metric can be written as \begin{equation} g_{\mu \nu}(x) = \eta_{\mu \nu} + h_{\mu \nu}(x)\; , \end{equation} and, expanding the Einstein-Hilbert action \begin{equation} S_{EH}[g] = \int \mathrm{d}^4 x\; \sqrt{-g}\; R \end{equation} to second order in the perturbation $h_{\mu \nu}(x)$, one gets the action \begin{equation}\label{intro:inv} S_{inv}[h]= \int \mathrm{d^4 x} \; \; \Big[ \; \frac{1}{2} h \partial^2 h \; - \; h_{\mu \nu } \partial^\mu \partial^\nu h \; - \;\frac{1}{2} h^{\mu \nu} \partial^2 h_{\mu \nu}\;+ \;h^{\mu \nu} \partial_\nu \partial^\rho h_{\mu \rho} \; \Big] \; , \end{equation} where $h(x)\equiv\eta^{\mu\nu}h_{\mu\nu}(x)$. It is well known that \eqref{intro:inv} is the most general action describing a rank-2 symmetric tensor in a Minkowski space-time and invariant under the infinitesimal gauge transformation \begin{equation}\label{intro:symmetry} h_{\mu \nu} \rightarrow h'_{\mu \nu}= h_{\mu \nu} + \partial_\mu \theta_\nu + \partial_\nu \theta_\mu \; , \end{equation} where $\theta(x)$ is a local infinitesimal gauge parameter. As pointed out in \cite{Blasi:2015lrg,Blasi:2017pkk}, when building an action for a MG theory, it is necessary first to gauge fix the invariant massless action \eqref{intro:inv}, and, after that, a mass term might be added. We now briefly recall why this is the case. We remark that even an intrinsically classic theory as linearized gravity needs a well defined generating functional of the Green functions, without which, for instance, the propagator does not exist, nor, consequently, the corresponding dynamical theory. Adding a mass term directly to the invariant action \eqref{intro:inv}, as done, for instance, in the Fierz-Pauli (FP) approach to MG \cite{Fierz:1939ix}, has a few fundamental flaws. Firstly, the mass term plays the primary and inappropriate role of gauge fixing the action, breaking the symmetry \eqref{intro:symmetry}. In fact, the FP mass term allows to define a propagator, but this trades the mass for a gauge fixing parameter, which is not physical, in contrast with the fact that mass should be an observable quantity. Secondly, the FP theory does not display a good massless limit since, at vanishing masses, one is left with the invariant action $S_{inv}[h]$ \eqref{intro:inv}, which has no propagator for the symmetric tensor field $h_{\mu \nu}(x)$. Furthermore, the gravitational couplings predicted by the FP action in the massless limit are inconsistent with those of GR. This fact is known as the vDVZ discontinuity \cite{vanDam:1970vg,Zakharov:1970cc}. A striking effect of the discontinuity is that, in the limit of small mass of the FP theory, the predicted gravitational bending of light due to the presence of a massive body, $e.g.$ a star, differs by 25 \% from that computed in GR. If, on the other hand, one proceeds as it is customary for a gauge field theory, $i.e.$ by fixing the gauge before adding a mass term to the action, when taking the zero-mass limit one is left with a well defined theory, for which a propagator exists. Therefore, in order to have a MG theory with physical mass parameters and a good massless limit, it is necessary, as a preliminary step, to choose a gauge. In the context of LG many gauge fixing conditions can be used \cite{Carroll:2004st}. Popular choices are: \begin{itemize} \item Transverse gauge \item Synchronous gauge \item Harmonic gauge. \end{itemize} Amongst these, the harmonic gauge condition is the only Lorentz invariant and, written in terms of $h_{\mu \nu}(x)$ and its trace $h(x)$, it reads \begin{equation}\label{intro:harmonic} \partial^\mu h_{\mu \nu} - \frac{1}{2}\partial_\nu h = 0 \; . \end{equation} In \cite{Blasi:2015lrg, Blasi:2017pkk} a generalization of the harmonic gauge is used, namely \begin{equation}\label{intro:gauge_kappa} \partial^\mu h_{\mu \nu} + \kappa \partial_\nu h = 0 \; . \end{equation} The aim of this Letter is to point out that the choice of the covariant harmonic gauge \eqref{intro:harmonic} is particularly clever in a theory of LMG since a physical property (the absence of the vDVZ discontinuity) turns out to be apparent in this gauge, while it is hidden otherwise. It would be interesting to investigate the absence of the vDVZ discontinuity in other gauges, or, even better, to show that this property does not depend on the gauge choice. This, however, goes beyond the scope of this paper, which is focused on the properties of the harmonic gauge in the framework of LMG. An important issue which must be faced concerns the number of degrees of freedom (DOFs), which must be five, for a theory describing a massive spin-2 particle. Therefore, we are dealing with a tough task: that of finding a theory of LMG with a well defined propagator, with a regular massless limit, no vDVZ discontinuity and five DOFs. Our claim is that, at least in the harmonic gauge, this is possible.\\ This paper is organized as follows. In Section 2 we realize the harmonic gauge \eqref{intro:harmonic} according to the standard Faddeev-Popov ($\Phi\Pi$) procedure used in gauge field theory, and we discuss the reason why, amongst the class of covariant gauge conditions \eqref{intro:gauge_kappa}, it is peculiar in the context of LG. We will then use it to build a LMG action and subsequently find the propagator of the theory. In Section 3 we use the equations of motion (EOMs) derived from our LMG action to study for which values of the massive parameters it is possible to recover the five DOFs propagated by a spin-2 massive particle. In Section 4 we show that the results obtained in Section 2 and 3 imply the absence of the vDVZ discontinuity in our theory. Our results are summarized and discussed in the concluding Section 5. \section{Harmonic gauge} The customary $\Phi\Pi$ procedure \cite{Faddeev:1967fc} to introduce a gauge fixing condition into a gauge field theory, is to add a gauge fixing term to the action, which, for the class of covariant gauges \eqref{intro:gauge_kappa}, is \begin{equation} S_{gf}[h;k,\kappa] = - \frac{1}{2k} \int \mathrm{d^4 x} \; \; \left[ \partial^\mu h_{\mu \nu} + \kappa \partial_\nu h \right]^2 \; , \label{gfterm}\end{equation} where $k$ and $\kappa$ are gauge fixing parameters. The gauge fixed action then reads \begin{equation}\label{1:FP} S[h;k,\kappa] = S_{inv}[h] + S_{gf}[h;k,\kappa] \; , \end{equation} the ghost sector being factorized out since LG is an abelian gauge theory, and therefore the ghosts are decoupled from the gauge field $h_{\mu\nu}(x)$, as it happens in the Maxwell theory of electromagnetism. As noticed, in LG the covariant gauge \eqref{intro:gauge_kappa} is realized by means of $two$ gauge parameters: $k$ and $\kappa$. The harmonic gauge \eqref{intro:harmonic}, which is obtained from \eqref{intro:gauge_kappa} by chosing $\kappa=-\frac{1}{2}$, should therefore be thought of as a class of choices, rather than a particular one, corresponding to generic $k$. We shall come again on this point later. In this Letter we are interested in the particular $k= \kappa=-\frac{1}{2}$ harmonic gauge, to which corresponds the gauge fixed action \begin{equation}\label{1:direct_action} S[h;k= \kappa=-\frac{1}{2}]= \int \mathrm{d^4 x} \; \; \Big[ \; \frac{1}{4} h \partial^2 h \; - \;\frac{1}{2} h^{\mu \nu} \partial^2 h_{\mu \nu}\; \Big] \; . \end{equation} The most general mass term which can be added to the action $S$ is \begin{equation}\label{1:mass} S_m[h;m_1^2,m_2^2] = \int \mathrm{d}^4 x \left[\frac{1}{2} m_1^2 h_{\mu \nu} h^{\mu \nu} + \frac{1}{2} m_2^2 h^2 \right]\; , \end{equation} where $m_1^2$ and $m_2^2$ are massive parameters. The whole LMG action is therefore given by \begin{equation}\label{1:MG_action} S_{MG}[h;m_1^2,m_2^2] = S[h;k= \kappa=-\frac{1}{2}] + S_m[h;m_1^2,m_2^2] \; . \end{equation} The action \eqref{1:MG_action} in momentum space reads \begin{equation} \label{quadr_action_mass} S_{MG}[\Tilde{h};m_1^2,m_2^2]= \int \mathrm{d^4 p} \quad \Tilde{h}_{\mu \nu} (-p) \: \Omega^{\mu \nu, \alpha \beta}(p;m_1^2,m_2^2) \:\Tilde{h}_{\alpha \beta}(p)\; , \end{equation} where $\tilde{h}_{\mu \nu}(p)$ is the Fourier transform of $h_{\mu \nu}(x)$, and the kinetic operator $\Omega$ is \begin{equation} \Omega_{\mu \nu,\alpha \beta}(p;m_1^2,m_2^2) = \frac{1}{2} \left( m_2^2 - \frac{1}{2} p^2 \right) \eta_{\mu \nu}\eta_{\alpha \beta} + \frac{1}{2}(p^2 + m_1^2)\mathcal{I}_{\mu \nu,\alpha \beta} \; , \end{equation} where $\mathcal{I}$ is the rank-4 tensor identity \begin{equation}\label{1:identity} \mathcal{I}_{\mu \nu, \rho \sigma} = \frac{1}{2} (\eta_{\mu \rho} \eta_{\nu \sigma} + \eta_{\mu \sigma} \eta_{\nu \rho}) \; . \end{equation} The propagator $G_{\alpha \beta, \rho \sigma}(p;m_1^2,m_2^2)$ is defined by the following equation \begin{equation} {\Omega_{\mu \nu}}^{\alpha \beta}G_{\alpha \beta, \rho \sigma} = \mathcal{I}_{\mu \nu, \rho \sigma} \end{equation} which gives \begin{equation}\label{1:propagator} \left<\tilde{h}_{\mu \nu} \tilde{h}_{\alpha \beta} \right>(p) = G_{\mu \nu, \alpha \beta}(p;m_1^2,m_2^2) = \frac{2}{p^2 +m_1^2} \left[ \mathcal{I}_{\mu \nu, \alpha \beta} - \frac{1}{2} \frac{p^2 - 2m_2^2}{p^2 - m_1^2 - 4m_2^2} \eta_{\mu \nu} \eta_{\alpha \beta}\right] \; . \end{equation} Note that the propagator \eqref{1:propagator} displays a good massless limit ($m_1, m_2 \rightarrow 0 $), as expected.\\ \paragraph{Remark} {\small It is worth to point out that plugging the harmonic gauge condition \eqref{intro:harmonic} directly into the invariant action \eqref{intro:inv}, one obtains the gauge fixed action \eqref{1:direct_action}, $i.e.$ the one coming from the $\Phi\Pi$ gauge fixing term \eqref{gfterm} with $k=- \frac{1}{2}$ and $\kappa=- \frac{1}{2}$. We give now an intuitive explanation of this fact. Defining the \textit{trace-reversed} field \begin{equation}\label{2:trace_inv} \bar{h}_{\mu \nu}\equiv h_{\mu \nu} - \frac{1}{2}\eta_{\mu \nu} h \; , \end{equation} the invariant action \eqref{intro:inv} can be written as \begin{equation}\label{1:harm_action} S_{inv}[\bar{h}] = \int \mathrm{d^4 x} \; \; \Big[ \; \frac{1}{4} \bar{h} \partial^2 \bar{h} \; - \;\frac{1}{2} \bar{h}^{\mu \nu} \partial^2 \bar{h}_{\mu \nu}\;+ \;\bar{h}^{\mu \nu} \partial_\nu \partial^\rho \bar{h}_{\mu \rho} \; \Big] \; , \end{equation} and the harmonic gauge condition \eqref{intro:harmonic} reduces to \begin{equation}\label{1:harm_bar} \partial^\mu \bar{h}_{\mu \nu}= 0\; . \end{equation} In terms of $\bar{h}_{\mu \nu}(x)$, the gauge symmetry \eqref{intro:symmetry} writes \begin{equation} \bar{h}_{\mu \nu} \rightarrow \bar{h}'_{\mu \nu}= \bar{h}_{\mu \nu} + \partial_\mu \theta_\nu + \partial_\nu \theta_\mu - \eta_{\mu \nu} \partial_\alpha \theta^\alpha \; . \end{equation} In fact, $S_{inv}[\bar{h}] = S_{inv}[\bar{h}']$ and, in close analogy with Maxwell theory, as long as $\partial^2 \theta_\mu(x) = 0$, the transformed field $\bar{h}'_{\mu \nu}(x)$ satisfies equation \eqref{1:harm_bar}. Looking at the action \eqref{1:harm_action}, we see that only the third term involves $\partial^\mu \bar{h}_{\mu \nu}(x)$. So it is clear that, in the EOMs, the terms proportional to $\partial^\mu \bar{h}_{\mu \nu}(x)$ come from the variation of \begin{equation} \int \mathrm{d}^4x \; \; \bar{h}^{\mu \nu} \partial_\nu \partial^\rho \bar{h}_{\mu \rho} \; . \end{equation} Plugging \eqref{1:harm_bar} into the action \eqref{1:harm_action} results in eliminating this term and therefore every term in the EOMs containing $\partial^\mu \bar{h}_{\mu \nu}(x)$ vanishes. The key observation is that we would have obtained the same result by substituting the constraint \eqref{1:harm_bar} into the EOMs obtained from the invariant action \eqref{1:harm_action}. Therefore, plugging the harmonic gauge condition \eqref{intro:harmonic} directly into the action is a valid way of gauge fixing, since this peculiarly corresponds to a particular choice $(k=\kappa=-\frac{1}{2})$ of the $\Phi\Pi$ gauge fixing term \eqref{gfterm}. } \section{EOMs and DOFs in the harmonic gauge} In their original paper [7] on the theory of a massive spin-$f$ particle, the issue faced by Fierz and Pauli in the case $f=2$ was to find a theory characterized by the following constraints: \begin{equation} (\partial^2 - m_1^2) h_{\mu \nu} = 0\ , \label{KKeq}\end{equation} and \begin{eqnarray} \partial^\mu h_{\mu \nu}&=&0 \label{transv}\\ h &=& 0\label{traceless}\ . \end{eqnarray} Eq. \eqref{KKeq} is the massive wave equation for a massive rank-2 symmetric tensor field, and Eqs. \eqref{transv} and \eqref{traceless} represent the five constraints (respectively transversality and tracelessness) which lower the number of independent components of $h_{\mu\nu}(x)$ from ten to five, as it should be for a massive spin-2 particle. In this way Fierz and Pauli recovered five DOFs from a theory which otherwise concerns ``only'' the ten components of a generic symmetric 4D rank-2 tensor field. In this Section we show that, at least in the case of the harmonic gauge choice, five DOFs are indeed obtained, which is the necessary preliminary condition which must be fulfilled before dealing with any further question. We follow here the same steps as in the original paper \cite{Fierz:1939ix}. The action $S_{MG}$ \eqref{1:MG_action} implies the following EOM \begin{equation}\label{2:eom} (- \partial^2 + m_1^2) h_{\mu \nu} + \left( \frac{1}{2}\partial^2 + m_2^2\right) \eta_{\mu \nu} h=0 \; . \end{equation} Taking the trace of \eqref{2:eom} we get \begin{equation} (\partial^2 + m_1^2 + 4m_2^2) h= 0 \; , \label{2:trace}\end{equation} while saturating \eqref{2:eom} with $\partial^\nu$ and using the harmonic gauge fixing condition \eqref{intro:harmonic} we find \begin{equation} \left( \frac{m_1^2}{2} + m_2^2 \right) \partial_\mu h = 0 \; . \label{2:derivative} \end{equation} Looking at \eqref{2:derivative}, if $m_2^2 \neq - \frac{m_1^2}{2}$ we obtain $\partial_\mu h(x) = 0$, which implies the transversality condition \eqref{transv} because of the harmonic gauge condition \eqref{intro:harmonic}, and inserting it into \eqref{2:trace} we get \begin{equation} (m_1^2 + 4m_2^2) h= 0\; . \label{2:m1+4m2} \end{equation} If $ m_1^2 + 4m_2^2 \neq 0 $, then \eqref{2:m1+4m2} implies the tracelessness condition $h(x)=0$ \eqref{traceless}, which, plugged into \eqref{2:eom} yields the massive wave equation \eqref{KKeq}. If instead $m_1^2 + 4m_2^2 = 0$, Eq. \eqref{2:eom} and $\partial_\nu h(x) = 0$ imply \begin{equation} (\partial^2 - m_1^2) H_{\mu \nu} = 0 \; , \end{equation} where $H_{\mu \nu}(x)$ is the traceless part of $h_{\mu \nu}(x)$ \begin{equation} H_{\mu \nu}\equiv h_{\mu \nu} - \frac{1}{4}\eta_{\mu \nu} h \; , \end{equation} which satisfies $\partial^\mu H_{\mu \nu}(x)=0$. Finally, considering the case $m_2^2 = - \frac{m_1^2}{2}$, Eq. \eqref{2:trace} becomes \begin{equation} (\partial^2 - m_1^2) h = 0 \; , \end{equation} which inserted into the EOMs \eqref{2:eom} gives again the wave equation \eqref{KKeq}.\\ The results of this section are summarized in the following table: \begin{center} \begingroup \setlength{\tabcolsep}{10pt} \renewcommand{\arraystretch}{1.5} \begin{tabular}{ c||c|c|c } Mass Condition & Propagation & Constraints & DOFs \\[6pt] \hline\hline $m_2^2 = - \frac{m_1^2}{2}$ & $(\partial^2 - m_1^2) h_{\mu \nu} = 0$ & $\partial^\mu h_{\mu \nu} =0$ & 6 \\[6pt] \hline $m_2^2 = -\frac{m_1^2}{4}$ & $(\partial^2 - m_1^2) H_{\mu \nu} = 0 $ & $\partial^\mu H_{\mu \nu}=0$ & 6 \\ [6pt] \hline $m_2^2 \neq - \frac{m_1^2}{2} \: \& \: m_2^2 \neq -\frac{m_1^2}{4}$ & $(\partial^2 - m_1^2) h_{\mu \nu} = 0$ & $\partial^\mu h_{\mu \nu}=0$, $h=0$ & 5 \\[6pt] \end{tabular} \endgroup \vspace{.2cm} {\footnotesize {\bf Table 1.} Mass conditions and corresponding DOFs.} \end{center} Only the third mass condition listed in Table 1 guarantees that the propagating graviton $h_{\mu\nu}(x)$ displays 5 DOFs, as expected for a massive spin-2 field. Notice that the FP prescription $m_1^2+m_2^2=0$ does satisfy this requirement: the FP theory, indeed, has been introduced in order to get the correct number of DOFs for MG \cite{deRham:2014zqa}. A theory of LMG satisfying the third mass condition, therefore, contains the FP tuning.\\ A comment is in order concerning the comparison with the FP theory. It has always been thought that the FP model is the unique local theory of MG that consistently (apart from the bad massless limit and the vDVZ discontinuity, but without ghost or tachyon instabilities) describes the five DOFs of a massive spin-2 representation of the Poincar\'e group. In particular, modifying the kinetic (derivative) part of MG away from that of general relativity results in ghost instabilities in the helicity-2 sector, which becomes obvious in the high-energy ($i.e.$ massless) limit, where this sector is supposed to reduce to GR, which is basically the statement that GR is the unique inconsistency-free theory of a massless helicity-2 particle. Moreover, adding a mass term other than the one of Fierz and Pauli $m_1^2 + m_2^2 \neq 0$ results in a scalar ghost (the ``sixth'' DOF) \cite{Boulware:1973my}. So the question arises naturally: how comes that this does not happen in the case discussed in this paper, where we just proved that it is possible to go outside the FP tuning, nonetheless keeping five DOFs ? The answer to this legitimate doubt resides in the definition of the physical sector of a gauge field theory. It is true that we are modifying the kinetic part of MG, but through a gauge fixing term. A true one, not like the FP ``mass'' term. We have in mind the case of any gauge field theory, where the gauge fixing term is necessary to define the partition function (and the Green functions it generates, starting from the propagator). Certainly the kinetic (derivative) part of the theory is modified, but in the non-physical sector (the gauge fixing one). This means that the observables are insensitive to this particular modification. As we are going to show in the next Section, the absence of the vDVZ discontinuity is exactly a consequence of this, since it concerns the continuity with GR of a particular observable (the scattering amplitude of two bodies). Therefore, as in Maxwell or Yang-Mills theory, the gauge fixing term does not change the physics of LG, despite the fact that it modifies its dynamic quadratic part. \section{Absence of the vDVZ discontinuity} The vDVZ discontinuity \cite{vanDam:1970vg,Zakharov:1970cc} is a well known issue affecting the FP theory of MG \cite{Rubakov:2008nh,Hinterbichler:2011tt}, and it is essentially a statement about the number of DOFs of a massive spin-2 particle. In this sense this Section is tightly related to the previous one. Unlike a massless graviton which has two DOFs, a massive graviton has five, as required by the representation theory of the Poincar\'e group. These five DOFs are comprised of the helicity-2 (two DOFs), helicity-1 (two DOFs), and helicity-0 (scalar, one DOF) components. In the short distance/high-energy (``massless'') limit of the theory, where helicity becomes a good quantum number, the helicity-2 component encodes the ``general relativistic'' part of the theory, while the helicity-0 component does not decouple from external sources (as far as the full graviton field couples minimally to matter), leading to a physical ``fifth force''. Hence the ``discontinuity'' of the linear theory.\footnote{We thank the Reviewer for this contribution} The common way to fix this problem of the FP theory is to adopt the Stueckelberg mechanism \cite{Hinterbichler:2011tt,Stueckelberg:1900zz}, at the rather expensive price of introducing additional fields in order to restore the diffeomorphism invariance broken by the mass terms. In this Section we show that, by choosing the harmonic gauge \eqref{intro:harmonic} belonging to the $k=-\frac{1}{2}$ class, the continuity with GR can be restored in a more natural way, without invoking extra fields. We will now follow the same steps described in \cite{Rubakov:2008nh}, which lead to the evidence of the presence of the vDVZ discontinuity in the FP theory, to verify, instead, its absence in the LMG with $k=\kappa=-\frac{1}{2}$ harmonic gauge fixing. As discussed in \cite{Rubakov:2008nh}, the propagator of the FP theory is \begin{equation}\label{fp_prop} \mbox{FP}: \quad G_{\mu \nu, \alpha \beta} = \frac{2}{p^2 + m_G^2} \left[\mathcal{I}_{\mu \nu, \alpha \beta} -\frac{1}{3}\eta_{\mu \nu}\eta_{\alpha \beta} + (p\text{-dependent terms}) \right]\; , \end{equation} where $m_G^2 = m_1^2 = -m_2^2$, while in the linearized limit of GR it is \begin{equation}\label{massless_prop} \mbox{GR}: \quad G_{\mu \nu, \alpha \beta} = \frac{2}{p^2} \Big[\mathcal{I}_{\mu \nu, \alpha \beta} -\frac{1}{2}\eta_{\mu \nu}\eta_{\alpha \beta} + (p\text{-dependent terms}) \Big]\; . \end{equation} In the $k=\kappa=-\frac{1}{2}$ harmonic gauge theory (denoted here by H), the propagator is given by \eqref{1:propagator}: \begin{equation} \mbox{H}: \quad G_{\mu \nu, \alpha \beta} = \frac{2}{p^2 +m_1^2} \left[ \mathcal{I}_{\mu \nu, \alpha \beta} - \frac{1}{2} \frac{p^2 - 2m_2^2}{p^2 - m_1^2 - 4m_2^2} \eta_{\mu \nu} \eta_{\alpha \beta}\right] \; . \end{equation} Following \cite{Rubakov:2008nh}, the interaction between two non relativistic bodies in the three cases (FP, GR and H) is computed by contracting the propagator with the 00-components of the energy-momentum tensors of the two bodies, $T_{\mu \nu}(x)$ and $T'_{\alpha \beta}(x)$, which are conserved ($i.e.$ $p_\nu \Tilde{T}^{\mu \nu} = 0$). In the non-relativistic case, all other components are negligible. So, taking into account the coupling constants of the three theories, which \textit{a priori} do not coincide, in the massless limit we get the interaction strengths \begin{align} \mbox{FP}: \quad G_{FP}\: \Tilde{T}^{\mu \nu} G_{\mu \nu, \alpha \beta} \Tilde{T}'^{\alpha \beta}=& \frac{4}{3}G_{FP}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{1}{p^2} \label{wrong_G} \; ,\\[10pt] \mbox{GR}: \quad G_{GR}\: \Tilde{T}^{\mu \nu} G_{\mu \nu, \alpha \beta} \Tilde{T}'^{\alpha \beta}=& G_{GR}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{1}{p^2} \; , \\[10pt] \mbox{H}: \quad G_{H}\: \Tilde{T}^{\mu \nu} G_{\mu \nu, \alpha \beta} \Tilde{T}'^{\alpha \beta}=& G_{H}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{1}{p^2} \; . \end{align} The constant $G_{GR}$ is the one that has been experimentally measured to a certain value $G_{GR}\equiv G_{\text{Newton}}$. Imposing that the couplings of FP and H coincide with that of GR, we get \begin{equation}\label{3:constants} \frac{4}{3} G_{FP}= G_{H} = G_{GR} \equiv G_{\text{Newton}}\; . \end{equation} We now consider the energy-momentum tensor of an electromagnetic wave (say $T'(x)$), which is traceless, and consider its gravitational interaction with that of a massive body ($T(x)$). In the massless limit we obtain the interaction strengths \begin{align} \mbox{FP}: \quad G_{FP}\: \Tilde{T}^{\mu \nu} G_{\mu \nu, \alpha \beta} \Tilde{T}'^{\alpha \beta}&= G_{FP}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{2}{p^2}= \frac{4}{3}G_{Newton}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{2}{p^2} \label{FP} \; , \\[10pt] \mbox{GR}: \quad G_{GR}\: \Tilde{T}^{\mu \nu} G_{\mu \nu, \alpha \beta} \Tilde{T}'^{\alpha \beta}&= G_{GR}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{2}{p^2}= G_{Newton}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{2}{p^2} \label{GR} \; , \\[10pt] \mbox{H}: \quad G_{H}\: \Tilde{T}^{\mu \nu} G_{\mu \nu, \alpha \beta} \Tilde{T}'^{\alpha \beta}&= G_{H}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{2}{p^2}=G_{Newton}\: \Tilde{T}_{00}\Tilde{T}'_{00}\frac{2}{p^2}\; , \end{align} where we used Eq. \eqref{3:constants}. It is clear from the above equations that, while the FP interaction differs from that of GR even in the massless limit, the $k=\kappa=-\frac{1}{2}$ harmonic MG result happily matches that of GR. \section{Summary and Discussion} In this Letter we highlighted a few properties of the covariant harmonic gauge which, as far as we know, have not been remarked elsewhere, although, in our opinion, deserve some attention. In textbooks, the harmonic, called also Lorenz, gauge is presented as a covariant condition on the gravitational perturbation $h_{\mu\nu}(x)$ which just simplifies the linearized Einstein equations (see for instance \cite{Carroll:2004st}). We believe that, besides this rather formal motivation, this choice can be strengthened by more physical motivations. Our observation comes from the close analogy between LG and ordinary gauge field theory. The approach of our paper, not that revolutionary indeed, is to treat the action (3) of Linearized Gravity as an ordinary free gauge field theory, like Maxwell theory, which, hence, needs a gauge fixing in order to be defined. Only after that, a mass term is added, thus avoiding {\it ab initio} the divergent massless limit. In this way the mass term is allowed to be a true one, without playing the double role of mass and gauge fixing term, as it happens in the FP theory. The FP tuning $m^2_1 + m^2_2 = 0$ is mandatory if the mass term is forced to serve as a gauge fixing too, as it is known. But, if LG is modified in its non-physical sector by a gauge fixing term (and the absence of the vDVZ discontinuity encourages to believe that this is the case), the mass parameters turn out to be less constrained, being granted that the DOFs are five, as it should and as we proved. As it is well known, the standard way to restrict the space of connections in order to eliminate the redundancy of the Green functions generating functional $Z[J]$, is the $\Phi\Pi$ procedure \cite{Faddeev:1967fc}, which consists in introducing in the path integral a $\delta$-functional, which is then exponentiated in order to be able to deal with a gauge fixed action. In the case of Maxwell theory, we have \begin{equation} Z^{(A)}[0] = \int DA_\mu\; e^{iS_{inv}[A] } \rightarrow \int DA_\mu\; \delta(F[A] -f(x))\; e^{iS_{inv}[A] } \propto \int DA_\mu\; e^{iS_{inv}[A]-\frac{i}{2\xi}\int (F[A])^2}\; , \label{zmax}\end{equation} where $F[A]=\partial A(x) $ identifies the covariant Lorenz gauge fixing condition, which is the unique linear possibility for the gauge field $A_\mu(x)$, and $\xi$ is the gauge parameter, which is unique as well. Taking, as it is, LG as a gauge field theory for a symmetric tensor $h_{\mu\nu}(x)$, the realization of the harmonic covariant gauge fixing condition \eqref{intro:gauge_kappa} should go analogously as follows \begin{equation} Z^{(h)}[0] = \int Dh_{\mu\nu}\; e^{iS_{inv}[h] } \rightarrow \int Dh_{\mu\nu}\; \delta(F[h;\kappa] -f(x))\; e^{iS_{inv}[h] } \propto \int DA_\mu\; e^{iS_{inv}[h]-\frac{i}{2k}\int (F[h;\kappa])^2}\; , \label{zh}\end{equation} where $S_{inv}[h]$ is the LG action \eqref{intro:inv}, and $F[h;\kappa]$ is the (vectorial) covariant gauge fixing condition on $h_{\mu\nu}(x)$ \eqref{intro:gauge_kappa}. The $\Phi\Pi$ procedure allows to have a well defined theory, with a propagator for the field $h_{\mu\nu}(x)$, which eventually can be given a mass, as discussed previously. As we remarked, the gauge fixing term \eqref{gfterm} depends on $two$ gauge parameters, $k$ and $\kappa$. The gauge parameter $k$ in \eqref{zh} (and in \eqref{gfterm}) is the analogous of $\xi$ for the Maxwell theory \eqref{zmax}: it defines, for instance, the Landau ($k=0$) gauge. We therefore might consider $k$ as a kind of ``primary'' gauge parameter, which is then fine-tuned by $\kappa$, which appears to be a ``secondary'' gauge parameter. We remark that, by substituting directly the harmonic gauge fixing condition \eqref{intro:gauge_kappa} into the action $S_{inv}[h]$ \eqref{intro:inv}, this non trivial structure of the gauge fixing is lost. According to this approach (rather standard, actually, despite the fact that it seems to be uncommon in the context of LG), one should refer to the harmonic gauge $\kappa=-\frac{1}{2}$ as a {\it class of choices}, rather than to a particular one. For instance, it makes sense to speak of a harmonic-Landau gauge, which corresponds to $k=0$ and $\kappa=-\frac{1}{2}$, or harmonic-Feynman gauge ($k=1,\ \kappa=-\frac{1}{2}$), and so on. In this Letter we hope to have given some insights concerning the meaning of the harmonic gauge in LG, motivating this choice in the case of a particular harmonic gauge, the one belonging to the larger $k=-\frac{1}{2}$ class. In this gauge, in fact, the five DOFs of the graviton can be given physical masses, which do not serve, as in the FP theory of LMG, as gauge parameters. The theory of LMG corresponding to the third condition in Table 1, which contains as a particular case the FP mass term, displays, we might say by construction, a good massless limit and, remarkably, it is not affected by the vDVZ discontinuity. Of course this physical property should depend on the particular mass term which has been chosen, and not on the gauge choice. Our claim is that, as it often happens in gauge field theory, in the particular $k=\kappa=-\frac{1}{2}$ - harmonic gauge, this property is apparent, differently from what happens in the standard FP theory, where it is absent, as it is well known. Probably the deep reason for this flaw is the fact the FP mass serves, quite unnaturally, as gauge fixing tool to allow the existence of a propagator, which nonetheless lacks a good massless limit, more than a real mass parameter. \medskip
{ "redpajama_set_name": "RedPajamaArXiv" }
9,517
{"url":"https:\/\/stats.stackexchange.com\/questions\/155396\/does-binomial-distribution-have-the-smallest-possible-variance-among-all-reason","text":"# Does binomial distribution have the smallest possible variance among all \"reasonable\" distributions that can model binary elections?\n\nImagine an election where $n$ people make a binary choice: they vote for A or against it. The outcome is that $m$ people vote for A, and so A's result is $p=m\/n$.\n\nIf I want to model these elections, I can assume that each person votes for A independently with probability $p$, leading to the binomial distribution of votes: $$\\text{votes for A}\\sim\\mathsf{Binom}(n,p).$$ This distribution has mean $m=np$ and variance $np(1-p)$.\n\nI can make other assumptions as well. For example, I can assume that probability $p$ is itself a random variable coming from some distribution (e.g. beta); this can lead to a beta-binomial distribution of votes for A. Or I can assume that people vote in groups of $k$, where each group of $k$ people makes the same choice and it is A with probability $p$. This will lead to a binomial distribution with larger variance. In all these cases, variance of the resulting distribution is larger than in the simplest binomial scheme.\n\nCan I make a claim that binomial distribution has the smallest possible variance? In other words, can this claim be somehow made precise, e.g. by specifying some reasonable conditions on the possible distributions? What would these conditions be?\n\nOr is there maybe some reasonable distribution that has lower variance?\n\nI can imagine lower variance, e.g. when all $n$ people agree in advance on how they will vote, and so $\\text{votes for A}$ is not really a random variable, but a fixed number $m$. Then the variance is zero. Or maybe almost all of them agreed but a few people did not, and then one can have tiny variance around $m$. But this feels like cheating. Can one have smaller-than-binomial variance without any prearrangements, i.e. when each person votes in some sense randomly?\n\n\u2022 A related question: Are these data underdispersed? If so, what mechanisms may explain this? Jun 3, 2015 at 22:42\n\u2022 The poisson binomial distribution has maximum variance when all p_i same (ie when reduced to binomial) for fixed mean and n.en.m.wikipedia.org\/wiki\/Poisson_binomial_distribution Sep 23, 2016 at 19:42\n\u2022 @seanv507 Thank you, yes. I realized this myself back in 2015, see my comment under whuber's answer. But if you want to post this as an answer (elaborating on what Poisson binomial is), I will be happy to upvote. Sep 23, 2016 at 19:48\n\nNo.\n\nSuppose the voters consist of $n=2k$ married pairs. The husbands get together and decide to vote against their wives, who themselves choose randomly. The outcome is always $k$ votes for each of the candidates, with zero variance.\n\nYou might cry foul because the husbands are not voting randomly. Well, they are--they just happen to be tied closely with the random votes of their wives. If that bothers you, change things a bit by having each husband flip ten fair coins. If all ten are heads, he will vote with his wife; otherwise he votes against her. You can check that the election outcome still has small (albeit nonzero) variance, even though every vote is unpredictable.\n\nThe crux of the matter lies in the negative covariance between two voting blocs, males and females.\n\n\u2022 Thanks, @whuber. It seems that there is another way to achieve lower variance too: voters should vote for A with different probabilities $p_i$ that are distributed around $p$. The compound distribution is apparently known as Poisson binomial, and if its mean $\\sum p_i$ is fixed at $np$, then the variance will be largest for the binomial case when all $p_i=p$. If probabilities are not equal, the variance will necessarily be smaller. Jun 3, 2015 at 22:46\n\u2022 Sure: there are plenty of ways to achieve under-dispersion (as I see you belatedly realized!). I just thought this husband-wife example was sufficiently clear, amusing, and memorable to be worth writing down. Because it amounted to an answer, it would not have been appropriate to bury it in a comment (which is how it started out life).\n\u2013\u00a0whuber\nJun 3, 2015 at 22:48\n\nDouble-no (it maximises the variance)\n\nThe answer from whuber is excellent. To supplement that answer, it is also worth examining what happens if you assume that the votes are independent. If we take the votes as mutually independent with probabilities $$p_1,...,p_n$$ then the mean and variance are:\n\n$$\\mathbb{E}(S_n) = \\sum_{i=1}^n p_i \\quad \\quad \\quad \\quad \\quad \\mathbb{V}(S_n) = \\sum_{i=1}^n p_i - \\sum_{i=1}^n p_i^2.$$\n\nIf we condition on a fixed expected value $$\\mu = \\mathbb{E}(S_n)$$ then it can be shown that the maximum variance is achieved when $$p_1 = \\cdots = p_n = \\mu$$. (To demonstrate this you can set up the Lagrangian optimisation to attain this solution.) So not only does the binomial distribution not minimise the variance, it maximises the variance out of all possible cases where we have independent votes.","date":"2023-03-26 13:25:37","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 4, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.8515486717224121, \"perplexity\": 556.7644149967804}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2023-14\/segments\/1679296945472.93\/warc\/CC-MAIN-20230326111045-20230326141045-00591.warc.gz\"}"}
null
null
Q: How to programmatically exit from Android Accessory Mode I've a system with an Android Tablet + an embedded board implementing AOA Protocol. All works fine, embedded board when connected to Android device send ACCESSORY_START command and Android enters in AOA mode. Then normal flow between two works fine too. Now I've a question: There is a way from embedded target to disable AOA mode without physically remove USB cable ? A sort of ACCESSORY_STOP, so my Android target regain usual PID:VID instead of PID:VID for AOA mode ? Or there is a way to do that programmatically with Android code ? A: If you want to close the accessory on app exit (without unplugging it), call System.exit(0) in Activity onDestroy(). This kills all app threads, including the accessory read thread which blocks the input stream. The accessory can then be reopened without re-plugging. This is a partial answer to your question (just to make it clear for the watchful pedants diligently monitoring other people's business). But it's useful, because at least you can exit your app and then reconnect the accessory again without unplugging. And yes, the problem is still with us in 2017., although it was documented ages ago. A: I am dealing with the same issue in an embedded project. In the case of Android devices, I believe that power needs to be removed from the USB pins in order to cause a reconnection. A USB reset at the data level from the host is not enough. I have personally tested resetting the bus, but the device simply reconnects as accesory mode. If the android accessory device has the ability to power the controller on or off, then a physical USB reconnection can be simulated. In the case of my embedded platform this is performed by using echo 0 or echo 1 into /sys/class/gpio/123/value where 123 is the pin number defined in a header file in the linux kernel sources. This pin number must exported to user space, and must be aligned with the schematic of the embedded project to the pin that controls the powering of the controller which may be called PWR_EN or ENABLE. Good luck!
{ "redpajama_set_name": "RedPajamaStackExchange" }
3,635
Q: Html button with no defined click event still calls a function I have 2 <buttons> in my html code, and one of them has an onclick function, but the other is just a button I haven't defined yet. The weird thing is that the button that hasn't been defined, has the same onclick property as the other. Could someone please explain why this is happening? Here is a code snippet: saveRuleSelections: function() { let blackjackRules = []; let rules = document.getElementsByClassName("rule"); for (let i = 0; i < rules.length; i++) { blackjackRules.push(rules[i].value); } let jsonBlackjackRules = JSON.stringify(blackjackRules); localStorage.setItem("blackjackRules", jsonBlackjackRules); document.getElementById("rules_overlay").style.display = "none"; } <form> <p>Surrender Allowed: <select class="rule"> <option value="early">Early</option> <option value="late">Late</option> <option value="no" selected>No</option> </select> </p> <button id="select_rules_button" onclick="trueCountApp.saveRuleSelections()">Select Rules</button> <button>Restore Default</button> </form> A: Both forms have the same value of submit since their inside the form with no different value now both will take the same value of submitting the form and therefore firing the function, it's like a clone. Try <form> <p>Surrender Allowed: <select class="rule"> <option value="early">Early</option> <option value="late">Late</option> <option value="no" selected>No</option> </select> </p> <button id="select_rules_button" onclick="trueCountApp.saveRuleSelections()">Select Rules</button> <button type="reset" value="Reset">Restore Default</button> </form> A: Could it be that your second button is just performing its default action? The default action depends on the button's type, which defaults to submit (except in IE). what's the standard behavior when < button > tag click? will it submit the form?
{ "redpajama_set_name": "RedPajamaStackExchange" }
4,845
\section{Introduction} \begin{comment} Add introduction why we are using edge detection... Biological inspiration of different objects in a picture being based off their edges. The current SNN image networks primarily consist of NxN neuron networks which correlate to each pixel in an image. There have been simplified models that find the primary ``features'' or pixels of an image but the network still uses convolutional methods requiring far more neurons than our proposed model. \textbf{CITE PAPER FROM CLASS} \end{comment} Neural encoding plays an important role in the brain-inspired neuromorphic systems, which use trains of action potentials, \textit{i.e.} spike trains, to process the input information. Neural encoding refers to the process of representing stimulus features in the form of spike trains. Before any type of learning or training can occur in spiking neural networks (SNNs), these spike trains must first be produced from input data using particular encoding mechanisms. As also mentioned in \cite{neural_encoding}, the study of neural coding can be divided into three questions, what is being encoded? how is it being encoded? and what is the precision of the encoding? In this paper, we are focusing on the encoding of static images for image classification with SNNs into spike trains. Two of the well-known methods for encoding static images are firing rate-based encoding \cite{ratecoding1,ratecoding2,ratecoding3} and population rank order encoding \cite{rankorder1,rankorder2}. In the rate-based encoding, each input is a Poisson spike train with a firing rate proportional to the intensity of the of the corresponding pixel in the image \cite{ratecoding3}. Although this approach has shown to be effective in practice, it normally requires very high firing rates, therefore it is not computationally efficient \cite{Rueckauer2017, Pfeiffer2018}. The population rank order encoding utilizes receptive fields to distribute input over several neurons, each of which fires only once during the coding interval based on the extent an input value belongs to its corresponding receptive field \cite{selectionencoding, LOBO20181}. This method drastically reduces the spikes that should be processed by network, however it significantly increases the network size. Another common approach is to represent the pixels of the image themselves as spikes and represent each pixel as a separate neuron in the input layer of the SNN \cite{vaila2019deep}. This approach, however, requires a large network of neurons compared to the even the aforementioned approaches. Even with some feature reduction in the images the network is still non-ideal in its size and immutable input size \cite{vaila2019deep}. Herein, we use temporal coding, which is traditionally suitable for encoding time-series and streaming data, to encode static images. Temporal encoding is an efficient and fast method that generates spikes at exact points in time based on the change in the input stimulus signal. \begin{comment} Temporal coding is most similar to the biological processes that occurs in the brain as a result of stimulus as the action potentials are directly correlate to the input stimuli \textcolor{red}{CITATION}. In 1959, Hubel and Wiesel demonstrated that moving an edge or line as stimulus in a visual cortex experiment to understand how that edge affected the receptive fields and thus the activity of action potentials firing in the visual cortex for a cat. \end{comment} To encode static images into the signals needed as input to the previously mentioned encoding algorithms, we use edge detection along with a conversion algorithm to convert the static images into two signals which will then be converted into two separate spike trains to be input into an SNN. As mentioned above, one of the important questions that needs to be addressed in the neural coding is the precision of the encoding \cite{neural_encoding}. The objective here is to generate spike trains with reduced number of spikes without losing the important information content of the signal. Therefore, evaluating the efficiency of the temporal encoding mechanism becomes very important. In this paper, in order to assess our proposed approach, we use MNIST handwritten digits \cite{MNIST} as representative static images, convert them to signals, encode the signal into spike trains, reconstruct the signals and compare them with original signals, and eventually reconstruct the static MNIST images. The remainder of this work is organized as follows. Section 2 discusses the image-to-signal conversion approach using an edge detection algorithm. Section 3 describes the adaptive temporal encoding mechanism. Section 4 provides a thorough evaluation of our proposed static image encoding method using intensive simulations and introducing a new fitness function. Finally, section 5 concludes the paper by proposing possible directions for future work. \begin{figure} \centering \includegraphics[width=3.3in]{/x_y_edges_image.png} \caption{(a) The original image. (b) Canny edge detection output. (c) X coordinate signal from image (b). (d) Y coordinate signal from image (b). Algorithm \ref{algo:coord_extract} was used to obtain the signals in (c) and (d).} \label{fig:x_y_edge_image} \end{figure} \begin{algorithm} \DontPrintSemicolon \SetNlSty{text}{}{:} \SetAlgoNlRelativeSize{0} \SetKwData{Thresh}{threshold}\SetKwData{X}{x}\SetKwData{Y}{y}\SetKwData{Image}{image} \SetKwData{List}{[\ ]} \SetKwFunction{Append}{.append}\SetKwFunction{Len}{length} \KwIn{A 2D image array of pixel intensities} \KwOut{Two arrays, x \& y, consisting of the x and y components of pixels with intensities greater than zero} \BlankLine \X$= \List$\; \Y$= \List$\; \For{$row = 1$ \KwTo $\Len(\Image)$}{ \For{$col = 1$ \KwTo $\Len(\Image[row])$}{ \If{$\Image[row][col] > 0$}{ $\X\Append(col)$\; $\Y\Append(row)$\; } } } \caption{Coordinate Extraction} \label{algo:coord_extract} \end{algorithm} \section{Image-to-Signal Conversion Method} In image processing, edge detection is used to find the edges of objects or shapes in images. This process, in general, consists of identifying where there is an abrupt change in the pattern of pixel intensities. The edge of an object represents the object's general shape or contour and therefore aids in identifying that object. This idea that an object's edges may contain enough information to classify an image, is what led us to investigate if encoding the edges of an image instead of the image itself would lead to a reduction in spikes in spike trains. From here, we implemented a Python program which employs the OpenCV Canny edge detection to find the edges of the MNIST handwritten digit dataset \cite{opencv_library}. Canny edge detection consists of four different image processing steps: (1) Gaussian Filter, (2) Sobel Filters, (3) Non-maximum Suppression, and (4) Hysteresis Thresholding. The first two steps in the Canny edge detection process involve applying two filters to the image using convolution. Convolution allows neighboring pixels around a central input pixel to be weighted and then summed up to determine the intensity of the central output pixel in the same location as the input pixel. In the case of Canny edge detection, a 5x5 Gaussian filter is first applied to smoothen the image and reduce the image noise \cite{opencv_library}. The Sobel filter is then applied to the smoothened image to get a preliminary edge detected image. Applying the Sobel filter computes the first derivative in both the horizontal and vertical directions which corresponds to two output images. These two output images, horizontal and vertical, are then used to find the edge gradient and the direction of the line perpendicular to the tangent line of the edge \cite{opencv_library}. The result is an image which has pixels with higher intensities roughly where the edges were located. While the resulting image from applying the Sobel filter process gives us the edges of the image, these edges are not ideal and the number of edge pixels are not minimized. This is not ideal because we wish to minimize the number of pixels that represent the edges so that the signal length and consequently spike train length is minimized. The next steps in Canny edge detection aid in minimizing the edge pixels. In the third step, a non-maximum suppression algorithm is used to suppress certain pixels that are not actually part of an edge. The algorithm looks at the pixels in the output of the second step and then, using the direction from the second step, analyzes the pixel and its surrounding pixels to determine if it is on the edge. If the pixel is determined to not be on the edge, then its intensity is set to zero \cite{opencv_library}. The final step in the Canny edge detection is to use hysteresis thresholding to eliminate any remaining pixels which are not actual edge pixels and output an image with semi-connected thin edges. The algorithm, specifically, looks for pixels which have intensities higher than a given threshold and determines them as edge pixels. If the pixel has an intensity smaller than a given lower threshold, then it is determined to not be on the edge. Finally, if the pixel is between the upper and lower intensity thresholds, then pixel is determined to be on the edge if and only if it is connected to an already determined edge pixel \cite{opencv_library}. After applying the Canny edge detection process, the edges of the original image in Figure \ref{fig:x_y_edge_image} (a) are detected and Figure \ref{fig:x_y_edge_image} (b) is generated. Figure \ref{fig:x_y_edge_image} (b) is then passed into Algorithm \ref{algo:coord_extract} to extract the X and Y coordinates of the edge pixels in the image and create the X and Y signals which will be later encoded into spike trains. As shown in Figure \ref{fig:x_y_edge_image} (c) and (d), there is a significant reduction in the length of the X and Y signals obtained from the edge image compared to those of the original raw image. In particular, for a random sample of 1000 MNIST digits, \textit{i.e.} 100 samples of each digit 0 through 9, there is a 41.7\% reduction in the length of the signal for edge images compared to the original images. \begin{algorithm} \DontPrintSemicolon \SetNlSty{text}{}{:} \SetAlgoNlRelativeSize{0} \SetKwData{Thresha}{$SamplingThreshold$}\SetKwData{Threshb}{$EncodingThreshold$}\SetKwData{S}{s}\SetKwData{Count}{count} \SetKwData{SA}{$s_a$}\SetKwData{N}{n}\SetKwData{Out}{out}\SetKwData{SP}{startpoint} \SetKwFunction{Len}{length}\SetKwFunction{Ceil}{ceil} \SetKwFunction{Zeros}{zeros}\SetKwFunction{Abs}{abs}\SetKwFunction{Sum}{sum} \SetKwFunction{TEnc}{TemporalEncoding} \KwIn{\S signal, \Thresha, \Threshb} \KwOut{\Out, \SP, \Count} \BlankLine \Count$= \Zeros(\Len(\S)-1)$\; \For{$t = 0$ \KwTo $\Len(\S)-1$}{ $\Count[t] = \Ceil(\Abs((\S[t+1]-\S[t]) / \Thresha))$\; } \SA$= \Zeros(\Sum(\Count)+1)$\; \N$= 0$\; \For{$i = 0$ \KwTo $\Len(\S)-1$}{ \For{$j = 0$ \KwTo $\Count[t]$}{ $\SA[\N] = \S[i] + (j) / \Count[t]*(\S[i+1] - \S[i])$\; \N$+=1$\; } } $\SA[\Len(\SA)-1] = \S[\Len(\S)-1]$\; $\Out, \SP = \TEnc(\SA, \Threshb, ...)$\; \caption{Temporal Encoding with Adaptive Sampling} \label{algo:adapt_encode} \end{algorithm} \begin{algorithm} \DontPrintSemicolon \SetNlSty{text}{}{:} \SetAlgoNlRelativeSize{0} \SetKwData{Threshb}{$EncodingThreshold$}\SetKwData{S}{s}\SetKwData{Count}{count} \SetKwData{SA}{$s_a$}\SetKwData{Out}{out}\SetKwData{SP}{startpoint}\SetKwData{VarM}{m} \SetKwData{Recon}{$recon$}\SetKwData{Recona}{$recon_a$}\SetKwData{Spikes}{spikes} \SetKwFunction{Append}{.append}\SetKwFunction{Len}{length}\SetKwFunction{Ceil}{ceil} \SetKwFunction{Zeros}{zeros} \SetKwFunction{Dec}{Decoding} \KwIn{\Spikes, \Threshb, \SP, \Count} \KwOut{\Recon} \BlankLine \Recona$=\Dec(\Spikes,\Threshb,\SP)$\; \VarM$= 0$\; \Recon$ =\Zeros(\Len(\Count)+1)$\; \For{$t = 0$ \KwTo $\Len(\Count)$}{ \Recon$[t]=\Recona[\VarM]$\; \VarM$+= \Count[t]$\; } \Recon$[\Len(\Recon)-1]=\Recona[\Len(\Recona)-1]$\; \caption{Temporal Decoding with Adaptive Sampling} \label{algo:adapt_decode} \end{algorithm} \section{Adaptive Temporal Encoding} \par Once the static images are converted to signals, as described in the previous section, temporal encoding mechanisms can be used to generate spike trains from the produced signals. In this step, selection and optimization of temporal encoding methods play an important role to achieve a high precision signal-to-spike train conversion. In our initial experiments, we used the known step-forward (SF) encoding \cite{selectionencoding} method to encode the X and Y signals obtained from edge detection. However, we noticed that using a fixed sampling rate to encode the signal will lead to either an overestimation (with high sampling rate) or an underestimation (with low sampling rate), which leads to high computation cost or low encoding precision, respectively. Thus, in this work, we propose an adaptive sampling approach, which works as a preprocessing step for temporal encoding mechanisms. The objective of the adaptive sampling is to increase the sampling rate when there are abrupt changes to the signal and reduce the sampling rate when the signal exhibits more gradual variations. The adaptive sampling algorithm for temporal encoding is presented in Algorithm \ref{algo:adapt_encode}. The algorithm first samples the signal with fixed intervals and then calculates how many more samples, (\textit{\textbf{count}} in Algorithm \ref{algo:adapt_encode}), are required between two consecutive points based on the change in signal between the two points. Next, the signal is sampled again, this time based on the number of samples calculated in the previous step, inserting more points for higher signal resolution based on the rate of change. Finally, the adaptively-sampled signal is converted to a spike train using any temporal encoding mechanisms such as threshold-based representation (TBR), SF, etc. \cite{selectionencoding}, as shown in line 11 of the Algorithm \ref{algo:adapt_encode}. The adaptive sampling approach includes a sampling threshold which defines the sensitivity of the algorithm to changes in the signal. The lower the threshold value is, the more samples will be taken (Line 3 of the Algorithm \ref{algo:adapt_encode}) between two consecutive points. This adaptive sampling thus optimizes the average firing rate (AFR) to be seen in section \ref{sec:sim-res} for minimal spikes in the resulting spike trains without compromising accuracy. Decoding the spike trains generated by adaptive sampling-based temporal encoding approaches requires a post-processing step that is described in Algorithm \ref{algo:adapt_decode}. Once the spike trains are decoded using normal decoding methods for spike trains \cite{selectionencoding} (Line 1 of Algorithm \ref{algo:adapt_decode}), the sample counts stored in the \textbf{\textit{count}} array during the adaptive sampling will be used to reconstruct the original signal. Here, without loss of generality, we used the adaptive sampling approach along with SF and TBR methods to develop an adaptive temporal spike encoding mechanism for static images. The TBR and SF encoding algorithms and their corresponding decoding algorithm is provided in Appendix A. \begin{figure*}[] \centering \includegraphics[width=6.5in]{/metrics/sf_comb_plot.png} \caption{Performance metrics for adaptive SF encoding using various threshold values. (a)-(d) X signal and (e)-(h) Y signal.} \label{fig:sf_metrics} \end{figure*} \begin{figure*}[!t] \centering \includegraphics[width=\textwidth]{/metrics/tbr_comb_plot.png} \caption{Performance metrics for adaptive TBR encoding using various threshold values. (a)-(d) X signal, and (e)-(h) Y signal.} \label{fig:tbr_metrics} \end{figure*} \section{Simulation Results} \label{sec:sim-res} In this section, we evaluate our adaptive temporal encoding approach by using MNIST handwritten digits \cite{MNIST} as representative static images, convert them to signals, encode the signal into spike trains, reconstruct the signals and compare them with original signals using various indicator and error metrics. For samples of complete encoding-to-reconstruction process on MNIST 0-9 digits images, readers can refer to Appendix B. \subsection{Error and indicator Metrics} Here, the difference between the original and reconstructed signals is considered to assess the precision and efficiency of the encoding methods. We use root mean square error (RMSE) and signal-to-noise ratio (SNR) metrics to assess the precision of the encoding approaches. SNR is defined as \begin{equation} SNR = 20 \cdot \log \frac{Power(s)}{Power(s-r)} [dB] \end{equation} where $s$ is the original signal, $r$ is the reconstructed signal, and $Power$ is calculated as \begin{equation} Power (s)=1/N \sum_{k=0}^{N-1}|s(k)|^2 \end{equation} \par \noindent where $N$ is the number of samples. RMSE is defined as \begin{equation} RMSE = \sqrt{\frac{\sum_{t=1}^N(s_t-r_t)^2}{N}} \end{equation} On the other hand, average firing rate (AFR) and spike count metrics are utilized to evaluate the computational efficiency of encoding methods. AFR indicates how saturated the spike train is and is defined as \begin{equation} AFR = \frac{\sum_t^N|sp_t|}{N} \end{equation} where $sp$ is the number of all spikes in a given spike train \cite{selectionencoding}. Here, the objective is increasing the SNR while decreasing RMSE, AFR and spike count. Figures \ref{fig:sf_metrics} and \ref{fig:tbr_metrics} exhibit the performance metrics for the adaptive and edge detected SF and TBR encoding experiments, respectively, with encoding and sampling thresholds ranging from 0.1 to 2.0 with 0.1 intervals. \subsection{Threshold Optimization} \par To co-optimize the sampling threshold in the adaptive sampling algorithm and encoding threshold in the temporal encoding mechanisms (see Appendix A), we introduce a Fitness function that combines several of the aforementioned metrics, as expressed in (\ref{alg:fitness}). The higher $Fitness$ value represents better reconstruction. \begin{equation} \label{alg:fitness} Fitness = \frac{SNR}{{RMSE}\times{Spike Count}} \end{equation} Figure \ref{fig:sf_tbr_fitness} shows the reconstruction fitness of the adaptive SF and TBR encoding methods for various sampling and encoding thresholds ranging from 0.1 to 2.0. The maximum fitness values for adaptive SF and TBR encoding methods are achieved at (\textit{SamplingThreshold}, \textit{EncodingThreshold}) equals (0.1, 0.2) for SF and (1.0, 0.9) for TBR, respectively. By contrast, the optimal \textit{EncodingThreshold} for non-adaptively sampled experiments are 2.0 (X) and 1.2 (Y) for SF and 2.0 (X) and 0.9 (Y) for TBR. Table \ref{tab:comparison} provides a comparison between adaptive SF and TBR encoding with the optimized threshold values mentioned above. As listed in the table, TBR is more efficient in terms of spike count, but the SF exhibits a greater SNR and smaller RMSE making it more desireable for precise reconstuction. It should be noted, however, that the average number of spikes is greatly increased due to the adaptive sampling increasing the resolution of the signal. It is worth noting that the fitness function can be adjusted, using $m$ and $n$ parameters in (\ref{eq:fitness_adjust}), based on the specific application requirement to emphasize on the precision or computation efficiency: \begin{equation} \label{eq:fitness_adjust} Fitness (m, n) = \frac{SNR}{{RMSE^{(m)}}\times{Spike Count^{(n)}}} \end{equation} As can be seen in table \ref{tab:comparison}, the lowest RMSE values occur in the experiments where adaptive sampling was used versus without adaptive sampling. The average number of spikes in all cases where edge detection was used does marginally reduce the number of spikes. \begin{figure}[!t] \centering \includegraphics[width=\linewidth]{/fitness/sf_tbr_fitness.png} \caption{Fitness plots. (a)-(b) The X signal. (c)-(d) The Y signal. (a) and (c) use SF encoding. (b) and (d) use TBR encoding.} \label{fig:sf_tbr_fitness} \end{figure} \begin{table}[] \caption{Performance comparison of the adaptive SF and TBR encoding with optimized thresholds for the x and y signals. \label{tab:comparison} \centering \resizebox{\columnwidth}{!}{% \begin{tabular}{c c c c c c c c c} \hline Method & Encoding & & RMSE & AFR & SNR & Avg. Spike \# & Fitness \\ \hline \multirow{4}{1.5cm}{Adapive Sampling w/ Edge Detection} & \multirow{2}{*}{SF} & X & \textbf{0.12} & 0.49 & \textbf{84.33} & 1538.7 & \textbf{0.47}\\ & & Y & \textbf{0.08} & 0.5 & \textbf{101.39} & 95.1 & 12.82\\ & \multirow{2}{*}{TBR} & X & 1.26 & 1.0 & 42.92 & 311.98 & 0.14\\ & & Y & 1.1 & 1.0 & 45.63 & 20.02 & 2.18\\ \hline \multirow{4}{1.5cm}{Adaptive Sampling w/o Edge Detection} & \multirow{2}{*}{SF} & X & \textbf{0.12} & 0.49 & \textbf{84.46} & 1555.9 & 0.46\\ & & Y & \textbf{0.08} & 0.5 & \textbf{102.72} & 93.64 & \textbf{13.27}\\ & \multirow{2}{*}{TBR} & X & 1.0 & 1.0 & 46.78 & 315.67 & 0.18\\ & & Y & 1.07 & 1.0 & 46.02 & 19.73 & 2.3\\ \hline \multirow{4}{1.5cm}{Only Edge Detection} & \multirow{2}{*}{SF} & X & 3.26 & 0.54 & 27.11 & 49.07& 0.17\\ & & Y & 0.64 & 0.19 & 54.84 & 15.13 & 5.63\\ & \multirow{2}{*}{TBR} & X & 10.43 & 0.47 & 9.28 & 39.75 & 0.05\\ & & Y & 1.08 & 0.23 & 46.29 & 19.06 & 2.61\\ \hline \multirow{4}{1.5cm}{Conventional} & \multirow{2}{*}{SF} & X & 3.01 & 0.43 & 28.55 & 70.43 & 0.13\\ & & Y & 0.64 & 0.11 & 54.96 & 14.83 & 5.82\\ & \multirow{2}{*}{TBR} & X & 15.85 & 0.15 & -0.03 & 22.02 & 0.03\\ & & Y & 1.02 & 0.13 & 46.86 & 18.73 & 2.79\\ \hline \end{tabular} } \end{table} \section{Conclusion and Future Work} \label{sec:conclusion} In this paper, we proposed an adaptive temporal encoding method to convert the static images into spike trains. The proposed encoding approach aims to allow static images to be processed by SNNs with smaller networks, using only two inputs x and y. However, when it comes to temporal encoding, the encoding precision becomes very important. Therefore, we performed intensive simulations to evaluate and optimize our proposed encoding approach. We introduced a novel fitness function which combines the accuracy and efficiency metrics to optimize the hyperparameters of the proposed adaptive temporal encoding. The results obtained exhibit an accurate spike encoding of MNIST handwritten digits as representative static images. Future work includes evaluating the effectiveness of the proposed approach for the whole SNN application through implementing it on neuromorphic hardware, \textit{e.g.} Loihi \cite{Loihi}, for image classification application on a variety of datasets. \section*{Acknowledgment} This work is partially supported by an ASPIRE grant from the Office of the Vice President for Research at the University of South Carolina. \bibliographystyle{IEEEtran}
{ "redpajama_set_name": "RedPajamaArXiv" }
1,453
Tourist attractions across the north and north-east of Scotland celebrated a bumper year in 2018 with record numbers of visitors. A 19th-century water feature at Crathes Castle has been restored following a lengthy programme of conservation and repair work undertaken by the National Trust for Scotland. An Aberdeen University law graduate is investigating the possibility that members of his family fought on both sides in the Great War. VisitScotland have launched a new ghost trail at Crathes Castle - just in time for Halloween. It was the middle of the 17th century and the sounds of war thundered through the halls of one of Aberdeenshire's strongholds. Scotland's finest tree collections have been celebrated at Crathes Castle in Banchory. The National Trust has altered a controversial event at Aberdeen's Crathes Castle due to pressure from mental health charities. Hundreds of people took part in a new charity event at the weekend in the grounds of a Deeside castle. A new initiative has been launched to give tourists and locals a greater chance to experience the history and heritage of the north-east. A cancer charity is launching a new event to raise cash this autumn. Knitting fans have been spinning a good yarn to help transform a popular tourist spot in Aberdeenshire. Classic car enthusiasts will be flocking to Milton of Crathes in Banchory tomorrow for the 21st vintage Car and Motor Cycle Rally. Tourism levels in the north-east soared last year with three major attractions in Aberdeenshire recording remarkable visitor numbers. Tree surgeons put their skills to the test yesterday when they felled two giants in Aberdeenshire. The organiser of an ill-fated north-east music festival has avoided jail after cheating the taxman of nearly £100,000. The organiser of a failed music festival at a historic north-east landmark has admitted swindling the tax man out of nearly £100,000. PICTURES: Is this Deeside Castle's infamous ghost? Pictures have surfaced appearing to show an infamous ghost said to haunt the hallways of a Deeside castle. Those were the days: when fine country living meant you could just laze around and ring a bell if you needed anything from the servants. An historic Aberdeenshire castle will travel back in time this festive season with a war time-themed event. With its granite grey buildings and this week's foggy weather, Aberdeen is once again shaping up its spooky ambience in time for Halloween.
{ "redpajama_set_name": "RedPajamaC4" }
5,277
ACCEPTED #### According to Index Fungorum #### Published in in Aptroot, Diederich, Sérusiaux & Sipman, Biblthca Lichenol. 64: 94 (1997) #### Original name Lichenopeltella megalosporae Diederich ### Remarks null
{ "redpajama_set_name": "RedPajamaGithub" }
3,668
Propergaanda / News / Opinion / Have We Taken the Hum Awards Boycott Too Far? Have We Taken the Hum Awards Boycott Too Far? Hum TV award week this year coincided closely with elections in Pakistan – naturally, this meant a large number of Pakistani celebrities headed to Canada for rehearsals earlier. This had sparked a major debate on social media, with the public demanding to know why it was so easy for celebs to abandon their 'civic duty' in lieu of what most consider a frivolous pursuit in comparison. What's more, a petition was circulating online aiming to boycott this year's awards. The petition is focusing on the 'hypocrisy' of Pakistani celebrities: "We are tired of the hypocrisy of these celebrities who can come in ads portraying patriotism to sell their brands and make money, but who do not even bother to vote when each vote counts the most." Farhan Saeed reprimands fellow celebrities for flying out to Toronto at 'such a crucial time'. Amidst the inquiries, Hum TV has released an official statement addressing the issue – essentially saying that "since a lot of resources have to be committed for the event it is not possible to change the date". Hum TV pointed out that the date had been fixed six months in advance. Conversely, Pakistan's election dates had not been finalized at the time. In fact, deliberation over the exact election date was still ongoing even by the time May rolled around. However, the issue that needs to be addressed is this – are celebrities perhaps receiving too much backlash for missing out on elections? Hum TV awards is always a highly publicised, much-anticipated affair. Actors, actresses, directors, and songwriters alike work hard all year to make the nominees – and for some artists, this award show is their "big break". The competition is fierce and spirits high. Although the two events cannot be compared with respect to magnitude and impact, the effort put into the award show is not unlike that which is invested in the electoral process to make it as successful and smooth as possible. In fact, Pakistani designer Feeha Jamshed is of the opinion that all celebrities who left to attend the awards 'also performed their civic duty'. Here is part of a message she posted on Instagram: Currently, there are two opposing views on social media: the one above and the other one which reiterates that it was 'careless' of celebrities to leave the country at the time of voting. However, it is not as simple as that. The more complex question is – why are we dragging our fellow Pakistanis through the dirt at a time when we need to unite ourselves? In fact, the very political parties whose right to support from the public we are apparently fighting for are the ones demanding that people remain united. We are all doing our part. Yes, it can be argued that precious votes were wasted. But boycotting Hum TV awards will show an insensitivity towards the hard-working creative sector of the country – and believe it or not, creativity can be just as important as politics. Before you praise Andrew turned Adnan Tate, don't forget why he was banned from all… Farmers who lost everything to massive floods will receive free wheat seeds from November 10 Maniha Hashmi becomes Pakistan's first Fulbright Scholar at Coumbia University By Rana Abdullah Hammad A misogynist and controversial Andrew Tate was finally banned from social media platforms!
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
2,760
Q: Define a function inside of a proof in Lean In Lean, we can define a function like this def f (n : ℕ) : ℕ := n + 1 However, inside a proof this is no longer possible. The following code is invalid: theorem exmpl (x : ℕ) : false := begin def f (n : ℕ) : ℕ := n + 1, end I would assume that it is possible with have instead, but attempts like theorem exmpl (x : ℕ) : false := begin have f (n : ℕ) : n := n + 1, have f : ℕ → ℕ := --some definition, end did not work for me. Is it possible to define a function inside of a proof in lean and how would you achive that? (In the example above, it would be possible to define it before the proof, but you could also imagine a function like f (n : ℕ) : ℕ := n + x, which can only be defined after x is introduced) A: Inside a tactic proof, you have the have and let tactics for new definitions. The have tactic immediately forgets everything but the type of the new definition, and it is generally used just for propositions. The let tactic in contrast remembers the value for the definition. These tactics don't have the syntax for including arguments to the left of the colon, but you can make do with lambda expressions: theorem exmpl (x : ℕ) : false := begin let f : ℕ → ℕ := λ n, n + 1, end (Try changing that let to have to see how the context changes.) Another way to do it is to use let expressions outside the tactic proof. These expressions do have syntax for arguments before the colon. For example, theorem exmpl (x : ℕ) : false := let f (n : ℕ) : ℕ := n + x in begin end
{ "redpajama_set_name": "RedPajamaStackExchange" }
8,098
Q: Is it possible to parse all public variables of an object in javascript? Imagine I have an object with a set of public variables and private ones function myObj() { var private1 = 1; var private2 = 2; this.func = function(){console.log('anything');}; this.public1 = 3; this.public2 = '4'; } Is there a way to create a function that can parse the object and retrieve the name, value and type of the public variables. The prototype of this function would be : parseObj(object) The console result would be : >object has public1 with value 3 of type Number >object has public2 with value 4 of type String A: Try this: Object.entries(object).forEach((prop) => { const [name, value] = prop; console.log(`object has ${name} with value of ${value} and type ${typeof(value)}`) }) I get this in console: // object has func with value of function (){console.log('anything');} and type function // object has public1 with value of 3 and type number // object has public2 with value of 4 and type string A: You can quite easily make such a function using for in loop: function parseObj(object) { for(var name in object) { if(object.hasOwnProperty(name)) { // ignoring methods if(typeof object[name] !== 'function') { console.log('object has '+name+' with value '+object[name]+' of type '+typeof object[name]); } } } } A: You didn't include the "not ECMAScript 2015" condition in the OP. If ECMAScript 5.1 is OK, then Object.keys will return own properties (there's a polyfill on MDN). There is no built-in function that accurately returns a value's Type (though you could do this yourself fairly easily). typeof returns values that are helpful but do not match types, e.g. there is no "function" type but: typeof function(){} returns "function". Also, host objects may return various values (e.g. "unknown"). function myObj() { var private1 = 1; var private2 = 2; this.func = function(){console.log('anything');}; this.public1 = 3; this.public2 = '4'; } var obj = new myObj(); function showProps(obj) { Object.keys(obj).forEach(function(key) { console.log('object has ' + key + ' with value ' + obj[key] + ' with typeof ' + (typeof obj[key])); }); } showProps(obj);
{ "redpajama_set_name": "RedPajamaStackExchange" }
4,516
using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Storage.Models { public partial class StorageAccountInternetEndpoints : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Blob != null) { writer.WritePropertyName("blob"); writer.WriteStringValue(Blob); } if (File != null) { writer.WritePropertyName("file"); writer.WriteStringValue(File); } if (Web != null) { writer.WritePropertyName("web"); writer.WriteStringValue(Web); } if (Dfs != null) { writer.WritePropertyName("dfs"); writer.WriteStringValue(Dfs); } writer.WriteEndObject(); } internal static StorageAccountInternetEndpoints DeserializeStorageAccountInternetEndpoints(JsonElement element) { string blob = default; string file = default; string web = default; string dfs = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("blob")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } blob = property.Value.GetString(); continue; } if (property.NameEquals("file")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } file = property.Value.GetString(); continue; } if (property.NameEquals("web")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } web = property.Value.GetString(); continue; } if (property.NameEquals("dfs")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } dfs = property.Value.GetString(); continue; } } return new StorageAccountInternetEndpoints(blob, file, web, dfs); } } }
{ "redpajama_set_name": "RedPajamaGithub" }
4,448
{"url":"https:\/\/mersenneforum.org\/showthread.php?s=b37fcfa23f070b890df623c87e9ca245&p=319083","text":"mersenneforum.org n!-(n-1)!-(n-2)!...-1!\n Register FAQ Search Today's Posts Mark Forums Read\n\n 2012-11-20, 19:52 #1 Mr. Odd \u00a0 Mar 2010 1101112 Posts n!-(n-1)!-(n-2)!...-1! Playing around with number sequences, I started factoring factorial subtractions - n!-(n-1)!-(n-2)!-...-1!. It's clear there's a pattern in the numbers but my algebra is too rusty to figure it out. For n>=11 it's 3^2*11*m. Anyone have a simplified formula?\n2012-11-20, 20:20 \u00a0 #2\nR. Gerbicz\n\n\"Robert Gerbicz\"\nOct 2005\nHungary\n\n2\u00d77\u00d7103 Posts\n\nQuote:\n Originally Posted by Mr. Odd Anyone have a simplified formula?\nA132371(n)\n\n 2012-11-20, 20:38 #3 Dubslow Basketry That Evening! \u00a0 \u00a0 \"Bunslow the Bold\" Jun 2011 40 a(n) = 1 + $\\sum_{i=2}^n{(i-2)*(i-1)!}$ = [j=i-1] 1 + $\\sum_{j=1}^{n-1}{(j-1)*j!}$, but the first term is 0, so a(n) = 1 + $\\sum_{j=2}^{n-1}{(j-1)*j!}$ ... n! + (n-1)! + ... = $\\sum_{i=1}^n{\\left(\\prod_{j=1}^ij\\right)}$ Last fiddled with by Dubslow on 2012-11-20 at 21:36\n2012-11-20, 22:03 \u00a0 #4\nscience_man_88\n\n\"Forget I exist\"\nJul 2009\nDumbassville\n\n26\u00b7131 Posts\n\nQuote:\n Originally Posted by Dubslow a(n) = n! - (n-1)! - ... a(n+1) = (n+1)! - n! - (n-1)! - ... = a(n) + (n+1)! - 2*n! = a(n) + n!*[(n+1) - 2] = a(n) + (n-1)*n! a(n) = a(n-1) + (n-2)*(n-1)! = (n-2)*(n-1)! + (n-3)*(n-2)! + a(n-2) = ... a(1) = 1! = 1 a(2) = 2! - 1! = 1 a(2) = a(1) + 0*1! = 1 + 0 = 1, good a(3) = 3! - 2! - 1! = 6 - 2 - 1 = 3 a(3) = 1*2! + 0*1! + a(1) = 2 + 0 + 1 = 3, good => a(n) = 1 + $\\sum_{i=2}^n{(i-2)*(i-1)!}$ = [j=i-1] 1 + $\\sum_{j=1}^{n-1}{(j-1)*j!}$, but the first term is 0, so a(n) = 1 + $\\sum_{j=2}^{n-1}{(j-1)*j!}$ ... n! + (n-1)! + ... = $\\sum_{i=1}^n{\\left(\\prod_{j=1}^ij\\right)}$\nsimplest I can get is: a(n)=a(n-1)+(n!-2*(n-1)!) I believe, reasoning:\n\na(3) = 3!-2!-1! = 3\na(4) = 4!-3!-2!-1! = 15\n\nthe lime is the same, the sign on 3! has opposite indicating a change from 1 to -1 (-1)-1=-2 the coefficient I give the other change is the addition of 4! , n=4 so n!-2*(n-1)! is the difference:\n\nCode:\na=[1];for(x=1,100,a=concat(a,a[#a]+(#a+1)!-2*eval(#a)!));a\n\nLast fiddled with by science_man_88 on 2012-11-20 at 22:04\n\n2012-11-20, 22:06 \u00a0 #5\nDubslow\n\n\"Bunslow the Bold\"\nJun 2011\n40<A<43 -89<O<-88\n\n160658 Posts\n\nQuote:\n Originally Posted by science_man_88 so n!-2*(n-1)! is the difference\nOf course it is, and that's what I did. n! - 2*(n-1)! = (n-1)!*(n - 2). (If you don't believe me, distribute the latter multiplication.)\n\nOf course, the sum I reduced it to is basically no simpler than the sum of factorials at the bottom of the post. If you can sum that, then you'll have a simple formula.\n\nPS @OP, what do you mean by m? n! ?\n\n2012-11-20, 22:13 \u00a0 #6\nscience_man_88\n\n\"Forget I exist\"\nJul 2009\nDumbassville\n\n838410 Posts\n\nQuote:\n Originally Posted by Dubslow Of course it is, and that's what I did. n! - 2*(n-1)! = (n-1)!*(n - 2). (If you don't believe me, distribute the latter multiplication.) Of course, the sum I reduced it to is basically no simpler than the sum of factorials at the bottom of the post. If you can sum that, then you'll have a simple formula. PS @OP, what do you mean by m? n! ?\nmaybe I got confused since now that i look at it your last equation suggest a sum of factorials is what's wanted by the OP, but I read it as subtraction in the OP.\n\nLast fiddled with by science_man_88 on 2012-11-20 at 22:19\n\n2012-11-20, 22:22 \u00a0 #7\nDubslow\n\n\"Bunslow the Bold\"\nJun 2011\n40<A<43 -89<O<-88\n\n3\u00b729\u00b783 Posts\n\nQuote:\n Originally Posted by science_man_88 maybe I got confused since now that i look at it your last equation suggest a sum of factorials is what's wanted by the OP, but I read it as subtraction in the OP.\nNo, it is the subtraction, but I was initially trying to see if there was a way to do the simple factorial sum, call if F(n) = sum_i=1^n of n!.\n\nThen a(n) = n! - F(n-1), so finding a formula for F would produce an easy formula for a. Of course, as I showed by reducing a(n) to a simpler series, that manner is no more promising than finding a formula for F itself.\n\nIn shorter words, finding a simple formula for both F and a is, AFAICT, essentially equivalent. That's what I was trying to say in my previous post.\n\n2012-11-20, 22:38 \u00a0 #8\nscience_man_88\n\n\"Forget I exist\"\nJul 2009\nDumbassville\n\n26\u00d7131 Posts\n\nQuote:\n Originally Posted by Dubslow No, it is the subtraction, but I was initially trying to see if there was a way to do the simple factorial sum, call if F(n) = sum_i=1^n of n!. Then a(n) = n! - F(n-1), so finding a formula for F would produce an easy formula for a. Of course, as I showed by reducing a(n) to a simpler series, that manner is no more promising than finding a formula for F itself. In shorter words, finding a simple formula for both F and a is, AFAICT, essentially equivalent. That's what I was trying to say in my previous post.\nbut if you look at the OEIS sequence for it, it doesn't start with 0 as you stated.\n\n2012-11-20, 22:52 \u00a0 #9\nDubslow\n\n\"Bunslow the Bold\"\nJun 2011\n40<A<43 -89<O<-88\n\n3\u00d729\u00d783 Posts\n\nQuote:\n Originally Posted by science_man_88 but if you look at the OEIS sequence for it, it doesn't start with 0 as you stated.\n0? Who said 0? a(1) = 1 = a(2), a(3) = 3.\n\nPS: Sums of factorials. (Hardly a simple form.)\n\n$\\sum_{k=1}^n{k!} = \\frac{1}{e}\\left(-e + \\int_\\infty^{-1}{\\frac{e^{-t}}{t}dt}+\\pi i + (n+1)! \\int_1^\\infty{\\frac{e^t}{t^{n+2}}dt} \\right)$\n\nLast fiddled with by Dubslow on 2012-11-20 at 23:15\n\n2012-11-20, 22:57 \u00a0 #10\nscience_man_88\n\n\"Forget I exist\"\nJul 2009\nDumbassville\n\n203008 Posts\n\nQuote:\n Originally Posted by Dubslow but the first term is 0, so\nthought this was part of it, apparently I'm mistaken.\n\n2012-11-21, 03:49 \u00a0 #11\nLaurV\nRomulan Interpreter\n\nJun 2011\nThailand\n\n220708 Posts\n\nQuote:\n Originally Posted by Dubslow PS @OP, what do you mean by m? n! ?\nHe means the decomposition of a_n into factors, last factor (prime or composite) being m. He claims after n>11, all have 3^2*11 as a common factor, which is totally true, because all factorials bigger then 10 contain 9 and 11, and the sum S=1!+2!+....+10! is divisible by 9 and 11, so their sum\/difference with S is too.\n\n(edit limit)\n\n1. because 1!+2!=3 is divisible by 3, all a(n), n>=3, will be divisible by 3\n\n2. because 1!+2!+3!+4!+5!=152=9*17 is divisible by 3^2, all a(n), n>=6, will be divisible by 3^2 (all factorials bigger or equal with 6 contain 3^2)\n\n3. because 1!+2!+...+10! is divisible by 3^2*11, all a(n), n>=11, will be divisible by 3^2*11 (all factorials bigger or equal with 11 contain 3^2*11)\n\nThis probably happens an infinite number of times, but it is difficult to spot due to the rapid growth of a(n) series. The necessary condition is that the factorial sum s(n) to have factors lower then n, and the probability of this is higher, as n is higher. The next value where it is happening would look something like:\n\n4. because 1!+2!+...+xxxxxx! is divisible by 3^2*11*yyy, with yyy<xxxxxx+1, then all a(n) for n>xxxxxx, will be divisible by 3^2*11*yyy (all factorials bigger then xxxxxx contain 3^2*11*yyy)\n\n(tip: you don't need to factor the sums, only to TF them with primes under n, which is very fast, and you don't need to do it sequentially, just pick a very big xxxxxx, like the binary search, and if lucky, come down by halving n. I tested s(20000) and it has not other smaller factors except 9 and 11)\n\nThis only in case I don't miss some theoretic trick which forbids the factorial sums s(n) to have factors smaller than n.\n\nLast fiddled with by Batalov on 2012-11-21 at 04:33 Reason: (merged)","date":"2021-02-28 22:59:20","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 9, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.7624378800392151, \"perplexity\": 2029.4884127404086}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-10\/segments\/1614178361776.13\/warc\/CC-MAIN-20210228205741-20210228235741-00519.warc.gz\"}"}
null
null
This is a list of butterflies of Togo. About 414 species are known from Togo, none of which is endemic. Papilionidae Papilioninae Papilionini Papilio antimachus Drury, 1782 Papilio zalmoxis Hewitson, 1864 Papilio nireus Linnaeus, 1758 Papilio chrapkowskoides nurettini Koçak, 1983 Papilio sosia Rothschild & Jordan, 1903 Papilio cynorta Fabricius, 1793 Papilio dardanus Brown, 1776 Papilio phorcas Cramer, 1775 Papilio cyproeofila Butler, 1868 Papilio nobicea Suffert, 1904 Papilio demodocus Esper, [1798] Papilio menestheus Drury, 1773 Leptocercini Graphium antheus (Cramer, 1779) Graphium policenes (Cramer, 1775) Graphium liponesco (Suffert, 1904) Graphium angolanus baronis (Ungemach, 1932) Graphium leonidas (Fabricius, 1793) Graphium adamastor (Boisduval, 1836) Graphium agamedes (Westwood, 1842) Graphium almansor carchedonius (Karsch, 1895) Pieridae Coliadinae Eurema brigitta (Stoll, [1780]) Eurema desjardinsii marshalli (Butler, 1898) Eurema regularis (Butler, 1876) Eurema hecabe solifera (Butler, 1875) Eurema senegalensis (Boisduval, 1836) Catopsilia florella (Fabricius, 1775) Pierinae Colotis euippe (Linnaeus, 1758) Colotis evagore antigone (Boisduval, 1836) Nepheronia argia (Fabricius, 1775) Nepheronia pharis (Boisduval, 1836) Nepheronia thalassina (Boisduval, 1836) Leptosia alcesta (Stoll, [1782]) Leptosia hybrida Bernardi, 1952 Leptosia marginea (Mabille, 1890) Leptosia medusa (Cramer, 1777) Leptosia wigginsi pseudalcesta Bernardi, 1965 Pierini Appias epaphia (Cramer, [1779]) Appias phaola (Doubleday, 1847) Appias sabina (Felder & Felder, [1865]) Appias sylvia (Fabricius, 1775) Mylothris aburi Larsen & Collins, 2003 Mylothris chloris (Fabricius, 1775) Mylothris jaopura Karsch, 1893 Mylothris poppea (Cramer, 1777) Mylothris rhodope (Fabricius, 1775) Mylothris schumanni Suffert, 1904 Belenois aurota (Fabricius, 1793) Belenois calypso (Drury, 1773) Belenois creona (Cramer, [1776]) Belenois hedyle (Cramer, 1777) Belenois theora (Doubleday, 1846) Lycaenidae Miletinae Liphyrini Euliphyra leucyania (Hewitson, 1874) Aslauga ernesti (Karsch, 1895) Aslauga marginalis Kirby, 1890 Miletini Megalopalpus metaleucus Karsch, 1893 Megalopalpus zymna (Westwood, 1851) Spalgis lemolea lemolea Druce, 1890 Spalgis lemolea pilos Druce, 1890 Lachnocnema emperamus (Snellen, 1872) Lachnocnema vuattouxi Libert, 1996 Poritiinae Liptenini Ptelina carnuta (Hewitson, 1873) Pentila pauli Staudinger, 1888 Pentila petreia Hewitson, 1874 Pentila phidia Hewitson, 1874 Telipna acraea (Westwood, [1851]) Telipna semirufa (Grose-Smith & Kirby, 1889) Mimacraea maesseni Libert, 2000 Mimacraea neurata Holland, 1895 Mimeresia libentina (Hewitson, 1866) Liptena alluaudi Mabille, 1890 Liptena pearmani Stempffer, Bennett & May, 1974 Liptena rochei Stempffer, 1951 Liptena septistrigata (Bethune-Baker, 1903) Tetrarhanis symplocus Clench, 1965 Larinopoda aspidos Druce, 1890 Eresiomera bicolor (Grose-Smith & Kirby, 1890) Citrinophila erastus (Hewitson, 1866) Citrinophila marginalis Kirby, 1887 Epitolini Epitola posthumus (Fabricius, 1793) Epitola urania Kirby, 1887 Epitola uranioides occidentalis Libert, 1999 Cerautola ceraunia (Hewitson, 1873) Cerautola crowleyi (Sharpe, 1890) Cerautola miranda (Staudinger, 1889) Geritola gerina (Hewitson, 1878) Stempfferia dorothea (Bethune-Baker, 1904) Stempfferia kholifa (Bethune-Baker, 1904) Stempfferia leonina (Staudinger, 1888) Stempfferia zelza (Hewitson, 1873) Cephetola cephena (Hewitson, 1873) Cephetola collinsi Libert & Larsen, 1999 Cephetola sublustris (Bethune-Baker, 1904) Epitolina dispar (Kirby, 1887) Epitolina melissa (Druce, 1888) Epitolina catori Bethune-Baker, 1904 Hypophytala benitensis (Holland, 1890) Hypophytala hyettoides (Aurivillius, 1895) Hypophytala ultramarina Libert & Collins, 1999 Aethiopana honorius (Butler, 1901) Hewitsonia inexpectata (Bouyer, 1997) Aphnaeinae Pseudaletis agrippina Druce, 1888 Pseudaletis catori Bethune-Baker, 1926 Pseudaletis leonis (Staudinger, 1888) Lipaphnaeus leonina ivoirensis Stempffer, 1966 Cigaritis avriko (Karsch, 1893) Cigaritis mozambica (Bertoloni, 1850) Axiocerses harpax (Fabricius, 1775) Axiocerses amanga borealis Aurivillius, 1905 Theclinae Myrina silenus (Fabricius, 1775) Oxylides faunus (Drury, 1773) Dapidodigma hymen (Fabricius, 1775) Hypolycaena antifaunus (Westwood, 1851) Hypolycaena dubia Aurivillius, 1895 Hypolycaena hatita Hewitson, 1865 Hypolycaena kakumi Larsen, 1997 Hypolycaena lebona (Hewitson, 1865) Hypolycaena liara Druce, 1890 Hypolycaena philippus (Fabricius, 1793) Iolaus eurisus (Cramer, 1779) Iolaus aethria Karsch, 1893 Iolaus bellina (Plötz, 1880) Iolaus iasis Hewitson, 1865 Iolaus laon Hewitson, 1878 Iolaus maesa (Hewitson, 1862) Iolaus iulus Hewitson, 1869 Iolaus ismenias (Klug, 1834) Iolaus alcibiades Kirby, 1871 Iolaus paneperata Druce, 1890 Iolaus theodori Stempffer, 1970 Iolaus calisto (Westwood, 1851) Iolaus timon (Fabricius, 1787) Pilodeudorix camerona (Plötz, 1880) Pilodeudorix diyllus (Hewitson, 1878) Pilodeudorix aucta (Karsch, 1895) Pilodeudorix aurivilliusi (Stempffer, 1954) Pilodeudorix catalla (Karsch, 1895) Paradeudorix eleala viridis (Stempffer, 1964) Paradeudorix moyambina (Bethune-Baker, 1904) Hypomyrina mimetica Libert, 2004 Deudorix antalus (Hopffer, 1855) Deudorix lorisona (Hewitson, 1862) Polyommatinae Lycaenesthini Anthene amarah (Guérin-Méneville, 1849) Anthene crawshayi (Butler, 1899) Anthene irumu (Stempffer, 1948) Anthene ligures (Hewitson, 1874) Anthene liodes (Hewitson, 1874) Anthene lunulata (Trimen, 1894) Anthene lysicles (Hewitson, 1874) Anthene rubricinctus (Holland, 1891) Anthene starki Larsen, 2005 Anthene sylvanus (Drury, 1773) Anthene chryseostictus (Bethune-Baker, 1910) Anthene hades (Bethune-Baker, 1910) Anthene lamias (Hewitson, 1878) Anthene lucretilis (Hewitson, 1874) Anthene nigeriae (Aurivillius, 1905) Anthene phoenicis (Karsch, 1893) Anthene rufoplagata (Bethune-Baker, 1910) Cupidesthes leonina (Bethune-Baker, 1903) Polyommatini Cupidopsis cissus (Godart, [1824]) Cupidopsis jobates mauritanica Riley, 1932 Pseudonacaduba sichela (Wallengren, 1857) Lampides boeticus (Linnaeus, 1767) Uranothauma falkensteini (Dewitz, 1879) Phlyaria cyara stactalla Karsch, 1895 Cacyreus lingeus (Stoll, 1782) Leptotes pirithous (Linnaeus, 1767) Tuxentius carana kontu (Karsch, 1893) Zizeeria knysna (Trimen, 1862) Zizina antanossa (Mabille, 1877) Zizula hylax (Fabricius, 1775) Azanus moriqua (Wallengren, 1857) Azanus isis (Drury, 1773) Eicochrysops hippocrates (Fabricius, 1793) Euchrysops malathana (Boisduval, 1833) Euchrysops osiris (Hopffer, 1855) Thermoniphas micylus (Cramer, 1780) Oboronia guessfeldti (Dewitz, 1879) Oboronia ornata (Mabille, 1890) Oboronia pseudopunctatus (Strand, 1912) Oboronia punctatus (Dewitz, 1879) Lepidochrysops parsimon (Fabricius, 1775) Lepidochrysops quassi (Karsh, 1895) Lepidochrysops synchrematiza (Bethune-Baker, [1923]) Lepidochrysops victoriae occidentalis Libert & Collins, 2001 Nymphalidae Libytheinae Libythea labdaca Westwood, 1851 Danainae Danaini Danaus chrysippus alcippus (Cramer, 1777) Tirumala petiverana (Doubleday, 1847) Amauris niavius (Linnaeus, 1758) Amauris tartarea Mabille, 1876 Amauris crawshayi camerunica Joicey & Talbot, 1925 Amauris damocles (Fabricius, 1793) Amauris hecate (Butler, 1866) Satyrinae Elymniini Elymniopsis bammakoo (Westwood, [1851]) Melanitini Gnophodes betsimena parmeno Doubleday, 1849 Gnophodes chelys (Fabricius, 1793) Melanitis leda (Linnaeus, 1758) Satyrini Bicyclus angulosa (Butler, 1868) Bicyclus campus (Karsch, 1893) Bicyclus dorothea (Cramer, 1779) Bicyclus istaris (Plötz, 1880) Bicyclus italus (Hewitson, 1865) Bicyclus madetes (Hewitson, 1874) Bicyclus maesseni Condamin, 1971 Bicyclus mandanes Hewitson, 1873 Bicyclus milyas (Hewitson, 1864) Bicyclus procora (Karsch, 1893) Bicyclus safitza (Westwood, 1850) Bicyclus martius (Fabricius, 1793) Bicyclus sandace (Hewitson, 1877) Bicyclus sangmelinae Condamin, 1963 Bicyclus sylvicolus Condamin, 1965 Bicyclus taenias (Hewitson, 1877) Bicyclus vulgaris (Butler, 1868) Bicyclus xeneas occidentalis Condamin, 1965 Heteropsis elisi (Karsch, 1893) Ypthima doleta Kirby, 1880 Ypthima pupillaris Butler, 1888 Ypthimomorpha itonia (Hewitson, 1865) Charaxinae Charaxini Charaxes varanes vologeses (Mabille, 1876) Charaxes fulvescens senegala van Someren, 1975 Charaxes protoclea Feisthamel, 1850 Charaxes boueti Feisthamel, 1850 Charaxes lucretius Cramer, [1775] Charaxes lactetinctus Karsch, 1892 Charaxes jasius Poulton, 1926 Charaxes epijasius Reiche, 1850 Charaxes castor (Cramer, 1775) Charaxes brutus (Cramer, 1779) Charaxes tiridates (Cramer, 1777) Charaxes ameliae doumeti Henning, 1989 Charaxes etesipe (Godart, 1824) Charaxes achaemenes atlantica van Someren, 1970 Charaxes eupale (Drury, 1782) Charaxes subornatus couilloudi Plantrou, 1976 Charaxes anticlea (Drury, 1782) Charaxes etheocles (Cramer, 1777) Charaxes viola Butler, 1866 Charaxes paphianus falcata (Butler, 1872) Charaxes lycurgus (Fabricius, 1793) Charaxes doubledayi Aurivillius, 1899 Nymphalinae Nymphalini Vanessa cardui (Linnaeus, 1758) Junonia chorimene (Guérin-Méneville, 1844) Junonia hierta cebrene Trimen, 1870 Junonia oenone (Linnaeus, 1758) Junonia orithya madagascariensis Guenée, 1865 Junonia sophia (Fabricius, 1793) Junonia stygia (Aurivillius, 1894) Junonia terea (Drury, 1773) Junonia cymodoce (Cramer, 1777) Salamis cacta (Fabricius, 1793) Protogoniomorpha anacardii (Linnaeus, 1758) Protogoniomorpha parhassus (Drury, 1782) Protogoniomorpha cytora (Doubleday, 1847) Precis octavia (Cramer, 1777) Precis pelarga (Fabricius, 1775) Hypolimnas anthedon (Doubleday, 1845) Hypolimnas misippus (Linnaeus, 1764) Hypolimnas salmacis (Drury, 1773) Catacroptera cloanthe ligata Rothschild & Jordan, 1903 Cyrestinae Cyrestini Cyrestis camillus (Fabricius, 1781) Biblidinae Biblidini Byblia anvatara crameri Aurivillius, 1894 Mesoxantha ethosea (Drury, 1782) Ariadne enotrea (Cramer, 1779) Neptidopsis ophione (Cramer, 1777) Eurytela dryope (Cramer, [1775]) Eurytela hiarbas (Drury, 1782) Epicaliini Sevenia umbrina (Karsch, 1892) Limenitinae Limenitidini Cymothoe caenis (Drury, 1773) Pseudoneptis bugandensis ianthe Hemming, 1964 Pseudacraea eurytus (Linnaeus, 1758) Pseudacraea lucretia (Cramer, [1775]) Pseudacraea semire (Cramer, 1779) Neptidini Neptis agouale Pierre-Baltus, 1978 Neptis conspicua Neave, 1904 Neptis najo Karsch, 1893 Neptis kiriakoffi Overlaet, 1955 Neptis metella (Doubleday, 1848) Neptis morosa Overlaet, 1955 Neptis nemetes Hewitson, 1868 Neptis nysiades Hewitson, 1868 Neptis puella Aurivillius, 1894 Neptis serena Overlaet, 1955 Adoliadini Catuna angustatum (Felder & Felder, 1867) Catuna crithea (Drury, 1773) Euryphura chalcis (Felder & Felder, 1860) Euryphura togoensis Suffert, 1904 Hamanumida daedalus (Fabricius, 1775) Aterica galene (Brown, 1776) Cynandra opis (Drury, 1773) Euriphene ampedusa (Hewitson, 1866) Euriphene aridatha transgressa Hecq, 1994 Euriphene atossa (Hewitson, 1865) Euriphene ernestibaumanni (Karsch, 1895) Bebearia tentyris (Hewitson, 1866) Bebearia mandinga (Felder & Felder, 1860) Bebearia oxione (Hewitson, 1866) Bebearia mardania (Fabricius, 1793) Bebearia cocalia continentalis Hecq, 1988 Bebearia sophus (Fabricius, 1793) Bebearia phantasina (Staudinger, 1891) Bebearia demetra (Godart, 1824) Euphaedra medon (Linnaeus, 1763) Euphaedra xypete (Hewitson, 1865) Euphaedra diffusa albocoerulea Hecq, 1976 Euphaedra sarcoptera (Butler, 1871) Euphaedra themis (Hübner, 1807) Euphaedra janetta (Butler, 1871) Euphaedra ceres (Fabricius, 1775) Euphaedra phaethusa (Butler, 1866) Euphaedra edwardsii (van der Hoeven, 1845) Euphaedra ruspina (Hewitson, 1865) Euphaedra harpalyce (Cramer, 1777) Euphaedra eupalus (Fabricius, 1781) Euptera crowleyi (Kirby, 1889) Euptera pluto occidentalis Chovet, 1998 Euptera zowa Fox, 1965 Pseudathyma falcata Jackson, 1969 Heliconiinae Acraeini Acraea eugenia Karsch, 1893 Acraea neobule Doubleday, 1847 Acraea quirina (Fabricius, 1781) Acraea zetes (Linnaeus, 1758) Acraea abdera eginopsis Aurivillius, 1899 Acraea egina (Cramer, 1775) Acraea caecilia (Fabricius, 1781) Acraea pseudegina Westwood, 1852 Acraea rogersi Hewitson, 1873 Acraea alcinoe Felder & Felder, 1865 Acraea epaea (Cramer, 1779) Acraea umbra (Drury, 1782) Acraea vestalis Felder & Felder, 1865 Acraea acerata Hewitson, 1874 Acraea alciope Hewitson, 1852 Acraea bonasia (Fabricius, 1775) Acraea encedon (Linnaeus, 1758) Acraea serena (Fabricius, 1775) Acraea jodutta (Fabricius, 1793) Acraea lycoa Godart, 1819 Acraea orestia Hewitson, 1874 Acraea peneleos Ward, 1871 Acraea pharsalus Ward, 1871 Acraea orina Hewitson, 1874 Acraea translucida Eltringham, 1912 Acraea perenna Doubleday, 1847 Vagrantini Lachnoptera anticlia (Hübner, 1819) Phalanta eurytis (Doubleday, 1847) Phalanta phalantha aethiopica (Rothschild & Jordan, 1903) Hesperiidae Coeliadinae Coeliades chalybe (Westwood, 1852) Coeliades forestan (Stoll, [1782]) Coeliades hanno (Plötz, 1879) Coeliades pisistratus (Fabricius, 1793) Pyrrhochalcia iphis (Drury, 1773) Pyrginae Celaenorrhinini Katreus johnstoni (Butler, 1888) Celaenorrhinus galenus (Fabricius, 1793) Celaenorrhinus proxima maesseni Berger, 1976 Eretis lugens (Rogenhofer, 1891) Eretis melania Mabille, 1891 Eretis plistonicus (Plötz, 1879) Sarangesa bouvieri (Mabille, 1877) Sarangesa laelius (Mabille, 1877) Sarangesa majorella (Mabille, 1891) Sarangesa tertullianus (Fabricius, 1793) Sarangesa thecla (Plötz, 1879) Tagiadini Tagiades flesus (Fabricius, 1781) Eagris denuba (Plötz, 1879) Eagris hereus quaterna (Mabille, 1890) Eagris tetrastigma subolivescens (Holland, 1892) Procampta rara Holland, 1892 Caprona adelica Karsch, 1892 Abantis bismarcki Karsch, 1892 Carcharodini Spialia ploetzi occidentalis de Jong, 1977 Spialia spio (Linnaeus, 1764) Gomalia elma (Trimen, 1862) Hesperiinae Aeromachini Astictopterus abjecta (Snellen, 1872) Astictopterus anomoeus (Plötz, 1879) Gorgyra aretina (Hewitson, 1878) Gorgyra diversata Evans, 1937 Gorgyra pali Evans, 1937 Ceratrichia nothus enantia (Karsch, 1893) Pardaleodes edipus (Stoll, 1781) Pardaleodes incerta murcia (Plötz, 1883) Pardaleodes sator (Westwood, 1852) Pardaleodes tibullus (Fabricius, 1793) Xanthodisca astrape (Holland, 1892) Osmodes laronia (Hewitson, 1868) Osmodes thora (Plötz, 1884) Acleros mackenii olaus (Plötz, 1884) Semalea pulvina (Plötz, 1879) Hypoleucis tripunctata Mabille, 1891 Meza meza (Hewitson, 1877) Paronymus budonga (Evans, 1938) Andronymus caesar (Fabricius, 1793) Zophopetes cerymica (Hewitson, 1867) Zophopetes ganda Evans, 1937 Artitropa comus (Stoll, 1782) Mopala orma (Plötz, 1879) Gretna balenge zowa Lindsey & Miller, 1965 Gretna cylinda (Hewitson, 1876) Gretna waga (Plötz, 1886) Pteroteinon laufella (Hewitson, 1868) Leona leonora (Plötz, 1879) Leona stoehri (Karsch, 1893) Leona meloui (Riley, 1926) Monza cretacea (Snellen, 1872) Melphina flavina Lindsey & Miller, 1965 Melphina unistriga (Holland, 1893) Fresna cojo (Karsch, 1893) Fresna netopha (Hewitson, 1878) Platylesches moritili (Wallengren, 1857) Baorini Pelopidas mathias (Fabricius, 1798) Pelopidas thrax (Hübner, 1821) Borbo borbonica (Boisduval, 1833) Borbo fatuellus (Hopffer, 1855) Borbo gemella (Mabille, 1884) Borbo perobscura (Druce, 1912) See also Wildlife of Togo List of moths of Togo References Seitz, A. Die Gross-Schmetterlinge der Erde 13: Die Afrikanischen Tagfalter. Plates Seitz, A. Die Gross-Schmetterlinge der Erde 13: Die Afrikanischen Tagfalter. Text Togo Togo Togo Butterflies
{ "redpajama_set_name": "RedPajamaWikipedia" }
1,482
\section{Introduction} An always-on lightweight keyword spotting system has been exploited to wake up smart audio devices. When the system detects the keyword, the following audio stream can be uploaded to speech recognition systems~\cite{gruenstein2017cascade, res15, tcresnet, mittermaier2020small, zhang2020deep, zhang2021autokws}. This process can reduce power consumption while maintaining a high recall rate and low false alarm rate. Conventional keyword spotting (C-KWS)~\cite{res15, bcresnet} aims to detect a small set of pre-defined speech signals such as wake-up words, {\it e.g.}, ``Alexa" and ``OK Google," and has been applied to the always-on keyword spotting system. However, this system is not personalized, {\it i.e.}, it only focuses on pre-defined keywords and does not consider the users. \sh{To adapt the system to the users, query-by-example keyword spotting~\cite{QBKWS_2, kim2019query, QBKWS_1} has been proposed to allow the users to enroll their own keywords, but these approaches only adapt to new keywords, not explicitly considering the user identity.} In practice, most user interactions come from the \bg{\it{target}} users, and hence the model requires to be biased on the target users. \sh{Moreover, since the aforementioned systems ignore user information, they cannot prevent detecting general negatives of background sounds containing target keywords or other keywords having similar pronunciation to the target, {\it e.g.}, streaming audios from TV, online meetings, and conversations.} It could lead to undesirable power consumption by unnecessarily activating the recognition systems. To address these problems, we introduce more practical, personalized KWS tasks, \sh{considering the target users enrolled in the device.} \begin{figure}[t] \centering \begin{subfigure}{1.0\linewidth} \centering \epsfig{figure=kws_tasks.png,width=1.0\linewidth} \caption{} \label{figure1_task} \end{subfigure} \begin{subfigure}{1.0\linewidth} \centering \epsfig{figure=Figure1_v5.pdf,width=1.0\linewidth} \caption{} \label{figure1_performance} \end{subfigure} \vspace{-8pt} \caption{(a): Inputs of keyword spotting systems can be categorized into four cases: ts-tk, nts-tk, ts-ntk, nts-ntk. TB- and TO-KWS consider \textit{nts-tk} as neutral and negative, respectively. (b): The conventional C-KWS system~\cite{bcresnet} shows low equal error rate (EER) on C-KWS, but it downgrades on two personalized tasks. Our system has a capability to conduct TB- and TO-KWS, while performing comparable result on C-KWS.} \label{task:figure} \vspace{-5pt} \end{figure} \begin{figure*}[!h] \centering \epsfig{figure=Figure_main_architecture.pdf,width=0.9\linewidth} \vspace{-10pt} \caption{\textbf{Personalized keyword spotting through multi-task learning} consists of two parts. (a) A multi-task learning part: the shared representation of keyword and speaker classification is encoded in low-level layers, and sub-networks learn the characteristics of each task in high-level features. (b) A task-adaptation part: initial representations are learned by the multi-task loss function, and these representations are adapted to each task through task-specific scoring functions.} \label{fig:mainfigure} \vspace{-10pt} \end{figure*} To describe personalized tasks, we categorize input utterances of the KWS system into four when a target speaker and a target keyword are given as Fig.~\ref{figure1_task} left. The four categories are \textit{ts-tk} (utterances from the target speaker and the target keyword), \textit{nts-tk} (utterances from a non-target speaker and the target keyword), \textit{ts-ntk}, and \textit{nts-ntk}. The vague one is \textit{nts-tk}, which is the target keyword to detect but from a non-target user. We design two personalized keyword spotting tasks considering \textit{nts-tk} differently as Fig.~\ref{figure1_task} right: Target user Biased KWS (TB-KWS) and Target user Only KWS (TO-KWS) to better focus on the target users. TB-KWS requires the model to be biased to the target users and does not explicitly consider \textit{nts-tk}. Moreover, some applications in devices prefer to be activated by only the target users, hence TO-KWS only detects \textit{ts-tk} and not \textit{nts-tk}. We evaluate the C-KWS system~\cite{bcresnet} on multiple KWS tasks in Fig.~\ref{figure1_performance}, and it shows performance degradation on our proposed personalized tasks since it does not consider user information. We propose personalized keyword spotting through multi-task learning (PK-MTL) that can be selectively utilized on all three tasks, C-KWS, TB-KWS, and TO-KWS. Our PK-MTL is a two\bg{-}stage system consisting of multi-task learning and task-adaptation. First, we propose to apply multi-task learning on keyword spotting and speaker verification to leverage speaker information to the keyword spotting system. With a slight increase in the number of parameters, our keyword spotting system learns both keyword and speaker characteristics\bg{,} and we can get both representations in a computation\bg{-}efficient way. Next, we introduce task-specific scoring functions to adapt learned representations to TB- and TO-KWS tasks. Since the purpose of \bg{the} two tasks is different (see Fig.~\ref{figure1_task}), a function that combines the information from keyword and speaker representations suitable to each task is needed. We propose two modules, Score Combination Module (SCM) and Task Representation Module (TRM), as task-specific scoring functions. SCM is an optimization-free approach that \bg{directly} combines initial representations from the multi-task learning part. The second approach is to construct a trainable Task Representation Module (TRM) that is designed to take the two representations and learn new task-specific representation\bg{s} for each task. With the aid of these modules, PK-MTL can be adapted to each task. We evaluate on Google Speech Commands~\cite{google_commands}. Upon the multiple keyword\bg{s} spotting backbones~\cite{res15,bcresnet,dsresnet}, our framework significantly boosts the performance of TB- and TO-KWS while performing comparable results of C-KWS, with a slight increase in the number of parameters and computation. We also test PK-MTL in a practical setting, where negative samples continuously come from TV or other sources. \is{Specifically}, we exploit WSJ-SI200~\cite{WSJ} and Librispeech~\cite{panayotov2015librispeech} as negative samples, and the results show that our system dramatically reduces the false alarm rate \sh{with the aid of task-specific scoring functions. \vspace{-2pt} \section{Method} As shown in Fig. \ref{fig:mainfigure}, the overall architecture of our system comprises two parts: multi-task learning on keyword spotting (KWS) and speaker verification (SV) and task-specific scoring functions to adapt to personalized KWS tasks. \noindent \textbf{Notations.} \bg{The training data, $\mathcal{D}_\text{train}$, consists of labeled samples, $\{(x_i, y_i)\}_{i=1}^{|\mathcal{D}_\text{train}|}$, where $x_i$ is an input audio feature, and $y_i = (y^k_i, y^s_i)$. $y^k_i$ and $y^s_i$ are the corresponding keyword and speaker labels, respectively. To leverage speaker characteristics to the keyword spotting system, we design a multi-task learning architecture that comprises a shared encoder, $f_\phi(\cdot)$, sub-networks for keyword spotting and speaker verification, $f^k_{\varphi}(\cdot)$ and $f^s_{\varphi}(\cdot)$, and classifiers, $g^{k}(\cdot)$ and $g^{s}(\cdot)$. } \noindent \textbf{Decision process.} \sh{Given a pre-defined target keyword, conventional keyword spotting system obtains a score $\psi_{i,\text{ref}}$ of a test sample $x_i$ belonging to the given target keyword using the trained keyword classifier~\cite{res15, tcresnet}. The system accepts $x_{i}$ as the positive sample when $\psi_{i,\text{ref}}>\delta$, where $\delta$ is a threshold; otherwise $x_{i}$ is rejected as the negative sample. In this paper, we additionally utilize an enrolled utterance of the target user $x_\text{ref}$ following personalized systems~\cite{Belli_2022_WACV, chung2020defence} and leverage the similarity of $x_{i}$ and $x_\text{ref}$ into the score $\psi_{i,\text{ref}}$.} \vspace{-5pt} \subsection{Multi-task learning for personalized keyword spotting} \vspace{-2pt} For a given backbone network, $f_\theta(\cdot)$, where $\theta = \{\phi, \varphi\}$, we adopt hard-parameter sharing~\cite{Caruana1993MultitaskLA, baxter1997bayesian} for low-level layers, {\it i.e.}, the shared encoder, $f_\phi(\cdot)$. The shared encoder can learn complementary information from both KWS and SV, and the shared design is more efficient in terms of memory and computation than using separate task designs~\cite{kanakis2020reparameterizing, Sun_2021_ICCV}. Since features for KWS and SV are adversarial in high-level concept\bg{s}~\cite{yun2019end}, {\it i.e.}, keyword features are speaker-agnostic and vice versa, sub-networks, $f^k_\varphi(\cdot)$ and $f^s_\varphi(\cdot)$, are added to learn the characteristics of each task. Then, we get keyword and speaker features, $z_{i}^{k} = f^k_\varphi(f_\phi(x_{i}))$ and $z_{i}^{s} = f^s_\varphi(f_\phi(x_{i}))$. On top of that, we apply cosine similarity based classifiers~\cite{liu2017sphereface, liu2020prototype} as follows: \vspace{-1mm} \begin{equation} g^{k}(z_{i}^{k}) = \softmax(w \cdot \cossim(z_{i}^{k}, W^{k}) + b), \vspace{-1mm} \end{equation} where $W^{k}$ is the learnable weight for keyword classification, $\cossim$ represents cosine similarity, $\cossim(a,b) = a\cdot b/(||a||\text{ }||b||)$, and $w$ and $b$ indicate scale and bias, respectively (for simplicity of notation, we omit the superscript $k$). We define a keyword classification loss by minimizing the negative log probability of the true class: \vspace{-1mm} \begin{equation} L_{k} = \sum_{i}{-y^k_i\log g^{k}(z^{k}_{i})}. \vspace{-1mm} \end{equation} We get $L_{s}$ for SV in the same manner and combine two task-specific loss functions as below: \vspace{-1mm} \begin{equation} L_\text{mtl} = L_{k} + \lambda L_{s}, \vspace{-1mm} \label{eq:mtlloss} \end{equation} where $\lambda$ indicates the importance of speaker information. Different from the goal of previous multi-task learning on KWS and SV~\cite{KWS_SV_MTL1, KWS_SV_MTL2} that focuses on boosting each task, our framework focuses more on leveraging user information for better\bg{-}personalized KWS. After training the network with the loss in Eq.~\ref{eq:mtlloss}, we use learned representations for TB- and TO-KWS. \subsection{Task-specific scoring functions for TB- and TO-KWS} \label{score_function} \noindent \textbf{Score Combination Module (SCM).} The first approach is to obtain two scores of keyword and speaker independently and combine them directly into a task-specific score for the decision process in each personalized task. Given the enroll utterance $x_\text{ref}$ of a target user $y_{ref}^{s}$, keyword and speaker scores of the test input sample $x_{i}$ for the user $y_{t}^{s}$ are calculated by: \begin{equation*} \psi_{i,\text{ref}}^{k} = \cossim(z_{i}^{k}, W^{k}_{\text{ref}}) \ \ \text{and} \ \ \psi_{i,\text{ref}}^{s} = \cossim(z_{i}^{s}, f^s_{\varphi}(f_\phi(x_\text{ref})), \end{equation*} where $\psi_{i,\text{ref}}^{k}$ is the cosine similarity score between the keyword embedding $z_{i}^{k}$ and the trained keyword classifier weight $W^{k}_{\text{ref}}$ that can be regarded as the most representative embedding of the pre-defined target keyword. $\psi_{i,\text{ref}}^{s}$ is the score between the speaker embedding of the input $z_{i}^{s}$ and the embedding of the enrolled target user $f^{s}_\varphi(f_\phi(x_{\text{ref}}))$. Note that target keywords are pre-defined, but speakers are not overlapped between training and test. Therefore, we use the reference embedding, \bg{$z_\text{ref}^s$}, of the target user at the test time. \sh{We define $\text{SCM}(\cdot,\cdot;\alpha)$ that combines two scores, $\psi^{k}$ and $\psi^{s}$, into new score for each task, $\psi^\text{tb}$ and $\psi^\text{to}$. $\text{SCM}$ can be any combination functions, but we use a simple linear combination function, $\alpha \cdot \psi^{k} + (1-\alpha) \cdot \psi^{s}$.} The objective of keyword spotting is to minimize the false rejection rate (FRR) at the given false alarm rate (FAR). Here, FAR is the percentage of negative samples being incorrectly accepted\bg{,} while FRR is that of positive samples being incorrectly rejected. To achieve this goal, we obtain the parameters of SCM at the target FAR $c$ (\%) as follows: \vspace{-1mm} \begin{equation} \alpha^{*} = \underset{\alpha}{\argmin} \text{FRR}(\text{SCM}(\psi^{k}, \psi^{s};\alpha)), \text{ s.t. FAR} = c. \label{SCM} \end{equation} \vspace{-4mm} \noindent \textbf{Task Representation Module (TRM).} The second approach is to add a trainable neural network, $\text{TRM}_\text{tb}(\cdot, \cdot)$ and $\text{TRM}_\text{to}(\cdot, \cdot)$, whose inputs are keyword and speaker embeddings\bg{,} and an output is a task-specific embedding. We apply metric learning loss with our proposed batch construction to train this module to form the discriminative embedding for TB- and TO-KWS. We define positive and negative samples based on an anchor sample mimicking the test case of each task as described in Fig.~\ref{figure1_task}. Then, we apply an angular prototypical loss function~\cite{chung2020defence} to make the positive samples closer and the negative samples apart from the anchor sample. First, we measure the similarity between query samples and prototypes as follows: \vspace{-1mm} \begin{equation} \label{task_specific_score} \psi_{i,j}^\text{tb} = \cossim(\text{TRM}_\text{tb}(z_{i}^{k}, z_{i}^{s}), \text{TRM}_\text{tb}(p_{j}^{k}, p_{j}^{s})), \vspace{-1mm} \end{equation} where prototypes $p_{j}^{k}$ and $p_{j}^{s}$ are reference embeddings of the corresponding keyword and speaker of $j$-th sample, here we use learned classifiers' weights $W_{j}^{k}$ and $W_{j}^{s}$ as prototypes \sh{in training while the embedding of the enrolled speaker is used for $p_{j}^{s}$ in test.} Then, we define a task-specific loss function as follows: \vspace{-1mm} \begin{equation} L_\text{tb} = -\frac{1}{N}\sum_{i=1}^{N}\frac{\exp(w \cdot {\psi^{tb}_{i,i}} + b)}{\sum_{j=1}^{N}\exp(w \cdot {\psi^{tb}_{i,j}} + b)}. \label{eq:metric-loss} \vspace{-1mm} \end{equation} We apply the same task-specific loss function for TO-KWS, but negative samples are selected differently, {\it i.e.}, \textit{nts-tk} is selected for negative samples. TRM can extract discriminative features for each task by minimizing Eq.~\ref{eq:metric-loss}. We denote our mutli-task learning architecture with TRM as PK-MTL. \noindent \textbf{Inference time.} Given the test input $x_{i}$, we use the score from keyword embeddings, $\psi^{k}_{i,\text{ref}}$, for C-KWS and task-specific scores from SCM or TRM, $\psi^{tb}_{i,\text{ref}}$ and $\psi^{to}_{i,\text{ref}}$, for personalized tasks, as illustrated in Fig.~\ref{fig:mainfigure}. \begin{table*}[] \begin{center} \caption{Comparison of Top-1 test accuracy (\%), EER (\%), and FRR (\%) at FAR $1\%$ and FAR $10\%$ of SV, C-KWS, TB-KWS, and TO-KWS on Google Speech Commands v1. Reported numbers are mean (std) over five trials.\label{main_table}} \vspace{-8pt} \resizebox{1.0\linewidth}{!}{ \begin{tabular}{lcc|cc|ccc|ccc|rr} \toprule & & \multicolumn{1}{c}{SV} & \multicolumn{2}{c}{C-KWS} & \multicolumn{3}{c}{TB-KWS} & \multicolumn{3}{c}{TO-KWS} \\ \cmidrule{3-4} \cmidrule{5-7} \cmidrule{8-11} Method & Backbone & EER & Acc. & EER & FRR at 1\% & FRR at 10\% & EER & FRR at 1\% & FRR at 10\% & EER & \#Mult & \#Param\\ \midrule Vanilla & BC-ResNet-3~\cite{bcresnet} & - & 97.57 (0.04) & {\bf 1.92 (0.15)} & 2.85 (0.09) & 1.89 (0.20) & 2.47 (0.03) & 96.50 (0.07) & 64.32 (0.26) & 21.17 (0.08) & 16.7M & 63.5k \\ Vanilla (+SV) & BC-ResNet-3~\cite{bcresnet} & {\bf 3.32 (0.10)} & 97.57 (0.04) & {\bf 1.92 (0.15)} & 2.85 (0.09) & 1.89 (0.20) & 2.47 (0.03) & 96.50 (0.07) & 64.32 (0.26) & 21.17 (0.08) & 22.5M & 82.4k \\ Naive MTL & BC-ResNet-3~\cite{bcresnet} & 3.36 (0.13) & {\bf 97.68 (0.18)} & 1.98 (0.07) & 2.82 (0.10) & 1.71 (0.32) & 2.44 (0.06) & 96.44 (0.09) & 64.26 (0.24) & 21.12 (0.09) & 17.5M & 80.2k \\ \midrule PK-MTL w/ SCM-M & BC-ResNet-3~\cite{bcresnet} & 3.36 (0.13) & {\bf 97.68 (0.18)} & 1.98 (0.07) & 2.99 (0.17) & 0.90 (0.09) & 2.12 (0.19) & 6.28 (0.27) & 2.73 (0.13) & 3.89 (0.06) & 17.5M & 80.2k \\ PK-MTL w/ SCM-GS & BC-ResNet-3~\cite{bcresnet} & 3.36 (0.13) & {\bf 97.68 (0.18)} & 1.98 (0.07) & 2.75 (0.14) & 1.08 (0.52) & 2.40 (0.05) & {\bf 6.24 (0.42)} & 1.97 (0.70) & 3.76 (0.17) & 17.5M & 80.2k \\ PK-MTL & BC-ResNet-3~\cite{bcresnet} & 3.36 (0.13) & {\bf 97.68 (0.18)} & 1.98 (0.07) & {\bf 2.58 (0.10)} & {\bf 0.75 (0.25)} & {\bf 2.02 (0.22)} & 6.56 (0.20) & {\bf 1.52 (0.18)} & {\bf 3.37 (0.15)} & 17.5M & 82.0k \\ \midrule \midrule Vanilla & Res15~\cite{res15}& - & 95.82 (0.21) & 2.38 (0.10) & 4.17 (0.23) & 2.23 (0.17) & 3.03 (0.05) & 96.36 (0.28) & 63.83 (0.82) & 21.25 (0.08) & 966.3M & 241.1k \\ PK-MTL & Res15~\cite{res15}& 4.43 (0.13) & 96.30 (0.19) & 2.25 (0.13) & 3.30 (0.33) & 0.92 (0.08) & 2.14 (0.19) & 9.35 (0.46) & 2.56 (0.21) & 4.44 (0.18) & 1,040.6M & 262.3k \\ \midrule Vanilla &DS-ResNet18~\cite{dsresnet} & - & 96.83 (0.21) & 1.85 (0.20) & 3.10 (0.17) & 1.33 (0.17) & 2.41 (0.17) & 96.11 (0.13) & 63.76 (0.30) & 21.18 (0.07) & 305.6M & 79.9k \\ PK-MTL &DS-ResNet18~\cite{dsresnet} & 3.29 (0.07) & 96.85 (0.32) & 1.91 (0.21) & 2.46 (0.12) & 0.81 (0.15) & 1.61 (0.06) & 6.62 (0.37) & 1.90 (0.18) & 3.68 (0.24) & 326.1M & 89.9k \\ \midrule Vanilla &BC-ResNet-8~\cite{bcresnet} & - & 98.01 (0.16) & 1.89 (0.17) & 2.69 (0.11) & 0.77 (0.41) & 2.43 (0.04) & 96.30 (0.32) & 63.20 (0.64) & 21.20 (0.09) & 91.9M & 386.9k \\ PK-MTL &BC-ResNet-8~\cite{bcresnet} & 2.58 (0.10) & 97.87 (0.12) & 1.79 (0.27) & 1.72 (0.10) & 0.47 (0.05) & 1.33 (0.04) & 5.01 (0.17) & 1.41 (0.28) & 3.22 (0.27) & 96.6M & 501.7k \\ \bottomrule \end{tabular} } \end{center} \vspace{-25pt} \end{table*} \begin{table}[] \begin{center} \caption{FAR (\%) at FRR $1\%$ and $5\%$ on WSJ and Librispeech datasets. Reported numbers are mean (std) over five trials.\label{sub_table2}} \vspace{-8pt} \resizebox{\linewidth}{!}{ \begin{tabular}{c|c|cc|cc} \toprule & & \multicolumn{2}{c}{GSC+WSJ} & \multicolumn{2}{c}{GSC+Librispeech} \\ Method & Backbone & FAR at $1\%$ & FAR at $5\%$ & FAR at $1\%$ & FAR at $5\%$ \\ \midrule Vanilla & Res15~\cite{res15} & 41.49 (2.37) & 1.31 (1.87) & 33.77 (2.34) & 0.51 (0.08) \\ Vanilla & DS-ResNet18~\cite{dsresnet} & 47.44 (5.76) & 0.25 (0.39) & 37.46 (9.05) & 0.48 (0.06) \\ Vanilla & BC-ResNet-3~\cite{bcresnet} & 46.61 (7.45) & 0.00 (0.01) & 27.59 (3.23) & 0.19 (0.02) \\ Vanilla & BC-ResNet-8~\cite{bcresnet} & 45.00 (4.98) & 0.00 (0.00) & 21.83 (2.79) & 0.12 (0.02) \\ \midrule PK-MTL (TB) & BC-ResNet-3~\cite{bcresnet} & 5.58 (4.20) & 0.00 (0.00) & 2.69 (1.98) & 0.02 (0.01) \\ \textbf{PK-MTL (TO)} & BC-ResNet-3~\cite{bcresnet} & \textbf{0.15 (0.11) }& \textbf{0.00 (0.00)} & \textbf{0.15 (0.07)} & \textbf{0.00 (0.00)} \\ \midrule PK-MTL (TB) & BC-ResNet-8~\cite{bcresnet} & 1.32 (1.55) & 0.00 (0.01) & 0.99 (0.36) & 0.01 (0.00) \\ \textbf{PK-MTL (TO)} & BC-ResNet-8~\cite{bcresnet} & \textbf{0.20 (0.30)} & \textbf{0.00 (0.01)} &\textbf{ 0.15 (0.06) }& \textbf{0.01 (0.00)} \\ \bottomrule \end{tabular} } \end{center} \vspace{-25pt} \end{table} \section{Experiments} \subsection{Experimental Setup} {\bf Datasets.} We evaluate conventional and personalized KWS systems on Google Speech Commands v1~\cite{google_commands}. The dataset contains 64,727 utterances of total 30 words from 1,881 speakers. We follow the conventional 12 class classification setting~\cite{google_commands}, which consists of ten classes of ``Yes," ``No," ``Up," ``Down," ``Left," ``Right," ``On," ``Off," ``Stop," and ``Go" with two additional classes ``Unknown" and ``Silence," which indicate remaining twenty words and no speech, respectively. We divide the dataset into training, validation, and test in the same way as~\cite{tcresnet, res15, bcresnet, google_commands, rybakov2020streaming}. For testing on TB- and TO-KWS, we make sample-to-sample pairs consisting of positive and negative pairs. We randomly select an anchor sample and choose \textit{ts-tk}, \textit{nts-tk}, \textit{ts-ntk}, and \textit{nts-ntk} samples of the anchor. To reduce the performance variation, we obtained 10 test splits where each test split contains 16,000 pairs. We report the average performance from 10 test splits. Note that ``Silence" and ``Unknown" classes can be selected for non-target keywords but not for target keywords. Moreover, we make 10 test splits to validate speaker verification performance, which contain 160,000 speaker pairs \bg{that} are randomly sampled from the test set. We also evaluate the models trained on Google Speech Commands in a practical scenario, where speeches continuously come from news or conversations containing words that are general negatives for the system. We exploit the WSJ-SI200~\cite{WSJ} and Librispeech~\cite{panayotov2015librispeech} datasets as the negatives for the above scenario. Negative samples from WSJ-SI200 are segmented from the whole audio stream into \bg{the} one-second-long following~\cite{kim2019query}. For Librispeech, we segment the entire audio stream into one-second-long in the public noisy test set. \sh{We make a test pair where one sample is from general negatives and the other is the target keyword with a randomly selected speaker from Google Speech Commands, and we conduct this process for all samples by pairing with $10$ target keywords. } \noindent {\bf Implementation details.} We exploit three keyword spotting architectures as \is{the} backbone network, BC-ResNet~\cite{bcresnet}, Res15~\cite{res15} \is{and} DS-ResNet~\cite{dsresnet}, for our PK-MTL. For BC-ResNet, we use input features of 40-dimensional log Mel spectrograms with 30 ms window length and 10 ms frameshift and apply data augmentations following~\cite{bcresnet}. For \is{the} other two backbones, we follow~\cite{res15,dsresnet} to add noise and random shift to each segment. Then, we extract $40$ dimensional Melfrequency cepstrum coefficient features and use them as inputs. We design the shared encoder using the backbones except the last two conv layers for BC-ResNet and the last conv block for Res15 and DS-ResNet. Sub-networks follow the shared encoder, which consist of the remaining layers of each backbone and an additional fully connected layer. We follow the official training strategy~\cite{res15, bcresnet, dsresnet} of each baseline network, {\it e.g.}, a learning rate and a mini-batch size. We set $\lambda$ to 0.1 in Eq.~\ref{eq:mtlloss}. For the baselines, {\it i.e.}, BC-ResNet, Res15, and DS-ResNet, we add an additional fully connected layer before the classifier and use the cosine classifier, $g^{k}(\cdot)$. This modification improves the performance with additional parameters and computational cost. We define Score Combination Module (SCM) as a linear combination function. We adopt the attention modules~\cite{hu2018squeeze} for Task Representation Module (TRM). TRM extracts the concatenated normalized keyword and speaker embeddings attended by the attention weights that are obtained by two fully connected layers whose intermediate feature size is $2$. TRM is trained for 50 epochs using the same training strategy of the backbones. \noindent {\bf Evaluation metric.} \sh{We use false alarm rate (FAR), false rejection rate (FRR), and equal error rate (EER) at which FAR and FRR are the same. Also, Top-1 test accuracy is used for evaluating multiple keywords classification (C-KWS).} \vspace{-3pt} \subsection{Ablation studies on Google Speech Commands} \vspace{-2pt} \noindent {\bf Effectiveness of multi-task learning.} We compare three methods: 1) Vanilla is the conventional KWS model, 2) Vanilla (+SV) uses an additional single task model for SV, and 3) Naive MTL indicates our MTL framework trained by Eq.~\ref{eq:mtlloss}. In Table~\ref{main_table}, the results of EER on SV and C-KWS demonstrate that the keyword spotting system can learn speaker representations without performance degradation on KWS with a marginal increase in the number of parameters and computation compared to Vanilla. Vanilla (+SV) also leverages speaker information using single-task SV model, but it requires a higher computational cost due to separately performing each task. \noindent {\bf Impact of task-specific scoring functions.} To analyze the impact of scoring functions, we apply SCM and TRM to Naive MTL whose backbone is BC-ResNet-3. With a combination function whose $\alpha$ is manually chosen as $0.5$, SCM-M, it cannot consistently improve TB-KWS even though speaker information is exploited to the task. We can improve the performance at the target FAR, especially 1\%, by finding $\alpha$ through grid-search minimizing Eq.~\ref{SCM} at the target FAR on the validation set, and PK-MTL w/ SCM-GS largely reduces FRR at FAR 1\% of TB- and TO-KWS. However, it has limited performance improvements because their representations cannot learn task-specific characteristics explicitly. Therefore, we utilize TRM so that PK-MTL fully adapts keyword and speaker representations to TB- and TO-KWS, and it helps reducing FRR and EER significantly. \noindent {\bf PK-MTL on various baselines.} Our framework can be applied to any C-KWS architectures, hence we use three backbones, Res15, DS-ResNet18, BC-ResNet-8. In Table~\ref{main_table}, even though the performance of SV and the influence of SV to KWS induced by multi-task learning are different depending on the structure and size of the backbones, PK-MTL improves the performance consistently on all personalized tasks with the aid of the speaker representations and the task-specific scoring function, TRM. \begin{figure}[] \vspace{-5pt} \centering \epsfig{figure=Figure_score.pdf,width=0.9\linewidth} \vspace{-7pt} \caption{The histograms (log scale) for Vanilla and PK-MTL show the distribution of scores from keyword and task-specific embeddings, respectively. The scatter plot for Naive MTL shows the distribution of keyword (x-axis) and speaker (y-axis) scores.} \label{figure_score} \vspace{-20pt} \end{figure} \vspace{-4pt} \subsection{Experiments on the realistic scenario} \vspace{-2pt} \sh{The KWS system trained on Google Speech Commands selects a threshold based on the target FRR of positive samples, {\it i.e.}, \textit{ts-tk}. With the threshold, we evaluate KWS systems on WSJ and Librispeech datasets to validate whether they can reject general negatives. } All vanilla methods cannot reject general negatives that contain the target keywords, {\it e.g.}, ``Yes" and ``On," or similar keywords because speaker information is ignored for detecting keywords. It makes KWS systems induce high FAR at the operating points of FRR $1\%$ as shown in Table~\ref{sub_table2}, and it can lead to increased power consumption. However, in our systems, general negatives are easily rejected by considering speaker representations since the speaker characteristics of general negatives are different from the enrolled users. Especially, PK-MTL (TO) can effectively reject general negatives even at the low operating point, FAR 1\%, because it learns to reject \textit{nts-tk}. We analyze the score distribution of KWS systems as shown in Fig. 3. We plot the scores of \textit{ts-tk}, \textit{nts-tk}, \textit{ts-ntk}, \textit{nts-ntk} pairs from Google Speech Commands and \sh{pairs of target keywords and general negatives from Librispeech.} In Vanilla, the scores of target keywords and non-target keywords are well split regardless of speaker identities, but a lot of general negatives also result in high scores. We plot both keyword and speaker scores through Naive MTL. As expected, general negatives have low speaker scores even though their keywords are similar or the same as the target. The figure for PK-MTL (TB) shows that the score of \textit{ts-tk} is higher than those of \textit{nts-tk}, which indicates the model is biased toward the target users. Moreover, \textit{ts-tk} is well separated from other samples in PK-MTL (TO), which objective is to accept \bg{the} target user only. In PK-MTL, the scores of general negatives are apart from those of positive samples, thus we can reject them through the scores of TB or TO. \vspace{-4pt} \section{Conclusions} \vspace{-1pt} In this paper, we propose to leverage speaker information into the keyword spotting system to tackle personalized keyword spotting tasks. Through proposed multi-task learning and task adaptation, our system can adapt to personalized tasks. Extensive experiments show that leveraging speaker information reduces false alarm and rejection rate\bg{s} significantly in personalized and realistic keyword spotting scenarios. \bibliographystyle{IEEEtran}
{ "redpajama_set_name": "RedPajamaArXiv" }
9,785
\section{Introduction and main results} \subsection{Determinantal point processes Let $X$ be a locally compact Polish space, $\mathcal{B}(X)$ be the Borel $\sigma$-algebra on $X$, and denote $\mathcal{B}_0(X)$ the collection of all pre-compact Borel sets. Let $\Conf(X)$ denote the space of all locally finite configurations over $X$, that is, \begin{equation*} \begin{split} \Conf(X):=\big\{\xi=\textstyle\sum_{i}\delta_{x_i}\,\big|\,\,\forall i,\,x_i\in X\, \text{and $\xi(\Delta)<\infty$ for all $\Delta\in\mathcal{B}_0(X)$}\big\}. \end{split} \end{equation*} Consider the vague topology on $\Conf(X)$, the weakest topology on $\Conf(X)$ such that all maps $\Conf(X)\ni\xi\mapsto\int_{X}fd\xi$, $f\in C_c(X)$, are continuous. Here $C_c(X)$ is the space of all continuous real-valued functions on $X$ with compact support. The configuration space $\Conf(X)$ equipped with the vague topology becomes a Polish space. The Borel $\sigma$-algebra $\mathcal{F}$ on $\Conf(X)$ is generated by the cylinder sets $C_n^\Delta=\big\{\xi\in\Conf(X)\,|\,\,\xi(\Delta)=n\big\}$, where $\Delta\in\mathcal{B}_0(X)$ and $n\in\mathbb{N} = \{0,1,2,\cdots\}$. By definition, a Borel probability measure $\mathbb{P}$ on $\Conf(X)$ is called a point process on $X$. For more details, see, e.g. \cite{DV,KK,Le}. Let $\mu$ be a reference Radon measure on $X$. The $n$-th ($n\in\mathbb{N_+}$) correlation function with respect to $\mu$ of a point process $\mathbb{P}$ on $X$, if exists, is a $\mu^{\otimes n}$-a.e. non-negative measurable symmetric function $\rho_n:X^n\to [0, +\infty)$, such that for any family of mutually disjoint subsets $\Delta_1,\Delta_2,\cdots,\Delta_n\in\mathcal{B}_0(X)$, $m\geq 1, n_i\geq 1, n_1+n_2+\cdots+n_m = n$, \begin{equation}\label{def-corre-func} \begin{split} \mathbb{E}_{\mathbb{P}}\Big[\prod_{i=1}^{n}\frac{(\#_{\Delta_i})!}{(\#_{\Delta_i}-n_i)!}\Big]=\int_{\Delta_1^{n_1}\times\cdots\times\Delta_m^{n_m}} \rho_n(x_1,\cdots,x_n)d\mu(x_1)\cdots d\mu(x_n), \end{split} \end{equation} where $\#_\Delta:\Conf(X)\to\mathbb{N}$ is defined by $\#_\Delta(\xi):=\xi(\Delta)$. A configuration $\xi=\textstyle\sum_{i}\delta_{x_i}\in\Conf(X)$ is called simple if $\xi(\{x\}) \le 1$ for all $x\in X$. When $\xi$ is simple, we identify $\xi=\textstyle\sum_{i}\delta_{x_i}$ with the subset $\{x_i\}\subset X$. A point process $\mathbb{P}$ on $X$ is called simple if $\PP$-almost every $\xi\in\Conf(X)$ is simple. Let $K:X\times X\to\mathbb{C}$ be a measurable function, by slightly abusing the notation, we also denote $K$ the associated integral operator with integral kernel $K(x,y)$, that is, $K:L^2(X,\mu)\to L^2(X,\mu)$ is defined by \begin{equation}\label{associ-opera} \begin{split} Kf(x)=\int_X K(x,y)f(y)d\mu (y)\,,\quad f\in L^2(X,\mu). \end{split} \end{equation} A simple point process is called determinantal with kernel $K$ with respect to $\mu$ if it admits correlation functions of all orders, and \begin{equation}\label{def-dpp} \begin{split} \rho_n(x_1,\cdots,x_n)=\det\big[K(x_i,x_j)\big]_{1\leq i, j\leq n} \end{split} \end{equation} for every $n\geq 1$ and $\mu^{\otimes n}$-a.e. $(x_1,\cdots ,x_n)\in X^n$. We refer the reader to \cite{Bo,HKPV,PV,ST,So} for further background and details of determinantal point processes. \subsection{DPPs with $J$-Hermitian kernels Suppose that the underlying space $X$ is split into two disjoint parts $X=X_1\sqcup X_2$ with $X_1,X_2\in\mathcal{B}(X)$. Hence we have the direct sum decomposition $L^2(X,\mu)=L^2(X_1,\mu)\oplus L^2(X_2,\mu)$, and for $i=1,2$, we denote $P_i$ the orthogonal projection of $L^2(X,\mu)$ onto $L^2(X_i,\mu)$. Let $J:=P_1-P_2$, and then we define a $J$-scalar product on $L^2(X,\mu)$ by \begin{equation*} \begin{split} [f,g]:=\left\langle Jf,g\right\rangle=\left\langle P_1f,P_1g\right\rangle-\left\langle P_2f,P_2g\right\rangle,\quad f,g\in L^2(X,\mu), \end{split} \end{equation*} here $\left\langle\cdot,\cdot\right\rangle$ is the usual scalar product in $L^2(X,\mu)$. A bounded linear operator $K$ on $L^2(X,\mu)$ is called $J$-self-adjoint if $[Kf,g]=[f,Kg]$ for all $f,g\in L^2(X,\mu)$. A $J$-self-adjoint operator $K$ can be expressed in block form: \begin{equation*} K= \begin{bmatrix} K_{11}&K_{12}\\ -K_{12}^*&K_{22} \end{bmatrix} \end{equation*} satisfying \begin{equation}\label{J-Hermitian} \begin{split} \left\{\begin{array}{l} P_1K^*P_1=P_1KP_1\\ P_1K^*P_2=-P_1KP_2\\ P_2K^*P_1=-P_2KP_1\\ P_2K^*P_2=P_2KP_2 \end{array}\right.. \end{split} \end{equation} A measurable function $K(x,y)$ is called $J$-Hermitian if it induces a bounded $J$-self-adjoint integral operator by \eqref{associ-opera}. Note that $K(x,y)$ is $J$-Hermitian iff for $\mu\otimes\mu$-a.e. $(x,y)\in X^2$, \begin{equation}\label{J-Hermitian-kernel} \begin{split} \left\{\begin{array}{l} K(x,y)=\overline{K(y,x)}\,,\quad\,x,y\in X_1\,\,\text{or}\,\,x,y\in X_2\,,\\ K(x,y)=-\overline{K(y,x)}\,,\quad\,x\in X_1$, $y\in X_2\,. \end{array}\right. \end{split} \end{equation} We denote an operator $\widehat K$ through $P_1$, $P_2$ and $K$ by \begin{equation}\label{def-Khat} \widehat K:=KP_1+(1-K)P_2, \end{equation} then the operator $\widehat K$ has the following block form: \begin{equation*} \widehat K= \begin{bmatrix} K_{11}&K_{12}\\ K_{12}^*&P_2-K_{22} \end{bmatrix}. \end{equation*} It is easy to see that $K$ is $J$-self-adjoint if and only if $\widehat{K}$ is self-adjoint. We refer the reader to \cite{BOls,BOlsh,BOl,BOlsha,BOO,BQ,Ly} for more details and examples of $J$-Hermitian kernels. In particular, the matrix tail kernel derived by Borodin and Olshanski in \cite[Theorem~VII]{BOl} is a $J$-Hermitian translation-invariant kernel on $\mathbb{R}\sqcup\mathbb{R}$. We denote by $\mathscr{L}_{1|2}(L^2(X,\mu))$ the set of all bounded linear operators $A$ on $L^2(X,\mu)$ such that $P_1AP_1+P_2AP_2$ is trace-class and $P_1AP_2+P_2AP_1$ is Hilbert-Schmidt. For $A\in\mathscr{L}_{1|2}(L^2(X,\mu))$, we set \begin{equation}\label{def-Tr} \begin{split} \Tr(A):=\Tr(P_1AP_1+P_2AP_2). \end{split} \end{equation} Note that when $n\geq2$, for any $A_1,A_2,\cdots,A_n\in\mathscr{L}_{1|2}(L^2(X,\mu))$, since $A_1,A_2,\cdots,A_n$ are Hilbert-Schmidt operators, $A_1A_2\cdots A_n$ is trace-class, hence we may define $\Tr(A_1A_2\cdots A_n)$ as the usual trace of $A_1A_2\cdots A_n$. Suppose that $K$ is a $J$-self-adjont, locally $\mathscr{L}_{1|2}(L^2(X,\mu))$, bounded linear operator on $L^2(X,\mu)$. Here $K$ is locally $\mathscr {L}_{1|2}(L^2(X,\mu))$ means that for each $\Delta\in\mathcal{B}_0(X)$, the operator $\chi_{\Delta}K\chi _{\Delta}$ belongs to $\mathscr{L}_{1|2}(L^2(X,\mu))$, where $\chi_{\Delta}$ denotes the multiplication operator by the indicator of $\Delta$. Then by \eqref{def-Tr}, $\Tr(\chi_{\Delta}K\chi_{\Delta})$ makes sense. We can choose an integral kernel $K(x,y)$ of $K$ such that \begin{equation*} \begin{split} \Tr(\chi_{\Delta}K\chi_{\Delta})=\int_{\Delta}K(x,x)d\mu(x) \end{split} \end{equation*} for any $\Delta\in\mathcal{B}_0(X)$, see \cite[Proposition~13]{Ly}. Lytvynov \cite[Theorem 3]{Ly} proves that there is a determinantal point process on $X$ with $J$-Hermitian kernel $K$ with respect to the Radon measure $\mu$ if and only if \begin{equation}\label{0<Khat<1} \begin{split} 0\leq \widehat K\leq 1. \end{split} \end{equation} Following Soshnikov \cite[Theorem~1]{Soshn}, in what follows, we always assume that we can choose a $J$-Hermitian integral kernel $K(x,y)$ such that for any $\Delta\in\mathcal{B}_0(X)$, the operator $K\chi_{\Delta}$ belongs to $\mathscr {L}_{1|2}(L^2(X,\mu))$, then for any $n\in \mathbb{N}_+$ and $\Delta_1,\Delta_2\cdots,\Delta_n\in\mathcal{B}_0(X)$, \begin{equation*} \begin{split} \Tr(&K\chi _{\Delta_1}K\chi _{\Delta_2}\cdots K\chi _{\Delta_n})\\ &=\int_{\Delta_1\times\Delta_2\times\cdots\times\Delta_n}K(x_1,x_2)K(x_2,x_3)\cdots K(x_n,x_1)d\mu (x_1)\cdots d\mu (x_n). \end{split} \end{equation*} And then a simple function approximation yields that for any $n\in \mathbb{N}_+$ and $f_1,f_2,\cdots,f_n\in B_c(X)$, \begin{equation}\label{trace-integral} \begin{split} \Tr(&Kf_1Kf_2\cdots Kf_n)\\ &=\int_{X^n}f_1(x_1)K(x_1,x_2)f_2(x_2)K(x_2,x_3)\cdots f_n(x_n)K(x_n,x_1)d\mu (x_1)\cdots d\mu (x_n). \end{split} \end{equation} \subsection{Gaussian limit for DPPs with Hermitian kernels Let us briefly recall the work of Soshnikov on the Gaussian limit of DPPs with Hermitian kernels. Let $\mathbb{P}$ be a determinantal point process on a locally compact Polish space $X$ with kernel $K$ with respect to Radon measure $\mu$. It is important to study the behavior of linear statistics \begin{equation*} \begin{split} S_f(\xi):=\sum_{x\in\xi}f(x)\,,\quad\xi\in\Conf(X), \end{split} \end{equation*} for test functions in a scaling limit, a lot of results have been obtained in \cite{Ba,BW,CL,DE,DS,Joh,Jo,Sosh,Soshn,Sos,Sp,Wi}. The mathematical expectation and variance of $S_f$ can be calculated by \eqref{def-corre-func} and \eqref{def-dpp}, \begin{equation}\label{expecsf} \begin{split} \mathbb{E}_\mathbb{P}S_f=\int_Xf(x)K(x,x)d\mu(x), \end{split} \end{equation} \begin{equation}\label{varsf} \begin{split} \Var_\mathbb{P}S_f=\int_Xf^2(x)K(x,x)d\mu(x)-\int_{X^2}f(x)f(y)K(x,y)K(y,x)d\mu(x)d\mu(y). \end{split} \end{equation} Suppose that integral operator $K$ is self-adjont, non-negative definite, locally trace-class and bounded on $L^2(X,\mu)$. By a theorem obtained by Macchi \cite{Ma} and Soshnikov \cite{So}, as well as Shirai and Takahashi \cite{ST}, the integral kernel $K(x,y)$ of the operator $K$ is the correlation kernel of a determinantal point process if and only if $0\leq K\leq1$. For $L\geq0$, let $\mathbb{P}_L$ be a determinantal point process on locally compact Polish space $X_L$ with Hermitian kernel $K_L$ with respect to Radon measure $\mu_L$. And suppose that for any $\Delta\in\mathcal{B}_0(X_L)$, the operator $K_L\chi_{\Delta}$ is trace-class. Let $f_L\in B_c(X_L)$, the space of bounded measurable real-valued functions on $X_L$ with compact support. The work of Soshnikov \cite[Theorem~1]{Soshn} gives that, under some mild conditions, the centered normalized linear statistics \begin{equation*} \begin{split} \frac{S_{f_L}-\mathbb{E}_LS_{f_L}}{\sqrt{{\Var_L}S_{f_L}}} \end{split} \end{equation*} converges in distribution to the standard normal law $N(0,1)$ as $L\to +\infty$. From now on, we always denote $\mathbb{E}_L$ and $\Var_L$ the mathematical expectation and variance with respect to $\mathbb{P}_L$. \subsection{Main results} For a family of determinantal point processes with $J$-Hermitian kernels, our main result gives the central limit theorem for linear statistics when the variance grows faster than some fixed sufficiently small power of the mathematical expectation. For $L\geq 0$, suppose that $\mathbb{P}_L$ is a determinantal point process on locally compact Polish space $X_L=X_L^{(1)}\sqcup X_L^{(2)}$ with $J$-Hermitian kernel $K_L$ with respect to Radon measure $\mu _L$. And suppose that for any $\Delta\in\mathcal{B}_0(X_L)$, the operator $K_L\chi_{\Delta}$ belongs to $\mathscr {L}_{1|2}(L^2(X_L,\mu_L))$. For $f_L\in B_c(X_L)$, consider the linear statistics \[ S_{f_L}(\xi)=\sum_{x\in\xi}f_L(x), \, \xi\in\Conf(X_L). \] \begin{theorem}\label{thm-1} Suppose that \begin{itemize} \item $\Var_L(S_{f_L})\to +\infty$ as $L\to +\infty$; \item $\sup_{x\in X_L}|f_L(x)|=o((\Var_L(S_{f_L}))^\varepsilon)$ as $L\to +\infty$ for any $\varepsilon>0$; \item $\mathbb{E}_LS_{|f_L|}=O((\Var_L(S_{f_L}))^\delta)$ as $L\to +\infty$ for some $\delta>0$. \end{itemize} Then the centered normalized linear statistics \begin{equation*} \begin{split} \frac{S_{f_L}-\mathbb{E}_LS_{f_L}}{\sqrt{{\Var_L}S_{f_L}}} \end{split} \end{equation*} converges in distribution to the standard normal law $N(0,1)$ as $L\to +\infty$. \end{theorem} \begin{aomment} Theorem~\ref{thm-1} extends the work of Soshnikov for linear statistics over determinantal point processes with Hermitian kernels. Soshnikov's proof in \cite[Theorem~1]{Soshn} relies on the fact that when bounded linear self-adjoint operator $K$ is positive definite, terms like $\Tr(Kf_1Kf_2)$ are non-negative for non-negative functions $f_1$, $f_2$ with compact support, which is not the case for $J$-Hermitian kernels. This can not applied directly to $J$-Hermitian situation. On the other hand, when the underlying space $X$ is discrete, under the particle-hole duality transformation \[ \Conf(X)\ni\xi\mapsto\widehat{\xi}:=(\xi\cap X_1)\cup(X_2\backslash\,\xi), \] a $J$-Hermitian DPP turns into a Hermitian DPP and vise versa. By this particle-hole duality, it is easy to see that in the discrete setting, Theorem~\ref{thm-1} follows from the work of Soshnikov, see \cite{BOO,BQ,Ly,Soshn}. \end{aomment} Next we consider $X=\mathbb{R}^d_1\sqcup\mathbb{R}_2^d:=\mathbb{R}^d\sqcup\mathbb{R}^d$, $d\mu=dx_1+dx_2$, where $dx_i$ is the Lebesgue measure on $\mathbb{R}_i^d$, $i=1,2$. Let $A$ be a $J$-self-adjoint integral operator on $L^2(X,\mu)$ with $J$-Hermitian translation-invariant integral kernel \begin{equation}\label{J-HT-IIK} \begin{split} A(x_i,y_j)= \begin{bmatrix} F(x_1-y_1)&G(x_1-y_2) \\ -\overline G(y_1-x_2)&H(x_2-y_2) \end{bmatrix}, \end{split} \end{equation} where $F,G,H\in L^2(\mathbb{R}^d)$. Denote $\mathscr{F}$ the Fourier transform on $L^2(\mathbb{R}^d)$, that is, for any $T\in L^2(\mathbb{R}^d)$, \begin{equation*} \begin{split} (\mathscr{F}T)(x)=\lim\limits_{R\to+\infty}\int_{|t|<R}T(t)e^{-2\pi it\cdot x}dt, \end{split} \end{equation*} where the limit is in $L^2(\mathbb{R}^d)$. The following proposition gives a criterion to judge when does a $J$-Hermitian translation-invariant integral kernel can be a correlation kernel of a determinantal point process. \begin{proposition}\label{prop-2} There exists a determinantal point process on $\mathbb{R}^d\sqcup \mathbb{R}^d$ with $J$-Hermitian translation-invariant kernel $A$ as in \eqref{J-HT-IIK} if and only if for almost every $x\in \mathbb{R}^d$, \begin{equation*} \begin{split} \left\{\begin{array}{l} 0\leq (\mathscr{F}F)(x)\leq 1\\ 0\leq (\mathscr{F}H)(x)\leq 1\\ |(\mathscr{F}G)(x)|^2\leq (\mathscr{F}F)(x)[1-(\mathscr{F}H)(x)]\\ |(\mathscr{F}G)(x)|^2\leq (\mathscr{F}H)(x)[1-(\mathscr{F}F)(x)] \end{array}\right.. \end{split} \end{equation*} \end{proposition} For $L\geq0$, let $\mathbb{P}_L$ be a determinantal point process on $X=\mathbb{R}_1^d\sqcup\mathbb{R}_2^d=\mathbb{R}^d\sqcup\mathbb{R}^d$ with $J$-Hermitian translation-invariant kernel \begin{equation}\label{kernelAL} \begin{split} A_L(x_i,y_j)= \begin{bmatrix} F_L(x_1-y_1)&G_L(x_1-y_2) \\ -\overline{G_L}(y_1-x_2)&H_L(x_2-y_2) \end{bmatrix}, \end{split} \end{equation} where $F_L,G_L,H_L\in L^2(\mathbb{R}^d)$. It follows from Proposition~\ref{prop-2} that for almost every $x\in \mathbb{R}^d$, \begin{equation*} \begin{split} |(\mathscr{F}G_L)(x)|^2&\leq \min{\big\{(\mathscr{F}F_L)(x)[1-(\mathscr{F}H_L)(x)],\,(\mathscr{F}H_L)(x)[1-(\mathscr{F}F_L)(x)]\big\}}\\ &=\frac{1}{2}(\mathscr{F}F_L)(x)+\frac{1}{2}(\mathscr{F}H_L)(x)-(\mathscr{F}F_L)(x)(\mathscr{F}H_L)(x)\\ &\quad-\frac{1}{2}|(\mathscr{F}F_L)(x)-(\mathscr{F}H_L)(x)|, \end{split} \end{equation*} and \begin{equation*} \begin{split} 0\leq |(\mathscr{F}F_L)(x)-(\mathscr{F}H_L)(x)|\leq 1, \end{split} \end{equation*} hence \begin{equation*} \begin{split} \sigma_L^2:&=F_L(0)+H_L(0)-\int_{\mathbb{R}^d}|F_L(x)|^2dx-\int_{\mathbb{R}^d}|H_L(x)|^2dx-2\int_{\mathbb{R}^d}|G_L(x)|^2dx\\ &=\int_{\mathbb{R}^d}\big[(\mathscr{F}F_L)(x)+(\mathscr{F}H_L)(x)-(\mathscr{F}F_L)(x)^2-(\mathscr{F}H_L)(x)^2-2|(\mathscr{F}G_L)(x)|^2\big]dx\\ &\geq\int_{\mathbb{R}^d}\big[|(\mathscr{F}F_L)(x)-(\mathscr{F}H_L)(x)|-|(\mathscr{F}F_L)(x)-(\mathscr{F}H_L)(x)|^2\big]dx\\ &\geq0. \end{split} \end{equation*} For a real-valued function $f\in L^1(\mathbb{R}^d)\cap L^2(\mathbb{R}^d)$, the linear statistics \begin{equation*} \begin{split} S_{(f,-f)_L}(\xi):=\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}f\big (\frac{x}{L}\big )-\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}f\big (\frac{y}{L}\big )\,,\,\,\,\,\xi\in\Conf(\mathbb{R}_1^d\sqcup\mathbb{R}_2^d)=\Conf(\mathbb{R}^d\sqcup\mathbb{R}^d), \end{split} \end{equation*} as a random variable makes sense. In fact, consider the linear statistics \begin{equation*} \begin{split} S_{(|f|,|f|)_L}(\xi)=\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}\big|f\big (\frac{x}{L}\big )\big|+\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}\big|f\big (\frac{y}{L}\big )\big|\,,\,\,\,\,\xi\in\Conf(\mathbb{R}_1^d\sqcup\mathbb{R}_2^d)=\Conf(\mathbb{R}^d\sqcup\mathbb{R}^d), \end{split} \end{equation*} we can show $\mathbb{E}_LS_{(|f|,|f|)_L}<+\infty$. \begin{theorem}\label{thm-3} If there exist constants $\sigma >0$ and $C$ such that $\sigma_L\to \sigma$ as $L\to +\infty$, $F_L(0)+H_L(0)\leq C$ for all $L\geq 0$. And suppose that there exist $\kappa_L\to +\infty$ as $L\to +\infty$ such that \begin{equation*} \begin{split} \int_{|x|>\frac{L}{\kappa_L}}\big[|F_L(x)|^2+|H_L(x)|^2+2|G_L(x)|^2\big]dx\to 0\,\,\,\text{as}\,\,\,L\to +\infty. \end{split} \end{equation*} Then for any real-valued function $f\in L^1(\mathbb{R}^d)\cap L^2(\mathbb{R}^d)$, the centered normalized linear statistics \begin{equation*} \begin{split} \frac{1}{\sigma L^{d/2}}\Big\{\big[\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}f\big (\frac{x}{L}\big )-\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}f\big (\frac{y}{L}\big )\big]-\big[F_L(0)-H_L(0)\big]L^d\int_{\mathbb{R}^d}f(x)dx\Big\} \end{split} \end{equation*} converges in distribution to the Gaussian random variable $N(0,\int_{\mathbb{R}^d}f^2(x)dx)$ as $L\to +\infty$. \end{theorem} \section{Proof of main results} \subsection{Proof of Theorem~\ref{thm-1}} We will use the method of moments to prove Theorem~\ref{thm-1}. Before proof, we remind the reader that for a real-valued random variable $\eta$ with all finite moments, the cumulants $C_n(\eta)$, $n\in\mathbb{N_+}$, are defined through the expansion of the second characteristic function: \begin{equation}\label{def-cumu} \begin{split} \log\mathbb{E}(e^{it\eta})=\sum_{n=1}^{N}\frac{C_n(\eta)}{n!}(it)^n+o(|t|^N)\,\,\,\text{as}\,\,\,t\to 0. \end{split} \end{equation} We will use the following standard lemma, see, e.g. \cite[Theorem~3.3.26]{Du}, \cite[Corollary to Theorem~7.3.3]{Lu} and \cite[Lemma~3]{Soshn}. \begin{lemma}\label{lemma-1} Let $\{\eta_L\}_{L\geq 0}$ be a family of real-valued random variables such that $C_1(\eta_L)=0$, $C_2(\eta_L)=1$ for all $L\geq 0$, and $C_n(\eta_L)\to 0$ as $L\to +\infty$ when $n$ is sufficiently large. Then $\eta_L$ converges in distribution to the standard normal law $N(0,1)$ as $L\to +\infty$. \end{lemma} The following lemma is established by Soshnikov in \cite[formulas (2.6) and (2.7)]{Sos}. \begin{lemma}\label{lemma-2} Let $\mathbb{P}$ be a determinantal point process in a locally compact Polish space $X$ with kernel $K$ with respect to Radon measure $\mu$. For $f\in B_c(X)$, the $n$-th $(n\in\mathbb{N_+})$ cumulant of linear statistics $S_f$ can be expressed by \begin{equation*} \begin{split} C_n(S_f)=&\sum_{m=1}^{n}\sum_{\substack{(n_1,\cdots,n_m)\in\mathbb{N}_+^m\\n_1+\cdots+n_m=n}}\frac{(-1)^{m+1}}{m}\frac{n!}{n_1!\cdots n_m!}\\ &\times\int_{X^m}f^{n_1}(x_1)K(x_1,x_2)f^{n_2}(x_2)K(x_2,x_3)\cdots f^{n_m}(x_m)K(x_m,x_1)d\mu (x_1)\cdots d\mu (x_m). \end{split} \end{equation*} \end{lemma} Using Lemma~\ref{lemma-2} we are able to estimate the cumulants of $S_f$. We are going to prove the following claim. \begin{claim}\label{claim-3} Under the assumptions of Theorem~\ref{thm-1}, for any $m\in\mathbb{N_+}$, any $(n_1,\cdots,n_m)\in\mathbb{N}_+^m$, and any $\varepsilon>0$, \begin{equation*} \begin{split} \Tr(K_Lf_L^{n_1}K_Lf_L^{n_2}\cdots K_Lf_L^{n_m})=O((\Var_L(S_{f_L}))^{\delta+\varepsilon})\,\,\,\text{as}\,\,\,L\to +\infty. \end{split} \end{equation*} \end{claim} Now suppose that we have proved Claim~\ref{claim-3}, then it follows from fomula \eqref{trace-integral} and Lemma~\ref{lemma-2} that for any $n\in\mathbb{N_+}$ and any $\varepsilon>0$, \begin{equation}\label{estimate-cumu} \begin{split} C_n(S_{f_L})=O((\Var_L(S_{f_L}))^{\delta+\varepsilon})\,\,\,\text{as}\,\,\,L\to +\infty. \end{split} \end{equation} Denote \begin{equation*} \begin{split} \eta_L:=\frac{S_{f_L}-\mathbb{E}_LS_{f_L}}{\sqrt{{\Var_L}S_{f_L}}}. \end{split} \end{equation*} Then by the definition of cumulants \eqref{def-cumu}, it is easy to see that $C_1(\eta_L)=0$, $C_2(\eta_L)=1$ for all $L\geq 0$. And when $n>2$, for any $\varepsilon>0$, by \eqref{estimate-cumu} we obtain \begin{equation*} C_n(\eta_L)=\frac{C_n(S_{f_L})}{(\Var_L(S_{f_L}))^{\frac{n}{2}}}=\frac{O((\Var_L(S_{f_L}))^{\delta+\varepsilon})}{(\Var_L(S_{f_L}))^{\frac{n}{2}}}\,\,\,\text{as}\,\,\,L\to +\infty\,, \end{equation*} hence $C_n(\eta_L)\to 0$ as $L\to +\infty$ when $n>\max{\{2,2\delta\}}$. Thus by Lemma~\ref{lemma-1}, $\eta_L$ converges in distribution to $N(0,1)$ as $L\to +\infty$. \begin{proof}[Proof of Claim~\ref{claim-3}] Note that $\Tr(K_Lf_L^{n_1}K_Lf_L^{n_2}\cdots K_Lf_L^{n_m})$ is a linear combination of terms $\Tr(K_Lf_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{n_2}\cdots K_Lf_{L,\upsilon_m}^{n_m})$, where $\upsilon_i$ represents $+$ or $-$, $i=1,2,\cdots,m$, and $f_{L,+}=\max{\{f_L,0\}}$, $f_{L,-}=\max{\{-f_L,0\}}$. Let us fix the choice of $\upsilon_i$ in each of the factors, it is enough to prove that for any $\varepsilon>0$, \begin{equation*} \begin{split} \Tr(K_Lf_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{n_2}\cdots K_Lf_{L,\upsilon_m}^{n_m})=O((\Var_L(S_{f_L}))^{\delta+\varepsilon})\,\,\,\text{as}\,\,\,L\to +\infty. \end{split} \end{equation*} For the case $m=1$, by \eqref{def-dpp} and \eqref{trace-integral}, we have \begin{equation}\label{Tr(Kf)} \begin{split} \Tr(K_Lf_{L,\upsilon_1}^{n_1})=\int_{X_L}f_{L,\upsilon_1}^{n_1}(x)K_L(x,x)d\mu_L(x)\geq0. \end{split} \end{equation} It follows from \eqref{expecsf} that \begin{equation*} \begin{split} |\Tr(K_Lf_{L,\upsilon_1}^{n_1})|&=\Tr(K_Lf_{L,\upsilon_1}^{n_1})\\ &\leq\left\|f_{L,\upsilon_1}\right\|_\infty^{n_1-1}\int_{X_L}f_{L,\upsilon_1}(x)K_L(x,x)d\mu_L(x)\\ &\leq\left\|f_L\right\|_\infty^{n_1-1}\int_{X_L}|f_L(x)|K_L(x,x)d\mu_L(x)\\ &=\left\|f_L\right\|_\infty^{n_1-1}\mathbb{E}_LS_{|f_L|}\\ &=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}). \end{split} \end{equation*} For the case $m=2$, \begin{equation*} \begin{split} \Tr(K_Lf_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{n_2})&=\Tr\big[K_L(P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(2)}f_{L,\upsilon_1}^{n_1})K_L(P_L^{(1)}f_{L,\upsilon_2}^{n_2}+P_L^{(2)}f_{L,\upsilon_2}^{n_2})\big]\\ &=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(1)}f_{L,\upsilon_2}^{n_2})+\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2})\\ &\quad+\Tr(K_LP_L^{(2)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2})+\Tr(K_LP_L^{(2)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(1)}f_{L,\upsilon_2}^{n_2})\\ &=I_1(L)+I_2(L)+I_3(L)+I_4(L), \end{split} \end{equation*} where $P_L^{(i)}$ is the orthogonal projection of $L^2(X_L,\mu_L)$ onto $L^2(X_L^{(i)},\mu_L)$, $i=1,2$. Since the arguments for $I_3(L)$ and $I_4(L)$ are similar to those for $I_1(L)$ and $I_2(L)$, we only prove $I_1(L)=O((\Var_L(S_{f_L}))^{\delta+\varepsilon})$ and $I_2(L)=O((\Var_L(S_{f_L}))^{\delta+\varepsilon})$. Note that from \eqref{J-Hermitian}, we have $(P_L^{(1)}K_LP_L^{(1)})^*=P_L^{(1)}K_LP_L^{(1)}$, hence \begin{equation}\label{I1(L)} \begin{split} I_1(L)&=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(1)}f_{L,\upsilon_2}^{n_2})\\ &=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}P_L^{(1)}K_LP_L^{(1)}f_{L,\upsilon_2}^{n_2}P_L^{(1)})\\ &=\Tr(f_{L,\upsilon_2}^{n_2/2}P_L^{(1)}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}P_L^{(1)}K_LP_L^{(1)}f_{L,\upsilon_2}^{n_2/2})\\ &=\Tr\big[(f_{L,\upsilon_2}^{n_2/2}P_L^{(1)}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1/2})(f_{L,\upsilon_2}^{n_2/2}P_L^{(1)}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1/2})^*\big]\\ &\geq0. \end{split} \end{equation} It follows from \eqref{trace-integral} and \eqref{varsf} that \begin{equation*} \begin{split} \Var_L(S_{P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(1)}f_{L,\upsilon_2}^{n_2}})&=\Tr\big[K_L(P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(1)}f_{L,\upsilon_2}^{n_2})^2\big]\\ &\quad-\Tr\big[K_L(P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(1)}f_{L,\upsilon_2}^{n_2})K_L(P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(1)}f_{L,\upsilon_2}^{n_2})\big]\\ &=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{2n_1})+\Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{2n_2})+2\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}f_{L,\upsilon_2}^{n_2})\\ &\quad-\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1})-\Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{n_2}K_LP_L^{(1)}f_{L,\upsilon_2}^{n_2})\\ &\quad-2I_1(L)\\ &\leq\Tr(K_Lf_{L,\upsilon_1}^{2n_1})+\Tr(K_Lf_{L,\upsilon_2}^{2n_2})+2\Tr(K_Lf_{L,\upsilon_1}^{n_1+n_2})-2I_1(L), \end{split} \end{equation*} where the last inequality is based on \eqref{Tr(Kf)} and \eqref{I1(L)}. Note that the variance of a random variable is non-negative, we get \begin{equation*} \begin{split} |I_1(L)|&=I_1(L)\\ &\leq\frac{1}{2}\big[\Tr(K_Lf_{L,\upsilon_1}^{2n_1})+\Tr(K_Lf_{L,\upsilon_2}^{2n_2})+2\Tr(K_Lf_{L,\upsilon_1}^{n_1+n_2})\big]\\ &=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}), \end{split} \end{equation*} where the last equality is from the case $m=1$. As for $I_2(L)$, note that from \eqref{J-Hermitian}, we have $(P_L^{(2)}K_LP_L^{(1)})^*=-P_L^{(1)}K_LP_L^{(2)}$, hence \begin{equation}\label{I2(L)} \begin{split} I_2(L)&=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2})\\ &=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}P_L^{(1)}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2}P_L^{(2)})\\ &=\Tr(f_{L,\upsilon_2}^{n_2/2}P_L^{(2)}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}P_L^{(1)}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2/2})\\ &=-\Tr\big[(f_{L,\upsilon_2}^{n_2/2}P_L^{(2)}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1/2})(f_{L,\upsilon_2}^{n_2/2}P_L^{(2)}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1/2})^*\big]\\ &\leq0. \end{split} \end{equation} It follows from \eqref{trace-integral} and \eqref{varsf} that \begin{equation*} \begin{split} \Var_L(S_{P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(2)}f_{L,\upsilon_2}^{n_2}})&=\Tr\big[K_L(P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(2)}f_{L,\upsilon_2}^{n_2})^2\big]\\ &\quad-\Tr\big[K_L(P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(2)}f_{L,\upsilon_2}^{n_2})K_L(P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(2)}f_{L,\upsilon_2}^{n_2})\big]\\ &=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{2n_1})+\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{2n_2})\\ &\quad-\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1})-\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2})\\ &\quad-2I_2(L), \end{split} \end{equation*} and \begin{equation*} \begin{split} \Var_L(S_{P_L^{(1)}f_{L,\upsilon_1}^{n_1}})+\Var_L(S_{P_L^{(2)}f_{L,\upsilon_2}^{n_2}})&=\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{2n_1})-\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1})\\ &\quad+\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{2n_2})-\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2}). \end{split} \end{equation*} Using the basic fact \begin{equation*} \begin{split} \Var_L(S_{P_L^{(1)}f_{L,\upsilon_1}^{n_1}+P_L^{(2)}f_{L,\upsilon_2}^{n_2}})&=\Var_L(S_{P_L^{(1)}f_{L,\upsilon_1}^{n_1}}+S_{P_L^{(2)}f_{L,\upsilon_2}^{n_2}})\\ &\leq2\big[\Var_L(S_{P_L^{(1)}f_{L,\upsilon_1}^{n_1}})+\Var_L(S_{P_L^{(2)}f_{L,\upsilon_2}^{n_2}})\big], \end{split} \end{equation*} together with \eqref{Tr(Kf)}, \eqref{I1(L)}, \eqref{I2(L)} and the case $m=1$, we obtain \begin{equation*} \begin{split} |I_2(L)|&=-I_2(L)\\ &\leq\frac{1}{2}\big[\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{2n_1})+\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{2n_2})\\ &\quad\quad-\Tr(K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1}K_LP_L^{(1)}f_{L,\upsilon_1}^{n_1})-\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2})\big]\\ &\leq\frac{1}{2}\big[\Tr(K_Lf_{L,\upsilon_1}^{2n_1})+\Tr(K_Lf_{L,\upsilon_2}^{2n_2})\big]\\ &=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}), \end{split} \end{equation*} where we used the inequality $\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2}K_LP_L^{(2)}f_{L,\upsilon_2}^{n_2})\geq0$ by arguments similar to \eqref{I1(L)}. For the case $m\geq3$, using the Cauchy-Schwarz inequality $|\Tr(AB)|^2\leq\Tr(AA^*)\Tr(BB^*)$ for Hilbert-Schmidt operators $A$ and $B$, we have \begin{equation*} \begin{split} &\quad\,\,\Big|\Tr(K_Lf_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{n_2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m})\Big|^2\\ &=\Big|\Tr\big[(f_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{{n_2}/2})(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L)\big]\Big|^2\\ &\leq\Tr\big[(f_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{{n_2}/2})(f_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{{n_2}/2})^*\big]\\ &\quad\times\Tr\big[(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L)(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L)^*\big]\\ &=\Tr(K_Lf_{L,\upsilon_2}^{{n_2}}K_L^*f_{L,\upsilon_1}^{{2n_1}})\\ &\quad\times\Tr(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_LK_L^*f_{L,\upsilon_m}^{n_m}K_L^*\cdots f_{L,\upsilon_4}^{n_4}K_L^*f_{L,\upsilon_3}^{n_3}K_L^*f_{L,\upsilon_2}^{{n_2}/2}).\\ \end{split} \end{equation*} And using the inequality $|\Tr(AB)|\leq\Tr(A)\left\|B\right\|$ for positive operator $A$ which is trace-class and bounded linear operator $B$, see, e.g. \cite[Theorem~2.7, ~2.14]{Si}, we have \begin{equation*} \begin{split} &\quad\,\,\Tr(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_LK_L^*f_{L,\upsilon_m}^{n_m}K_L^*\cdots f_{L,\upsilon_4}^{n_4}K_L^*f_{L,\upsilon_3}^{n_3}K_L^*f_{L,\upsilon_2}^{{n_2}/2})\\ &=\Tr(f_{L,\upsilon_3}^{n_3}K_L^*f_{L,\upsilon_2}^{{n_2}/2}f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_LK_L^*f_{L,\upsilon_m}^{n_m}K_L^*\cdots f_{L,\upsilon_4}^{n_4}K_L^*)\\ &=\Tr\big[(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3})^*(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3})(K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L)(K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L)^*\big]\\ &\leq\Tr\big[(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3})^*(f_{L,\upsilon_2}^{{n_2}/2}K_Lf_{L,\upsilon_3}^{n_3})\big]\left\|(K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L)(K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L)^*\right\|\\ &\leq\Tr(K_Lf_{L,\upsilon_3}^{{2n_3}}K_L^*f_{L,\upsilon_2}^{{n_2}})\left\|K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L\right\|^2. \end{split} \end{equation*} These estimations deduce that \begin{equation*} \begin{split} &\quad\,\,\Big|\Tr(K_Lf_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{n_2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m})\Big|^2\\ &\leq\Tr(K_Lf_{L,\upsilon_2}^{{n_2}}K_L^*f_{L,\upsilon_1}^{{2n_1}})\Tr(K_Lf_{L,\upsilon_3}^{{2n_3}}K_L^*f_{L,\upsilon_2}^{{n_2}})\left\|K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L\right\|^2\\ &=J_1(L)J_2(L)\left\|D_L\right\|^2. \end{split} \end{equation*} Based on \eqref{0<Khat<1} and \cite[Proposition~7]{Ly}, we have $\left\|K_L\right\|\leq1$, then \begin{equation*} \begin{split} \left\|D_L\right\|&=\left\|K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m}K_L\right\|\\ &\leq\left\|f_{L,\upsilon_4}\right\|_{\infty}^{n_4}\cdots\left\|f_{L,\upsilon_m}\right\|_{\infty}^{n_m}\left\|K_L\right\|^{m-2}\\ &\leq\left\|f_L\right\|_{\infty}^{n_4+\cdots+n_m}\\ &=o((\Var_L(S_{f_L}))^\varepsilon). \end{split} \end{equation*} Split $J_1(L)$ into four parts as follow: \begin{equation*} \begin{split} J_1(L)&=\Tr(K_Lf_{L,\upsilon_2}^{{n_2}}K_L^*f_{L,\upsilon_1}^{{2n_1}})\\ &=\Tr\big[K_L(P_L^{(1)}f_{L,\upsilon_2}^{{n_2}}+P_L^{(2)}f_{L,\upsilon_2}^{{n_2}})K_L^*(P_L^{(1)}f_{L,\upsilon_1}^{{2n_1}}+P_L^{(2)}f_{L,\upsilon_1}^{{2n_1}})\big]\\ &=\Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(1)}f_{L,\upsilon_1}^{{2n_1}})+\Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(2)}f_{L,\upsilon_1}^{{2n_1}})\\ &\quad+\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(1)}f_{L,\upsilon_1}^{{2n_1}})+\Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(2)}f_{L,\upsilon_1}^{{2n_1}}).\\ \end{split} \end{equation*} It follows from \eqref{J-Hermitian} and the case $m=2$ that \begin{equation*} \begin{split} \Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(1)}f_{L,\upsilon_1}^{{2n_1}})&=\Tr\big[K_Lf_{L,\upsilon_2}^{{n_2}}(P_L^{(1)}K_L^*P_L^{(1)})f_{L,\upsilon_1}^{{2n_1}}\big]\\ &=\Tr\big[K_Lf_{L,\upsilon_2}^{{n_2}}(P_L^{(1)}K_LP_L^{(1)})f_{L,\upsilon_1}^{{2n_1}}\big]\\ &=\Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{{n_2}}K_LP_L^{(1)}f_{L,\upsilon_1}^{{2n_1}})\\ &=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}), \end{split} \end{equation*} and \begin{equation*} \begin{split} \Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(2)}f_{L,\upsilon_1}^{{2n_1}})&=\Tr\big[K_Lf_{L,\upsilon_2}^{{n_2}}(P_L^{(1)}K_L^*P_L^{(2)})f_{L,\upsilon_1}^{{2n_1}}\big]\\ &=-\Tr\big[K_Lf_{L,\upsilon_2}^{{n_2}}(P_L^{(1)}K_LP_L^{(2)})f_{L,\upsilon_1}^{{2n_1}}\big]\\ &=-\Tr(K_LP_L^{(1)}f_{L,\upsilon_2}^{{n_2}}K_LP_L^{(2)}f_{L,\upsilon_1}^{{2n_1}})\\ &=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}). \end{split} \end{equation*} Similarly, we have \begin{equation*} \Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(1)}f_{L,\upsilon_1}^{{2n_1}})=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}), \end{equation*} and \begin{equation*} \Tr(K_LP_L^{(2)}f_{L,\upsilon_2}^{{n_2}}K_L^*P_L^{(2)}f_{L,\upsilon_1}^{{2n_1}})=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}), \end{equation*} hence we obtain $J_1(L)=O((\Var_L(S_{f_L}))^{\delta+\varepsilon})$. As for $J_2(L)$, we also have $J_2(L)=O((\Var_L(S_{f_L}))^{\delta+\varepsilon})$ by arguments similar to $J_1(L)$. Together with the estimations of $\left\|D_L\right\|$, $J_1(L)$ and $J_2(L)$, this concludes that \begin{equation*} \begin{split} \Tr(K_Lf_{L,\upsilon_1}^{n_1}K_Lf_{L,\upsilon_2}^{n_2}K_Lf_{L,\upsilon_3}^{n_3}K_Lf_{L,\upsilon_4}^{n_4}\cdots K_Lf_{L,\upsilon_m}^{n_m})=O((\Var_L(S_{f_L}))^{\delta+\varepsilon}). \end{split} \end{equation*} This completes the proof of Theorem~\ref{thm-1}. \end{proof} \subsection{Proof of Proposition~\ref{prop-2}} By slightly abusing the notation, the associated integral operator $A$ with $J$-Hermitian translation-invariant kernel $A$ in \eqref{J-HT-IIK} can be written in block form: \begin{equation*} \begin{split} A= \begin{bmatrix} F&G\\ -G^*&H \end{bmatrix}, \end{split} \end{equation*} and then the operator $\widehat A$ denoted by \eqref{def-Khat} has the following block form: \begin{equation*} \begin{split} \widehat A= \begin{bmatrix} F&G\\ G^*&P_2-H \end{bmatrix}. \end{split} \end{equation*} It follows from \eqref{0<Khat<1} that there exists a determinantal point process on $\mathbb{R}^d\sqcup \mathbb{R}^d$ with kernel $A$ if and only if $0\leq\widehat A\leq1$. Using the fomula $\mathscr{F}(T_1*T_2)=(\mathscr{F}T_1)(\mathscr{F}T_2)$ when $T_1, T_2\in L^2(\mathbb{R}^d)$, for any function in $L^2(\mathbb{R}^d\sqcup\mathbb{R}^d)=L^2(\mathbb{R}^d)\oplus L^2(\mathbb{R}^d)$, i.e. for any $f_1,f_2\in L^2(\mathbb{R}^d)$, we have \begin{equation*} \begin{split} \begin{bmatrix} \mathscr{F}&0\\ 0&\mathscr{F} \end{bmatrix} \begin{bmatrix} F&G\\ G^*&P_2-H \end{bmatrix} \begin{bmatrix} f_1\\ f_2 \end{bmatrix} = \begin{bmatrix} \mathscr{F}F&\mathscr{F}G\\ \overline{\mathscr{F}G}&1-\mathscr{F}H \end{bmatrix} \begin{bmatrix} \mathscr{F}&0\\ 0&\mathscr{F} \end{bmatrix} \begin{bmatrix} f_1\\ f_2 \end{bmatrix}, \end{split} \end{equation*} hence \begin{equation*} \begin{split} \begin{bmatrix} F&G\\ G^*&P_2-H \end{bmatrix} = \begin{bmatrix} \mathscr{F}^{-1}&0\\ 0&\mathscr{F}^{-1} \end{bmatrix} \begin{bmatrix} \mathscr{F}F&\mathscr{F}G\\ \overline{\mathscr{F}G}&1-\mathscr{F}H \end{bmatrix} \begin{bmatrix} \mathscr{F}&0\\ 0&\mathscr{F} \end{bmatrix}. \end{split} \end{equation*} Since the Fourier transform $\begin{bmatrix}\mathscr{F}&0\\0&\mathscr{F}\end{bmatrix}$ is an unitary operator on $L^2(\mathbb{R}^d\sqcup\mathbb{R}^d)$, the operator $\widehat A=\begin{bmatrix}F&G\\G^*&P_2-H\end{bmatrix}$ and the multiplication operator $\begin{bmatrix}\mathscr{F}F&\mathscr{F}G\\\overline{\mathscr{F}G}&1-\mathscr{F}H \end{bmatrix}$ are unitary equivalent, hence $0\leq\widehat A\leq1$ is equivalent to \begin{equation}\label{Four-tran-matr} \begin{split} 0\leq \begin{bmatrix} \mathscr{F}F&\mathscr{F}G\\ \overline{\mathscr{F}G}&1-\mathscr{F}H \end{bmatrix} \leq1. \end{split} \end{equation} Denote \begin{equation*} \begin{split} M_1(x)=\begin{bmatrix}(\mathscr{F}F)(x)&(\mathscr{F}G)(x)\\\overline{(\mathscr{F}G)}(x)&1-(\mathscr{F}H)(x)\end{bmatrix} \text{and } M_2(x)=\begin{bmatrix}1-(\mathscr{F}F)(x)&-(\mathscr{F}G)(x)\\-\overline{(\mathscr{F}G)}(x)&(\mathscr{F}H)(x)\end{bmatrix}. \end{split} \end{equation*} Hence \eqref{Four-tran-matr} implies that Proposition~\ref{prop-2} requires us to find the necessary and sufficient conditions such that \begin{equation}\label{integral1} \begin{split} \int_{\mathbb{R}^d}\big(\overline{f_1}(x)\,\,\,\,\overline{f_2}(x)\big)M_1(x)\big({f_1}(x)\,\,\,\,{f_2}(x)\big)^{\mathrm{T}}dx\geq0 \end{split} \end{equation} and \begin{equation}\label{integral2} \begin{split} \int_{\mathbb{R}^d}\big(\overline{f_1}(x)\,\,\,\,\overline{f_2}(x)\big)M_2(x)\big({f_1}(x)\,\,\,\,{f_2}(x)\big)^{\mathrm{T}}dx\geq0 \end{split} \end{equation} for any $f_1,f_2\in L^2(\mathbb{R}^d)$. \begin{claim}\label{claim-4} \eqref{integral1} and \eqref{integral2} hold for any $f_1,f_2\in L^2(\mathbb{R}^d)$ if and only if for almost every $x\in\mathbb{R}^d$, the matrices $M_1(x)$ and $M_2(x)$ are non-negative definite. \end{claim} For a fixed $x\in\mathbb{R}^d$, the matrix $M_1(x)$ is non-negative definite is equivalent to saying that $(\mathscr{F}F)(x)\geq0$, $1-(\mathscr{F}H)(x)\geq0$, and $\det[M_1(x)]\geq0$, that is \begin{equation}\label{Fourier1} \begin{split} \left\{\begin{array}{l} (\mathscr{F}F)(x)\geq0\\ (\mathscr{F}H)(x)\leq1\\ |(\mathscr{F}G)(x)|^2\leq (\mathscr{F}F)(x)[1-(\mathscr{F}H)(x)] \end{array}\right.. \end{split} \end{equation} Similarly, the matrix $M_2(x)$ is non-negative definite is equivalent to \begin{equation}\label{Fourier2} \begin{split} \left\{\begin{array}{l} (\mathscr{F}F)(x)\leq1\\ (\mathscr{F}H)(x)\geq0\\ |(\mathscr{F}G)(x)|^2\leq (\mathscr{F}H)(x)[1-(\mathscr{F}F)(x)] \end{array}\right.. \end{split} \end{equation} Combining \eqref{Fourier1}, \eqref{Fourier2} with Claim \ref{claim-4}, Prpposition \ref{prop-2} follows. \begin{proof}[Proof of Claim~\ref{claim-4}] If for almost every $x\in\mathbb{R}^d$, the matrices $M_1(x)$ and $M_2(x)$ are non-negative definite, then for any $f_1,f_2\in L^2(\mathbb{R}^d)$, we have \begin{equation*} \begin{split} \big(\overline{f_1}(x)\,\,\,\,\overline{f_2}(x)\big)M_1(x)\big({f_1}(x)\,\,\,\,{f_2}(x)\big)^{\mathrm{T}}\geq0\,\,\,\,\text{a.e.}\,\,x\in\mathbb{R}^d, \end{split} \end{equation*} and \begin{equation*} \begin{split} \big(\overline{f_1}(x)\,\,\,\,\overline{f_2}(x)\big)M_2(x)\big({f_1}(x)\,\,\,\,{f_2}(x)\big)^{\mathrm{T}}\geq0\,\,\,\,\text{a.e.}\,\,x\in\mathbb{R}^d, \end{split} \end{equation*} these imply \eqref{integral1} and \eqref{integral2}. Conversely, we shall prove that for almost every $x\in\mathbb{R}^d$, the matrix $M_1(x)$ is non-negative definite and we omit the arguments of $M_2(x)$ which is similar to $M_1(x)$. Fix any $N\in\mathbb{N_+}$, it is enough to prove that the matrix $M_1(x)$ is non-negative definite for almost every $x\in[-N,N]^d$. Let $\mathcal{Q}=\{q_n\}_{n=1}^{\infty}$ be a fixed countable dense subset of $\mathbb{C}$. For $m,n\in\mathbb{N_+}$, set $f_1=q_m\chi_{[-N,N]^d}$, $f_2=q_n\chi_{[-N,N]^d}$, then we have \begin{equation*} \begin{split} \int_{[-N,N]^d}(\overline{q_m}\,\,\,\,\overline{q_n})M_1(x)(q_m\,\,\,q_n)^{\mathrm{T}}dx\geq0. \end{split} \end{equation*} Since almost every $x\in[-N,N]^d$ is Lebesgue point of the integrand $(\overline{q_m}\,\,\,\,\overline{q_n})M_1(x)(q_m\,\,\,q_n)^{\mathrm{T}}$, and the integral over any ball supported in ${[-N,N]^d}$ is always non-negative by \eqref{integral1}, there is a zero measure set $E_{mn}$ such that for any $x\in[-N,N]^d\big\backslash E_{mn}$, \begin{equation*} \begin{split} (\overline{q_m}\,\,\,\,\overline{q_n})M_1(x)(q_m\,\,\,q_n)^{\mathrm{T}}\geq0. \end{split} \end{equation*} Hence for any $x\in[-N,N]^d\big\backslash\big(\bigcup_{m,n\geq1}E_{mn}\big)$ and any $p,q\in\mathcal{Q}$, \begin{equation*} \begin{split} (\overline{p}\,\,\,\overline{q})M_1(x)(p\,\,\,q)^{\mathrm{T}}\geq0. \end{split} \end{equation*} This yields that for any $x\in[-N,N]^d\big\backslash\big(\bigcup_{m,n\geq1}E_{mn}\big)$ and any $a,b\in\mathbb{C}$, \begin{equation*} \begin{split} (\overline{a}\,\,\,\overline{b})M_1(x)(a\,\,\,b)^{\mathrm{T}}\geq0. \end{split} \end{equation*} Note that $\bigcup _{m,n\geq1}E_{mn}$ has zero measure, thus for almost every $x\in[-N,N]^d$, the matrix $M_1(x)$ is non-negative definite. This shows that for almost every $x\in\mathbb{R}^d$, the matrix $M_1(x)$ is non-negative definite. This completes the proof of Proposition~\ref{prop-2}. \end{proof} \subsection{Proof of Theorem~\ref{thm-3}} For a real-valued function $f\in L^1(\mathbb{R}^d)\cap L^2(\mathbb{R}^d)$ and $L\geq0$, let us first consider the linear statistics \begin{equation*} \begin{split} S_{(|f|,|f|)_L}(\xi)=\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}\big|f\big (\frac{x}{L}\big )\big|+\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}\big|f\big (\frac{y}{L}\big )\big|\,,\,\,\,\,\xi\in\Conf(\mathbb{R}_1^d\sqcup\mathbb{R}_2^d)=\Conf(\mathbb{R}^d\sqcup\mathbb{R}^d), \end{split} \end{equation*} according to \eqref{expecsf} and \eqref{kernelAL}, by a simple function approximation, we obtain \begin{equation}\label{calculation1} \begin{split} \mathbb{E}_LS_{(|f|,|f|)_L}&=\int_{\mathbb{R}^d}|f(x/L)|F_L(x-x)dx+\int_{\mathbb{R}^d}|f(x/L)|H_L(x-x)dx\\ &=[F_L(0)+H_L(0)]L^d\int_{\mathbb{R}^d}|f(x)|dx\\ &\leq CL^d\int_{\mathbb{R}^d}|f(x)|dx\\ &=O(L^d). \end{split} \end{equation} Hence for fixed $L\geq0$, the linear statistics \begin{equation*} \begin{split} S_{(f,-f)_L}(\xi)=\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}f\big (\frac{x}{L}\big )-\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}f\big (\frac{y}{L}\big )\,,\,\,\,\,\xi\in\Conf(\mathbb{R}_1^d\sqcup\mathbb{R}_2^d)=\Conf(\mathbb{R}^d\sqcup\mathbb{R}^d), \end{split} \end{equation*} as a random variable makes sense, and \begin{equation}\label{calculation2} \begin{split} \mathbb{E}_LS_{(f,-f)_L}&=\int_{\mathbb{R}^d}f(x/L)F_L(x-x)dx-\int_{\mathbb{R}^d}f(x/L)H_L(x-x)dx\\ &=[F_L(0)-H_L(0)]L^d\int_{\mathbb{R}^d}f(x)dx. \end{split} \end{equation} Through a simple function approximation, \eqref{J-Hermitian-kernel}, \eqref{varsf} and \eqref{kernelAL} yield that \begin{equation*} \begin{split} \Var_LS_{(f,-f)_L}&=\int_{\mathbb{R}^d}f^2(x/L)F_L(x-x)dx+\int_{\mathbb{R}^d}f^2(x/L)H_L(x-x)dx\\ &\quad-\int_{\mathbb{R}^d\times\mathbb{R}^d}f(x/L)f(y/L)F_L(x-y)F_L(y-x)dxdy\\ &\quad-\int_{\mathbb{R}^d\times\mathbb{R}^d}f(x/L)f(y/L)H_L(x-y)H_L(y-x)dxdy\\ &\quad+2\int_{\mathbb{R}^d\times\mathbb{R}^d}f(x/L)f(y/L)G_L(x-y)G_L(y-x)dxdy\\ &=[F_L(0)+H_L(0)]L^d\int_{\mathbb{R}^d}f^2(x)dx\\ &\quad-\int_{\mathbb{R}^d\times\mathbb{R}^d}f(x/L)f(y/L)|F_L(x-y)|^2dxdy\\ &\quad-\int_{\mathbb{R}^d\times\mathbb{R}^d}f(x/L)f(y/L)|H_L(x-y)|^2dxdy\\ &\quad-2\int_{\mathbb{R}^d\times\mathbb{R}^d}f(x/L)f(y/L)|G_L(x-y)|^2dxdy. \end{split} \end{equation*} Using the Fourier transform and Plancherel theorem, we get \begin{equation*} \begin{split} \Var_LS_{(f,-f)_L}&=[F_L(0)+H_L(0)]L^d\int_{\mathbb{R}^d}f^2(x)dx\\ &\quad-L^d\int_{\mathbb{R}^d}|(\mathscr{F}f)(x)|^2(\mathscr{F}|F_L|^2)(x/L)dx\\ &\quad-L^d\int_{\mathbb{R}^d}|(\mathscr{F}f)(x)|^2(\mathscr{F}|H_L|^2)(x/L)dx\\ &\quad-2L^d\int_{\mathbb{R}^d}|(\mathscr{F}f)(x)|^2(\mathscr{F}|G_L|^2)(x/L)dx\\ &=\sigma_L^2L^d\int_{\mathbb{R}^d}f^2(x)dx\\ &\quad+L^d\int_{\mathbb{R}^d}|(\mathscr{F}f)(x)|^2\Big\{\big[(\mathscr{F}|F_L|^2)(0)+(\mathscr{F}|H_L|^2)(0)+2(\mathscr{F}|G_L|^2)(0)\big]\\ &\quad\qquad\quad\quad-\big[(\mathscr{F}|F_L|^2)(x/L)+(\mathscr{F}|H_L|^2)(x/L)+2(\mathscr{F}|G_L|^2)(x/L)\big]\Big\}dx\\ &=(\sigma^2+o(1))L^d\int_{\mathbb{R}^d}f^2(x)dx+L^dr(L)\\ &=\sigma^2L^d\int_{\mathbb{R}^d}f^2(x)dx+o(L^d)+L^dr(L). \end{split} \end{equation*} \begin{claim}\label{claim-5} Under the assumptions of Theorem~\ref{thm-3}, $r(L)=o(1)$ as $L\to+\infty$. \end{claim} It follows from Claim \ref{claim-5} that \begin{equation}\label{calculation3} \begin{split} \Var_LS_{(f,-f)_L}=\sigma^2L^d\int_{\mathbb{R}^d}f^2(x)dx+o(L^d)\,\,\,\text{as}\,\,\,L\to +\infty. \end{split} \end{equation} Hence if $f\in B_c(\mathbb{R}^d)$, together with \eqref{calculation1}, \eqref{calculation2}, \eqref{calculation3} and Theorem \ref{thm-1}, we have \begin{equation*} \begin{split} \frac{\big[\sum_{x\in\xi\cap\mathbb{R}_1^d}f(\frac{x}{L})-\sum_{y\in\xi\cap\mathbb{R}_2^d}f(\frac{y}{L})\big]-\big[F_L(0)-H_L(0)\big]L^d\int_{\mathbb{R}^d}f(x)dx}{\sqrt{\sigma^2L^d\int_{\mathbb{R}^d}f^2(x)dx+o(L^d)}} \end{split} \end{equation*} converges in distribution to $N(0,1)$ as $L\to +\infty$. And then we can deduce that \begin{equation*} \begin{split} \frac{1}{\sigma L^{d/2}}\Big\{\big[\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}f\big (\frac{x}{L}\big )-\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}f\big (\frac{y}{L}\big )\big]-\big[F_L(0)-H_L(0)\big]L^d\int_{\mathbb{R}^d}f(x)dx\Big\} \end{split} \end{equation*} converges in distribution to $N(0,\int_{\mathbb{R}^d}f^2(x)dx)$ as $L\to +\infty$. As for general real-valued function $f\in L^1(\mathbb{R}^d)\cap L^2(\mathbb{R}^d)$, we choose $f_n\in B_c(\mathbb{R}^d)$ such that $f_n$ approach to $f$ as $n\to\infty$ in $L^2$-sense. Observe that \begin{equation*} \begin{split} &\quad\mathbb{E}_L\Big[\Big(\frac{S_{(f,-f)_L}-\mathbb{E}_LS_{(f,-f)_L}}{\sigma L^{d/2}}-\frac{S_{(f_n,-f_n)_L}-\mathbb{E}_LS_{(f_n,-f_n)_L}}{\sigma L^{d/2}}\Big)^2\,\Big]\\ &=\frac{1}{\sigma^2L^d}\mathbb{E}_L\Big[\big(S_{(f-f_n,\,-(f-f_n))_L}-\mathbb{E}_LS_{(f-f_n,\,-(f-f_n))_L}\big)^2\,\Big]\\ &=\frac{1}{\sigma^2L^d}\Var_LS_{(f-f_n,\,-(f-f_n))_L}\\ &=\frac{1}{\sigma^2L^d}\Big(\sigma^2L^d\int_{\mathbb{R}^d}[f(x)-f_n(x)]^2dx+o(L^d)\Big)\\ &=\int_{\mathbb{R}^d}[f(x)-f_n(x)]^2dx+o(1) \end{split} \end{equation*} can be arbitrarily small when $n$ and $L$ are sufficiently large. Since \begin{equation*} \begin{split} \frac{1}{\sigma L^{d/2}}\Big\{\big[\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}f_n\big (\frac{x}{L}\big )-\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}f_n\big (\frac{y}{L}\big )\big]-\big[F_L(0)-H_L(0)\big]L^d\int_{\mathbb{R}^d}f_n(x)dx\Big\} \end{split} \end{equation*} converges in distribution to $N(0,\int_{\mathbb{R}^d}f_n^2(x)dx)$ as $L\to +\infty$, and \begin{equation*} \begin{split} \lim\limits_{n\to\infty}\int_{\mathbb{R}^d}f_n^2(x)dx=\int_{\mathbb{R}^d}f^2(x)dx, \end{split} \end{equation*} a simple analysis implies that \begin{equation*} \begin{split} \frac{1}{\sigma L^{d/2}}\Big\{\big[\sum\limits_{x\in\xi\cap \mathbb{R}_1^d}f\big (\frac{x}{L}\big )-\sum\limits_{y\in\xi\cap \mathbb{R}_2^d}f\big (\frac{y}{L}\big )\big]-\big[F_L(0)-H_L(0)\big]L^d\int_{\mathbb{R}^d}f(x)dx\Big\} \end{split} \end{equation*} converges in distribution to $N(0,\int_{\mathbb{R}^d}f^2(x)dx)$ as $L\to +\infty$. \begin{proof}[Proof of Claim \ref{claim-5}] Denote $W_L=|F_L|^2+|H_L|^2+2|G_L|^2$, a simple calculation about Fourier transform gives that \begin{equation*} \begin{split} (\mathscr{F}W_L)(x)=\int_{\mathbb{R}^d}\big[&(\mathscr{F}F_L)(t)(\mathscr{F}F_L)(x-t)+(\mathscr{F}H_L)(t)(\mathscr{F}H_L)(x-t)\\ &+2(\mathscr{F}G_L)(t)\overline{(\mathscr{F}G_L)}(x-t)\big]dt. \end{split} \end{equation*} Hence by Cauchy-Schwarz inequality and Plancherel theorem, we obtain \begin{equation}\label{W(L)-estimateion} \begin{split} |(\mathscr{F}W_L)(x)|&\leq\int_{\mathbb{R}^d}\big[|(\mathscr{F}F_L)(t)|^2+|(\mathscr{F}H_L)(t)|^2+2|(\mathscr{F}G_L)(t)|^2\big]dt\\ &=\int_{\mathbb{R}^d}\big[|F_L(x)|^2+|H_L(x)|^2+2|G_L(x)|^2\big]dt\\ &=F_L(0)+H_L(0)-\sigma_L^2\\ &\leq F_L(0)+H_L(0)\\ &\leq C. \end{split} \end{equation} Split $r(L)$ into two parts as follow: \begin{equation*} \begin{split} r(L)&=\int_{\mathbb{R}^d}|(\mathscr{F}f)(x)|^2\big[(\mathscr{F}W_L)(0)-(\mathscr{F}W_L)(x/L)\big]dx\\ &=\int_{|x|>\sqrt{\kappa_L}}|(\mathscr{F}f)(x)|^2\big[(\mathscr{F}W_L)(0)-(\mathscr{F}W_L)(x/L)\big]dx\\ &\quad+\int_{|x|\leq\sqrt{\kappa_L}}|(\mathscr{F}f)(x)|^2\big[(\mathscr{F}W_L)(0)-(\mathscr{F}W_L)(x/L)\big]dx\\ &=r_1(L)+r_2(L). \end{split} \end{equation*} It follows from \eqref{W(L)-estimateion} that \begin{equation}\label{r1(L)} \begin{split} |r_1(L)|&\leq\int_{|x|>\sqrt{\kappa_L}}|(\mathscr{F}f)(x)|^2\big|(\mathscr{F}W_L)(0)-(\mathscr{F}W_L)(x/L)\big|dx\\ &\leq2C\int_{|x|>\sqrt{\kappa_L}}|(\mathscr{F}f)(x)|^2dx\\ &=o(1). \end{split} \end{equation} To deal with $r_2(L)$, note that $W_L$ is non-negative and estimate by \eqref{W(L)-estimateion}, we have \begin{equation*} \begin{split} |(\mathscr{F}W_L)(0)-(\mathscr{F}W_L)(x/L)|&=\Big|\int_{\mathbb{R}^d}W_L(t)(1-e^{-2\pi it\cdot \frac{x}{L}})dt\Big|\\ &\leq\int_{|t|>\frac{L}{\kappa_L}}W_L(t)\big|1-e^{-2\pi it\cdot \frac{x}{L}}\big|dt\\ &\quad+\int_{|t|\leq\frac{L}{\kappa_L}}W_L(t)\big|1-e^{-2\pi it\cdot \frac{x}{L}}\big|dt\\ &\leq2\int_{|t|>\frac{L}{\kappa_L}}W_L(t)dt+\frac{2\pi|x|}{\kappa_L}\int_{|t|\leq\frac{L}{\kappa_L}}W_L(t)dt\\ &\leq2\int_{|t|>\frac{L}{\kappa_L}}W_L(t)dt+\frac{2\pi|x|}{\kappa_L}\int_{\mathbb{R}^d}W_L(t)dt\\ &=2\int_{|t|>\frac{L}{\kappa_L}}W_L(t)dt+\frac{2\pi|x|}{\kappa_L}(\mathscr{F}W_L)(0)\\ &\leq2\int_{|t|>\frac{L}{\kappa_L}}W_L(t)dt+\frac{2\pi C|x|}{\kappa_L}\,. \end{split} \end{equation*} Therefore, \begin{equation}\label{r2(L)} \begin{split} |r_2(L)|&\leq\int_{|x|\leq\sqrt{\kappa_L}}|(\mathscr{F}f)(x)|^2\big|(\mathscr{F}W_L)(0)-(\mathscr{F}W_L)(x/L)\big|dx\\ &\leq\Big(2\int_{|t|>\frac{L}{\kappa_L}}W_L(t)dt+\frac{2\pi C}{\sqrt{\kappa_L}}\Big)\int_{|x|\leq\sqrt{\kappa_L}}|(\mathscr{F}f)(x)|^2dx\\ &\leq2\Big(\int_{|t|>\frac{L}{\kappa_L}}W_L(t)dt+\frac{\pi C}{\sqrt{\kappa_L}}\Big)\int_{\mathbb{R}^d}|(\mathscr{F}f)(x)|^2dx\\ &=o(1). \end{split} \end{equation} The estimations \eqref{r1(L)} and \eqref{r2(L)} imply $r(L)=o(1)$. This completes the proof of Theorem~\ref{thm-3}. \end{proof}
{ "redpajama_set_name": "RedPajamaArXiv" }
4,350
\section{Introduction} This paper studies a disclosure game in which evidence is endogenously and flexibly acquired at a cost by a sender. Once she has acquired the evidence, the sender chooses whether to pay a third-party firm to certify it.\footnote{Equivalently, the sender must incur some cost in order to disclose her findings.} In the absence of such certification, the sender's message is merely cheap talk (equivalently, the sender simply does not disclose her evidence). Upon observing the sender's message the receiver takes an action that affects both players' payoffs. Real-world examples that are captured by this setup abound. For instance, this model is an extension of the seminal papers \cite{verr1} and \cite{verr2}, in which the sender is a manager of a risky asset and the receiver is a collection of market traders. It is natural to suppose that the evidence available to the manager for disclosure takes time and effort to acquire. Another suitable example is that of a monopolist generating information about its product in order to convince consumers to purchase it. Product tests are costly yet can be designed with care, justifying the flexible approach we allow our sender. We grant the sender complete flexibility over what evidence she acquires, but impose that more and finer information is more costly to acquire. This is realistic. Consider our leading example, in which the sender is the manager of a firm (or the firm itself) and the state is the value of some economic asset. In this setting, the manager has significant freedom about the type and quality of information she acquires. She can instruct her employees to scrutinize certain aspects of the asset more than others, hire accountants with expertise in different areas, or conduct tests or reviews with different emphases. Furthermore, more (finer) information is more expensive. More thorough tests are more expensive to run, more skilled employees are more expensive to hire, and hiring more workers costs more. Within this environment we are interested in the following three things. First, what is the impact of transparency in the evidence gathering stage? We look at two different cases--covert, in which the sender's evidence acquisition is secret; and overt, in which it is public--and compare the equilibria between the two. Second, what is the role played by evidence acquisition costs? In particular, how do the equilibria and players' welfare change as it becomes more difficult for the sender to acquire information? As such costs vanish, what equilibrium in the costless acquisition benchmark serves as the limit? Third, what is the role of the certification fee given that the evidence is exogenous? We find that the receiver always prefers covert to overt evidence acquisition, strictly if there is an equilibrium with covert acquisition in which the sender acquires information. That is, transparency is always detrimental to the receiver's welfare. This phenomenon arises since transparency grants the sender a form of partial commitment absent when her evidence acquisition is hidden. Our sender would like to credibly commit not to acquire any information at all, but when evidence acquisition is covert and information is not too costly, she finds it too tempting to secretly deviate and acquire information, to the receiver's benefit. That the overtness of evidence acquisition may lead to total uninformativeness is also observed by \cite{demarzo} (who specify that a sender's test may fail to return evidence \'{a} la \cite{dye}), and the intuition behind their result is identical to ours. They also find that the receiver may strictly benefit from opacity but the intuition behind their result is different from that for ours. Specifically, in their setting, all tests are equally costly (or costless), and so a ``minimum principle'' holds, which imposes that the market is maximally pessimistic about the asset's quality following non-disclosure. Not so in our setting; instead, the belief by our receiver (or the market) upon observing non-disclosure is the fixed-point lower point of support in our sender's optimal flexible learning. Even when evidence acquisition is covert, if the costs of obtaining evidence or certification are too high, the sender acquires no information in any equilibrium. However, if obtaining evidence is sufficiently cheap and the certification cost is relatively low, the sender acquires evidence in every equilibrium. We also look at what happens as information costs vanish. We find that when this occurs, all equilibria converge to the Pareto-worst free-learning equilibrium, which highlights a significant difference between cheap information and free information. This is reminiscent of the main finding of \cite{ravid2020learning}, but the mechanics behind the results are different. Our result occurs because when information is costly, the sender always seeks extremely coarse evidence: she either acquires evidence that the state is high, which she gets certified; or evidence that it is low, which she does not. We also look at the effect of the certification fee. Perhaps surprisingly, since it stands in stark contrast to the findings in the papers with exogenous information, when evidence acquisition is covert, the receiver always weakly prefers a strictly positive certification fee and may strictly prefer it. The certification fee cannot be too high, or else the sender will not learn, but a low but positive certification fee strictly improves the receiver's welfare. The reason for this result is subtle and stems from the endogeneity (and cost) of the information available to the sender. There cannot be an equilibrium in which the sender acquires evidence when certification is free since the receiver's conjectured belief following non-certification \textit{can never be correct}. Because certification is free, the sender's payoff as a function of the expected value of the state is locally strictly convex at the conjectured belief (there is a kink precisely at the conjectured expected value) and so it is never optimal for the sender to obtain that value and not certify it.\footnote{We illustrate this in Figure \ref{fig3} \textit{infra}.} Given this, the only possible equilibrium is that the sender acquires no evidence and always gets it certified, which is indeed the equilibrium when there is no certification cost. We finish this section by discussing related work. Section \ref{model} introduces the model, Section \ref{bench} goes through a benchmark when evidence acquisition is costless, and Section \ref{main} contains the (bulk of the) main results. Section \ref{pareto} details our free-learning equilibrium selection result, and Section \ref{discus} concludes. Appendix \ref{eqdef} specifies our equilibrium concept, and Appendix \ref{omitproof} contains the proofs omitted from the text. We argue that our findings persist when our setting is instead that of \cite{dye} in a \href{https://whitmeyerhome.files.wordpress.com/2022/08/costly_evidence_and_discretionary_disclosure_supplement_v2.pdf}{Supplementary Appendix} \subsection{Related Work} \cite{shishkin}, who also endogenizes evidence acquisition in the model of \cite{dye} but imposes that such acquisition is costless, is the closest paper to this one. \citeauthor{shishkin} also distinguishes between the overt and covert scenarios and shows that the equilibrium evidence structures take remarkably simple forms: for a low failure rate it is a pass-fail test; and it is two-sided censorship (in which an intermediate region of states is fully disclosed) otherwise. Our sender also chooses simple evidence (she always acquires at most two pieces of evidence), but in our setting this is a consequence of the fact that more precise evidence is more expensive. \cite{transwhitjain} is also similar. There, the authors study a disclosure game with two senders, each of whom acquires evidence (for free) in order to obtain the favor of a receiver. The commitment power engendered by overt evidence acquisition (what they term ``transparency of protocol'') also makes the receiver worse off vis-a-vis the covert scenario, though the mechanism is different to this one. Things are more complicated there since a sender's payoff is itself an equilibrium object, generated by the strategy of the other sender. This paper is also related to \cite{bert}, who study a problem in which a regulator designs a measurement system (a signal) about an asset's value, the realization of which is observed by manager (privately) with some exogenous probability, which she may then disclose to investors (the receiver) if she obtained evidence. Their problem is similar to \cite{shishkin} in that generating evidence is costless, although in their setting it is a third party who designs the information. \cite{demarzo} also endogenizes evidence acquisition in the setting of \cite{dye} by allowing a sender to choose a test from set $K$ of available tests, before choosing whether to disclose its outcome or pretend to have received a null result (which occurs with some probability). In part of the paper they assume that tests are costly but importantly this cost is \textit{independent of the test, its result, or the asset's quality (the state)}, which is not the case in our paper. This creates significant divergences between our results and theirs: they find that as the testing costs vanish, nearly all of their agents (the testing cost, for them, is a random variable) take the test; whereas our limiting outcome, in contrast, is particularly inefficient: our sender chooses the Pareto-worst equilibrium evidence structure. Likewise, our finding about the benefits (to the receiver) of a certification cost (or positive test failure rate) is absent from their paper since their constant cost precludes the local convexity at the conjectured belief property that we encounter. Other works that endogenize the sender's information in disclosure games are \cite{pae}, who, like \cite{demarzo}, allows the sender to pay an nondiscriminatory cost to acquire information about the (in \citeauthor{pae}'s paper) endogenous state; and \cite{hughespae}, who stipulate that the sender may pay some (again, fixed) cost to receive the ``precision information'' about the unknown state. In \cite{bendekellip}, the manager (sender) chooses from different projects the random outcome from which she may disclose. Surprisingly, the manager takes excessive risks even if the expected return is lower. Competition is a key feature of \cite{kartikleesuen} who study a competitive disclosure game with multiple senders. Each (privately) chooses the probability with which she obtains evidence (subject to an increasing cost), which she may subsequently disclose. \cite{hardinfo} study the problem of a buyer who chooses publicly what (distribution over) hard evidence to obtain, which she may then disclose to a monopolistic seller who engages in nonlinear pricing.\footnote{A couple other less similar but still relevant papers are \cite{henry}, who also studies transparency in a disclosure game with information acquisition in which acquired evidence can be concealed; and \cite{penno}, who allows a sender to choose the precision of the firm's financial reporting system.} There is also a literature on information acquisition in cheap-talk games. In a general cheap-talk environment, \cite{pei} looks at covert costly information acquisition and establishes that a sender always communicates what she finds to the receiver. The intuition driving this result is similar to that implying our Lemmas \ref{mainlemma1} and \ref{mainlemma2}. \cite{argenz} compare covert and overt costly information acquisition, and find that under both regimes, the sender over-acquires information and that the receiver may prefer either to delegation. \cite{escude} allows a sender to costlessly and covertly acquire partially verifiable information about the state, which he discovers is always revealed by the sender. In \cite{lyusuen}, the authors study overt, costless information acquisition preceding cheap talk. Finally, our sender, taking as given her disclosure strategy, faces a Bayesian persuasion/information acquisition problem (\cite{kam} and \cite{kamcostly}), and so our paper fits broadly within these literatures.\footnote{\cite{macksurvey} and \cite{bpsurvey} provide comprehensive surveys of the two areas.} Specifically, we use techniques from \cite{gent}, \cite{linearprog}, \cite{martini} and \cite{bipool} throughout. To the best of our knowledge, we are the only paper to study costly flexible evidence acquisition in a game of verifiable disclosure. This is valuable for two reasons. First, it is realistic: an asset manager has significant freedom about what evidence to acquire, and finer and more granular information is more expensive. Second, it leads to effects and predictions absent from settings with exogenous evidence, endogenous but free (or equally costly) evidence, or endogenous evidence from a family of distributions parameterized by a scalar. \section{The Model}\label{model} There is a sender (she, $S$) and a receiver (he, $R$). There is an unknown state of the world $\theta \in \left[0,1\right]$ about which $S$ and $R$ share a common prior with cdf $F$ and mean $\mu \in \left(0,1\right)$. $F$ admits a strictly positive density $f$. For technical convenience, $F$ is strictly log-concave. $R$'s set of actions is $A = \left[0,1\right]$ and her utility is the commonly-used ``quadratic'' loss specification: $u_{R}\left(a,\theta\right) = -\left(a-\theta\right)^2$. The sender's utility is state-independent and linear in the sender's action: $u_{S} = a$. Before communicating to $R$, $S$ acquires information flexibly subject to a cost. We allow her considerable freedom in this regard: she may choose any signal $\pi \colon \left[0,1\right] \to \Delta\left(X\right)$, where $X$ is a (compact) set of signal realizations.\footnote{For a compact metrizable space \(Y\), let \(\Delta (Y)\) denote the set of all probability measures on the Borel subsets of \(Y\).} As is well-known, the quadratic loss utility of $R$ means that $R$'s (uniquely) optimal action at any posterior distribution is simply the posterior expectation.\footnote{Thus, an alternative interpretation of our setup is that given by \cite{verr1} and the literature that follows: he specifies that the receiver is a market and that the sender wants to maximize the expected market value of the project (belief about the state).} For this reason, it is without loss to restrict attention on the class of signals where \(X = [0,1]\), and each \(x \in X\) equals the induced posterior mean: \(x = \mathbb{E}[\theta | x]\). Moreover, the set of distributions of posterior means that is consistent with some signal is the set of mean-preserving contractions (MPCs) of the prior $F$,\footnote{This is established formally in \cite{linearprog}. A distribution \(G \in \Delta([0,1])\) is a mean-preserving contraction of \(F\) if \(\int_{0}^{x} G(s) d s \leq \int_{0}^{x} F(s) d s\) for all \(x \in [0,1]\), where the inequality holds with equality at \(x=1\).} which we denote by $\mathcal{M}\left(F\right)$. Given this, we specify that the sender's cost of acquiring information is posterior-mean measurable: the cost of acquiring any $G \in \mathcal{M}(F)$ is \[C\left(G\right) = \kappa \int_{0}^{1}c\left(x\right)dG\left(x\right) \text{,}\] where $c$ is a twice-differentiable, strictly convex function that is bounded on $\left(0,1\right)$ and satisfies $c\left(\mu\right) = 0$; and $\kappa > 0$ is a scaling parameter. Note that this cost function has the desirable feature that it is monotone with respect to informativeness: if $G$ is a MPC of $\hat{G}$, i.e., corresponds to a less informative Blackwell experiment than $\hat{G}$, $C\left(G\right) \leq C\left(\hat{G}\right)$. One specific example of such a cost function is that in which $c\left(x\right) = \left(x-\mu\right)^2$, which we use in Section \ref{uniformsec}'s example.\footnote{We impose that the cost of acquiring information is mean-measurable for simplicity of exposition. By identifying with the prior $F$ a joint distribution $\Phi\left(x_1, x_2, x_3, \dots, x_n\right)$ over the first $n$ non-centered posterior moments, we could instead that the cost of acquiring information is functional $C\left(\Upsilon\right) = \kappa \int c d\Upsilon$ where $\Upsilon$ is a fusion (the $n$-dimensional generalization of an MPC) of $\Phi$ and $c \colon \mathbb{R}^{n} \to \mathbb{R}_{+}$ is a convex function. As we note in the \href{https://whitmeyerhome.files.wordpress.com/2022/08/costly_evidence_and_discretionary_disclosure_supplement_v2.pdf}{Supplementary Appendix}, our main findings all continue to hold in this generalization.} It is only the posterior mean that is strategically relevant for $R$, and therefore the same holds for $S$. Because of this, we limit the space of messages available to $S$ to be $M \coloneqq \left[0,1\right] \cup \left\{m_{\varnothing}\right\}$, where $m_{\varnothing}$ corresponds to non-disclosure (non-certification). This is a game of verifiable disclosure: if $S$ acquires posterior mean $x$, her set of available messages is $M_{x} \coloneqq \left\{x, m_{\varnothing}\right\}$. Disclosure of $x$ is costly, so we can think of the choice of message $x$ as paying a certifier cost $\gamma > 0$ to verify that the posterior mean is indeed $x$ and the choice of message $m_{\varnothing}$ as $S$ declining to have her claim certified. We specify that the sender's overall payoff is additively separable in $u_S$, the cost of certification ($\gamma$), and the cost of acquiring information. We are interested in the effects of transparency in this environment and, therefore, look at two different cases: \begin{enumerate}[noitemsep,topsep=0pt] \item \textbf{Covert Evidence Acquisition} $R$ does not observe $G$ and $G$ cannot be certified. \item \textbf{Overt Evidence Acquisition} $R$ observes $G$. \end{enumerate} The latter case is ``more transparent'' than the former: $R$ observes $S$'s information gathering activities, no matter whether $S$ gets the outcome certified. The timing of the game is as follows: \begin{enumerate}[noitemsep,topsep=0pt] \item $S$ acquires information by choosing some distribution of posterior means $G \in \mathcal{M}\left(F\right)$. \item $S$ observes the realization $x$ from $G$ then chooses whether to get $x$ certified (send message $x$) and incur cost $\gamma$ or not (send message $m_{\varnothing}$). \item $R$ observes $S$'s message and $G$ if evidence acquisition is overt. \item $R$ takes action $a$ and payoffs realize. \end{enumerate} We study perfect Bayesian equilibria of the game. A formal definition of the equilibria, for both covert and overt evidence acquisition, can be found in Appendix \ref{eqdef}. \section{Costless Evidence Benchmark}\label{bench} We begin by discussing a natural benchmark; the case when $\kappa = 0$, and, therefore, it is costless for $S$ to acquire information. First, let us look at the overt acquisition case. Suppose first that the certification fee is not too high: $\gamma < 1- \mu$; in which case, given a conjectured (expected) value of non-disclosed evidence, $\alpha$, the sender's payoff from acquiring posterior $x$ is \[V\left(x\right) = \begin{cases} \alpha, \quad &\text{if} \quad 0 \leq x < \alpha + \gamma\\ x-\gamma, \quad &\text{if} \quad \alpha + \gamma \leq x \leq 1 \end{cases}\text{,}\] where $\alpha \leq \mu$. This function is convex and piecewise linear, with one inflection point at $\alpha + \gamma < 1$. Thus, in any best response by $S$, she will not pool any states below $\alpha + \gamma$ with those above when she acquires information. She does not want to contract the distribution across the inflection point as doing so would strictly lower her payoff. Consequently, in any equilibrium the disclosure must be a truncation: the sender will not disclose any evidence below the equilibrium inflection point $\alpha^{*} + \gamma$ of the value function. Strict log-concavity of $F$ (\cite{bag}) ensures that the state of indifference, and therefore $\alpha^{*}$, is unique: \begin{lemma}\label{firstlemma} With covert evidence acquisition and a low certification cost ($\gamma < 1-\mu$), in any equilibrium, the expected value of the state conditional on non-certification, $\alpha^{*}$, solves \[\label{star}\tag{$\star$}\alpha^{*} = \mathbb{E}_{F}\left[\left. \theta \right| \theta \leq \alpha^{*}+\gamma\right]\text{.}\] \end{lemma} On the other hand, when obtaining evidence is free, the sender's payoff is linear on $[\alpha^* + \gamma, 1]$, and hence she is indifferent as to what evidence she acquires about states above $\alpha^{*}+\gamma$. The receiver, of course, is not indifferent and prefers more information. As a result, there is a large multiplicity of equilibria, which can be Pareto ranked. \begin{proposition}\label{firstprop} With covert evidence acquisition and a low certification cost ($\gamma < 1-\mu$), any evidence acquisition protocol in which the sender does not pool states above $x^{*} \coloneqq \alpha^{*} + \gamma$ (where $\alpha^*$ is defined in \ref{star}) with those below, then certifies a posterior, $x$, if and only if $x \geq x^*$, is an equilibrium. There are no other equilibria. These equilibria can be Pareto ranked: the Pareto-best equilibrium is that in which the sender acquires full information and discloses above $x^{*}$. The Pareto-worst equilibrium is that in which the distribution of posterior means above $x^*$ is degenerate on $\mathbb{E}\left[\left.\theta\right|\theta \geq x^*\right]$. \end{proposition} It is clear that the Pareto-maximal payoff is uniquely induced (since it is an MPS of all other equilibrium distributions of posteriors) by the stated equilibrium.\footnote{By uniquely we mean unique up to the distribution of non-certified posteriors, which are behaviorally and payoff-irrelevant.} Moreover, the receiver's (and sender's) payoffs are precisely those that they would obtain if the information were exogenously $F$. \textit{Viz.,} the receiver obtains the same payoff as if the sender were fully informed about the state exogenously. Similarly, the Pareto-minimal payoff is also uniquely induced (since it is an MPC of all other equilibrium distributions). In this equilibrium, the sender (and receiver) learn only whether the state is above $x^*$, nothing more. When certification is expensive: $\gamma \geq 1-\mu$, in any equilibrium there is no certification. \begin{proposition}\label{secondprop} With covert evidence acquisition and a high certification cost ($\gamma \geq 1-\mu$), there is no certification in equilibrium. \end{proposition} Because there is no certification, these equilibria are all equivalent in the sense that there is no information transmission and the sender's and receiver's payoffs are unaffected by the distribution of posterior means acquired by the sender. When obtaining evidence is overt, the analysis is equally simple: \begin{proposition}\label{lastbenchprop} With overt evidence acquisition, there is an equilibrium in which the sender acquires no information and never certifies. In every equilibrium, the sender acquires no posteriors strictly greater than $\min\{\mu + \gamma,1\}$ and never certifies. \end{proposition} For all intents and purposes, all of the equilibria with overt evidence acquisition are the same and equivalent to the one in which the sender chooses the degenerate distribution, i.e., acquires zero evidence and never certifies. In each, there is no information transmission and the sender does not waste any resources on certification. The partial commitment power granted to the sender by transparency hurts the receiver. The sender may now credibly commit to effectively learn nothing about the state, which she does in every equilibrium. As we will see, this result persists when evidence is costly ($\kappa > 0$). \section{Main Analysis}\label{main} Now we introduce a cost to acquiring information, i.e., the cost parameter is $\kappa > 0$. \subsection{Covert Evidence Acquisition} Our first result notes that at most one piece of certified evidence is followed by certification (with positive probability) in any equilibrium. \begin{lemma}\label{mainlemma1} In any equilibrium, the distribution of posterior means acquired by the sender, $G$, has support on at most one posterior that is certified with positive probability. \end{lemma} Key to this lemma is the fact that $S$'s payoff is linear (gross of the cost of obtaining the belief) in $R$'s posterior $x$, but the cost of obtaining a belief $x$ is strictly convex. Thus, by learning less collapsing beliefs to their average, $S$ can save on costs while not affecting the direct payoff from certification. \begin{lemma}\label{mainlemma2} In any equilibrium, the distribution of posterior means acquired by the sender, $G$, has support on at most one posterior that is not certified with positive probability. \end{lemma} In Lemma \ref{mainlemma1}, it was the linearity of the gross payoff that rendered a single certified posterior optimal. Here, the gross payoff from a non-certified posterior is just a constant--recall that it is the conjectured posterior following non-certification (message $m_{\varnothing}$)--which again makes coarse(r) learning superior for the sender. Combining these lemmas, we have the following proposition, which pins down coarse learning as a necessary feature of any equilibrium: \begin{proposition}\label{simplify} In any equilibrium, the distribution of posterior means acquired by the sender, $G$, has support on at most two points. The sender never randomizes following information acquisition: a posterior in support of $G$ is either certified or not. \end{proposition} We see that the costliness of obtaining evidence leads to coarse information. The sender optimally acquires at most two pieces of evidence: good news, which she finds worthwhile to get certified; or bad news, which she does not. This hints at our convergence result of the next section. Information is valuable for the receiver, but this is not internalized by the sender, who instead saves on her privately-incurred costs of obtaining evidence by omitting fine details. Next, we turn our attention to equilibrium existence, before moving on to the more interesting (and economically relevant) discussion of properties of equilibria. \begin{theorem}\label{maintheorem} An equilibrium always exists. It is not necessarily unique. \end{theorem} Here is a sketch of the proof: if the cost of certification is sufficiently high ($\gamma \geq 1-\mu$), the result is immediate since there exists an equilibrium in which the sender acquires no information and certifies with probability $0$. Now let $\gamma < 1-\mu$. For a fixed (conjectured) value of non-certification, $\alpha \in \left[0,\mu\right]$, the sender's payoff as a function of her acquired posterior $x$ is \[V_{\alpha}\left(x\right) = \begin{cases} \alpha - \kappa c\left(x\right), \quad &\text{if} \quad \alpha + \gamma > x\\ x-\gamma- \kappa c\left(x\right), \quad &\text{if} \quad \alpha + \gamma \leq x\\ \end{cases} \text{.}\] In her evidence acquisition problem, the sender chooses a distribution $G_{\alpha}$ that solves \[\label{maxprob}\tag{$\triangle$}\max_{G \in \mathcal{M}\left(F\right)}\int V_{\alpha} \, dG \text{.}\] We finish by showing that there must always exist a fixed point $\alpha$ that corresponds to the sender's optimally acquired $G_{\alpha}$. At equilibrium there are four potential types of information acquisition. First, the sender may acquire coarse evidence about whether the state is high or low (Figure \ref{figsub1}). There, the sender's evidence acquisition corresponds to a truncation of the distribution: she is sure whether the state is above some threshold, but nothing more. This occurs if the cost of acquiring information ($\kappa$) is sufficiently low and the certification cost ($\gamma$) is also low (but not $0$). In the parlance of \cite{martini} or \cite{bipool}, this is a monotone partitional evidence structure. Second, the sender may acquire evidence but occasionally conflate high states with low ones and \textit{vice versa} (Figure \ref{figsub2}). This may occur (depending on the cost function) if $\kappa$ and $\gamma$ are moderately low. In the parlance of \cite{bipool}, this is a ``bi-pooling'' evidence structure. Third, the sender may acquire no evidence but always certify it (Figure \ref{figsub3}). This occurs if $\kappa$ is high but $\gamma$ is low. Non-certification is off-path and is met with extreme pessimism ($0$ belief) if the receiver observes it. Fourth, the sender may acquire no evidence and never certify it (Figure \ref{figsub4}). This occurs if $\kappa$ and $\gamma$ are high. In both of these cases, the sender collapses the entire distribution to its barycenter (mean), learning nothing. \begin{figure \centering \begin{subfigure}{.5\textwidth} \centering \includegraphics[scale=.15]{mono1fin.png} \caption{Low $\kappa$ and $\gamma$.} \label{figsub1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[scale=.15]{mono4fin.png} \caption{Moderate $\kappa$ and low $\gamma$.} \label{figsub2} \end{subfigure} \par \bigskip \par \bigskip \par \begin{subfigure}{.5\textwidth} \centering \includegraphics[scale=.15]{mono3fin.png} \caption{High $\kappa$ and low $\gamma$.} \label{figsub3} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[scale=.15]{mono2fin.png} \caption{High $\kappa$ and $\gamma$.} \label{figsub4} \end{subfigure} \caption{\textbf{The Four Varieties of Covert Equilibria:} The equilibrium payoff functions as functions of the acquired posterior mean ($x$) given the conjectured non-certification value ($\alpha$) are the colored curves. The dual in this optimization problem (the ``price function'' of \cite{martini}), in black, determines the sender's optimal evidence.} \label{fig2} \end{figure} \subsection{Some Properties of (Covert) Equilibria} No matter the cost functional, the prior, or the cost of certification, if information is sufficiently costly, there exists an equilibrium in which the sender does not acquire any information, and there exist no equilibria in which the sender acquires information. \begin{proposition}\label{costofinfoprop} For any prior $F$, cost functional $C$, and certification cost $\gamma > 0$, if $\kappa$ is sufficiently high, there exist no equilibria with evidence acquisition. \end{proposition} That is, for any fixed combination of the other primitives, there exists a threshold cost of information $\bar{\kappa}$ such that if $\kappa$ exceeds $\bar{\kappa}$ the only equilibria are those in which the sender does not obtain any evidence. Moreover, as we illustrate in the proof, for $\kappa$ sufficiently large, there is a multiplicity: in any equilibrium the sender acquires no evidence, but there is an equilibrium in which the sender never gets the evidence (or lack thereof) certified \textit{and} an equilibrium in which the sender gets the evidence certified. In contrast, unless $\gamma \geq 1-\mu$, if $\kappa$ is sufficiently small, the sender acquires information then discloses if the evidence is good. \begin{proposition}\label{costofinfoprop2} For any prior $F$, cost functional $C$, and certification cost $0 < \gamma < 1-\mu$, there exists a threshold cost of information $\ubar{\kappa} > 0$ such that if $\kappa \leq \ubar{\kappa}$, all equilibria must involve information acquisition. \end{proposition} The effect of the certification on the existence of equilibria in which the sender acquires information is more ambiguous. Roughly, as $\gamma$ decreases, it makes it harder to sustain equilibria in which the sender neither acquires evidence nor gets it certified. However, it makes it easier to sustain equilibria in which the sender does not acquire evidence but nevertheless gets it certified. In fact, when $\gamma = 0$, this is the only equilibrium that exists: \begin{proposition}\label{nodisccostprop} If certification is costless, $\gamma = 0$, but evidence gathering is costly, $\kappa >0$, the unique equilibrium is that in which the sender acquires no evidence but gets it certified. \end{proposition} This proposition reveals a key difference between this paper's setting--with costly (flexible) evidence acquisition--and the exogenous information environment. In the latter, the receiver's welfare is strictly decreasing as the disclosure (verification) cost increases since the equilibrium level of information transmitted is strictly decreasing. Here, we see that costless certification is the worst case for the receiver. Due to the endogeneity of the sender's evidence, it is only when the certification cost is strictly positive that the sender faces sufficient incentives to acquire information. As we explain in the introduction, the force driving the result is the local convexity in the payoff from acquiring evidence at the conjectured ``no-certification belief'' $\alpha$. Figure \ref{fig3} depicts this for various cost functions. \begin{figure} \centering \includegraphics[scale=.15]{localconvexfin.png} \caption{The Local Convexity of $V\left(x\right)$ at $\alpha$.} \label{fig3} \end{figure} Naturally, the certification cost cannot be too high: if $\gamma \geq 1-\mu$, there is no evidence acquisition (and hence no information transmission) at equilibrium. However, provided $\gamma$ is in an intermediate range, and the cost of acquiring information is not too high (refer to Proposition \ref{costofinfoprop2}), there is information transmission in any equilibrium, a strict improvement for the receiver. Summing things up, \begin{corollary} The receiver prefers a strictly positive certification cost to no certification cost. If the cost of acquiring evidence is sufficiently low, this preference is strict. \end{corollary} \subsection{Overt Evidence Acquisition} The presence of evidence acquisition costs does not change the effects of transparency. Now, however, the equilibrium is unique. The sender acquires no information, obtaining her maximal payoff, to the receiver's chagrin: \begin{proposition}\label{overtbad} The unique equilibrium is for the sender to acquire no information and not disclose. \end{proposition} \begin{proof} The maximal payoff the sender can obtain in any equilibrium is $\mu$, the expected state. Thus, in any equilibrium she must get this payoff, because otherwise she could deviate by acquiring no information and not certifying. This is credible, since her evidence acquisition (at least her distribution of posteriors) is public. Because evidence acquisition is costly, a payoff of $\mu$ corresponds uniquely to acquiring no evidence followed by $m_{\varnothing}$. \end{proof} Of course, by Jensen's inequality, this result continues to hold as long as long as the sender's reduced-form payoff as a function of the receiver's posterior is strictly concave. An easy sufficient condition for this is that the sender's reduced-form payoff (gross of the cost of obtaining evidence) is weakly concave. Another sufficient condition is that the second derivative of the sender's reduced-form payoff (gross of cost) is bounded on $\left[0,1\right]$ and the cost parameter $\kappa$ is sufficiently large. In light of Proposition \ref{lastbenchprop}, which states that there is no information transmission when information is free and its acquisition is overt, this result is not surprising. A cost of acquiring evidence only discourages evidence acquisition, which gives the sender more of an incentive to forgo learning. \subsection{Uniform Prior, Quadratic Cost Example}\label{uniformsec} \begin{figure} \centering \includegraphics[scale=.15]{regionsforpaperfin.png} \caption{Division of the Parameter Space for the Uniform Prior, Quadratic Cost Example. In Regions $A$ and $B$, the sender acquires no evidence and either always does not disclose, or always discloses, respectively. In Region $C$, these equilibria coexist. In Region $D$, the sender acquires evidence at equilibrium.} \label{figregions} \end{figure} Next, we will briefly discuss an example in which the state's distribution is the standard uniform and the information cost is $c\left(x\right) = \left(x-\mu\right)^2$. \begin{proposition}\label{upqc} Except for a knife-edge case, there exists an equilibrium in which the sender acquires evidence if and only if $\kappa$ is sufficiently small ($\kappa \in \left[0,1\right]$) and $\gamma$ is neither too large nor too small ($\frac{\kappa}{4} \leq \gamma \leq \frac{1}{2}-\frac{\kappa}{4}$). Otherwise, the sender does not acquire evidence. \end{proposition} In Appendix \ref{app11}, we specify the exact parametric regions, which are depicted in Figure \ref{figregions}. When $\kappa \geq 1$, the two types of no-evidence-acquisition equilibria coexist for intermediate values of the certification cost ($\gamma \in \left[\frac{1}{4\kappa}, \frac{1}{2}-\frac{1}{4\kappa}\right]$). The key qualitative features of the equilibria in this example relate directly to our earlier propositions. The sender acquires evidence and there is information transmission at equilibrium, if and only if information is relatively cheap ($\kappa \leq 1$) and certification costs are relatively small, but not too small. \section{Selecting the Pareto-Worst Equilibrium}\label{pareto} In this section we discuss what happens to covert equilibria when the cost of learning vanishes, i.e., $\kappa \downarrow 0$. When $\gamma \ge 1-\mu$, there is no certification and hence no information transmission in any equilibrium; consequently, whether $\kappa$ is nonzero does not matter. We henceforth focus on the more interesting case in which $\gamma < 1-\mu$. A distribution of posterior means $G \in \mathcal{M}(F)$ is \textbf{monotone partitional} if there exists $t \in [0,1]$ such that $\supp\left(F\right) \subseteq \left\{x_L(t), x_H(t)\right\}$ with $x_L(t) = \mathbb{E}\left[x \, | \, x \in [0,t]\right]$ and $x_H(t) = \mathbb{E}\left[x \, | \, x \in [t,1]\right]$. Say that an equilibrium is \textbf{monotone partitional} if in this equilibrium, the distribution of posterior means acquired by $S$ is monotone partitional. By Proposition \ref{costofinfoprop2}, when $\kappa$ is sufficiently small, the sender must acquire information. The following result characterizes the set of equilibria in this case. \begin{lemma}\label{lemma61} For any $\gamma \in (0,1-\mu)$, there is a threshold $\Tilde{\kappa}\left(\gamma\right) > 0$ such that for all $\kappa \leq \Tilde{\kappa}\left(\gamma\right)$ any equilibrium is monotone partitional. \end{lemma} Intuitively, as $\kappa$ decreases, the sender's value function is ``less distorted'' by the cost. In particular, when $\kappa$ gets very small, it gets ``close'' to the piecewise linear and convex value function in the $\kappa=0$ benchmark. Any feasible distribution of posterior means that is not monotone partitional must involve contracting some high states and low ones to an intermediate state, and hence cannot be optimal for any sufficiently small $\kappa$. \iffalse \textcolor{ForestGreen}{(KZ 83) I am not very sure about ``monotone partitional is more learning''. Indeed, for a fixed truncation point $t$, it is true that any feasible non-monotone partitional distribution is less informative than the distribution induced by $t$. But if we are comparing an arbitrary non-MP distribution and a MP distribution, we might not be able to rank them in the Blackwell sense.} If there is an equilibrium that is not monotone partitional, the support points of the equilibrium distribution, $x_L$ and $x_H$, solve \[c'\left(x_H\right)- c'\left(x_L\right) = \frac{1}{\kappa} \text{,}\] and \[x_H \kappa c'\left(x_H\right) - x_L \kappa c'\left(x_L\right) -\gamma - \kappa c\left(x_H\right) - x_L + \kappa c\left(x_L\right) = 0 \text{.}\] And we get from the first equation that $c'\left(x_H\right) = c'\left(x_L\right) + 1/\kappa$; plugging into the second equation, we obtain \[x_L + \gamma + \left(1-x_H\right) = \kappa c\left(x_L\right) - \kappa (1-x_H+x_L) c'\left(x_L\right). \label{vani} \tag{$\diamondsuit$}\] We claim that $\lim_{\kappa \downarrow 0} x_L\left(\kappa\right) = 0$. Suppose not, then as $\kappa$ vanishes, the right-hand side of Equation \ref{vani} approaches zero, but the left-hand side is strictly positive, a contradiction. Similarly, it can be shown that $\lim_{\kappa \downarrow 0} x_H\left(\kappa\right) = 1$. Then for every $\varepsilon > 0$, we can find sufficiently small $\Tilde{\kappa}(\varepsilon)$ such that whenever $\kappa < \Tilde{\kappa}(\varepsilon)$, $x_L(\kappa) < \varepsilon$, and $x_H(\kappa) > 1 - \varepsilon$. Because $F$ admits a full-support density, by Lemma 1 in \cite{bipool}, for $\varepsilon$ small enough, there does not exist a MPC of $F$ whose support is $\{x_L(\kappa), x_H(\kappa)\}$. A contradiction. \fi If the equilibrium is monotone partitional and involves information acquisition, the sender solves \[\max_{t}\left\{F\left(t\right)\left(\alpha - \kappa c\left(x_L\left(t\right)\right)\right) + \int_{t}^{1}adF\left(a\right) - \left(1-F\left(t\right)\right)\left(\gamma + \kappa c\left(x_H\left(t\right)\right)\right) \right\} \text{,}\] where $x_{L}\left(t\right) \coloneqq \mathbb{E}\left[\left.\theta\right|\theta \leq t\right]$ and $x_{H}\left(t\right) \coloneqq \mathbb{E}\left[\left.\theta\right|\theta > t\right]$. Taking the FOC then setting $\kappa = 0$ and replacing $\alpha$ in the FOC with $x_L$, we obtain $x_L = t - \gamma $; and so the limiting truncation point, $t$, is precisely that described in Equation \ref{star} in the costless evidence benchmark. Moreover, for arbitrary small $\kappa > 0$, the sender's posterior distribution is binary. Thus, the limit distribution is the Pareto-worst distribution described in Proposition \ref{firstprop}. \begin{theorem}\label{thm62} Take any sequence of equilibria as $\kappa \downarrow 0$. The limit equilibrium is the Pareto-Worst equilibrium when evidence is free. \end{theorem} Theorem \ref{thm62} reveals that there is a significant difference between ``free'' evidence and ``cheap evidence'' when information acquisition is covert. Even a minuscule (but strictly positive) cost to acquiring evidence leads the sender to acquire extremely coarse information. The finer details about the state are completely unimportant to the sender, who does not learn them no matter how cheap it is to do so. On the other hand, the receiver, who wants to ``match the state'' is hurt by any mismatch. This benefit is not internalized by the sender, so even though when information is vanishingly cheap it would be efficient to learn the state precisely, the sender does not do so. In contrast, there is no real difference between the two concepts when evidence acquisition is overt: both when information is free and when it is cheap, the sender does not acquire information and does not disclose either. \section{Discussion}\label{discus} The three main contributions of this paper are that \begin{enumerate}[noitemsep,topsep=0pt] \item When evidence acquisition is costly, transparency in the acquisition process is negative as it grants the sender a form of commitment to acquire less information. \item The receiver always weakly (and sometimes strictly) prefers a positive certification cost, in stark contrast to models with exogenous evidence. \item Cheap information is different from free information: allowing evidence acquisition costs to vanish selects for the Pareto-worst free-information equilibrium. \end{enumerate} It is natural to wonder whether these effects occur in the other ``warhorse'' disclosure model--namely, that of \cite{dye} and \cite{jungkwon}. In their paradigm, the disclosure cost of \cite{verr1} is replaced with exogenous failure: with some probability $\gamma \in \left(0,1\right)$ the sender obtains no evidence. They do: we argue in the \href{https://whitmeyerhome.files.wordpress.com/2022/08/costly_evidence_and_discretionary_disclosure_supplement_v2.pdf}{Supplementary Appendix} that these findings persist in \citeauthor{dye}'s setting. The commitment engendered by transparency, the optimality of coarse information when evidence is costly, and detrimental effects of unraveling on evidence acquisition continue to hold, and, therefore, continue to drive the results. Beyond this, other interesting questions and extensions remain. For one, we assume that the sender cannot falsify or hide evidence. In many applications--our leading example of an asset manager is one--this is reasonable: deception, omission, and falsification are prohibited by law. However, there are other applications in which hiding evidence may be realistic. It is possible that this may generate instances in which overt evidence acquisition is superior to covert. It might also be interesting to look at behavior from the certifier's point of view. How would the certifier choose her fee--and possibly other instruments, coarse classifications, say--to maximize profits?
{ "redpajama_set_name": "RedPajamaArXiv" }
3,118
\section{Introduction} \label{intro} Recall an integer valued random variable $X$ is said to be log-concave if its probability mass function $p$ satisfies $$p^2(z)\geq p(z-1)p(z+1)\,\,\,\,\text{for all $z \in \mathbb{Z}$}$$ and the support of $X$ is contiguous. The log-concave assumption provides a broad, yet natural, convolution stable class of distributions on $\mathbb{Z}.$ Examples include Bernoulli, sums of independent Bernoulli, geometric, binomial, negative binomial and Poisson. We refer to \cite{SW},\cite{S},\cite{JG},\cite{NO},\cite{BJRP} for more details about discrete log-concavity. In recent years, there has been a great deal of interest in studying these distributions and producing results, in analogy with log-concave distributions in the continuous setting \cite{KL,JKM,MM2,MP}. The purpose of this article is to investigate information-theoretic properties of such random variables using a sophisticated localization-type argument. More specifically, we adapt the notion of degree of freedom to explore sharp entropy-variance inequalities in the log-concave setting. \ \vskip1mm The notion of degree of freedom of a log-concave function was first introduced in \cite{FG} by Fradelizi and Gu\'{e}don. Therein, the authors used it to develop a localization technique, which provides a powerful tool for proving geometric and functional inequalities for log-concave measures in $\mathbb{R}^n$. A discrete analog of localization has been developed in \cite{MarMel}. Applications include dilation inequalities, a discrete Pr\'{e}kopa-Leindler, concentration for ultra log-concave distributions \cite{HesMarMel} and a proof of a strengthened version of a conjecture of Feige \cite{AAMM}. Broadly speaking, these problems were treated as optimization problems with one constraint where the reduction of proofs to a certain type of distribution was possible due to the identification of extreme points and the use of the Krein-Milman theorem. However, one needs a more general approach to deal with problems involving more than one constraint. In such cases, discrete degree of freedom can be leveraged. In particular, this notion can be used to describe extreme points of a subset of integer valued log-concave probabilities satisfying more than one constraint. \ \vskip1mm Let us begin with the notion of discrete convexity. A function $I:\mathbb{Z} \to \mathbb{R} \cup \{+ \infty\}$ is said to be convex if $$\Delta^2 I(z):= I(z-1)- 2I(z)+I(z+1)\geq 0\,\,\,\,\text{for all $z \in \mathbb{Z}$.}$$ Equivalently, $I$ is convex on $\mathbb{Z}$ if and only if there exists a continuous and convex\footnote{ Let $E \subseteq \mathbb{R}$ be convex. A function $u \colon E \to \mathbb{R}$ is convex iff for all $0\leq t\leq 1$ and $x,y \in E$, $u(tx + (1-t)y)\leq tu(x) + (1-t)u(y)$. } function $\Bar{I}$ such that $\Bar{I} = I$ on $\mathbb{Z}$. $I$ is concave on $\mathbb{Z}$ if and only if $-I$ is convex on $\mathbb{Z}$. A function is affine (discrete) if it is both discrete convex and concave. If the support of $I$ only contains two points, say $\{z-1,z\}$ for some $z \in \mathbb{Z}$, then $I$ is necessarily affine, since $\Bar{I}$ is affine on $[z-1,z]$. $I$ is said to be log-concave if $\log(I)$ is concave, or equivalently, if $I^2 (z)\geq I(z-1)I(z+1)$ for all $z \in \mathbb{Z}$. Similarly, one can define the log-convexity of functions defined on integers.\ \vskip1mm We now define the notion of degree of freedom in the discrete setting. For our purpose, it suffices to consider compactly supported log-concave functions. Let $a,b \in \mathbb{Z}$ with $a<b$. Denote by $\llbracket a,b \rrbracket$, an interval of integer points from $a$ to $b$. $[a,b] \subset \mathbb{R}$ is the smallest closed convex set containing $\llbracket a,b \rrbracket$. Suppose $f$ is log-concave supported on $\llbracket a,b \rrbracket$, i.e. $f$ is of the form $e^{-V}$, where $V$ is convex and $V(z)< \infty$ on $\llbracket a,b \rrbracket$. \begin{defn} \label{deg. of freedom} The degree of freedom of $e^{-V}$ is the largest $k$ such that there exist $\alpha>0$ and linear independent functions $W_1,W_2,...W_k$ defined on $\llbracket a,b \rrbracket$ such that for all $\epsilon_1,\epsilon_2,...,\epsilon_k \in [-\alpha,\alpha]\,,$ the function $e^{-V} (1 + \sum_{i=1}^k \epsilon_i W_i)$ is log-concave on $\llbracket a,b \rrbracket$. \end{defn} Our first main result (see also \cite{NS}\footnote{In their recent work, Nayar and Słobodianiuk have independently developed results that overlap with Theorem 1.2.}) is as follows. One may view this as a discrete analog of \cite[Proposition 2]{FG}, where the authors have established a necessary and sufficient condition for the finiteness of degree of freedom of a continuous log-concave function. \begin{theorem} \label{necessary condition} If the degree of freedom of $e^{-V}$ is $k+1$, then there exist $k$ number of affine functions $\psi_1, \psi_2,...,\psi_k$ on $\llbracket a,b \rrbracket$ such that $V = \displaystyle \max_{i=1}^k \psi_i.$ \end{theorem} The proof of the theorem relies on the continuous case. In fact, we prove a stronger result. Namely, we will show that the degrees of freedom of $e^{-V}$ and its continuous linear extension are equal (Lemma 2.1). This result allows one to determine the degree of freedom of a given discrete log-concave function, whereas Theorem \ref{necessary condition} only provides a necessary condition for degree of freedom to be finite. \ \vskip1mm Let us recall \cite[Proposition 2]{FG}, which states that the degree of freedom of a continuous log-concave function $g$ is $k+1$ if and only if there exist $k$ (but not less than $k$) continuous affine functions $\phi_1,\phi_2,...,\phi_k$ such that the potential $-g = \max\{\phi_1, \phi_2,...,\phi_k\}$. In general, this is false in the discrete setting, as can be seen by taking $f=e^{-V}$, where $V = \{3,2, \frac{4}{3}, 2\}$ defined on $\llbracket 0,3 \rrbracket$. The log-concavity of $f$ follows directly from the definition. In order to determine the degree of freedom, let us first construct $\bar{V}$ by extending $V$ linearly on each sub-interval $[z-1,z]$ for $z=1,2,3$. $\bar{V}$ is as follows. \[\bar{V}(x) = \begin{cases} 3-x & x \in [0,1] \\ \frac{8}{3} -\frac{2}{3}x & x \in [1,2]\\ \frac{2}{3}x & x \in [2,3] \end{cases} \] Clearly, $\bar{V}$ is convex on $[0,3]$. It follows from \cite[Proposition 2]{FG} that the degree of freedom of $e^{-\bar{V}}$ is $4$. By Lemma \ref{discrete and continuous deg. of freedom} (to be proved), $e^{-V}$ has $4$ degrees of freedom. However, $V$ can be written as the maximum of $\psi_1(z) = 3-z$ and $\psi_2(z) = \frac{2}{3}z$ defined on $\llbracket 0,3 \rrbracket$.\ \vskip1mm As mentioned, the main goal of this paper is to investigate the relationship between entropy and variance within the class of discrete log-concave probabilities. In particular, it is interesting to understand entropy minimizers among these random variables when variance is fixed. Such problems have been considered in the continuous setting \cite{MNT,BN,BM,MK}. However, the work in the discrete setting is limited. First, let us recall the following: given an integer valued random variable $X$ with the mass function $p$, the R\'{e}nyi entropy of order $\alpha>0$, $\alpha \neq 1$, is defined by, $$ H_{\alpha}(X) =\dfrac{-1}{\alpha-1}\log \displaystyle \sum_{z \in \mathbb{Z}}\,p(z)^{\alpha}.$$ If $ \alpha \to \infty$, one obtains the min-entropy $H_{\infty}(X) = - \log \max_z\, p(z)$. The limiting case $\alpha \to 1$ recovers the Shannon entropy $H(X) = H_1(X) = - \sum_{z \in \mathbb{Z}} p(z)\log p(z)$. The R\'{e}nyi entropy power of order $\alpha$ is, $$N_{\alpha}(X) = e^{2H_{\alpha}(X)} = \left( \displaystyle \sum_{z \in \mathbb{Z}} p(z)^{\alpha}\right)^{\frac{-2}{\alpha-1}}.$$ Similarly, one can define the R\'{e}nyi entropy for absolutely continuous random variables with densities with respect to the Lebesgue measure.\ \vskip1mm Entropy inequalities are a central topic of study in information theory. They have found striking applications in combinatorics \cite{K,MMT,B}. We refer the reader to \cite{MT},\cite{J},\cite{G} for recent works on discrete R\'{e}nyi entropy inequalities for log-concave random variables and their variants.\ \vskip1mm Our next main result is motivated by the work of Bobkov-Marsiglietti-Melbourne \cite{BobMarMel}, in which they have utilized a majorization technique to establish variance bounds for min-entropy. Namely, it has been shown that $N_{\infty}(X) \geq \frac{1}{4} + \mathrm{Var}(X)$ for $X$- discrete log concave (see \cite[Theorem 1.1]{BobMarMel}). We will show the following: \begin{theorem} \label{min-entropy} If $X$ is a discrete log-concave random variable, then \begin{equation} \label{b1} N_{\infty}(X) \geq 1 + \mathrm{Var}(X). \end{equation} \end{theorem} The bound is sharp for the geometric distribution\footnote{We use the convention that the geometric distribution with the parameter $\theta$ satisfies $p(z) = \theta(1-\theta)^z,\, z \in \{0,1,2,...\}$.} with the parameter $\theta \to 0$. Since $\alpha \to N_{\alpha}(X)$ is non-increasing, one may obtain an inequality for the case of the Shannon entropy, i.e. $N(X)\geq 1 + \mathrm{Var}(X)$ with the lower bound is asymptotically attained for the aforementioned geometric distribution. However, this inequality may be improved. \ \vskip1mm In the Euclidean setting, the entropy power inequality (EPI) states that the sum of independent random vectors is at least the sum of their entropy powers; equality holds if and only if the random vectors are Gaussian with proportional covariance matrices. A more general inequality also holds for the R\'{e}nyi entropy of order $\alpha$ up to some $\alpha$ - dependent factor \cite{BC}. In general, the discrete analog of the EPI does not hold. Nonetheless, there have been numerous attempts to formulate discrete versions of the EPI. See the recent works in this direction \cite{HAT,HV,MWJ}. \vskip1mm Theorem \ref{min-entropy} implies a discrete entropy power inequality for log-concave random variables, providing a partial answer to a question left open in \cite{BobMarMel}. As mentioned therein, we consider the quantity $\Delta_{\alpha}(X) = N_{\alpha}(X)-1$ to be the discrete analog of the usual R\'{e}nyi entropy power. \begin{theorem} \label{EPI} Let $S_n = \sum_{i=1}^n X_i$, where $\{X_i\}_{1\leq i \leq n}$ is a collection of independent discrete log-concave random variables. Then, \begin{equation} \label{bo1} \Delta_{\alpha} (S_n) \geq c_{\alpha} \displaystyle \sum_{i=1}^n \Delta_{\alpha} (X_i) \end{equation} for $\alpha>1$ with $c_{\alpha} = \dfrac{\alpha -1}{{4(3 \alpha -1)}}.$ \end{theorem} In the regime $1< \alpha \leq 2$, the constant $c_{\alpha}$ can be improved to $\frac{\alpha-1}{3 \alpha-1}$ \cite{BobMarMel}. It has also been shown that the inequality (\ref{bo1}) holds for the Poisson-Bernoulli random variables and $\alpha \geq 2$ with $c_{\alpha} = \frac{\alpha}{6 (\alpha-1)}$ \cite{MMR}. \vskip1mm Let us outline the paper. In Section \ref{S2}, we prove a key lemma that unveils the relationship between the degrees of freedom of a compactly supported discrete log-concave function and its continuous counterpart. As an immediate consequence, we get Theorem \ref{necessary condition}. Section \ref{S3} contains entropy inequalities. We show that Theorem \ref{min-entropy} can be reduced to a certain class of random variables, which we identify using Theorem \ref{necessary condition}. It turns out their mass functions are necessarily log-concave with `V-shaped' potentials. The proof of the inequality for such distributions is included in section \ref{S4}. \section*{Acknowledgements} I would like to thank my advisor Arnaud Marsiglietti for numerous helpful discussions. \section{Degree of freedom in the discrete setting} \label{S2} We start with the following lemma. \begin{lemma} \label{discrete and continuous deg. of freedom} Let $a,b \in \mathcal{Z}$ such that $a \leq b$. Let $V \colon \llbracket a,b \rrbracket \to \mathbb{R}$ be convex. Then, \begin{center} \text{Degree of freedom of $e^{-V}=$} \text{Degree of freedom of $e^{-\Bar{V}}$,} \end{center} where $\bar{V}$ is the continuous function obtained by extending $V$ linearly on each sub-interval $[z-1,z] \subset [a,b]$ , $z \in \mathcal{Z}$. \end{lemma} Note that $\Bar{V}$ in Lemma \ref{discrete and continuous deg. of freedom} is convex on $[a,b].$ Indeed, since $\Delta^2 V(z)\geq 0$ on $\llbracket a,b \rrbracket$ and $\Bar{V}^\prime(x)= V(z)- V(z-1)$ on each $(z-1,z)$, i.e. $\Bar{V}^\prime$ is non-decreasing. Therefore, the degree of freedom of $e^{-\Bar{V}}$ is defined. In fact, it is finite, whereas the degree of freedom of a compactly supported continuous log-concave function can be infinite, as can be seen by taking $g(x) =e^{-x^2}$ on $[-1,1]$. Let us now give a proof of Theorem \ref{necessary condition}. \begin{proof}[Proof of Theorem \ref{necessary condition}] Let $k+1$ be the degree of freedom of $e^{-V}$. Equivalently, by Lemma 2.1, $e^{-\Bar{V}}$ has $k+1$ degrees of freedom. By \cite[Proposition 2]{FG}, there exist $k$ affine functions $\Bar{\psi_1},\Bar{\psi_2},\cdots,\Bar{\psi_k}$ on $[a,b]$ such that $\Bar{V} = \max\{ \Bar{\psi_1}, \Bar{\psi_2},\cdots,\Bar{\psi_k}\}$. Restricting $\Bar{V}$ to $\llbracket a,b \rrbracket$, we get $V = \max\{\psi_1,\psi_2,\cdots,\psi_k\}$, where $\psi_i = $ $\restr{\Bar{\psi_i}}{ \llbracket a,b \rrbracket }$, the restriction of each $\Bar{\psi_i}$ to $ \llbracket a,b \rrbracket$. \end{proof} It remains to prove Lemma \ref{discrete and continuous deg. of freedom}. As in the continuous case, we begin with the following important fact. \vskip2mm \noindent \textbf{FACT I:} Suppose $\alpha,k$ and $W_1,W_2,...,W_k$ satisfy Definition \ref{deg. of freedom}. If $V$ is affine on $\llbracket a,b \rrbracket$, then each $W_i$ is affine on $\llbracket a,b \rrbracket$. \ \vskip1mm We simply adapt the argument used in \cite{FG} to our setting. The result is trivial if $b-a=1$. Let us assume that $b-a\geq 2$. Fix $i \in \{1, \dots, k\}$ and let $\epsilon_j=0$ for all $j \neq i$. Then, for all $\epsilon \in [-\alpha,\alpha]$, the function $e^{-V} (1 + \epsilon W_i)$ is log-concave on $\llbracket a,b \rrbracket$. Equivalently, $V - \log(1 + \epsilon W_i)$ is convex. This implies $\log(1 + \epsilon W_i)$ is concave, i.e. $\Delta^2 h_{\epsilon}(z)\leq 0$ for all $z \in \llbracket a,b \rrbracket$, where $h_{\epsilon}(z) = \log(1 + \epsilon W_i(z))$. Consider the two cases: $\frac{\Delta^2 h_{\epsilon}(z)}{\epsilon} \leq 0$ when $\epsilon>0$ and $\frac{\Delta^2 h_{\epsilon}(z)}{\epsilon} \geq 0$ when $\epsilon<0$. Since $\lim_{\epsilon \to 0}\, \frac{h_{\epsilon}(z)}{\epsilon} = W_i (z)$, we conclude by taking the limit $\epsilon \to 0$ in $\frac{\Delta^2 h_{\epsilon}(z)}{\epsilon}$. \ \vskip1mm The following fact verifies Lemma \ref{discrete and continuous deg. of freedom} for log-affine functions $e^{-V}$ (equivalently when $V$ is affine).\vskip2mm \noindent \textbf{FACT II:} Let $m,n \in \mathbb{R}$. Let $V(z) = mz+n$ be defined on $\llbracket a,b \rrbracket$. Then, the degree of freedom of $e^{-V}$ is $2$. \ \vskip1mm Without loss of generality, assume that $V$ is non-constant affine. Choose $W_1(z) = 1_{\llbracket a,b \rrbracket} $ and $W_2(z) = V(z) $. Let $\alpha = \min(\frac{1}{2},(2\max(|W_1| +|W_2|))^{-1}).$ Then, for each $(\epsilon_1,\epsilon_2) \in [-\alpha,\alpha]^2$, we have $1+ \epsilon_1W_1 + \epsilon_2W_2 \geq \frac{1}{2}$, i.e. $\log(1+ \epsilon_1W_1 + \epsilon_2W_2)$ is defined for all $z \in \llbracket a,b \rrbracket$. Moreover, $W_1$ and $W_2$ are linear independent. Let us check the log-concavity condition. For convenience, let $\mu = e^{-V}(1+ \epsilon_1W_1 + \epsilon_2W_2)$. The result is trivial if $b-a=1$. Assume $b-a\geq 2$. Then, $$\mu^2(z) - \mu(z-1)\mu(z+1) = e^{-2(mz+n)} (\epsilon_2 m)^2,$$ which is non-negative for all $\abs{\epsilon_i}\leq \alpha$ and $z \in \llbracket a,b \rrbracket$. This proves that $e^{-V}$ has at least $2$ degrees of freedom. In fact, the degree of freedom cannot exceed $2$, since our choice for linear independent functions satisfying Definition \ref{deg. of freedom}, is necessarily affine.\ \begin{remark} Note that if $V$ is a dirac function, i.e. $V = 1_{\{a\}}$, where $a \in \mathbb{Z}$, then we identify the degree of freedom of $e^{-V}$ as $1$. Indeed, since one can choose $W_1=V$ and $\alpha = 1/2$ satisfying Definition \ref{deg. of freedom}. \end{remark} Let us now prove Lemma \ref{discrete and continuous deg. of freedom}. We shall assume that $V$ is not affine, i.e. $b-a \geq 2$. \begin{proof}[Proof of Lemma \ref{discrete and continuous deg. of freedom}] By construction, $\Bar{V}$ is piecewise linear with a finite number of parts, say $k (\geq 2)$, i.e. $\Bar{V}$ is the maximum of $k$ (and no less) affine functions defined on $[a,b]$. Then by \cite[Proposition 2]{FG}, the degree of freedom of $e^{-\Bar{V}}$ is $k+1$. We will show that the degree of freedom of $e^{-V}$ is $k+1$. Let $z_0=a$ and $z_{k} = b$. There exist points $a<z_1<z_2<...<z_{k-1}<b$ such that $\bar{V}$ is affine on $[z_{i-1},\, z_i]\,$ for $i=1,2,...,k$. First, we show that the degree of freedom of $e^{-V}$ is \textbf{\textit{at least $k+1$}}. The idea is to use the construction in \cite{FG} to obtain $k+1$ linear independent functions satisfying Definition \ref{deg. of freedom}.\ \vskip1mm Due to convexity of $\bar{V}$, one can find $x_1<x_2<...<x_k$ such that \begin{itemize} \item $z_{i-1}<x_i<z_i.$ \item $\bar{V}^\prime (x_i) < \bar{V}^\prime(x_{i+1})$ for $i=1,2,..,k-1.$ \end{itemize} For each $i=1,2,...,k$, define \[\Bar{W}_i(x) = \begin{cases} \Bar{V}(x) & x < x_i\\ \Bar{V}(x_i) + (x-x_i)\Bar{V}^\prime (x_i) & x \geq x_i \end{cases} \] and $\bar{W}_0 = 1_{[a,b]}\,$ (let us assume $\Bar{V}^\prime (x_1) \neq 0$. If not, then we let $x_1=z_0$, and replace $\Bar{V}^\prime (x_1)$ with $\Bar{V}^\prime (x_k)$). Denote by $W_i$, the restriction of $\Bar{W}_i$ to $\llbracket a,b \rrbracket$, i.e. for $z \in \llbracket a,b \rrbracket$ \[W_i(z) = \begin{cases} V(z) & z < x_i\\ \Bar{V}(x_i) + (z-x_i)\Bar{V}^\prime (x_i) & z\geq x_i \end{cases} \] and $W_0 = 1_{\llbracket a,b \rrbracket}$. \ \vskip1mm We claim that $\{W_i\}_{i=0}^k$ satisfies Definition \ref{deg. of freedom}. First, we show the log-concavity condition. It follows from \cite[Proposition 2]{FG} that for a sufficiently small $\alpha>0$, the function $e^{-\Bar{V}}(1+ \sum_{i=0}^k \epsilon_i \Bar{W}_i)$ is log-concave on $[a,b]$. Since $e^{-\Bar{V}}(1+ \sum_{i=0}^k \epsilon_i \Bar{W}_i) = e^{-V}(1+ \sum_{i=0}^k \epsilon_i W_i)$ on $\llbracket a,b \rrbracket$, we conclude that for all $\epsilon_i \in [-\alpha,\alpha]$, $e^{-V}(1+ \sum_{i=0}^k \epsilon_i W_i)$ is log-concave on $\llbracket a,b \rrbracket$. \ \vskip1mm Next, we verify the linear independence of $\{W_i\}_{i=0}^k$. Let $h(z) = \sum_{i=0}^k c_i W_i(z)$. We need to show that $h(z) = 0$ for all $z \in \llbracket a,b \rrbracket$ implies $c_i=0,\,i=0,1,2,...k.$ Let us show the argument for $c_{k}=0$. Letting $z=z_k, z_{k-1}$ and $z=z_{k-2}$ in $h(z)=0$, respectively, we obtain the following linear equations. \begin{align*} L_1\coloneqq c_0 + \sum_{i=1}^k c_i \left(\Bar{V}(x_i) + (z_{k}-x_i)\Bar{V}^\prime (x_i)\right) &= 0.\\ L_2 \coloneqq c_0 + \sum_{i=1}^{k-1} c_i \left(\Bar{V}(x_i) + (z_{k-1}-x_i)\Bar{V}^\prime (x_i)\right) + c_k V(z_{k-1}) &= 0.\\ L_3\coloneqq c_0 + \sum_{i=1}^{k-2} c_i \left(\Bar{V}(x_i) + (z_{k-2}-x_i)\Bar{V}^\prime (x_i)\right) + (c_{k-1}+c_k) V(z_{k-2}) &= 0. \end{align*} $L_1- L_2 =0$ and dividing by $z_k - z_{k-1}$ yield $\sum_{i=1}^k c_i \Bar{V}^\prime (x_i) = 0$. Similarly, $\sum_{i=1}^{k-1} c_i \Bar{V}^\prime (x_i) + c_k \Bar{V}^\prime (x_{k-1}) = 0$ follows from $L_2-L_3 = 0$, and dividing by $z_{k-1} - z_{k-2}$. Then, the result follows by subtracting these two equations.\ \vskip1mm One may proceed similarly to show $c_i=0$ for $i=1,...,k-1$. After plugging $z=z_{k-3},z_{k-4},...,z_0$ into $h(z)=0$, simplifying as before and combining with the case $c_k = 0$, one obtains the following system of $k-1$ linear equations. \begin{align*} M_1 \coloneqq \sum_{i=1}^{k-1} c_i \Bar{V}^\prime (x_i) &=0.\\ M_2 \coloneqq\sum_{i=1}^{k-2} c_i \Bar{V}^\prime (x_i) + c_{k-1} \Bar{V}^\prime (x_{k-2}) &=0.\\ M_3 \coloneqq\sum_{i=1}^{k-3} c_i \Bar{V}^\prime (x_i) + (c_{k-2}+ c_{k-1}) \Bar{V}^\prime (x_{k-3}) &=0.\\ .\\ .\\ .\\ M_{k-1} \coloneqq \sum_{i=1}^{k-1} c_i &= 0. \end{align*} $M_1 - M_2 = 0 \implies c_{k-1}=0,\, M_2-M_3 = 0 \implies c_{k-2} = 0$ and so on. \ \vskip1mm Let us now prove the reverse direction, i.e. the degree of freedom of $e^{-V}$ is \textbf{\textit{ at most $k+1$}}. The argument is analogous to the continuous case. For completeness, we explain the details below.\ \vskip1mm Suppose on contrary that the degree of freedom of $e^{-V}$ is more than $k+1$. Then, there exist $\alpha>0$ and $k+2$ linear independent functions $V_1,V_2,...,V_{k+2}$ satisfying Definition \ref{deg. of freedom}. Since $\bar{V}$ is affine on each $[z_{i-1}, z_i],\,$ its restriction to $\llbracket a,b \rrbracket$, $V$ is also affine on each $\llbracket z_{i-1}, z_i \rrbracket.$ By \textbf{Fact I}, each $ V_j$ should also be affine on $\llbracket z_{i-1}, z_i \rrbracket$ for $i=1,2,..,k$. Let $C$ be the space of functions defined on $\llbracket a,b \rrbracket$ that are affine on each $\llbracket z_{i-1}, z_i \rrbracket.$ We claim that $\dim(C) = k+1$. \ \vskip1mm For each $i\in \{0,1,2,...,k\},\,$ define $f_i : \llbracket a,b \rrbracket \to \mathbb{R}$ such that \begin{equation*} f_i(z)= \begin{cases} \dfrac{z-z_{i-1}}{z_i-z_{i-1}}& z \in \llbracket z_{i-1},z_i \rrbracket \\ 1 - \dfrac{z-z_i}{z_{i+1}-z_i}& z \in \llbracket z_i,z_{i+1}\rrbracket\\ 0& \mathrm{otherwise} \end{cases} \end{equation*} \vskip1mm Clearly, $f_i \in C$ for all $i=0,1,...,k.$ By construction, $\{f_i\}_{i=0}^k$ is linear independent. Take any function $\ell \in C$. Then, its restriction to $\llbracket z_i, z_{i+1} \rrbracket$, denoted by $\Hat{\ell_i}$, is given by $$\Hat{\ell_i}(z) \coloneqq \ell(z_i)+\frac{\ell(z_{i+1})-\ell(z_i)}{z_{i+1}-z_i}\,(z-z_i).$$ Choose $\beta = \ell(z_{i+1})$ and $\gamma = \ell(z_i)$ so that $\beta f_{i+1} + \gamma f_i = \Hat{\ell_i}$ for all $i=0,1,...,k-1$. This implies $\{f_i\}_{i=0}^k$ spans $C$. Therefore, the collection $\{f_i\}_{i=0}^k$ forms a basis for $C$, proving the claim, and hence contradicting the supposition. \end{proof} \section{Min-entropy-variance \& R\'enyi entropy inequalities} \label{S3} This section is devoted to the investigation of entropy inequalities. First, we prove Theorem \ref{EPI}. We need the following proposition from \cite{BobMarMel}. \begin{proposition}[\cite{BobMarMel}] \label{entropy bounds} Let $1< \alpha \leq \infty$. If $X$ is any integer valued random variable with finite variance, then $$1 \leq N_{\alpha}(X) \leq 1 + \dfrac{4(3 \alpha-1)}{\alpha -1} \mathrm{Var}(X).$$ \end{proposition} \begin{proof}[Proof of Theorem \ref{EPI}] Let $S_n = X_1+ X_2 +...+X_n$, where $X_i$'s are independent discrete log-concave. Since log-concavity is preserved under independent summation, we apply inequality (\ref{b1}) of Theorem \ref{min-entropy} to $X = S_n$ to get the following: $$\Delta_{\infty}(S_n) \geq \sum_{i=1}^n\mathrm{Var}(X_i).$$ The function $\alpha \to N_{\alpha}(X)$ is non-increasing. Therefore, one can extend the same lower bound to $\Delta_{\alpha}(S_n)$. We conclude by applying Proposition \ref{entropy bounds} to $X_i$, i.e. $$\Delta_{\alpha}(S_n) \geq \sum_{i=1}^n\mathrm{Var}(X_i) \geq \dfrac{\alpha -1}{4(3 \alpha-1)} \sum_{i=1}^n\Delta_{\alpha}(X_i). $$ \end{proof} \begin{remark}\ \label{concentration function} Given a discrete random variable $X$, its concentration function is defined by \begin{equation*} Q(X;\lambda) = \displaystyle \sup_{z} \mathbb{P}\{z \leq X \leq z + \lambda\}, \,\,\, \lambda \geq 0. \end{equation*} In particular, \begin{equation*} N^{-\frac{1}{2}}_{\infty}(X) = Q(X ; 0). \end{equation*} Theorem \ref{min-entropy}, together with \cite[Lemma 8.1]{BobMarMel}, implies the following for $X$- discrete log-concave random variables: \begin{equation*} Q(X ;\lambda) \leq \frac{\lambda+1}{\sqrt{1+\frac{\lambda (\lambda+2)}{12} + \Var(X) }}. \end{equation*} This improves Proposition 8.3 from \cite{BobMarMel}. \end{remark} We now proceed to the proof of Theorem \ref{min-entropy}. The idea is to set up the problem as an optimization problem with two constraints. This will allow us to reduce the inequality (\ref{b1}) to an extremal case, which we can characterize using Theorem \ref{necessary condition}.\ \vskip1mm Denote by $M(X)$, the $M$-functional, which is defined as $\sup_n \mathbb{P}(X=n)$. By letting $\alpha \to \infty$ in $N_{\alpha}(X)$, we have $$N_{\infty}(X) = M(X)^{-2}.$$ Therefore, inequality (\ref{b1}) is equivalent to \begin{equation} \label{M-fun} M^2(X) (1 + \mathrm{Var}(X)) \leq 1. \end{equation} \begin{proof}[Proof of Theorem \ref{min-entropy}] Fix a log-concave random variable $X_0$. By approximation, one may assume that $X_0$ is compactly supported. Moreover, inequality (\ref{M-fun}) is invariant under translation. So is log-concavity. Therefore, we further assume that $X_0$ is supported on $\llbracket 0,L \rrbracket$, where $L \in \mathbb{Z}^{+}$. Denote by $\mathcal{P}(\llbracket 0,L \rrbracket)$, the set of log-concave probabilities supported on $\llbracket 0,L \rrbracket$. Let $h_1$ and $h_2$ be arbitrary functions defined on $\llbracket 0,L \rrbracket$ such that $h_1(n)=n^2 - \mathbb{E}[X_0^2]$ and $h_2(n)= \mathbb{E}[X_0]-n$ for all $n \in \llbracket 0,L \rrbracket $. Let $h = (h_1,h_2)$.\ \vskip1mm Consider the set of all log-concave probability sequences supported on $\llbracket 0,L \rrbracket$ satisfying $\mathbb{E}[h_1(X)] \geq 0$ and $\mathbb{E}[h_2(X)] \geq 0$, $$\mathcal{P}_h(\llbracket 0,L \rrbracket) = \{\mathbb{P}_X \in \mathcal{P}(\llbracket 0,L \rrbracket) \,:\, X \,\,\text{log-concave}\,,\, \mathbb{E}[h_1(X)]\geq 0 \,\text{and}\, \, \mathbb{E}[h_2(X)]\geq 0 \,\}\,.$$ Note that $\P_{X_0} \in \mathcal{P}_h(\llbracket 0,L \rrbracket)$ so ${P}_h(\llbracket 0,L \rrbracket)$ is non-empty. Denote by $\mathrm{conv} (\mathcal{P}_h(\llbracket 0,L \rrbracket))$, the convex hull of $\mathcal{P}_h(\llbracket 0,L \rrbracket)$. Suppose $\mathbb{P}_X$ is any extreme point in $\mathrm{conv} (\mathcal{P}_h(\llbracket 0,L \rrbracket))$. By translation, one may assume that $\mathbb{P}_X$ is supported on $\llbracket 0,M \rrbracket \subseteq \llbracket 0,L \rrbracket$. Let $e^{-V}$ be the probability mass function of $\mathbb{P}_X$, where $V$ is convex on $\llbracket 0,M \rrbracket$.\\\\ \textbf{STEP I:} The reduction of the inequality (\ref{M-fun}) to extreme points.\ \vskip1mm This is essentially a consequence of the Krein-Milman (finite-dimensional) theorem, i.e. the supremum of any convex functional $\Phi$ over the set $\mathcal{P}_h(\llbracket 0, L \rrbracket)$ is attained at extreme points. Letting $\Phi(\mathbb{P}_X) = \sup_n \mathbb{P}(X=n)$, it suffices to prove the inequality (\ref{M-fun}) for $\mathbb{P}_X$- extreme.\\\\ \textbf{STEP II:} $e^{-V}$ has at most $3$ degrees of freedom. \vskip1mm By contradiction, assume the degree of freedom of $e^{-V}$ is more than $3$. Then, there exist linear independent functions $W_1,W_2,W_3$ and $W_4$ defined on $\llbracket 0,M \rrbracket$ and $\alpha>0$ such that for any $(\epsilon_1, \epsilon_2,\epsilon_3, \epsilon_4) \in [-\alpha,\alpha]^4$, the function $e^{-V} (1+ \sum_{i=1}^4 \epsilon_iW_i)$ is log-concave on $\llbracket 0,M \rrbracket$. Let us consider the following set, which can be viewed as a $4-$dimensional cube centered at $\mathbb{P}_{X}$: $$A=\{\,\text{log-concave functions of the form}\,\,e^{-V} (1+ \sum_{i=1}^4\epsilon_iW_i):\, |\epsilon_i| \leq \alpha\,\,\text{for all\,\,}i\}.$$ The set $A$ is not necessarily contained in $\mathcal{P}_h(\llbracket 0,M \rrbracket)$. Denote by $\Tilde{A}$, the following subset of $A$: \begin{equation*} \{\text{log-concave probability mass functions in $A$ satisfying \,\,} \mathbb{E}[h_1(X)]= 0\,\text{and}\,\, \mathbb{E}[h_2(X)]= 0 \}. \end{equation*} $\Tilde{A} \neq \emptyset$ and $\Tilde{A}\subset \mathcal{P}_h(\llbracket 0,M \rrbracket)$. Moreover $(\epsilon_1,\epsilon_2,\epsilon_3,\epsilon_4)$ satisfies 3 linear equations. Hence, the solutions of $(\epsilon_1,\epsilon_2,\epsilon_3,\epsilon_4)$ must lie on a line segment passing through the origin. In particular, there exist $\mathbb{P}_{X_1}$ and $\mathbb{P}_{X_2}$ with mass functions of the form $e^{-V} (1+ \sum_{i=1}^4\epsilon_iW_i)$ and $e^{-V} (1 - \sum_{i=1}^4\epsilon_iW_i)$, respectively. But then, $\mathbb{P}_X = \frac{\mathbb{P}_{X_1} + \mathbb{P}_{X_2}}{2},\,$ a contradiction.\\\\ \textbf{STEP III:} Extreme points are log-affine or piecewise log-affine with 2 parts.\ \vskip1mm It follows from Theorem \ref{necessary condition} that the mass function of any extremal is $e^{-V}$, where $V$ is 1) affine or 2) the maximum of $2$ affine functions on $\llbracket 0,M \rrbracket$. If $V$ is affine, then $e^{-V}$ is monotone. Moreover, $e^{-V}$ is monotone if $V$ is non-increasing (or non-decreasing) with $2$ parts. If $e^{-V}$ is non-monotone, then it is of the following form. \begin{equation*} \mathbb{P}(X=n)= C e^{-\alpha_1(N-n)} \mathbbm{1}_{\llbracket0,N \rrbracket}(n) + C e^{-\alpha_2(n-N)} \mathbbm{1}_{\llbracket N+1,M \rrbracket}(n), \end{equation*} where $C, \alpha_1, \alpha_2>0, N\geq 1$ and $M\geq2$. \end{proof} \section{Proof for extremals} \label{S4} \underline{\textit{CASE I}:} When $e^{-V}$ is monotone.\vskip2mm We shall prove a slightly stronger result, i.e. we show that the inequality (\ref{M-fun}) holds for any non-negative monotone log-concave random variable (not necessarily having $3$ degree of freedom). Without loss of generality, assume that $X$ is non-increasing and supported on $\llbracket 0,M \rrbracket.$ Let $p$ be its probability mass function. Let $Z$ be geometric with the mass function $q(n) = \theta (1-\theta)^n,\, n=0,1,2,...$ Choose $\theta = \frac{1}{\mathbb{E}[X]+1}$ so that $\mathbb{E}[Z] = \mathbb{E}[X]$. It follows from [Theorem 2.6, \cite{MM2}] that $Z$ majorizes\footnote{A random variable $X$ is majorized by $Z$ in the convex order if $\mathbb{E}[\varphi(X)] \leq \mathbb{E}[\varphi(Z)]$ holds for any convex function $\varphi$.} $X$ in the convex order. In particular, we have $\mathbb{E}[X^2] \leq \mathbb{E}[Z^2]$. Equivalently, $\mathrm{Var}(X) \leq \mathrm{Var}(Z).$\vskip1mm In fact, more is proven in \cite[Theorem 2.6]{MM2}, functions $p$ and $q$ cross exactly twice. However, since $\log(p)$ is concave and $\log(q)$ is affine, these functions crossing exactly twice necessarily imply that $p(0) \leq q(0)$. Since $p$ and $q$ are non-increasing, we have $\sup_n \mathbb{P}(X=n)=p(0)$ and $\sup_n \mathbb{P}(Z=n) = q(0)$, which imply $$M(X)\leq M(Z).$$ For $Z$ geometric, it is easy to see that $$ M^2(Z) (1 + \Var(Z)) \leq 1. $$ Therefore, combining the above, we conclude that $$ M^2 (X) (1 + \Var(X))\leq M^2 (Z) (1 + \Var(Z))\leq 1. $$ \underline{\textit{CASE II}:} When $e^{-V}$ is non-monotone.\vskip2mm We need to verify the inequality (\ref{M-fun}) for distributions of the following form $$\mathbb{P}(X=n)= C p_1^{-(N-n)} \mathbbm{1}_{\llbracket0, N \rrbracket}(n) + C p_2^{-(n-N)} \mathbbm{1}_{\llbracket N+1, N+K \rrbracket}(n),$$ where $p_1 = e^{\alpha_1}, p_2 = e^{\alpha_2}$ and $K = M-N.$ \ \vskip1mm Observe $M(X) = C$. Since $\displaystyle \sum_{n=0}^{N+K} \mathbb{P}(X=n) = 1$, we have $$C \left( \sum_{n=0}^N p_1^{-n} + \sum_{n=1}^K p_2^{-n} \right) = 1.$$ Let $A = \displaystyle\sum_{n=0}^N p_1^{-n} $ and $B = \displaystyle \sum_{n=1}^K p_2^{-n}.$ Then, $C(A+B) = 1$. Let us compute the variance of $X$. $$\mathbb{E}[X^2] = C \left(\sum_{n=0}^N \frac{n^2} {p_1^{N-n}} + \sum_{n=N+1}^{N+K} \frac{n^2}{p_2^{n-N}} \right)= C \left(\sum_{n=0}^N \frac{(N-n)^2}{p_1^n} + \sum_{n=1}^{K} \frac{(N+n)^2 }{p_2^n} \right).$$ After simplifying and substituting $A$ and $B$, the right-hand side is equal to, $$C \left( N^2 (A+B) + 2N \left( \sum_{n=1}^K \frac{n}{ p_2^n}- \sum_{n=1}^N \frac{n}{ p_1^n} \right ) + \sum_{n=1}^K \frac{n^2}{ p_2^n}+ \sum_{n=1}^N \frac{n^2}{ p_1^n} \right).$$ By proceeding similarly, we get the following expression for $\mathbb{E}[X]^2.$ $$\mathbb{E}[X]^2 = C^2 \left((A+B)^2 N^2 + 2N (A+B) \left( \sum_{n=1}^K \frac{n}{ p_2^n}- \sum_{n=1}^N \frac{n}{ p_1^n} \right) + \left(\sum_{n=1}^K \frac{n}{ p_2^n}- \sum_{n=1}^N \frac{n }{p_1^n} \right)^2\,\right).$$ Combining $\mathbb{E}[X^2]$ and $\mathbb{E}[X]^2$, we get $$\mathrm{Var}(X) = \frac{1}{(A+B)^2}\left( (A+B) \left( \sum_{n=1}^K \frac{n^2}{ p_2^n}+ \sum_{n=1}^N \frac{n^2}{ p_1^n}\right)- \left(\sum_{n=1}^K \frac{n}{ p_2^n}- \sum_{n=1}^N \frac{n }{p_1^n} \right)^2\,\right).$$ After plugging the expressions for $M(X)$ and $\mathrm{Var}(X)$ into inequality (\ref{M-fun}) and rearranging the terms, we wish to prove for all integers $N, K\geq 1$ and real numbers $p_1,p_2\geq 1$, \begin{equation} \label{E4} (A+B)^2 -1- \frac{1}{(A+B)} \left( \sum_{n=1}^K \frac{n^2}{ p_2^n}+ \sum_{n=1}^N \frac{n^2 }{p_1^n}\right) + \frac{1}{(A+B)^2} \left(\sum_{n=1}^K \frac{n}{p_2^n}- \sum_{n=1}^N \frac{n }{p_1^n} \right)^2 \geq 0. \end{equation} \begin{remark} The term $\frac{1}{(A+B)^2} \left(\sum_{n=1}^K \frac{n}{p_2^n}- \sum_{n=1}^N \frac{n }{p_1^n}\right)^2$ in the inequality may not be dropped. For example, take $p_1= \frac{5}{3}, p_2 = 500, N=9$ and $K=1$. Then \begin{align*} (A+B)^3 - (A+B) - \left( \sum_{n=1}^K \frac{n^2}{ p_2^n}+ \sum_{n=1}^N \frac{n^2 }{p_1^n} \right)<0. \end{align*} \end{remark} The rest of the paper is devoted to the proof of inequality (\ref{E4}). In fact, we will prove a more general result. Let $x,y>0$. Let $S = \sum_{n=0}^N x^n$ and $T = \sum_{n=1}^K y^n.$ We show for all $N,K\geq 1$, \begin{align} \label{E5} (S+T)^4 - (S+T)^2 - (S+T)\left(\sum_{n=1}^N n^2\,x^n + \sum_{n=1}^K n^2\,y^n\right) + \left(\sum_{n=1}^N n\,x^n - \sum_{n=1}^K n\,y^n\right)^2 \geq 0. \end{align} After simplifying and rearranging the terms, the inequality (\ref{E5}) is equivalent to, \begin{align*} S^4 - S^2 - S \sum_{n=1}^N n^2\,x^n & + \left( \sum_{n=1}^N n\,x^n\right)^2 \\ & + 2S^3\,T - T\sum_{n=1}^N n^2\,x^n- 2S\,T +3S^2\,T^2- 2\sum_{n=1}^N n\,x^n \,\sum_{n=1}^K n\,y^n \\ & + 2S\,T^3 - S\sum_{n=1}^K n^2\,y^n + 3S^2\,T^2 + S^3\,T\\ & + T^4 - T^2 + 2S\,T^3 + S^3\,T - T\sum_{n=1}^K n^2\,y^n + \left( \sum_{n=1}^K n\,y^n\right)^2 \geq 0. \end{align*} Therefore, it suffices to prove each of the following inequalities. \begin{enumerate}[(I)] \item \label{I} $S^4 - S^2 - S \sum_{n=1}^N n^2\,x^n + \left( \sum_{n=1}^N n\,x^n\right)^2\geq 0.$ \item \label{II} $2S^3\,T - T\sum_{n=1}^N n^2\,x^n- 2S\,T + 3S^2\,T^2 - 2\sum_{n=1}^N n\,x^n \,\sum_{n=1}^K n\,y^n \geq 0.$ \item \label{III} $2S\,T^3 - S\sum_{n=1}^K n^2\,y^n + 3S^2\,T^2 + S^3\,T \geq 0.$ \item \label{IV} $T^4 - T^2 + 2S\,T^3 + S^3\,T - T\sum_{n=1}^K n^2\,y^n + \left( \sum_{n=1}^K n\,y^n\right)^2 \geq 0$. \end{enumerate} We need the following lemma. The proof is elementary and included in the appendix. \begin{lemma} \label{poly}\ \begin{enumerate}[(a)] \item \label{a} $S^2 = \displaystyle \sum_{n=0}^N (n+1)\,x^n + \displaystyle \sum_{n=N+1}^{2N} (2N-n+1)\,x^n.$ \item \label{b} $S^3\geq \dfrac{1}{2}\, \displaystyle \sum_{n=0}^{N} (n+1)(n+2)\,x^n + \dfrac{1}{2} \sum_{n=N+1}^{2N} \big[(3N-n+1)(n-N) + (n+2)(2N-n+1)\big]\,x^n$. \item \label{c} $T^2 = \displaystyle \sum_{n=2}^{K+1} (n-1)\,y^n + \sum_{n=K+2}^{2K} (2K - n+1)\, y^n.$ \item \label{d} $T^3 \geq \displaystyle \dfrac{1}{2}\, \sum_{n=3}^{K+2} (n-1)(n-2)\,y^n + \dfrac{1}{2} \sum_{n=K+3}^{2K+1} \big[(n-K-2)(3K-n+1)+(n-1)(2K-n+2)\big]\,y^n$. \item \label{e} $T^4 \geq \dfrac{1}{6}\, \displaystyle \sum_{n=4}^{K+3} (n-1)(n-2)(n-3)\,y^n + \displaystyle \sum_{n={K+4}}^{2K+2} e_{K}(n)\,y^n,$ \\ where $e_K (n) = \dfrac{1}{6}\, \big[(2K-n+3)(n^2 + 2nK-3n-2K^2-6K+2) + 2(n-K-3)(n-K-2)(4K-n+1) \big]$. \item \label{f}$ T \displaystyle\sum_{n=1}^K n^2y^n = \frac{1}{6}\, \displaystyle \sum _{n=2}^{K+1} n(n-1)(2n-1)\,y^n + \displaystyle \sum_{n=K+2}^{2K} f_{K}(n) \,y^n$, \\ where $f_{K}(n)= \dfrac{1}{6}\, (2K-n+1)(2n^2- n(2K+1)+2K(K+1))$. \item \label{g} $ \left(\displaystyle \sum_{n=1}^K n\,y^n\right)^2= \dfrac{1}{6} \,\displaystyle \sum _{n=2}^{K+1} n(n-1)(n+1)\,y^n +\displaystyle \sum _{n=K+2}^{2K} g_K(n)\, y^n$, \\ where $g_K(n) = \dfrac{1}{6}\,(2K-n+1)(n^2 + n(2K +1) -2K(K+1))$.\ \end{enumerate} \end{lemma} \vskip2mm \begin{proof}[Proof of inequality (\ref{I})] By (\ref{a}) in Lemma \ref{poly}, \begin{align*} S^4 = (S^2)^2 \geq \left(\sum_{n=0}^N (n+1)\,x^n\right)^2 \geq \left(\displaystyle \sum_{n=1}^N n\,x^n \right)^2 + \left(\displaystyle \sum_{n=1}^N x^n \right)^2 + \sum_{n=0}^N x^n \sum_{n=1}^N n\,x^n. \end{align*} Therefore, \begin{align*} S^4 - S^2 - S \sum_{n=1}^N n^2\,x^n + \left( \sum_{n=1}^N n\,x^n\right)^2 & \geq 2 \left(\displaystyle \sum_{n=1}^N n\,x^n \right)^2 + \sum_{n=0}^N x^n \sum_{n=1}^N n\,x^n - \sum_{n=0}^N x^n\sum_{n=1}^N n^2\,x^n \\ & = 2 \left(\displaystyle \sum_{n=1}^N n\,x^n \right)^2 + \sum_{n=0}^N x^n \left(\sum_{n=1}^N n(1-n)\,x^n\right) \\ & = \sum_{n=0}^{2N} c_n\, x^n, \end{align*} where $c_n = \displaystyle \sum_{i+j=n} 2ij + i (1-i)$. $n$ ranges from $0$ to $2N$ while $0\leq i,j \leq n$. We conclude since, \begin{equation*} c_n= \begin{cases} \displaystyle \sum_{i=0}^n 2i(n-i)+ i(1-i) = 0, & 0\leq n \leq N\\ \displaystyle \sum_{i=n-N}^N 2i(n-i)+ i(1-i) = (N+1)(n-N)(2N+1-n), & N<n\leq 2N \end{cases} \end{equation*} \end{proof} \begin{proof}[Proof of inequality (\ref{II})] By (\ref{b}) in Lemma \ref{poly} \begin{equation} \begin{aligned} 2S^3\,T - T\sum_{n=1}^N n^2\,x^n- 2S\,T &= T \left(2S^3 - \sum_{n=1}^N n^2\,x^n -2S \right)\\ &\geq T \left(\sum_{n=0}^N (n+1)(n+2)\,x^n - \sum_{n=1}^N n^2\,x^n - 2 \sum_{n=0}^N x^n\right)\\ &= 3 T \sum_{n=1}^N n\,x^n. \end{aligned} \end{equation} Together with (6), we can easily verify the desired inequality for $K=1$. Assume $K\geq 2$. By (\ref{a}) and (\ref{c}) in Lemma \ref{poly}, \begin{equation} \begin{aligned} 3S^2\,T^2 - 2\sum_{n=1}^N n\,x^n \,\sum_{n=1}^K n\,y^n & \geq 3\sum_{n=0}^N (n+1)\,x^n \sum_{m=2}^{K+1} (m-1)\,y^m - 2\sum_{n=1}^N n\,x^n \,\sum_{m=1}^K m\,y^m\\ &> \sum_{{0\leq n\leq N} \atop {2 \leq m \leq K}} \left(3(n+1)(m-1) -2nm \right) \,x^n\,y^m -2y \sum_{n=1}^N n\,x^n \\ & > -3\sum_{{0\leq n\leq N} \atop {2 \leq m \leq K}}n\,x^n\,y^m -2y \sum_{n=1}^N n\,x^n\\ &= -3 \sum_{m=2}^K y^m \sum_{n=1}^N n\,x^n -2y \sum_{n=1}^N n\,x^n > -3T \sum_{n=1}^N n\,x^n. \end{aligned} \end{equation} We conclude by combining (6) and (7). \end{proof} \begin{proof}[Proof of inequality (\ref{III})] Since $S\geq 1,$ \begin{align*} 2S\,T^3 - S\sum_{n=1}^K n^2y^n + 3S^2\,T^2 + S^3\,T \geq S \left(2T^3-\sum_{n=1}^K n^2\,y^n + 3T^2 + T\right). \end{align*} It is enough to show $2T^3-\sum_{n=1}^K n^2\,y^n + 3T^2 + T>0$. This is immediate when $K=1,2$. Suppose $K\geq 3$. By (\ref{c}) and (\ref{d}) in Lemma \ref{poly}, \begin{align*} 2T^3-\sum_{n=1}^K n^2y^n + 3T^2 + T &\geq \sum_{n=3}^{K+2} (n-1)(n-2)\,y^n - \sum_{n=1}^K n^2\,y^n + 3\sum_{n=2}^{K+1} (n-1)\,y^n + \sum_{n=1}^K y^n\\ &> \sum_{n=3}^K \left( (n-1)(n-2)-n^2 + 3(n-1)+1 \right)\,y^n=0. \end{align*} \end{proof} \begin{proof}[Proof of inequality (\ref{IV})] Note that \begin{align*} T^4 - T^2 + 2S\,T^3 &+ S^3\,T - T\sum_{n=1}^K n^2y^n + \left( \sum_{n=1}^K n\,y^n\right)^2 \\ & \geq T^4 - T^2 + 2T^3 + T - T\sum_{n=1}^K n^2\,y^n + \left( \sum_{n=1}^K n\,y^n\right)^2. \end{align*} We will show \begin{align*} P_K(y) \coloneqq T^4 - T^2 + 2T^3 + T - T\sum_{n=1}^K n^2\,y^n + \left( \sum_{n=1}^K n\,y^n\right)^2\geq 0. \end{align*} The cases $K=1,2$ can be checked directly. Let us assume $K\geq 3$. $P_K(y)$ is a polynomial of degree $4K$, say of the form $\sum_{n=0}^{4K} d_n y^n$. We will show $d_n>0$ for $0\leq n \leq 4K$. Due to $T^4$ and $T^3$ terms, necessarily $d_n>0$ for $2K+1 \leq n \leq 4K$. It remains to show $d_n \geq 0$ for $0\leq n \leq 2K$. First, observe the following: $d_0=0$, $d_1=1$, and $d_2=d_3=0$. In order to treat the remaining cases, we apply (\ref{c})-(\ref{g}) in Lemma \ref{poly} to $d_n.$ \\\\ \textit{When $4\leq n \leq K$}: $d_n \geq \frac{(n-1)(n-2)(n-3)}{6}\, - \,(n-1)\, + \,(n-1)(n-2)\, + 1 \,-\, \,\frac{n(n-1)(2n-1)}{6} + \frac{n(n-1)(n+1)}{6} =\frac{(n-2)(n-3)}{2}>0$.\\\\ \textit{When $n= K+1$}: $d_n\geq \frac{K(K-1)(K-2)}{6}\,-\,K\,+\,K(K-1)\,-\, \frac{K(K+1)(2K+1)}{6}+ \,\frac{K(K+1)(K+2)}{6} = \frac{K(K-3)}{2}\geq 0$.\\\\ \textit{When $n= K+2$}: $d_n \geq \frac{K(K-1)(K+1)}{6} - \,(K-1)\, + \,K(K+1)\, - \frac{(K-1)(2K^2+5K+6)}{6}\,+ \,\frac{(K-1)(K+1)(K+6)}{6} = \frac{3K^2-K+2}{2}>0$.\\\\ \textit{When $n= K+3$}: $d_n \geq \frac{K(K+1)(K+2)}{6}\, - \,(K-2) \,+\, (K-1)(K+4)\,- \frac{(K-2)(2K^2 +7K+15)}{6} +\frac{(K-2)(K^2 +11K+12)}{6} = \frac{5K^2+K-2}{2}>0$.\\\\ \textit{When $K+4\leq n \leq 2K$}: After applying Lemma \ref{poly}, simplifying and rearranging the terms, we get \begin{align*} d_n \geq -\frac{1}{3}n^3 + \left(K+ \frac{1}{2} \right)n^2 +\frac{11}{6}n -\frac{2K^3}{3}-K^2 - \frac{13K}{3} -2. \end{align*} Let \begin{equation*} V_K(n) = -\frac{1}{3}n^3 + \left(K+ \frac{1}{2} \right)n^2 +\frac{11}{6}n -\frac{2K^3}{3}-K^2 - \frac{13K}{3} -2. \end{equation*} We will show that $V_K \geq 0$ for all $K+4\leq n \leq 2K$. Taking the derivative of $V_K$ w.r.t $n$ yields \begin{equation*} \dfrac{dV_K}{dn} = - n^2 + n (2K+1) + \dfrac{11}{6}. \end{equation*} $\dfrac{dV_K}{dn}\geq 0$ iff \begin{equation*} \dfrac{1}{6} \left(-\sqrt{3} \sqrt{12K^2 + 12K + 25}+6K +3\right) \leq n \leq \dfrac{1}{6} \left(\sqrt{3} \sqrt{12K^2 + 12K + 25}+6K +3\right). \end{equation*} But, \begin{equation*} \left[\dfrac{1}{6} \left(-\sqrt{3} \sqrt{12K^2 + 12K + 25}+6K +3\right), \dfrac{1}{6} \left(\sqrt{3} \sqrt{12K^2 + 12K + 25}+6K +3\right) \right] \supseteq [K,2K] \end{equation*} for all $K\geq 0.$\ \vskip1mm Therefore $\dfrac{dV_K}{dn}\geq 0$ for all $K+4\leq n \leq 2K$. Moreover, $V_K(K+4) = \frac{K(7K+3)}{2}-8>0$ for all $K\geq 3$, completing the proof. \end{proof} \begin{appendix} \section*{Appendix: Some polynomial identities} Each identity in Lemma \ref{poly} can be obtained by the standard product of polynomials. The desired coefficients are given by convolution operation. \begin{proof}[Proof of Lemma \ref{poly}]\ \label{polynomial identities} \begin{enumerate}[(a)] \item \begin{align*} S^2 & = \sum_{n=0}^{2N}\left(\sum_{i+j=n} 1\right)x^n \\ & = \sum_{n=0}^N \left(\sum_{i=0}^n 1\right)x^n + \sum_{n=N+1}^{2N} \left(\sum_{i=n-N}^{N} 1 \right)x^n\\ &= \sum_{n=0}^N (n+1)\, x^n + \sum_{n=N+1}^{2N} (2N-n+1)\,x^n. \end{align*} \item \begin{align*} S^3=S \cdot S^2= \sum_{n=0}^N x^n \left( \sum_{n=0}^N (n+1)x^n + \sum_{n=N+1}^{2N} (2N-n+1)x^n\right). \end{align*} Let us consider the two summations separately. \begin{align*} \sum_{n=0}^N x^n \sum_{n=0}^N (n+1)\,x^n &= \sum_{n=0}^{2N} \left(\sum_{i+j=n}(i+1)\right)x^n\\ & = \sum_{n=0}^N \left(\sum_{i=0}^n (i+1) \right)x^n + \sum_{n=N+1}^{2N} \left(\sum_{i=n-N}^N (i+1) \right)x^n\\ & = \frac{1}{2}\, \sum_{n=0}^N (n+1)(n+2)\,x^n + \frac{1}{2} \sum_{n=N+1}^{2N} (n+2)(2N-n+1)\, x^n. \end{align*} \begin{align*} \sum_{n=0}^N x^n \sum_{n=N+1}^{2N} (2N- n+1)\,x^n &= x^{N+1} \sum_{n=0}^N x^n \sum_{n=0}^{N-1} (N-n)\,x^n \\ & \geq x^{N+1} \sum_{n=0}^{N-1} x^n \sum_{n=0}^{N-1} (N-n)\,x^n\\ & \geq x^{N+1} \sum_{n=0}^{2N-2} \left(\sum_{i+j=n} (N-i)\right)x^n\\ &\geq x^{N+1} \displaystyle \sum_{n=0}^{N-1} \left( \sum_{i=0}^n (N-i)\right) x^n\\ &= x^{N+1} \cdot \frac{1}{2}\sum_{n=0}^{N-1} (n+1)(2N-n)\,x^n\\ &= \frac{1}{2}\, \sum_{n=N+1}^{2N} (n-N)(3N-n+1)\,x^n. \end{align*} We conclude by combining the two summations. \item Since $T^2 = y^2 \left(\displaystyle \sum_{n=0}^{K-1} y^n\right)^2$, apply (a) with $N=K-1$ and $x=y$. \item Since $T^3 = y^3 \left(\displaystyle \sum_{n=0}^{K-1} y^n\right)^2$, apply (b) with $N=K-1$ and $x=y$. \item First, we consider $S^4$. By (a), \begin{align*} S^4 \geq \left(\sum_{n=0}^N (n+1)\,x^n\right)^2 + 2\,\sum_{n=0}^N (n+1)\,x^n \sum_{n=N+1}^{2N} (2N-n+1)\,x^n \end{align*} Let us consider the two summations on the right-hand side separately. \begin{align*} &\left( \sum_{n=0}^N (n+1)\,x^n\right)^2\\ &=\sum_{n=0}^{2N} \left(\sum_{i+j = n}(i+1)(j+1)\right)x^n \\ &= \sum_{n=0}^{N} \left(\sum_{i=0}^n (i+1)(n-i+1)\right)x^n + \sum_{n=N+1}^{2N} \left(\sum_{i=n-N}^N (i+1)(n-i+1)\right)x^n\\ &= \frac{1}{6}\, \sum_{n=0}^{N} (n+1)(n+2)(n+3)\,x^n \\ & + \frac{1}{6} \sum_{n=N+1}^{2N} \big[(2N-n+1)(n^2 + n(2N+7) - 2(N^2 + N-3) \big]\,x^n. \end{align*} \begin{align*} \sum_{n=0}^N (n+1)\,x^n \sum_{n=N+1}^{2N} (2N-n+1)\,x^n &= x^{N+1} \sum_{n=0}^N (n+1)\,x^n \sum_{n=0}^{N-1}(N-n) \,x^n\\ & \geq x^{N+1} \sum_{n=0}^{N-1} (n+1)\,x^n \sum_{n=0}^{N-1}(N-n)\, x^n\\ &= x^{N+1} \sum_{n=0}^{2N-2} \left(\sum_{i+j = n}(N-i)(j+1)\right)\,x^n\\ &\geq x^{N+1}\sum_{n=0}^{N-1} \left(\sum_{i=0}^n(N-i)(n-i+1)\right)x^n\\ &= x^{N+1} \cdot \frac{1}{6} \sum_{n=0}^{N-1} (n+1)(n+2)(3N-n)\, x^n\\ &= \frac{1}{6} \sum_{n=N+1}^{2N} (n-N)(n-N+1)(4N-n+1)\,x^n. \end{align*} After combining the two inequalities, we get \begin{equation*} S^4 \geq \frac{1}{6} \,\displaystyle \sum_{n=0}^{N} (n+1)(n+2)(n+3)\,x^n + \displaystyle \sum_{n=N+1}^{2N} \Tilde{e}_K (n)\, x^n, \end{equation*} where $\Tilde{e}_K (n) = \dfrac{1}{6}\, \big[(2N-n+1)(n^2 + n(2N+7) - 2(N^2 + N-3)) + 2(n-N)(n-N+1)(4N-n+1) \big]$.\\\\ Since $T^4 = y^4 \left(\displaystyle \sum_{n=0}^{K-1} y^n \right)^4,$ by letting $N= K-1$ and $x=y$ in $S^4$, we can deduce the desired inequality. \item \begin{align*} T \displaystyle \sum_{n=1}^K n^2y^n & = \displaystyle \sum_{n=1}^K y^n \displaystyle \sum_{n=1}^K n^2\,y^n \\ &= \sum_{n=2}^{2K} \left(\sum_{i+j=n} i^2 \right)\,y^n\\ &= \sum_{n=2}^{K+1} \left(\sum_{i=1}^{n-1} i^2\right)\,y^n + \sum_{n=K+2}^{2K} \left(\sum_{i=n-K}^{K}i^2\right)\,y^n\\ & = \frac{1}{6} \sum _{n=2}^{K+1} n(n-1)(2n-1)\,y^n \\ &+ \frac{1}{6}\sum_{n=K+2}^{2K} (2K-n+1)(2n^2- n(2K+1)+2K(K+1))\,y^n. \end{align*} \item \begin{align*} \left(\sum_{n=1}^K n\,y^n\right)^2 & = \sum_{n=2}^{2K} \left(\sum_{i+j=n}ij\right)\,y^n \\ &= \sum_{n=2}^{K+1} \left( \sum_{i=1}^{n-1} i(n-i)\right)\,y^n + \sum_{n=K+2}^{2K} \left( \sum_{i=n-K}^{K} i(n-i)\right)\,y^n\\ & = \frac{1}{6}\, \sum_{n=2}^{K+1} n(n-1)(n+1)\,y^n \\ & + \frac{1}{6} \sum_{n=K+2}^{2K} (2K-n+1)(n^2 + n(2K+1) -2K(K+1))\, y^n. \end{align*} \end{enumerate} \end{proof} \end{appendix}
{ "redpajama_set_name": "RedPajamaArXiv" }
3,071
\section{Introduction} Open quantum systems are ubiquitous in the sense that any system can be thought of as being surrounded by its environment (reservoir or bath) which influences its dynamics. They provide a natural route for discussing damping and dephasing. One of the first testing grounds for open system ideas was in quantum optics \cite{wl73}. Its application to other areas gained momentum from the works of Caldeira and Leggett \cite{cl83}, and Zurek \cite{wz93}, among others. The total Hamiltonian is $H = H_S + H_R + H_{SR}$ , where $S$ stands for the system, $R$ for the reservoir and $SR$ for the system-reservoir interaction. The evolution of the system of interest $S$ is studied taking into account the effect of its environment $R$, through the $SR$ interaction term, making the resulting dynamics non-unitary. Depending upon the system-reservoir ($S-R$) interaction, open systems can be broadly classified into two categories, viz., quantum non-demolition (QND), which we consider here, or dissipative (cf. for example Ref. \cite{ingold}). A particular type of quantum nondemolition (QND) $S-R$ interaction is given by a class of energy-preserving measurements in which dephasing occurs without damping the system, i.e., where $[H_S, H_{SR}] = 0$ while the dissipative systems correspond to the case where $[H_S, H_{SR}] \neq 0$ resulting in decoherence along with dissipation \cite{bg07}. A class of observables that may be measured repeatedly with arbitrary precision, with the influence of the measurement apparatus on the system being confined strictly to the conjugate observables, is called QND or back-action evasive observables \cite{bvt80, bk92, wm94, zu84}. Such a measurement scheme was originally introduced in the context of the detection of gravitational waves \cite{ct80, bo96}. The energy preserving measurements, referred to above, form an important class of such a general QND measurement scheme. The interest in the relevance of open system ideas to quantum information has increased in recent times because of the impressive progress made, and the potential for future progress (cf. for example Ref. \cite{erika}), on the experimental front in the manipulation of quantum states of matter towards quantum information processing and quantum communication. Myatt {\it et al.} \cite{myatt} and Turchette {\it et al.} \cite{turch} have performed a series of experiments in which they induced decoherence and decay by coupling the atom (their system-$S$) to engineered reservoirs, in which the coupling to, and the state of, the environment are controllable. An experiment reported in Ref. \cite{jb03} demonstrated and completely characterized a QND scheme for making a nondeterministic measurement of a single photon nondestructively using only linear optics and photo-detection of ancillary modes, to induce a strong nonlinearity at the single photon level. The dynamics of decoherence in continuous atom-optical QND measurements has been studied in \cite{vo98}. Quantum entanglement is the inherent property of a system to exhibit correlations, the physical basis being the non-local nature of quantum mechanics \cite{bell}, and hence is a property that is exclusively quantum in nature. Entanglement plays a central role in quantum information theory \cite{nc}, in quantum computation as in the Shor algorithm \cite{shor}, and quantum error correction \cite{css}. A number of methods have been proposed for creating entanglement involving trapped atoms \cite{beige, fy00, sm02}. An important issue is to study how quantum entanglement is affected by noise, which can be thought of as a manifestation of an open system effect \cite{bp02}. A recent experimental investigation of the dynamics of entanglement with a continuous monitoring of the environment, i.e., via a realization of quantum trajectories \cite{car93}, has been made in \cite{am07}. Here we study the effect of noise on the entanglement generated between two spatially separated qubits, by means of their interaction with the bath, which is taken to be in an initial squeezed-thermal state \cite{bg07,sqgen}. This is of relevance to evaluate the performance of two-qubit gates in practical quantum information processing systems. The two qubits are intially uncorrelated. With the advent of time entanglement builds up between them via their interaction with the bath but eventually gets destroyed because of the quantum to classical transition mediated by the noise. In this paper we study the effect of noise generated by a QND $S-R$ interaction. The issue of a dissipative noise is taken up in a separate work. Since we are dealing here with a two qubit system which very rapidly evolves into a mixed state, a study of entanglement would necessarily involve a measure of entanglement for mixed states. Entanglement of a bipartite system \cite{bz08} in a pure state is unambigious and well defined. However, mixed state entanglement (MSE) is not so well defined. Thus, although a number of criteria such as entanglement of formation \cite{bd96, ww98, mc05} and negativity \cite{fw89} exist, there is a realization \cite {bd96} that a single quantity is inadequate to describe MSE. This was the principal motivation for the development of a new prescription of MSE \cite{br08} in which it is characterized not by a number, but as a probability density function (PDF). This generalization provides an exhaustive and geometrical characterization of entanglement : by exploring the entanglement content in the various subspaces spanning the two-qubit Hilbert space. The known prescriptions such as concurrence and negativity emerge as particular elements in the set of parameters that characterize the probability density function. We will study entanglement in the two-qubit system using concurrence as well as the probability density function. The plan of the paper is as follows. In Sections II and III, we develop our open system model for the multi-qubit dynamics under the influence of a QND $S-R$ interaction. Section II develops the general dynamics for a multi-qubit system, where the qubits are spatially separated and initially uncorrelated, and the bath is in a general squeezed-thermal state. Section III specializes these considerations to the case of two qubits. In Section IV, we point out some interesting symmetries obeyed by the two-qubit dynamics. Section V makes a brief application of the model to practical quantum communication, in particular, in the realization of a quantum repeater \cite{chb96,bdcz98}. In Section VI, we give a brief description of the recently developed entanglement measure of MSE \cite{br08}. Section VII deals with the entanglement analysis of the two-qubit open system using the PDF as a measure of entanglement. We also dwell upon the usual measure of MSE, concurrence. We deal with the scenarios where the two qubits effectively interact via localized $S-R$ interactions, called the localized (independent) decoherence model, as also when they interact collectively with the bath, called the collective decoherence model. The usefulness of the PDF measure of entanglement is that it allows us to demonstrate the existence of noise regimes where even though entanglement vanishes, the state is still available for applications like NMR quantum computation, because of the presence of a pseudo-pure component. In Section VIII, as an application of the PDF, we make a brief discussion of the temperature dependent effective dynamics obeyed by the two-qubit open system in the collective decoherence regime. In Section IX, we make our conclusions. \section{Multi -Qubit QND interaction with a Squeezed Thermal Bath} We consider the Hamiltonian, describing the QND interaction of $L$ qubits with the bath as \cite{rj02, bg07, bgg07} \begin{eqnarray} H & = & H_S + H_R + H_{SR} \nonumber \\ & = & \sum\limits_{n=1}^L \hbar \varepsilon_n J^n_z+ \sum\limits_k \hbar \omega_k b^{\dagger}_k b_k + \sum\limits_{n,k} \hbar J^n_z (g^n_k b^{\dagger}_k + g^{n*}_k b_k). \label{basich} \end{eqnarray} Here $H_S$, $H_R$ and $H_{SR}$ stand for the Hamiltonians of the system, reservoir and system-reservoir interaction, respectively. $b^{\dagger}_k$, $b_k$ denote the creation and annihilation operators for the reservoir oscillator of frequency $\omega_k$, $g^n_k$ stands for the coupling constant (assumed to be position dependent) for the interaction of the oscillator field with the qubit system and are taken to be \begin{equation} g^n_k = g_k e^{-ik.r_n}, \label{coupling} \end{equation} where $r_n$ is the qubit position. Since $[H_S, H_{SR}]=0$, the Hamiltonian (1) is of QND type. In the parlance of quantum information theory, the noise generated is called the phase damping noise \cite{gp06, bg07}. The position dependence of the coupling of the qubits to the bath (\ref{coupling}) helps to bring out the effect of entanglement between qubits through the qubit separation: $ r_{mn} \equiv r_m - r_n$. This allows for a discussion of the dynamics in two regimes: (A). localized decoherence where $k.r_{mn} \sim \frac{r_{mn}}{\lambda} \geq 1$ and (B). collective decoherence where $k.r_{mn} \sim \frac{r_{mn}}{\lambda} \rightarrow 0$. The case (B) of collective decoherence would arise when the qubits are close enough for them to experience the same environment, or when the bath has a long correlation length (set by the effective wavelength $\lambda$) compared to the interqubit separation $r_{mn}$ \cite{rj02}. Our aim is to study the reduced dynamics of the qubit system. As in the case of a single qubit QND interaction with bath \cite{bg07, bgg07}, the density matrix is evaluated in the system eigenbasis $|i_n \rangle = |\pm \frac{1}{2} \rangle$ (the possible eigenstates of $J^n_z$ with eigenvalues $j_n = \pm \frac{1}{2}$). The system-plus-reservoir composite is closed and hence obeys a unitary evolution given, in the interaction picture, by \begin{equation} \rho (t) = U_I (t) \rho (0) U^{\dagger}_I (t), \end{equation} where \begin{equation} U_I (t) = {\cal T} e^{- (i/\hbar)\int_0^t dt^\prime H_I (t^\prime)}, \end{equation} with $H_I (t) = e^{ i(H_S + H_R) t / \hbar} H_{SR} e^{- i(H_S + H_R) t / \hbar}$, and ${\cal T}$ denotes time ordering. Also \begin{equation} \rho (0) = \rho^s (0) \rho_R (0), \label{initial} \end{equation} i.e., we assume separable initial conditions. Here \begin{equation} \rho^s (0) = \rho^s_1(0) \otimes \rho^s_2(0)\cdots \otimes \rho^s_L(0), \label{sysinitial} \end{equation} is the initial state of the qubit system and the subscripts denote the individual qubits. In Eq. (\ref{initial}), $\rho_R (0)$ is the initial density matrix of the reservoir which we take to be a broadband squeezed thermal bath \cite{bg07,bgg07,gp06} given by \begin{equation} \rho_R(0) = S(\alpha, \Phi) \rho_{th} S^{\dagger} (\alpha, \Phi), \label{rhorin} \end{equation} where \begin{equation} \rho_{th} = \prod_k \left[ 1 - e^{- \beta \hbar \omega_k} \right] e^{-\beta \hbar \omega_k b^{\dagger}_k b_k} \label{rhoth} \end{equation} is the density matrix of the thermal bath at temperature $T$, with $\beta \equiv 1/(k_B T)$, $k_B$ being the Boltzmann constant, and \begin{equation} S(\alpha_k, \Phi_k) = \exp \left[ \alpha_k \left( {b^2_k \over 2} e^{-2i \Phi_k} - {b^{\dagger 2}_k \over 2} e^{2i \Phi_k} \right) \right] \label{sqop} \end{equation} is the squeezing operator with $\alpha_k$, $\Phi_k$ being the squeezing parameters \cite{cs85}. In order to obtain the reduced dynamics of the system , we trace over the reservoir variables. The matrix elements of the reduced density matrix in the system eigenbasis are obtained for the localized and collective decoherence models as: \subsection{Localized decoherence model} \begin{equation} \rho^s_{\{i_n,j_n\}} (t) = \exp[i\{ \Theta_{\{i_n,j_n\}}^{\rm {lc}} (t) - \Lambda_{\{i_n,j_n\}}^{\rm {lc}} (t)\}] \exp[-\Gamma^{\rm {lc}}_{\{i_n,j_n\} (\rm {sq})} (t)] \rho^s_{\{i_n,j_n\}} (0). \label{ind} \end{equation} Here $\rho^s_{\{i_n,j_n\}} (t)$ stands for $\langle i_L, i_{L-1},...,i_1| {\rm Tr}_R{\rho^s (t)}|j_L, j_{L-1},...,j_1 \rangle$ and the symbol ${\{i_n,j_n\}}$ stands collectively for ${i_1,j_1;i_2,j_2;...;i_L,j_L}$. The superscript {\it lc} is to indicate that these expressions are for the localized decoherence model and the subscript {\it sq} indicates that the bath starts in a squeezed thermal initial state. As seen from the expressions given below, $\Theta_{\{i_n,j_n\}}^{\rm {lc}}$ and $\Lambda_{\{i_n,j_n\}}^{\rm {lc}}$ are independent of the bath initial conditions and are given in the continuum limit (assuming a quasi-continuous bath spectrum) by \begin{equation} \Theta_{\{i_n,j_n\}}^{\rm {lc}} (t) = 2\int\limits^{\infty}_0 d\omega I(\omega) S(\omega,t) \sum^L_{\stackrel{m=1,n=2}{(m \neq n)}} (i_m i_n - j_m j_n) \cos(\omega t_s), \label{thetain} \end{equation} \begin{equation} \Lambda_{\{i_n,j_n\}}^{\rm {lc}} (t) = 2\int\limits^{\infty}_0 d\omega I(\omega) C(\omega,t) \sum^L_{(m \neq n)} i_m j_n \sin(\omega t_s). \label{lambdain} \end{equation} In the above equations, $I(\omega)$ is the bath spectral density given in terms of the system (qubits) and bath coupling constant as $I(\omega)= \sum\limits_{k} \delta (\omega - \omega_k) g^2_k$, which for the Ohmic case considered here has the form \begin{equation} I(\omega) = {\gamma_0 \over \pi} \omega e^{-\omega/\omega_c}, \label{ohmic} \end{equation} where $\gamma_0$ and $\omega_c$ are two bath parameters. Also \begin{equation} S(\omega, t) = \frac{\omega t - \sin(\omega t)}{\omega^2}, \label{sin} \end{equation} and \begin{equation} C(\omega, t) = \frac{1 - \cos(\omega t)}{\omega^2}. \label{cos} \end{equation} In Eqs. (\ref{thetain}) and (\ref{lambdain}), $\omega t_s \equiv k. r_{mn}$ \cite{rj02}, where $t_s$ is the transit time introduced in order to express the system-bath coupling in the frequency domain. $\Gamma^{lc}_{sq} (t)$ in Eq. (\ref{ind}) is given as \begin{eqnarray} \Gamma^{\rm {lc}}_{\{i_n,j_n\} (\rm {sq})} (t) &=& \int\limits^{\infty}_0 d\omega I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \nonumber\\ &\times& \left[\cosh(2\alpha)C(\omega, t) \Big\{\sum^L_{m=1}(i_m - j_m)^2 + 2 \sum^L_{\stackrel{m=1,n=2}{(m \neq n)}} (i_m- j_m) (i_n- j_n) \cos(\omega t_s)\Big\}\right.\nonumber\\ &-& \left. \frac{2}{\omega^2}\sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \Big\{\cos(\omega(t-2a))[\sum^L_{m=1}(i_m - j_m)^2 \cos(\omega t_{corr1})\right. \nonumber\\ &+& \left. 2 \sum^L_{\stackrel{m=1,n=2}{(m \neq n)}} (i_m- j_m) (i_n- j_n) \cos(\omega t_{corr2})]+ \sin(\omega(t-2a))[\sum^L_{m=1}(i_m - j_m)^2 \sin(\omega t_{corr1}) \right. \nonumber\\ &+& \left. 2 \sum^L_{\stackrel{m=1,n=2}{(m \neq n)}} (i_m- j_m) (i_n- j_n) \sin(\omega t_{corr2})]\Big\}\right], \label{gammain} \end{eqnarray} where we have defined two new time scales $\omega t_{corr1} \equiv 2k.r_m$ and $\omega t_{corr2} \equiv k.(r_n + r_m)$ which are due to the non-stationary effects introduced by the squeezed thermal bath. Here we have for simplicity taken the squeezed bath parameters as \begin{eqnarray} \cosh \left( 2\alpha(\omega) \right) & = & \cosh (2\alpha),~~ \sinh \left( 2\alpha (\omega) \right) = \sinh (2\alpha), \nonumber\\ \Phi (\omega) & = & a\omega, \label{sqpara} \end{eqnarray} where $a$ is a constant depending upon the squeezed bath. \subsection{Collective decoherence model} The reduced density matrix is given by \begin{equation} \rho^s_{\{i_n,j_n\}} (t) = \exp[i\{ \Theta_{\{i_n,j_n\}}^{\rm {col}} (t) - \Lambda_{\{i_n,j_n\}}^{\rm {col}} (t)\}] \exp[-\Gamma^{\rm {col}}_{\{i_n,j_n\} (\rm{sq})} (t)] \rho^s_{\{i_n,j_n\}} (0). \label{col} \end{equation} The superscript $\rm {col}$ is to indicate that these expressions are for the collective decoherence model and the subscript $\rm {sq}$ indicates that the bath starts in a squeezed thermal initial state. As in the case of localized decoherence, $\Theta^{\rm {col}}$ and $\Lambda^{\rm {col}}$ are independent of the bath initial conditions and are given in the continuum limit (assuming a quasi-continuous bath spectrum) by \begin{equation} \Theta^{\rm {col}} (t) = \int\limits^{\infty}_0 d\omega I(\omega) S(\omega,t) \left[(\sum^L_{m=1} i_m)^2 - (\sum^L_{m=1} j_m)^2\right], \label{thetacol} \end{equation} \begin{equation} \Lambda^{\rm {col}} (t) = 0. \label{lambdacol} \end{equation} The bath spectral density $I(\omega)$ is as in Eq. (\ref{ohmic}). In Eq. (\ref{col}), $\Gamma^{\rm {col}}_{\{i_n,j_n\} (\rm{sq})} (t)$ is \begin{eqnarray} \Gamma^{\rm {col}}_{\{i_n,j_n \}(\rm{sq})} (t) &=& \int\limits^{\infty}_0 d\omega I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \left[\cosh(2\alpha)C(\omega, t) [\sum^L_{m=1}(i_m - j_m)]^2 \right. \nonumber\\ &-& \left. \frac{2}{\omega^2}\sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \Big\{\cos(\omega(t-2a))[\sum^L_{m=1}(i_m - j_m)^2 \cos(\omega t_{corr1})\right. \nonumber\\ &+& \left. 2 \sum^L_{\stackrel{m=1,n=2}{(m \neq n)}} (i_m- j_m) (i_n- j_n) \cos(\omega t_{corr2})] + \sin(\omega(t-2a))[\sum^L_{m=1}(i_m - j_m)^2 \sin(\omega t_{corr1}) \right. \nonumber\\ &+& \left. 2 \sum^L_{\stackrel{m=1,n=2}{(m \neq n)}} (i_m- j_m) (i_n- j_n) \sin(\omega t_{corr2})]\Big\}\right], \label{gammacol} \end{eqnarray} All the other terms are as defined above. On comparing Eq. (\ref{gammacol}) with (\ref{gammain}), we find that the terms proportional to $\sinh(2\alpha)$, arising from the non-stationarity of the squeezed bath, are same while the terms proportional to $\cosh(2\alpha)$ differ from each other. For the collective decoherence model, $\omega t_s \equiv k. r_{mn} \equiv 0$, but the two time-scales coming from the non-stationary components of the squeezed thermal bath, i.e., $\omega t_{corr1} \equiv 2k.r_m$ and $\omega t_{corr2} \equiv k.(r_n + r_m)$ are both non-zero, indicative of correlations induced between the qubits by the bath squeezing. For the case of zero bath squeezing, both the Eqs. (\ref{gammacol}) and (\ref{gammain}) reduce to their corresponding values for the case of a thermal bath \cite{rj02}. \section{Two qubit interaction} Here we specialize the general considerations of the previous section to the case of two qubits. \subsection{Localized decoherence model \label{sec:3a}} The reduced density matrix is a specialization of Eq. (\ref{ind}) to the case of two qubits, say a and b. Here $\rho^s_{\{i_n,j_n\}}(t)$ would be $\rho^s_{\{i_a,j_b\}} (t)$ which represents $\langle i_a, i_b| {\rm Tr}_R{\rho^s (t)}|j_a, j_b \rangle$, where the states $|i_a\rangle$ or $|i_b\rangle$ have eigenvalues $\pm \frac{1}{2}$. We will collectively represent the two-particle index $ab$ by a single 4-level index according to the following scheme: $$ -\frac{1}{2},-\frac{1}{2} \equiv 0,~~ -\frac{1}{2},\frac{1}{2} \equiv 1,~~ \frac{1}{2},-\frac{1}{2} \equiv 2,~~ \frac{1}{2},\frac{1}{2} \equiv 3. $$ Thus there will be sixteen elements of the density matrix, which we enumerate below. They are seen to satisfy the symmetries \begin{equation} \rho^s_{32} (t) = \rho^{\ast s}_{23} (t) = \rho^s_{01} (t) = \rho^{\ast s}_{10} (t), \label{ina} \end{equation} where $\ast$ in the superscript indicates complex conjugation, and of course the first and last equality follow from the hermiticity of the density operator. In the Eqs. (\ref{ina}), $\Theta_{\{i_n,j_n\}}^{\rm {lc}} (t)$, $\Lambda_{\{i_n,j_n\}}^{\rm {lc}} (t)$ can be obtained from the Eqs. (\ref{thetain}), (\ref{lambdain}), respectively, and $\Gamma^{\rm {lc}}_{\{i_n,j_n\} (\rm {sq})} (t)$ from Eq. (\ref{gammain}) and are given by \begin{equation} \Theta^{\rm {lc}}_{32}(t) = \Theta^{\rm {lc}}_{01}(t) = \int\limits^{\infty}_0 d\omega I(\omega) S(\omega,t) \cos(\omega t_s), \label{theta1} \end{equation} \begin{equation} \Lambda^{\rm {lc}}_{32}(t) = \Lambda^{\rm {lc}}_{01}(t) = -\int\limits^{\infty}_0 d\omega I(\omega) C(\omega,t) \sin(\omega t_s), \label{lambda1} \end{equation} \begin{equation} \Theta^{\rm {lc}}_{23}(t) = \Theta^{\rm {lc}}_{10}(t) = -\Theta^{\rm {lc}}_{32}(t) = -\Theta^{\rm {lc}}_{01}(t), \label{theta2} \end{equation} \begin{equation} \Lambda^{\rm {lc}}_{23} (t) = \Lambda^{\rm {lc}}_{10}(t) = -\Lambda^{\rm {lc}}_{32}(t) = -\Lambda^{\rm {lc}}_{01}(t), \label{lambda2} \end{equation} and \begin{eqnarray} \Gamma^{\rm {lc}}_{\rm {sq}} (t) &=& \int\limits^{\infty}_0 d\omega I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \left[\cosh(2\alpha)C(\omega, t)- \frac{2}{\omega^2}\sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \Big\{\cos(\omega(t-2a)) \cos(\omega t_{corr1}^{(1)}) \right. \nonumber\\ &+& \left. \sin(\omega(t-2a)) \sin(\omega t_{corr1}^{(1)})\Big\}\right], \label{gamma1} \end{eqnarray} for all the above combinations. In the above equations, $\omega t_s$ stands for $k\cdot r_{ab}$ while $\omega t_{corr1}^{(1)} \equiv 2k\cdot r_b$. Interestingly, for the above cases, the correlation time $\omega t_{corr2} \equiv k.(r_a + r_b)$ is absent. It can be seen that \begin{eqnarray} \rho^s_{aa} (t) &=& \rho^s_{aa} (0), ~~~~(a = 0,1,2,3) \label{inb}, \end{eqnarray} from which follows that the population remains unchanged. This is a consequence of QND nature of the $S-R$ interaction. Also, \begin{eqnarray} \rho^s_{21} (t) = \rho^{\ast s}_{12} (t) = \rho^s_{12} (t),\nonumber\\ \rho^s_{30} (t) = \rho^{\ast s}_{03} (t) = \rho^s_{03} (t), \label{inc} \end{eqnarray} i.e., these components are purely real. In Eqs. (\ref{inc}), $\Theta^{\rm {lc}} (t)$, $\Lambda^{\rm {lc}} (t)$ and $\Gamma^{\rm {lc}}_{\rm {sq}} (t)$ are given by \begin{equation} \Theta^{\rm {lc}} (t) = 0 = \Lambda^{\rm {lc}} (t), \label{theta3} \end{equation} and \begin{eqnarray} \Gamma^{\rm {lc}}_{ {\rm sq},30} (t) &=& \Gamma^{\rm {lc}}_{ {\rm sq},03} (t) = \nonumber\\ &=& \int\limits^{\infty}_0 d\omega I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \left[2\cosh(2\alpha)C(\omega, t) [1 + \cos(\omega t_s)] - \frac{2}{\omega^2}\sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \right. \nonumber\\ &\times& \left. \Big\{\cos(\omega(t-2a)) [\cos(2k\cdot r_a) + \cos(2k\cdot r_b) + 2\cos(k\cdot [r_a+r_b])] \right. \nonumber \\ &+& \left. \sin(\omega(t-2a)) [\sin(2k\cdot r_a) + \sin(2k\cdot r_b) + 2\sin(k\cdot [r_a+r_b])] \Big\}\right], \label{gamma2} \end{eqnarray} \begin{eqnarray} \Gamma^{\rm {lc}}_{\rm {sq}, 21} (t) &=& \Gamma^{\rm {lc}}_{\rm {sq}, 12} (t) \nonumber\\ &=& \int\limits^{\infty}_0 d\omega I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \left[2\cosh(2\alpha)C(\omega, t) [1 - \cos(\omega t_s)] - \frac{2}{\omega^2}\sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \right. \nonumber\\ &\times& \left. \Big\{\cos(\omega(t-2a)) [\cos(2k\cdot r_a) + \cos(2k\cdot r_b) - 2\cos(k\cdot [r_a+r_b])] \right. \nonumber\\ &+& \left. \sin(\omega(t-2a)) [\sin(2k\cdot r_a) + \sin(2k\cdot r_b) - 2\sin(k\cdot [r_a+r_b])]\Big\}\right]. \label{gamma3} \end{eqnarray} Thus we see that the Eqs. (\ref{gamma2}), (\ref{gamma3}), depend on both $2 k\cdot r_a$ and $2 k\cdot r_b$, and $\omega t_{corr2}$ which is as defined above. Further, \begin{equation} \rho^s_{31} (t) = \rho^{\ast s}_{13} (t) = \rho^s_{02} (t) = \rho^{\ast s}_{20} (t), \label{rhoind} \end{equation} where $\ast$ in the superscript indicates complex conjugation. In Eqs. (\ref{rhoind}), $\Theta^{\rm {lc}} (t)$, $\Lambda^{\rm {lc}} (t)$ are \begin{equation} \Theta^{\rm {lc}}_{31}(t) = \Theta^{\rm {lc}}_{02}(t) = \int\limits^{\infty}_0 d\omega I(\omega) S(\omega,t) \cos(\omega t_s), \label{theta4} \end{equation} \begin{equation} \Lambda^{\rm {lc}}_{31}(t) = \Lambda^{\rm {lc}}_{02}(t) = \int\limits^{\infty}_0 d\omega I(\omega) C(\omega,t) \sin(\omega t_s), \label{lambda4} \end{equation} \begin{equation} \Theta^{\rm {lc}}_{13}(t) = \Theta^{\rm {lc}}_{20}(t) = -\Theta^{\rm {lc}}_{31}(t) = -\Theta^{\rm {lc}}_{02}(t), \label{theta5} \end{equation} \begin{equation} \Lambda^{\rm {lc}}_{13} (t) = \Lambda^{\rm {lc}}_{20}(t) = -\Lambda^{\rm {lc}}_{31}(t) = -\Lambda^{\rm {lc}}_{02}(t), \label{lambda5} \end{equation} and \begin{eqnarray} \Gamma^{\rm {lc}}_{\rm {sq}} (t) &=& \int\limits^{\infty}_0 d\omega I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \left[\cosh(2\alpha)C(\omega, t)- \frac{2}{\omega^2}\sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \Big\{\cos(\omega(t-2a)) \cos(\omega t_{corr1}^{(2)}) \right. \nonumber\\ &+& \left. \sin(\omega(t-2a)) \sin(\omega t_{corr1}^{(2)})\Big\}\right], \label{gamma5} \end{eqnarray} for all the above combinations. In the above equations, $\omega t_s$ stands for $k\cdot r_{ab}$ while $\omega t_{corr1}^{(2)} \equiv 2k\cdot r_a$. Interestingly, for the above cases, the correlation time $\omega t_{corr2} \equiv k.(r_a + r_b)$ is absent. The Eqs. (\ref{ina}), (\ref{inb}), (\ref{inc}) and (\ref{rhoind}) cover all the density matrices for the two-qubit localized decoherence model. It can be shown from these results that with the increase in temperature, as also evolution time $t$ and bath squeezing $\alpha$, the system becomes more mixed and hence looses its purity. \subsection{Collective decoherence model} The reduced density matrix is a specialization of Eq. (\ref{col}) to the case of two qubits, say a and b. The notations are as before. \begin{equation} \rho^s_{32} (t) = \rho^{\ast s}_{23} (t) = \rho^s_{01} (t) = \rho^{\ast s}_{10} (t), \label{cola} \end{equation} where $\ast$ in the superscript indicates complex conjugation. In the Eqs. (\ref{cola}), $\Theta^{\rm {col}} (t)$, $\Lambda^{\rm {col}} (t)$ ($= 0$) are obtained from the Eqs. (\ref{thetacol}), (\ref{lambdacol}), respectively and $\Gamma^{\rm {col}}_{\rm {sq}} (t)$ from Eq. (\ref{gammacol}). They are given by \begin{equation} \Theta^{\rm {in}}_{32}(t) = \Theta^{\rm in}_{01}(t) = \int\limits^{\infty}_0 d\omega I(\omega) S(\omega,t), \label{thetacol1} \end{equation} \begin{equation} \Theta^{\rm {col}}_{23}(t) = \Theta^{\rm {col}}_{10}(t) = -\Theta^{\rm {col}}_{32}(t) = -\Theta^{\rm {col}}_{01}(t), \label{thetacol2} \end{equation} and $\Gamma^{\rm {col}}_{\rm {sq}} (t)$ is as in Eq. (\ref{gamma1}) for all the cases in Eq. (\ref{cola}), with $\omega t_{corr1}$ and $\omega t_{corr2}$ as defined there. As before, \begin{eqnarray} \rho^s_{aa} (t) &=& \rho^s_{aa} (0), ~~~~(a = 0,1,2,3) \label{colb}. \end{eqnarray} This is indicative of QND nature of the $S-R$ interaction which preserves the population. Also, \begin{eqnarray} \rho^s_{21} (t) = \rho^{\ast s}_{12} (t) = \rho^s_{12} (t),\nonumber\\ \rho^s_{30} (t) = \rho^{\ast s}_{03} (t) = \rho^s_{03} (t). \label{colc} \end{eqnarray} In the Eqs. (\ref{colc}), $\Theta^{\rm {col}} (t)$, $\Lambda^{\rm {col}} (t)$ and $\Gamma^{\rm {col}}_{\rm {sq}} (t)$ are given by \begin{equation} \Theta^{\rm {col}} (t) = 0 = \Lambda^{\rm {col}} (t), \label{thetacol3} \end{equation} and \begin{eqnarray} \Gamma^{\rm {col}}_{\rm {sq}, 30} (t) &=& \Gamma^{\rm {col}}_{\rm {sq}, 03} (t) \nonumber\\ &=& \int\limits^{\infty}_0 d\omega I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \left[4 \cosh(2\alpha)C(\omega, t) - \frac{2}{\omega^2}\sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \right. \nonumber\\ &\times& \left. \Big\{\cos(\omega(t-2a)) [\cos(2k\cdot r_a) + \cos(2k\cdot r_b) + 2\cos(k\cdot [r_a+r_b])] \right. \nonumber\\ &+& \left. \sin(\omega(t-2a)) [\sin(2k\cdot r_a) + \sin(2k\cdot r_b) + 2\sin(k\cdot [r_a+r_b])]\Big\}\right], \label{gammacol2} \end{eqnarray} \begin{eqnarray} \Gamma^{\rm {col}}_{\rm {sq}, 21} (t) &=& \Gamma^{\rm {col}}_{\rm {sq}, 12} (t) \nonumber\\ &=& - 2 \int\limits^{\infty}_0 \frac{d\omega} {\omega^2} I(\omega) \coth(\frac{\beta \hbar \omega}{2}) \sin^2(\frac{\omega t}{2}) \sinh(2\alpha) \nonumber\\ &\times& \left[\cos(\omega(t-2a)) [\cos(2k\cdot r_a) + \cos(2k\cdot r_b) - 2\cos(k\cdot [r_a+r_b])] \right. \nonumber\\ &+& \left. \sin(\omega(t-2a)) [\sin(2k\cdot r_a) + \sin(2k\cdot r_b) - 2 \sin(k\cdot [r_a+r_b])]\right]. \label{gammacol3} \end{eqnarray} It is interesting to note from Eqs. (\ref{colc}), (\ref{thetacol3}) and (\ref{gammacol3}), that for the case of a purely thermal bath with zero bath squeezing, $\Gamma^{\rm {col}}_{\rm {sq}, 21} (t) = \Gamma^{\rm {col}}_{\rm {sq}, 12} (t) = 0$, thereby implying that for these cases, the corresponding density matrix elements do not decay even though they are interacting with the bath. Also, since in a QND $S-R$ interaction, the diagonal terms $\rho_{1,1}$ and $\rho_{2,2}$ do not change, this implies that any state $\alpha|1\rangle + \beta|2\rangle$ in the subspace span $\{|1\rangle,|2\rangle\}$ remains invariant, thereby leading to a {\it decoherence-free subspace}. Further, \begin{equation} \rho^s_{31} (t) = \rho^{\ast s}_{13} (t) = \rho^s_{02} (t) = \rho^{\ast s}_{20} (t), \label{cold} \end{equation} where $\ast$ in the superscript indicates complex conjugation. In Eq. (\ref{cold}), $\Theta^{\rm {col}}(t)$, $\Lambda^{\rm {col}} (t)$ $(=0)$ are \begin{equation} \Theta^{\rm {col}}_{31}(t) = \Theta^{\rm col}_{02}(t) = \int\limits^{\infty}_0 d\omega I(\omega) S(\omega,t), \label{thetacol4} \end{equation} \begin{equation} \Theta^{\rm {col}}_{13}(t) = \Theta^{\rm {col}}_{20}(t) = -\Theta^{\rm {col}}_{31}(t) = -\Theta^{\rm {col}}_{02}(t), \label{thetacol5} \end{equation} and $\Gamma^{\rm {col}}_{\rm {sq}} (t)$ is as in Eq. (\ref{gamma1}), with $2k\cdot r_b \rightarrow 2k\cdot r_a$. The Eqs. (\ref{cola}), (\ref{colb}), (\ref{colc}) and (\ref{cold}) cover all the density matrices for the two-qubit collective decoherence model. As with the localized case, it can be seen that with the increase in temperature, as also evolution time $t$ and bath squeezing $\alpha$, the system becomes more mixed and hence looses its purity. \section{Symmetries in the dynamical system} In this section we consider the two qubit evolution, developed in the previous section from the point of view of some fundamental symmetries. This enables us to view the dynamics from a fresh perspective and is also interesting from its own point of view. Employing the two-particle index notation used in the previous section, we find that the transformation connecting the initial and final density operations can be given by the following operation \begin{equation} \rho_{ab}(t) = {\cal L}_{ab}(t) \rho_{ab}(0). \end{equation} The non-trivial aspect of the dynamics that this relation represents is that here ${\cal L}$ represents, not a matrix, but a two-dimensional array, and the multiplication is done element-wise. The most general array ${\cal L}$ that satisfies this property, following only from the hermiticity of $\rho(0)$ and $\rho(t)$ is: \begin{equation} {\cal L} = \left( \begin{array}{cccc} 1 & c_1 & c_2 & c_3 \\ c_1^* & 1 & c_4 & c_5 \\ c_2^* & c_4^* & 1 & c_6 \\ c_3^* & c_5^* & c_6^* & 1 \end{array} \right) \label{eq:L} \end{equation} However, further constraints on the structure of ${\cal L}$ appear because the dynamical evolution due to QND interaction respects spin-flip symmetry (see Eq. (\ref{spinflip}) below), which is for example (given for clarity, in the single-qubit notation): \begin{equation} {\cal L}_{\frac{1}{2},-\frac{1}{2};\frac{1}{2},\frac{1}{2}} = {\cal L}_{-\frac{1}{2},\frac{1}{2};-\frac{1}{2},-\frac{1}{2}}. \end{equation} This has the effect that $c_3$ and $c_4$ are real, which we denote by $r_1$ and $r_2$ respectively. Further $c_2 = c_5^*$ and $c_1 = c_6^*$. These are seen by noting that: \begin{eqnarray} c_3 &\equiv& {\cal L}_{e,g} = {\cal L}^*_{g,e} = {\cal L}_{g,e} = {\cal L}^*_{e,g} \equiv c_3^*, \nonumber \\ c_4 &\equiv& {\cal L}_{s,a} = {\cal L}^*_{a,s} = {\cal L}_{a,s} = {\cal L}^*_{s,a} \equiv c_4^*, \nonumber \\ c_2 &\equiv& {\cal L}_{e,a} = {\cal L}^*_{a,e} = {\cal L}_{g,s} = {\cal L}^*_{s,g} \equiv c_5^*, \nonumber \\ c_1 &\equiv& {\cal L}_{e,s} = {\cal L}^*_{s,e} = {\cal L}_{g,a} = {\cal L}^*_{a,g} \equiv c_6^*, \end{eqnarray} where the first and third equalities in each equation follow from hermiticity. Accordingly, Eq. (\ref{eq:L}) can be rewritten as: \begin{equation} {\cal L} = \left( \begin{array}{cccc} 1 & c_1 & c_2 & r_1 \\ c_1^* & 1 & r_2 & c_2^* \\ c_2^* & r_2 & 1 & c_1^* \\ r_1 & c_2 & c_1 & 1 \end{array} \right), \label{eq:LL} \end{equation} Consider the operator $\hat{\cal L}$ corresponding to ${\cal L}_{j,k}$, defined by: \begin{equation} \hat{\cal L} = \sum_{j,k} {\cal L}_{j,k} |j\rangle\langle k|,~~~~ (j,k = 0,1,2,3). \end{equation} The spin-flip symmetry can be represented by \begin{equation} \Sigma \hat{\cal L} \Sigma^\dag = \hat{\cal L},~~~~\Sigma=\sigma_x \otimes \sigma_x . \label{spinflip} \end{equation} Since $\Sigma = (-i\sigma_x) \otimes (i\sigma_x)$, the above spin-flip symmetry may be described as a rotational symmetry, with angle $\pi/2$ (resp. $3\pi/2$) in the first (resp. second) qubit coordinate about the $x$-axis. \section{An application to quantum communication: quantum repeaters} We now make an application of the two-qubit reduced dynamics obtained from QND system-reservoir interaction to a quantum repeater \cite{bdcz98}, used for quantum communication over long distances. The efficiency of quantum communication over long distances is reduced due to the effect of noise, which can be considered as a natural open system effect. For distances much longer than the coherence length of a noisy quantum channel, the fidelity of transmission is usually so low that standard purification methods are not applicable. In a quantum repeater set-up, the channel is divided into shorter segments that are purified separately and then connected by the method of entanglement swapping, which is the quantum teleportation \cite{qtele} of entanglement. This method can be much more efficient than schemes based on quantum error correction, as it makes explicit use of two-way classical communication. The quantum repeater system allows entanglement purification over arbitrary long channels and tolerates errors on the percent level. It requires a polynomial overhead in time, and an overhead in local resources that grows only logarithmically with the length of the channel. Here we consider the effect of noise, introduced by imperfect local operations that constitute the protocols of entanglement swapping and purification \cite{chb96}, on such a compound channel, and how it can be kept below a certain threshold. The noise process studied is the one obtained from the two-qubit reduced dynamics via a QND interaction, instead of the depolarizing noise considered in \cite{bdcz98}. A detailed study of the effect of the two-qubit noise on the performance of a quantum repeater is underway and will be reported elsewhere. Here we treat this problem in a simplified fashion, and study the applicability and efficiency of entanglement purification protocols in the situation of imperfect local operations. A quantum repeater involves the two tasks of entanglement swapping, involving Bell-state measurements, and entanglement purification, involving CNOT gates. The Bell-state measurement may be equivalently replaced by a CNOT followed by a projective single-qubit measurement. In entanglement swapping, two distant parties initially not sharing entanglement with each other, but sharing entanglement separately with a third party, become entangled by virtue of a multi-partite measurement by the third party on the latter's two halves of entanglement. Entanglement purification involves two parties employing local operations and classical communication (LOCC) to improve the fidelity $F$ of Einstein-Podolsky-Rosen (EPR) pairs they share, with respect to a maximally entangled state. The local operations involve two-qubit gates such as the CNOT operation, followed by single qubit measurement, and a possible discarding of an EPR pair. Provided $F>0.5$, and at the cost of losing shared (impure) entanglement, the two parties can increase the fidelity of the remaining shared entanglement to \begin{equation} F^\prime = \frac{F^2 + [(1-F)/3]^2}{F^2 + [2F(1-F)/3] + (5/9)(1-F)^2}, \label{eq:bennett} \end{equation} where $F$ and $F^\prime$ are, respectively, the input and output fidelities (with respect to a Bell state) of the entanglement purification protocol proposed by Bennett {\it et al.} \cite{chb96}. We consider two repeaters in a realistic situation where they are well separated and hence lie in the localized regime of our model. If they initially share a Bell state $|\psi\rangle \equiv (1/\sqrt{2})(|00\rangle - |11\rangle) \equiv (1/\sqrt{2})(|g\rangle - |e\rangle)$, a QND interaction will asymptotically drive the state to the maximally mixed state with support in span$\{|g\rangle, |e\rangle\}$, i.e., $\rho_r \equiv (1/2)(|g\rangle\langle g| + |e\rangle\langle e|)$. The asymptotic fidelity is given by $F=\sqrt{\langle\psi|\rho_r|\psi\rangle} = \frac{1}{\sqrt{2}} \approx 0.707$, a pattern evident from Figure \ref{fig:repeater-00}. A similar result of course can be given for the other Bell states. Since this value exceeds 0.5, pairs of qubits that start out in a maximally entangled state can always be distilled via the quantum repeater scheme. In all the figures in this article, we consider the initial state to be an equal superposition state, which can be obtained by applying $H \otimes H$ on the state $|0\rangle \equiv |-\frac{1}{2},-\frac{1}{2}\rangle$, where $H$ is the Hadamard transformation. The figure shows that environmental squeezing, like temperature, impairs fidelity, and can thus not be used to counter thermal effects. This concurrent behavior of squeezing and temperature for QND type of interactions is mirrored also in phase diffusion \cite{bgg07} and the evolution of geometric phase \cite{gp06}. \begin{figure} \includegraphics[width=7.0cm]{repeaterfidelityqnd.eps} \caption{Fidelity (with respect to the Bell state $|00\rangle - |11\rangle$) as a function of time for a two-qubit system interacting with its environment via a QND interaction. The bold curve corresponds to a finite temperature and no squeezing ($T=4, \alpha=0$); the small-dashed curve corresponds to zero temperature but finite squeezing ($T=0, \alpha=2$); the large-dashed curve corresponds to finite temperature and squeezing ($T=4, \alpha=2$). For sufficiently large time, the fidelity approaches $1/\sqrt{2} \approx 0.707$.} \label{fig:repeater-00} \end{figure} \section{Characterization of Mixed State Entanglement through a Probability Density Function} As mentioned in the introduction, it is important to determine the entanglement in the two qubit system, if it is to be of utility in quantum information processing. There is, however, no straightforward way of determining the entanglement when the system is in a mixed state since, as is well known, entanglement, as an observable, cannot be represented by a linear hermitian operator. Indeed, it is impossible to capture the information on the entanglement in a mixed state by a single parameter \cite{bd96}, notwithstanding the fact that useful benchmarks such as concurrence and negativity exist . Thus , for instance, negativity and concurrence are not relative monotones. For this reason, we employ a recently proposed description of MSE via a probability density function. We also determine the concurrence (negativity for a state can never exceed its concurrence), and show it along with the PDF, for comparison, and to display the extent to which it captures the information on the entanglement in the state. Here we briefly recapitulate the characterization of mixed state entanglement (MSE) through a PDF as developed in \cite{br08}. The basic idea is to express the PDF of entanglement of a given system density matrix (in this case, a two-qubit) in terms of a weighted sum over the PDF's of projection operators spanning the full Hilbert space of the system density matrix. Consider first a system in a state which is a projection operator of dimension $d$. The pure states correspond to $d=1$, and the completely mixed states to $d=4$. The PDF of a system in a state which is a projection operator $\rho = \frac{1}{M}\Pi_M$ of rank $M$ is defined as: \begin{equation} {\cal P}_{\Pi_M}({\cal E}) = \frac{\int d{\cal H}_{\Pi_M}\delta ({\cal E}_{\psi} - {\cal E})}{\int d{\cal H}_{\Pi_M}}, \label{entproject} \end{equation} where $\int d{\cal H}_{\Pi_M}$ is the volume measure for ${\cal H}_{\Pi_M}$, which is the subspace spanned by $\Pi_M$. The volume measure is determined by the invariant Haar measure associated with the group of automorphisms of $\int d{\cal H}_{\Pi_M}$, modulo the stabilizer group of the reference state generating ${\cal H}_{\Pi_M}$. Thus for a one dimensional projection operator, representing a pure state, the group of automorphisms consists of only the identity element and the PDF is simply given by the Dirac delta. Indeed, if $\rho= \Pi_1 \equiv \vert \psi \rangle \langle \psi \vert$, the PDF has the form ${\cal P}_{\rho}({\cal E}) = \delta ({\cal E} - {\cal E}_{\psi})$ thereby resulting in the description of pure state entanglement, as expected, by a single number. The entanglement density of a system in a general mixed state $\rho$ is given by resolving it in terms of nested projection operators with appropriate weights as \begin{eqnarray} \rho &=& (\lambda_1 - \lambda_2)\Pi_1 + (\lambda_2 - \lambda_3)\Pi_2 + .......(\lambda_{N-1} - \lambda_N)\Pi_{N-1} + \lambda_N \Pi_N \nonumber\\ &\equiv& \sum_{M=1}^N \Lambda_M \Pi_M, \label{nested} \end{eqnarray} where the projections are $\Pi_M =\sum_{j=1}^M|\psi_j\rangle\langle \psi_j|$, with $M = 1,2,...,N$ and the eigenvalues $\lambda_1 \ge \lambda_2 \ge ....$, i.e., the eigenvalues are arranged in a non-increasing fashion. Thus the PDF for the entanglement of $\rho$ is given by \begin{equation} {\cal P}_{\rho} ({\cal E}) = \sum_{M=1}^N \omega_M {\cal P}_{\Pi_M} ({\cal E}), \label{PDF} \end{equation} where the weights of the respective projections ${\cal P}_{\Pi_M} ({\cal E})$ are given by $\omega_M = \Lambda_M/\lambda_1$. For a two qubit system, the density matrix would be represented as a nested sum over four projection operators, $\Pi_1$, $\Pi_2$, $\Pi_3$, $\Pi_4$ corresponding to one, two, three and four dimensional projections, respectively, with $\Pi_1$ corresponding to a pure state and $\Pi_4$ corresponding to a a uniformly mixed state, is a multiple of the identity operator. The most interesting structure is present in $\Pi_2$, the two-dimensional projection, which is characterized by three parameters, viz. ${\cal E}_{cusp}$, the entanglement at which the PDF diverges, ${\cal E}_{max}$, the maximum entanglement allowed and ${\cal P}_2 ({\cal E}_{max})$, the PDF corresponding to ${\cal E}_{max}$. The three dimensional projection $\Pi_3$ is characterized by the parameter ${\cal E}_{\perp}$, which parametrizes a discontunity in the entanglement density function curve. By virtue of the convexity of the sum over the nested projections (\ref{nested}), it can be seen that the concurrence of any state $\rho$ is given by the inequality ${\cal C}_{\rho} \leq (\lambda_1 - \lambda_2){\cal C}_{\Pi_1} + (\lambda_2 - \lambda_3){\cal C}_{\Pi_2}$. Thus while the concurrence for a three and four dimensional projection is identically zero, through the PDF one is able to make a statement about the entanglement content of states which span these spaces. Also, as pointed out in \cite{br08}, in the case of NMR quantum computation, concurrence and negativity are zero, whereas the PDF is able to elucidate the role of entanglement utilized by the NMR operations. These features as well as the fact that the PDF (\ref{PDF}) enables us to study entanglement of a physical state by exploiting the richness inherent in the subspaces spanned by the system Hilbert space makes the PDF an attractive statistical and geometric characterization of entanglement. We provide an explicit illustration of this in the next section. \section{Entanglement analysis} In this section, we will study the development of entanglement in the two qubit system, both for the localized as well as the collective decoherence model. Recall that concurrence \cite{ww98} is defined as \begin{equation} {\cal C} = \max(0, \sqrt{\lambda_1} - \sqrt{\lambda_2} - \sqrt{\lambda_3}- \sqrt{\lambda_4}), \label{concur} \end{equation} where ${\lambda_i}$ are the eigenvalues of the matrix \begin{equation} R = \rho \tilde{\rho}, \label{concur1} \end{equation} with $\tilde{\rho} = \sigma_y \otimes \sigma_y \rho^* \sigma_y \otimes \sigma_y$ and $\sigma_y$ is the usual Pauli matrix. ${\cal C}$ is zero for unentangled states and one for maximally entangled states. In the above expression, it is implicitly assumed that $\rho$ is expressed in a seperable basis. \begin{figure} \subfigure[]{\includegraphics[width=7.0cm]{ndp_effectofsqueezing.eps}} \hfill \subfigure[]{\includegraphics[width=7.0cm]{clc_effectofsqueezing.eps}} \caption{Concurrence ${\cal C}$ (\ref{concur}) as a function of time of evolution $t$ at $T = 5.0$ and bath squeezing parameter $\alpha$ (\ref{sqpara}) equal to $0$, $0.5$, $1.0$, corresponding to the bold, dashed and dotted curves, respectively. Figure (a) refers to the localized decoherence model and (b) the collective decoherence model.} \label{fig:concurrence} \end{figure} In figure (\ref{fig:concurrence} (a)), we plot the concurrence (\ref{concur}) with respect to time for the case of the localized decoherence model, while figure (\ref{fig:concurrence} (b)) depicts the temporal behavior of concurrence for the collective decoherence model, for different bath squeezing parameters. In all figures in this article, $k r_{12}$ is set equal to 1.1 for the localized decoherence model and 0.05 for the collective model. It is clearly seen from the figures that the two qubit system is initially unentangled, but with time there is a build up of entanglement between them as a result of their interaction with the bath. Also the entanglement builds up more quickly in the collective decoherence model when compared to the localized model. This is expected as the effective interaction between the two qubits is stronger in the collective case. Another interesting feature that can be inferred from figure (\ref{fig:concurrence} (a)) is the phenomena of entanglement birth and death \cite{ye09} in the localized decoherence model. Figure (\ref{fig:concurrence} (b)) exhibits entanglement death followed by revival, in the collective decoherence model. It is clear from the figures that bath squeezing retards the dynamical generation of entanglement. However, interestingly, it is observed that the disentanglement time is the same for different bath squeezing parameters, as in figure (\ref{fig:concurrence} (b)), while it varies for the independent decoherence model, figure (\ref{fig:concurrence} (a)). This indicates a kind of robustness of the phenomena of disentanglement with respect to bath squeezing, in the collective regime. There have been a number of investigations in the phenomena of entanglement sudden death and revival. In \cite{ye06} a study of entanglement sudden death and revival was made between two isolated atoms each in its own lossless Jaynes-Cummings cavity, while in \cite{ye07} the evolution of entanglement was studied via information exchange between subsystems rather than decoherence. Thus these studies revealed features of the dynamics of entanglement generation in the absence of decoherence. In another study \cite{ft06} was revealed the interesting effect that irreversible spontaneous decay, due to interaction with a vacuum bath, can have on the revival of entanglement between two qubits with the collective decoherence regime being most conducive to the revival of entanglement. Even though this work involved a dissipative system-bath interaction, this conclusion is supported here, for QND interactions, as the generation of entanglement is seen to be much more effective in the collective regime when compared to the independent one. The effect of non-Markovian influences, due to a dissipative interaction, on the dynamics of entanglement between two qubits was studied in \cite{bc08} for the localized decoherence model and in \cite{mp08} for the collective regime. Here our study concentrates on QND interactions and localized as well as collective regimes are treated under a common footing. Now we take up the issue of entanglement from the perspective of the PDF as in Eq. (\ref{PDF}). In figures (\ref{fig:weights} (a)) and (b), we plot the weights $\omega_1$, $\omega_2$, $\omega_3$ and $\omega_4$ (\ref{PDF}) of the entanglement densities of the projection operators of the various subspaces which span the two qubit Hilbert space with respect to $T$ for the localized and collective decoherence models, respectively. As can be seen from both the figures , with increase in temperature $T$, the weight $\omega_1$, depicting the pure state component monotonically decreases, while the other weights start from zero at $T=0$ and increase. Eventually, the weight $\omega_4$ depicting a maximally mixed state would be expected to dominate, though for the parameter range used in the plots, this feature is not seen. This feature of the dynamics of the reduced two-qubit system, specially in the case of the collective decoherence model, has an interesting application which will be discussed in detail in Section VIII where it will be seen to obey an {\it effective} temperature dependent Hamiltonian, bringing out the persistence of entanglement even at finite temperatures. In the case of the collective decoherence model, the weights $\omega_2$ and $\omega_3$ have a greater growth than that for the localized decoherence model, depicting the greater entanglement development in the collective model as is also borne out by the concurrence plots in figure (\ref{fig:concurrence}). \begin{figure} \subfigure[]{\includegraphics[width=7.0cm]{indep2qnd_w1234_t5_r0p2.eps}} \hfill \subfigure[]{\includegraphics[width=7.0cm]{colc2qnd_w1234_t5_r0p2.eps}} \caption{The weights (\ref{PDF}) as a function of $T$, with an evolution time $t = 5$ and bath squeezing parameter $\alpha$ (\ref{sqpara}) equal to $0.2$. Figure (a) refers to the localized decoherence model and (b) the collective decoherence model. In both the figures, the bold curve corresponds to the weight $\omega_1$, while the large-dashed, small-dashed and dotted curves correspond to the weights $\omega_2$, $\omega_3$ and $\omega_4$, respectively.} \label{fig:weights} \end{figure} As explained in Section VI, the characterization of MSE for a two qubit system via the PDF involves the distribution functions of four projection operators, $\Pi_1$, $\Pi_2$, $\Pi_3$, $\Pi_4$ corresponding to one, two, three and four dimensional projections, respectively. These will be represented here as ${\cal P}_1 ({\cal E})$, ${\cal P}_2 ({\cal E})$, ${\cal P}_3 ({\cal E})$ and ${\cal P}_4 ({\cal E})$, respectively. Also, as discussed above, ${\cal P}_4 ({\cal E})$ would be universal for the two qubit density matrices and would involve the Haar measure on $SU(4)$ \cite{br08,tbs02}. Consideration of the ${\cal P}_2 ({\cal E})$ and ${\cal P}_3 ({\cal E})$ density functions for some representative states of the two qubit system, both for the localized as well as collective decoherence models, enables us to compare the entanglement in the respective subspaces of the system Hilbert space. The details of these density functions for different parameters, pertaining to the two-qubit reduced dynamics, have been presented in \cite{entqnd09}. Figures (\ref{fig:PfullT50} (a)) and (b) give the full density function ${\cal P}(\cal E)$ for the localized and collective decoherence models, respectively, with a bath evolution time $t = 10.0$ and $T = 50.0$. For these conditions, the value of concurrence (\ref{concur}) is 0, which would indicate a complete breakdown of entanglement. This would be expected as with the increase in the bath temperature $T$, the effect of entanglement would be destroyed quickly. This is partially borne out by the fact that for this case ${\cal C}_{\Pi_2} = 0$. However, as seen from figure (\ref{fig:PfullT50} (b)), the PDF for the full density function still exhibits a rich entanglement structure, coming principally from the contributions from the one and three dimensional projections. In contrast, figure (\ref{fig:PfullT50} (a)), for the localized decoherence model, exhibits the Haar measure on $SU(4)$ and thus represents a maximally mixed state. Figures (\ref{fig:PfullT20}) represents the full density function ${\cal P}(\cal E)$ for the localized decoherence model with an evolution time $t = 10.0$, $T = 20.0$ and bath squeezing parameter $\alpha$ equal to $0.2$, figure (a), and equal to $0$ in figure (b). This case is interesting since it is analogous to that discussed in \cite{br08} for NMR quantum computation where concurrence would be zero, and the excess of entangled states over the unpolarized background (exhibited by the uniform distribution coming from the density function $\Pi_4$, related to the fourth dimensional projection) is exploited as a resource allowing for non-trivial gate operations, thus depicting pseudopure states over the four dimensional background, with the excess being the ``deviation density matrix". A comparison of the two figures shows that the generation of entanglement is greater for the case of zero bath squeezing, as in figure (b), when compared to the case of finite bath squeezing, figure (a). \begin{figure} \subfigure[]{\includegraphics[width=7.0cm]{indepGEGEpfull_tim10_T50_r0p2.eps}} \hfill \subfigure[]{\includegraphics[width=7.0cm]{collcGEGEpfull_tim10_T50_r0p2.eps}} \caption{The full density function ${\cal P}({\cal E})$ (\ref{PDF}) with respect to the entanglement ${\cal E}$ for an evolution time $t = 10.0$, $T = 50.0$ and bath squeezing parameter $\alpha$ equal to $0.2$. Figure (a) refers to the localized decoherence model and (b) to the collective decoherence model.} \label{fig:PfullT50} \end{figure} \begin{figure} \subfigure[]{\includegraphics[width=7.0cm]{indepGEGEpfull_tim10_T20_r0p2.eps}} \hfill \subfigure[]{\includegraphics[width=7.0cm]{pfullt10T20sq0.eps}} \caption{The full density function ${\cal P}({\cal E})$ (\ref{PDF}) with respect to the entanglement ${\cal E}$ for the localized decoherence model with an evolution time $t = 10.0$, $T = 20.0$ and bath squeezing parameter $\alpha$ equal to $0.2$ (figure (a)) and $0$ (figure (b)).} \label{fig:PfullT20} \end{figure} \section{ Effective temperature dependent dynamics in the collective decoherence model: a brief discussion} In a QND $S-R$ interaction, the reduced density matrix of the system does not approach a unique distribution asymptotically \cite{bg07}. It turns out that the PDF for the full density function (for the collective decoherence model) exhibits a rich entanglement structure, coming principally from the contributions from the one and three dimensional projections which carry equal weights. This feature is seen to persist for higher temperatures and evolution times, for the collective decoherence model, with the weights of the subspaces spanned by the four projection operators of the PDF remaining intact. From this emerges the fact that for the collective decoherence model, studied here, as the effect of the bath on the system increases, the PDF instead of becoming uniform, as expected, gets distributed between the subspaces spanned by the one and three dimensional projection operators suggesting a tendency of the system to resist randomization. We may ask if the description of the mixed state entanglement in terms of the probability density function which we employ here can throw, as a nontrivial application, light on the effective dynamics of the two qubit system. It has been seen in earlier studies that such a state of affairs would be encountered if the effect of the bath is not a counterpart of the collision term (in a Boltzmann equation), but is more like a Vlasov term, causing long range mean field contributions \cite{ce94}. We analyse our system in detail below. Indeed, from the numerical results, it is not difficult to see that the effect of the bath can be mapped to a $T$ dependent effective hamiltonian whose energy eigenvalues scale with temperature. The eigenstates are given by the standard Bell states with the ground state being $|B_1 \rangle = \frac{1}{\sqrt{2}} (|01 \rangle + |10 \rangle)$ while the orthogonal singlet state ($|B_4 \rangle = \frac{1}{\sqrt{2}} (|01 \rangle - |10 \rangle)$) is the highest energy state, and is practically decoupled (with no population). The next excited state is degenerate, with two Bell states ($|B_2 \rangle = \frac{1}{\sqrt{2}} (|00 \rangle - |11 \rangle)$, $|B_3 \rangle = \frac{1}{\sqrt{2}} (|00 \rangle + |11 \rangle)$) spanning the two dimensional subspace. Thus it follows that the effective temperature dependent hamiltonian is given by $$ H_{\rm eff} = \sum^{4}_{i=1} E_i(\beta) |B_i\rangle\langle B_i|, \label{heffec} $$ where $|B_1 \rangle$, $|B_2\rangle \langle B_2| + |B_3\rangle \langle B_3| = |00 \rangle \langle 00| + |11 \rangle \langle 11|$ and $|B_4 \rangle$ are the Bell states, as defined above, with eigenvalues $\lambda_1 = 0.5$, $\lambda_2 = \lambda_3= 0.25$ and $\lambda_4 \approx 0$, respectively. Since the Bell states are completely entangled, the effective hamiltonian has no linear terms in the qubit polarizations and has the form \begin{equation} H_{eff} \sim \frac{\ln (2)}{2\beta} (1- (-\sigma_x^{(1)} \sigma_x^{(2)} + \sigma_y^{(1)} \sigma_y^{(2)} - \sigma_z^{(1)} \sigma_z^{(2)})) + \frac{\ln (4)}{\beta} (\frac{1}{2} + 2 \sigma_z^{(1)} \sigma_z^{(2)}), \label{heffec1} \end{equation} in writing which the singlet term has been dropped, as it is energetically very far separated from the other three levels. The above analysis places in perspective the surprising result that although the system is evolving, through the effective Hamiltonian, the entanglement density function remains practically restricted to the 3-dimensional subspace, with a large contribution from a Bell state, as the signal with the 3-dimensional background acting as noise. The restriction of the effective dynamics from four to three levels is also seen in the case of two qubit evolution via a dissipative $S-R$ interaction with a thermal bath initially at $T=0$ \cite{ft02}, for the collective decoherence model. However, there the reason for it is simply given by the fact that for the above conditions, the coupling term connecting one of the levels to the others goes to zero, thereby reducing the dynamics to that between three levels. An interesting analog of the discussion in this Section comes in the work presented in \cite{hn03}. There it was shown by the authors that for the scenario where there exists a system consisting of three subsystems with the first and the third interacting with each other via their interactions with the mediating second subsystem, a signature of entanglement between the first and the third subsystems is the degeneracy in the ground state of the system. Here we have a similar situation with the two qubits interacting with a bath which in turn mediates the inter-qubit interaction. From our effective Hamiltonian $H_{eff}$, we see that the first excited state (not the ground state), spanned by the Bell states $|B_2 \rangle$ and $|B_3 \rangle$, is degenerate and the system exhibits a strong entanglement even at finite temperatures. Another work by the same authors \cite{on02}, studied the persistence of mixed state entanglement at finite $T$. This would be important as quantum effects can be expected to dominate in regions where entanglement is nonzero. They considered the transverse Ising model and studied the two-site entanglement, using concurrence as the entanglement measure, and found appreciable entanglement in the system at finite $T$ above the ground state energy gap, one of their motivations being the influence of nearby critical points to the finite $T$ entanglement. The persistence of entanglement in a two-qubit system interacting with the bath via a purely dephasing interaction (QND) would suggest a broad applicability of these concepts, thereby highlighting the interconnection of ideas of quantum information to quantum statistical mechanics. \section{Conclusions} In this article, we have analyzed in detail the dynamics of entanglement in a two-qubit system interacting with its environment via a purely dephasing QND $S-R$ interaction. The system and reservoir are initially assumed to be separable with the reservoir being in an initial squeezed thermal state. Since the resulting dynamics becomes mixed, in order to analyze the ensuing entanglement, we have made use of a recently introduced measure of mixed state entanglement via a PDF. This enables us to give a statistical and geometrical characterization of entanglement. After developing the general dynamics of $N$ qubits interacting with their bath (reservoir) via a QND $S-R$ interaction, we specialized to the two-qubit case for applications. Due to the position dependent coupling of the qubits with the bath, the dynamics could be naturally divided into a localized and collective decoherence regime, where in the collective decoherence regime, the qubits are close enough to feel the bath collectively. We analyzed the open system dynamics of the two qubits, both for the localized as well as the collective regimes and saw that in the collective regime, there emerges the possibility of a decoherence-free subspace for the case of zero bath squeezing. Interestingly, the dynamics was found to obey a non-trivial spin-flip symmetry operation. The existence of the nontrivial spin-flip symmetry would explain the emergence of a decoherence-free subspace (DFS) \cite{dfs}, thereby providing a concrete instance of a DFS. We made an application of the two-qubit system to a simplified model of a quantum repeater, which can be adapted for quantum communication over long distances. We then made an analysis of the two-qubit entanglement for different bath parameters. We analyzed both concurrence as well as the PDF by finding the entanglement content of the various subspaces that span the two-qubit Hilbert space. The analysis of concurrence revealed the interesting feature of so called entanglement birth and death in the localized decoherence model, while the collective model saw a subsequent revival of entanglement. Reservoir squeezing was seen to hinder the generation of entanglement, though the process of disentanglement, as seen from concurrence, was robust, in the collective regime, against the effects of squeezed bath. Although the PDF agrees qualitatively in its predictions with concurrence, it is able to extract more information out of the system as a result of its statistical-geometrical nature. Thus we were able to consider an example analogous to NMR quantum computation, wherein the concurrence would be zero, and the excess of entangled states over the unpolarized background is exploited as a resource allowing for non-trivial quantum information processing. For the collective decoherence model the PDF for the full density function exhibits a rich entanglement structure, coming principally from the contributions from the one and three dimensional projections which carry equal weights thereby suggesting a tendency of the system to resist randomization. This feature is seen to persist even for higher temperatures and evolution times with the weights of the subspaces spanned by the four projection operators of the PDF remaining intact. The probability density description of entanglement sheds light on the underlying dynamics thereby enabling us to give an effective $T$ dependent dynamics in the collective decoherence regime. A comparison of this with some related works suggests the applicability of quantum information theoretic ideas to quantum statistical mechanical systems. \acknowledgments We wish to thank Shanthanu Bhardwaj for numerical help.
{ "redpajama_set_name": "RedPajamaArXiv" }
8,947
Q: Can anyone explain how this memory leak in Java/Android works in detail? I have been doing Java development for a long time, but I am ashamed to say I still don't have a good grasp on how memory leaks actually takes place. I however have no experience with Android development. Take the following code for example taken from this presentation: I have the following questions (please note that I am new to Android, but this example is not primarily focused on Android) * *How is memory leak even possible here ? The author says that its because the inner class is not marked as static and it will hold a reference to the outer class. So if I keep creating objects of the outer class like so: MainActivity one = new MainActivity(); one.onCreate(bundle); MainActivity two = new MainActivity(); two.onCreate(bundle); MainActivity three = new MainActivity(); three.onCreate(bundle); How does it matter ? If I am not wrong about how static references work, then only one object of LeakClass is created, right? Unless a separate classloader is involved, right? *Is the memory leak only possible here because of how Android works? If I were to manually create these objects then this would not be a problem, right? A: Because LeakClass is an inner class, it has an inherent reference to the instance of the outer class that owns it. Since you're storing that value in a static variable, that means you're storing a reference to the outer class in that static transitively. Storing an Activity in a static is ALWAYS a leak, and ALWAYS a bad idea. Activities aren't singletons, you cannot assume there will only be one of them. If you don't need that parent reference, you can make it a static inner class. Static inner classes do not have an implicit outer reference, but cannot access member variables of functions of the owning class. Or you can make it a standalone, non-inner class (the two are equally good solutions). If you do need that parent reference, you cannot store it in a static variable without a leak. Figure out another way to make that data available.
{ "redpajama_set_name": "RedPajamaStackExchange" }
5,875
AT&T in Asia Pacific We make it possible for businesses across Asia Pacific to mobilize people, assets and information across the region and the rest of the world. AT&T Asia Pacific overview Trust us to connect your region and world with integrated solutions and outstanding service Truly global, regional and local With a dedicated regional presence within Asia Pacific dating back over 40 years, AT&T provides local account management, design and operational support from a multitude of locations across the Asia Pacific region. From Australia to Vietnam, we provide the tools, technologies, skills, expertise and insight that gives our customers confidence in their daily communications solutions and in our ability to help them take advantage of current and nascent innovations. AT&T Japan boasts a heritage of providing AT&T global networking and application solutions to multinational customers, whist the Asia Pacific region is positioned at the epicentre of global customer care operations. The AT&T difference What sets AT&T apart is a heritage that goes right back to the invention of the telephone, a relentless drive for innovation and a truly global presence. We support the needs and share the ambitions of businesses ranging from large multinational corporations to single person start-ups. You'll find AT&T is the partner of choice for financial services, manufacturing, education, healthcare, retail, hospitality and government organizations. Explore AT&T solutions* Learn how we can help grow your business *Not all solutions are available in all countries, check with your AT&T sales representative for specific products in your country. Communicate effectively, reduce costs and improve productivity by combining voice, video and conferencing with easy-to-use tools. Learn more. Secure networking solutions for all businesses including VPN, Internet, SDN and Ethernet solutions. Learn more. We can help you realize the promise of IoT and navigate the intricacies to quickly build your solution. Learn more. End-to-end cloud solutions designed to scale with your business. Learn more. Simplify security monitoring and respond to threats faster with assessment and planning, protection and prevention, detection and response. Learn more. Explore how AT&T Mobility is being used to help our customer's business needs with 5G, workforce management, messaging, connectivity and device management. Learn more. To thrive in ths new world, businesses must prepare to alter their very DNA. The first step is to understand the capabilities that 5G can unleash. (Sold U.S. Domestic) Learn more. AT&T Asia Pacific offices* Extending network and communications solutions across the globe Australia China Hong Kong India Indonesia Japan Korea Malaysia New Zealand Philippines Singapore Taiwan Thailand Vietnam Level 6, 41 Walker St, North Sydney 2060, Sydney, Australia Level 17, 120 Spencer St, Melbourne, VIC 3000 Unit 2228, 22nd Floor, China World Tower 1, 1, Jian Guo Men Wai Avenue., Beijing, 100004 Room 2104-08, Shanghai Times Square, Huai Hai Zhong Lu, Lu Wan District, Shanghai, 200021 Room1323, Teem Tower, 208 Tian He Road, Tian He District, Guangzhou, 510620 Room 2645, Anlian Centre, 4018 Jin Tian Road, Futian District, Shenzhen, 518026 8th Floor, Regus Tianjin Center, No.219 Nanjing Road Helping District, Tianjin, 300061 Asia Pacific Headquarters, 22/F, Citiplaza One, 1111 King's Road, Taikoo Shing, Hong Kong, Email (Marketing): mktg@intl.att.com Vatika Triangle, 3rd Floor, Sushant Lok -1, Block A, MG Road, Gurgaon – 122002 Haryana, India, Tel: +91 12 4486 8777 10th & 11th Floor, Innovator Building, International Technology Park Bangalore (ITPB), Whitefield Road, Bangalore 560 066, India, Tel: +91 80 4131 8000 4th Floor, Platina Building, C-59, G Block, Bandra Kurla Complex, Bandra East, Mumbai-400 051, India, Tel: +91 22 6681 7900/21 Module 4C , 10th Floor, Block A, West Wing, SP Infocity, Plot No 40, MGR Salai, Kandanchavadi, Perungudi, Chennai – 600 096 10th Floor, Vega Block, Ascendas 'The V', Madhapur Software Units Layout, Hyderabad – 500081 Suite No. 14, 5th Floor, Vatika Business Center, C-Wing, Panchshil Tech Park – 1, Airport Road, Yerwada, Pune – 411 006 If you find any objectionable content on this website please contact: Adarsh Chauhan Contact No. + 91 12 4486 8727 Sampoerna Strategic Square, South Tower, 18th floor, Jl. Jend. Sudirman Kav. 45-46, Jakarta 12930, Indonesia, Tel: +62 21 575 0805, Fax: +62 21 577 0801, Email: sales.id@intl.att.com Toranomon Twin Building, 2-10-1 Toranomon, Minato-Ku Tokyo, 105-0001 Meiji Yasuda Life Osaka Umeda Building, 3-3-20 Umeda, Kita-ku, Osaka, 530-0001 15th Floor, Seoul City Tower Building, #581 Namdaemun-ro 5-ga, Jung-gu, Seoul, 100-741 Level 8, Block B, Quill 18, Lingkaran Teknokrat 3 Barat, Cyber 4, 63000 Cyberjaya, Selangor, Malaysia Level 2, 7-9 Fanshawe Street, Viaduct Harbour, Auckland 1010, New Zealand Suite 6, Level 6, I – Center, 50 Manners St., Wellington 6011, New Zealand 28th Floor, Tower 2, The Enterprise Center Building, 6766 Ayala Avenue, 1226 Makati City, Philippines, Tel: +63 2 8849 3971, Fax: +63 2 8886 5008 85 Science Park Drive, The Cavendish, Unit #03-01 to 08, Singapore 118259 Rm. D, 16/f Hung Tai Financial Plaza, 156, Min Sheng E. Road Sec. 3, Taipei, 105 Empire Tower, 15th Floor, Unit 1504, 1 South Sathorn Road, Yannawa, Sathorn, Bangkok 10120, Tel: +66 2 670 9700, Fax: +66 2 670 9707 Saigon Tower, 16/F, 29 Le Duan, District 1, Ho Chi Minh City, Vietnam, Tel: +84 28 3520 7608, Fax: +84 28 3520 7604, Email: rm-apvietlocon@intl.att.com AT&T implements, and legally obligates its suppliers to comply with, the Human Rights in Communication Policy set forth here. View additional regional market information AT&T's India CSR Vision & Policy – View our CSR Vision and Policy for AT&T India Pricing – View pricing for the India market Pricing – Tariff filing for the AT&T Virtual Private LAN Service Pricing – AT&T VNO (Internet) Service AT&T VNO (Internet) Service Service Guide *office locations as of July 15th, 2020 Global news and events Discover what's happening around the world with AT&T AT&T and Aston Martin Red Bull Racing Common values are the secret to success for our Formula 1 collaboration. Insight and information on key events around the world. All you need to know about AT&T in the world. Read the latest news about how AT&T is positively effecting the community through social engagement. AT&T works closely with some of the world's most respected consultants and industry analysts. Request a follow-up To contact us: please complete the form below To report any billing related issue, please click here. For more information on available job postings at AT&T, please click here Job title Select your job title CEO / Owner C-Level / Business Partner VP / Department Head Director / Senior Manager Manager Influencer / Analyst / Consultant / Staff Administrator Student / Other Region Select region Asia-Pacific Europe, Middle East & Africa Latin-America & Caribbean North America Department Select department Sales++ Marketing/Communication++ Press/Media++ Yes, I want to be kept informed about AT&T services and solutions. Yes, I agree to be contacted by an AT&T representative. Thank you for contacting us about Asia Pacific. An AT&T Representative will contact you shortly to provide any additional information and answer any questions. Worldwide Form Anchor
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
9,889
THE ZENITH ANGLE Bruce Sterling CONTENTS Title page Epigraph Prologue Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Adcard Copyright ZENITH ANGLE: _a measured angle between the sky directly overhead and any object seen in the sky._ PROLOGUE COLORADO, SEPTEMBER 1999 **T** he Most Important Man in the World put his pants on one leg at a time. Then he put on his boots and his Stetson. He checked the cabin's rusty mirror. The Most Important Man in the World looked pretty good in his cowboy hat. His haunted burnt-out eyes, his white stubble, and his lined sunken cheeks . . . wearing a cowboy hat changed all those things. In his Stetson, Tom DeFanti looked downright weather-beaten. Rugged. Solid. He was a man of the earth. The little cabin was stark, lonely, old, and simple. It lacked running water, wiring, and a toilet. It required this mountain cabin and the 16,812 acres of Pinecrest Ranch to free Tom DeFanti from his monuments. His cable franchises. His newspapers. His Web sites. His news magazine. His Internet fiber-optic backbone. His international charitable foundation. His monuments loomed over him like so many tombstones. Then there were his other, less mentionable monuments. They orbited high overhead, watching the globe around the clock. DeFanti carefully buttoned his thick flannel shirt. September light was fading in the small glass panes. Though he had been raised like an ugly swan by a working-class Italian family, Thomas DeFanti had always wanted and expected to become a very important man. However, DeFanti had never expected to become as incredibly rich as he was in the autumn of 1999. His holdings had blown up like a mushroom cloud, due to the Internet boom. This brought new attention to DeFanti that he didn't much like. It brought new expectations that he didn't know how to fulfill. Life for the very rich was always strange, and often dangerous. The man who had built this old Colorado cabin had also been a very rich man. DeFanti had studied him closely. He was grateful for the dead man's useful lessons in how to get by. The dead man had once been a very important Chicago banker. In 1911 he'd built the Colorado cabin, a tiny shelter for his astronomical observatory. The cabin was a quiet place, a safe place. The banker's ghost still hung there under the close black rafters, in a vapor of horse sweat, brandy, and fine cigars. Just like Tom DeFanti, the dead man had slept in that narrow, no-nonsense iron bed, its frame as solid as a torture rack. There was no room in that bed for his fireball society wife. The dead man's demanding rich kids were also three days away by a good long train ride. As for the dead man's lawyers, accountants, vice presidents, and stockholders, they might as well be stuck up on the Moon. Here in the mountains of Pinecrest, the world had to let a man live. Clear air, elk, forests, red granite, fine fishing, good shooting. And the telescope, of course. Telescopes justified everything, for both Tom DeFanti and his dear friend and mentor, the dead banker. Telescopes brought both of them perspective, and solace, and a true kind of happiness. Telescopes, long nights left alone, and those sweet, dark, endless skies. The cabin's stone hearth held a fragrant tang of pine ashes. In an old cedar chest, the dead banker had carefully hidden the sacred books of his boyhood. They were a boy's turn-of-the-century reading, adventure stories about industry and engineering, bought for a nickel each from the newsstands of boomtown Chicago. _Steam Man of the Plains_ by "NoName," and about three dozen others. On overcast nights when the seeing was bad, DeFanti had read the flaking novelettes by lantern light. They were simple, good stories. Lots of manly action. DeFanti removed the cowboy hat and splashed at his face from the tin bowl and white pitcher. He yanked open a rustic wooden drawer and thumbed through his private galaxy of pills. What would it be tonight? Prozac yes, aspirin yes, Viagra no thank you. Gingko yes. Valium yes, half a Valium, just to take some of the edge off. Plus yohimbe and vitamin A: they were good for his night vision. DeFanti knocked his pills back with sips from a steaming coffee thermos. He gnawed at buffalo jerky to settle the drugs in his gut. DeFanti had discovered bison meat in his pursuit of a heart-healthy diet. Bison meat was the very best meat in America. Tom DeFanti now owned over four thousand bison. DeFanti unlatched the cabin's door and left, carrying his fringed rawhide jacket. There was no sign of civilization, not a glimmer of light, not a telephone pole. One exception: far below in a stony bowl of hills, faint amber glows flicked on at the ranch's main hacienda. Over at the sprawling Pinecrest headquarters, Wife Number Four and her ranch staff were hosting a happy crowd of German cowboy tourists. The Germans had paid fifteen hundred dollars each to shoot a Pinecrest bull bison with their choice of Colt six-shooters or historical buffalo rifles. DeFanti's fourth wife was an energetic young woman from Taipei. She was from a prominent Chinese family, spoke six languages, and had very strong working habits. Wife Number Four never slept in the astronomy cabin's iron bed. DeFanti did his best to keep her busy. In the thin chill air of evening, DeFanti quickly missed his felt Stetson. He was too stubborn to climb back downhill for it. Besides, the cold dry breeze had chased off the smoke from the wildfires in the huge federal park to the east. It was the best observing he'd enjoyed all week. Colorado's Continental Divide scraped at the fading orange sky. That colossal glow could restore any man's soul, if he still owned one. A crowd of man-made satellites was busily climbing from the planet's shadow. And if the zenith angle was exactly right, then the solar panels on a passing satellite might gleam down at the Earth for a few precious instants: a flare five times brighter than Venus. DeFanti had extremely personal and very complicated feelings about satellites. Especially Iridium satellites, though spy satellites had always been his premier line of work. He had wanted in on the Iridium project so very badly. He had violently hated the engineers and financiers who had somehow launched a major global satellite communications network without him. And then he'd been astounded to see the whole enterprise simply fold up and collapse. These wonderful Iridium satellites, dozens of high-tech metal birds each the size of a bus, beautifully designed, working perfectly and just as planned, costing more per pound than solid gold: they were glories of technology with no business model. The engineers had built them, and yet no one had come. Earthly cell phones were so much quicker, cheaper, smaller. The bankrupted satellites were doomed to be de-orbited and flung, one by one, into the black, chilly depths of the Atlantic Ocean. This awful fate made the Iridium satellites very precious to DeFanti. The Most Important Man in the World had known some failures of his own, true agonies of the spirit. He never gloated at the wreckage of anybody else's grand ambitions. He had learned to watch such things with care, searching for men with drive who had the guts to survive the midnight of the soul. Such men were useful. A long feathery brushstroke in the west touched his steadily darkening sky. DeFanti scowled. That mark was a jet's contrail, and by its angle across the heavens, DeFanti knew at once that the jet was headed for the Pinecrest private airstrip. DeFanti wheeled his heavy spotter's binoculars on their black metal stand. The intruder, gleaming in fading sunlight high above the Rockies, was a sleek white Boeing Business Jet. It could jump the Pacific in two hops. The Dot-Commie had returned. Moments later, the jet roared overhead, shattering his serenity. The Dot-Commie had sent him some e-mail, DeFanti knew that, but the kid and his latest screaming crisis had somehow slipped DeFanti's mind. The Dot-Commie always had dozens of irons in the fire. No e-biz fad ever escaped his notice. DeFanti had five adult children. He got it about the nineties generation, as far as anyone did. But the Dot-Commie was special even by those weird standards, he was like . . . DeFanti rubbed his grizzled chin. The yohimbe was coming on, with a ticklish mental itch. DeFanti knew that the Dot-Commie, for better or worse, was his spiritual heir. DeFanti's two sons wanted nothing to do with their father's empire. And properly so, because his sons, like their mothers, just didn't have what that took. The Dot-Commie took after DeFanti, though. The Dot-Commie always took plenty. The Dot-Commie was entirely at home with DeFanti's many holdings. The cable, the cell phones, the Taiwanese chip fabricators, the Houston aerospace companies, the federally subsidized fiber-optic Internet supercomputers . . . Not only was the Dot-Commie at ease with all this high technology, he was downright nostalgic about it. The jet slid behind a sharp ridge of pines. It missed the approach on DeFanti's short mountain runway, roared up gushing smoke, then circled and tried again. So much for clear skies. Was the kid letting his latest girlfriend pilot the thing? Why had DeFanti ever agreed to have a runway installed here in the first place? Surely it would take the Dot-Commie a good long while to find him, up here in the cabin. Maybe Wife Number Four would politely force the kid to shower, shave, eat, and possibly even sleep. Maybe the German tourists would force him to drink a round of German beers. DeFanti opened his laptop and checked its heavy-duty battery. He loaded the latest orbits for passing spacecraft. Tom DeFanti had always been very keen about the role of computers in outer space. He had shared those professional interests with the NORAD Space Defense Operations Center, and the National Security Agency, and the National Reconnaissance Office. With the CIA Office of Imagery Analysis. With the Consolidated Space Operations Center, at Colorado Springs. With the Air Force, and with the Space Force, and with the Navy's FLTSATCOM, and with the National Photographic Interpretation Center. With aerospace engineering labs in Houston. With R&D labs in Northern Virginia. With camera labs in Rochester, New York. With antenna labs in Boulder, Colorado. And with Communists. One glorious day during perestroika 1988, Tom DeFanti had found that he was helping American and Soviet space spies to share some very intimate notes. Long before the Hubble Space Telescope had ever appeared to scan the distant galaxies, Cold War spy satellites had carried giant telescopes into orbit. Those orbiting telescopes always looked down. Through persistence and competence, Tom DeFanti had become the planet's go-to guy for "national technical means of verification." Not because DeFanti himself was a spy, although passing those notes at a disarmament conference certainly made him into one. No: it was because Tom DeFanti was basically running the spy-sat business. He was carrying the technical torch for the world's most secret industry. A very secret industry, nothing at all like normal astronomy, and not very much like normal computers, but an industry that combined both. It was quite a big, advanced, very high-tech industry. A big, dark, powerful industry. Tom DeFanti was the man within private enterprise who was most advancing that industry. He was building satellite hardware for gigantic spaceborne spy cameras. He was financing analysis software for huge torrents of visual data. That made him an important man. Him, Tom DeFanti: a frantic business hustler who had stuck together a Houston aerospace company on a wing, a prayer, and some very quiet yachts packed with bales of Acapulco gold. He'd done some crazy things, for some desperate reasons. But he'd always had one business goal in mind: his own personal charge card for the Deep Black. Because the Deep Black budget for spy satellites was twice the size of the CIA's budget. And the Congress never ran any audits there. The spy-sat community never advertised in _Aviation Week._ Once you became a trusted Deep Black supplier, though, you were a made man. If you could deliver their hardware on time, quietly, and within specs, you were a miracle for them. You were a major asset and to hell with the so-called budget. Six-thousand-dollar hammers; only to be expected. Ten-thousand-dollar toilet seats; go enjoy yourself. To launder his Deep Black money, to try to make his own taxes make sense, DeFanti had started a cable company, and then a microwave phone network. He'd never guessed that cable TV would spread like crabgrass, or that cell phones would web Planet Earth with their white roadside antennas. Time passed. Tom DeFanti grew older in his boardrooms. The wives cycled through his bedrooms, and his kids grew up and left. The Space Age gently faded into the yellowing pages of _Life_ magazine. By the 1990s, aerospace jobs were fading away by double-digit percentages, while the Cyberspace Age exploded in the NASDAQ and a million Web sites. Business and the profit motive ruled the heavens and the earth. But now, breaking his thoughts, here came the ugly racket of a trail bike. It was, of course, the Dot-Commie. The Dot-Commie was making a beeline for DeFanti's hidden cabin. He must have ridden the motorbike straight down his jet's embarkation stairs. The Dot-Commie waved cheerfully as his bike veered wildly up the stony, darkening slope. The Dot-Commie wore a tartan shirt, jeans, boots, and an Australian outback hat. He looked both rugged and tidy. Jet lag never bothered the Dot-Commie. He ate like a weasel and he slept like a tomcat. The Dot-Commie pulled up with a squeal of brand-new brakes. He hunted for the off switch on his spotless Japanese toy. Despite his fondness for fancy transportation, the Dot-Commie was no man of action. He tended toward pallor and plumpness. He would have shuddered at a horse. The kid leaned the spotless bike against the gray wooden hulk of the dead man's abandoned observatory. The dead banker's old telescope had long since gone blind. His doors to the zenith had rusted shut on their iron pulleys and chains. The place had been used as a hay barn for decades. DeFanti had never altered the dead man's observatory, he had always just let it be. Now that the red Kawasaki trail bike leaned against its patient sides, he realized how much he loved that old building. What an affront that was. " _Komban-wa,_ Chairman-san!" said the Dot-Commie. The Dot-Commie had a nice tapered chin and a smooth, tall genius forehead. He was the ladies' man version of a geek. Determined to avoid the kid's eager handshake, DeFanti absently patted the barrel of his faithful old Questar. The gingko was hitting his brain with a hot quiet rush now. The Dot-Commie had something big on his mind, and it would be complicated. It would be way too complicated. The Dot-Commie's personal schemes always included lots of extra gears and switches, just for their geeky coolness. "So, kid, how'd it go across the big water?" "Oh, Tom, in Tokyo, they are So Over. They just don't Get It." The Dot-Commie removed his Australian hat. His hair looked like a nice toupee on a solid stone egg. He flipped the hat and tossed it over. "This is for you, Tom." DeFanti caught the hat, startled. "I don't need this," he lied. "I bought it for you in Sydney. It's brand-new. It's fully adjustable, see? You just pull that little tab in the back." DeFanti groaned in disbelief. Then he settled the kid's body-heated hatband around his own chilled scalp. The hat felt pretty good, really. The hat felt great. DeFanti always wore a hat when observing. Mountain nights were bitterly cold. "Cell phones, the Japanese get," said the Dot-Commie. He opened his black laptop bag. "Cameras and faxes and stereos, the Japanese get. E-commerce, that stuff the Japanese never get." From an interior pocket of the bag he removed a two-ounce plastic windbreaker. He peeled it open with the delicacy of a man folding an origami crane. "I saw the Super-Kamiokande," the Dot-Commie announced. "That was this trip's high point. That neutrino observatory. Tom, it's all you said it was, and it's more. It is insanely great." "So, what, they gave you the lunch tour? Take this hat back." "The name of DeFanti-san opens every door in astronomy! They loved me at Kamiokande. Keep the hat, Tom. The acolyte wears no hat when the Master lacks a hat." The Dot-Commie tunneled into his plastic windbreaker. It featured a snug little drawstring hood. He yanked the hood over his big egg head and grinned winningly. He looked like a plastic elf. "At Kamiokande, they're underground and galactic at the same time!" the Dot-Commie crowed, dancing in place a little to shake off the cold. "About a billion photon tubes down there. They catch neutrinos inside giant tubs of water. The Japanese are underground, underwater, and observing the galaxy. All at the same time!" "That scheme works out for them, does it?" "They get major results!" The Dot-Commie dug into his magic black bag and retrieved his gleaming silver laptop. "So, which is bigger, DeFanti-sensei? The universe, or the screen that shows us the universe?" "It's all about the screens now, kid." "You bet, Ascended Master! You are beyond Zen!" DeFanti chewed mournfully at his grizzled lower lip. "Quit bragging. It's more of the same, that's all. That LINEAR nonsense. And NEAT, and LONEOS, and SPACEWATCH. Shipping astronomy on Internet routers. Why in hell did I ever pay for those things?" "They can search every pixel in the sky, Tom." DeFanti ignored him. "Nowadays, an amateur couldn't spot a fresh comet to save his life! Those stupid scanning machines will always beat him to that. God damn it, I always wanted to bag my own comet. Always. 'Comet DeFanti'!" DeFanti put his twitching eyelid to the chilly rubber eyepiece of his Questar. He knew very well that the sky was being mapped with ruthless digital detail. That wasn't the part that scared him. No, the scary part was what space telescopes had done to the Earth. Pinecrest Ranch was easily visible from space. Any passing cosmonaut could see the place with the naked eye. The National Reconnaissance Office, as a meaningful gesture to a favorite supplier, had sent DeFanti a digital map of his whole Colorado spread. The NRO had given Pinecrest Ranch the same loving attention that they gave to the garish palaces of Saddam Hussein. All the NRO data was stuffed inside DeFanti's laptop now. It wasn't just a flat simple map, oh, no. It was an interactive, topographic, 3-D computer model map, military-style, just like the Delta Force studied before they parachuted into some hellhole in the middle of nowhere. Tom DeFanti could ride across his Colorado spread with a mouse instead of a horse. He dreaded the day when he would really prefer life that way. The Dot-Commie turned with solemn interest to DeFanti's second telescope. "So, Tom, what's with the tarp on this cool new hardware?" DeFanti felt a pill-driven mental pang. He scratched below the hat brim. "I don't much care for that one, kid." "Why not?" "Because it auto-aligns to the zenith angle. It's got a forty-thousand-object stellar database built in. That's not a telescope. That thing's a damn Nintendo." "Nintendo, the Japanese get! So, mind if I boot this baby up? Looks like terrific seeing up here tonight. The clarity of those skies!" DeFanti clenched his chilly, wrinkled hands. "Yeah, except for your jet trail! That's a cloud of burning kerosene! You add that filth to the smog from the drought, and those wildfires on federal land . . . What has a man got to do?" The Dot-Commie touched a fat black switch on the base of the telescope. The digital instrument perked up with an instant click and an obedient hum. "Wow, sweet! So, Tom, what's on our viewing agenda tonight?" DeFanti glanced at the screen of his laptop. "An Iridium will flash at 9:17. There's a wonky old Soviet booster I've been keeping an eye on—pretty soon, it burns out big time. And after midnight, they're parking a MAGNUM/VORTEX in its graveyard orbit. We might catch a little glimpse of that, if we're lucky." He looked up. "Were you ever cleared for that one? MAGNUM/VORTEX?" "Oh, sure. I'm cleared. I'm Mr. Cleared. We got some time to kill, huh? Can I show you something, Tom? It's important." The Dot-Commie deftly spun his laptop and confronted DeFanti with the glowing screen. It was a long, dense computer image, all colored nodes and knobs. It looked like a galaxy, or maybe a globular cluster, violently ripped to shreds. "Okay, so you're showing this to me." "Tom, this is your intranet's traceroute map." "And?" The Dot-Commie sighed and changed gears. "Okay. The board of directors. Our latest member. That guy named Derek Vandeveer." DeFanti said nothing. He'd been having a whole lot of trouble remembering proper names lately. Not even the ginkgo helped him. "The big blond guy. Beard. Glasses. Shy, endearing type. Stares into space a lot. Doodles whenever other people talk to him. Everybody calls him 'Van.' " "'Van.' Yeah, I know Van. The big geek." "That's our man. Dr. Derek Vandeveer, star computer scientist, widely noted security expert. Van was a Stanford professor. He's the VP for research at Mondiale. Van won the Turing Prize in 1994. The Vandeveer Algorithm was named after Van. Okay? We recruited Van, we put Van on our board. Because Van is our token super-geek. And Derek Vandeveer just made this map that I'm showing you." "I knew that crazy bastard would be trouble. Is that what this is all about? This little visit of yours tonight?" "Tom, I love it here in Colorado. I love satellites, I love an Iridium flashing. But yes, Tom. This is an emergency." DeFanti levered the scope aside. "All right, then spill it." "Corporate networks are complex and dynamically changing. We've got supply-chain and legacy partnerships, mergers and acquisitions activity, and a lot of staff turnover. The people come and go, and the deals come and go. But the machines just sit there. They're getting more and more cluttered as time goes on. It's the nervous system of the enterprise, that network and all its connections, and it's a living, growing thing, Tom. It's like it's got its own agenda." "Yeah. I know that. Its agenda is to break our budget." "Well, we didn't keep up with it properly. We let our corporate intranet grow just like the Internet grows, like a briar patch. So check out all these unauthorized connections into our enterprise network. Look at these bad links that Van found. He's outlined them for us in red here. They're mostly free connections that our people gave out for handshakes and goodwill, back when the Net was still new. This is a very interesting business structure that Van has revealed to us here, Tom. I don't think anybody has ever mapped your business activities to quite this level of detail." DeFanti pulled down on the brim of his new hat. "Am I supposed to like this? I don't like it." "Neither do I. Tom, you divested Pacific Data a good six years ago. But there are still IP host links in our system that date back to 1993. They still tie into Net machines that are running your news magazine's online presence, and running your charity foundation . . . Tom, your nonprofit people are _incredible._ Those clowns give away Internet access to _everybody they know._ Worldwide. They are tied into Russians, Czechs and Germans, the U.N., Gorbachev's foundations, Jimmy Carter's charities . . . They are tied into _Greenpeace,_ Tom. We've got Exorbital and its deep-black projects tied into a network that is also open to Greenpeace. If the NSA ever gets wind of that, they'll go ballistic." DeFanti peered at the densely crowded screen. "So, this yellow yarn-ball here. Which one is that?" "That yellow one is Visual Research Labs. That's a spin-off, too. VRL is owned by the French now. But Vandeveer's global IP traceroute mapping has opened up VRL like a can of tuna fish. We could stroll through every machine they've got. Because VRL may be based in Paris now, but they're still running their graphics code off our Sun workstations in San Diego. Not one cent do they pay us for that service, either. They're freeloading on us!" DeFanti said nothing. He hated virtual reality people. They were chock-full of crazy hype. They always had weird hair and peculiar shoes. And the French virtual reality crowd was, of course, much worse. "We never knew the French were still hanging around in there, until Vandeveer started looking. Nobody ever asked our permission to come and go. It's just the old-school Net. They just linked up to us, and whenever they moved, nobody ever unplugged them." "So who is carrying the damn flag here, them or us?" "That's the big question, and so far, luckily, it's still us. In hackerspeak, we 'own' them. I mean, I'm no Derek Vandeveer. I don't hack, I'm a conceptualist. But with this traceroute map in my hands, yeah, basically I _am_ their Internet. With a little work, I could pose as their system administrators, and download every confidential file they've got. And if they catch on to this bad-security situation, then that's much worse, of course. Because then they would 'own' us." "I get it now. Cut to the chase. Who knows about this mess?" "I do. And Derek Vandeveer. And now you, Mr. Chairman." "Let me drive." DeFanti took the Dot-Commie's laptop. He spooled across the clustered tangle of Net connections. Vandeveer's map was the size of a bathroom carpet: tens of thousands of machines, spreading from busy hubs and linked into long, snaky webs. The networks were neatly labeled with pop-up company names and numeric IP addresses. DeFanti's Internet backbone company ran straight through the body of it, like the cloudy spine of the Milky Way. The Internet backbone business was never an outfit that DeFanti had taken seriously. Running the Internet was a high-tech hobby for computer geeks. It was a favor he'd done to put a nice smile on the face of the National Science Foundation. But by now, 1999, in terms of market cap, it was by far the biggest part of DeFanti's empire. It had never, ever cleared one dime of profit, but the day-traders had it figured for the next Ford or General Motors. They were insane. The whole world had gone crazy. DeFanti owned a cable company that owned movie studios. He owned a big, solemn news magazine that could make or break presidents. But in cyberspace and according to the NASDAQ, this makeshift wad of broadband fiber optics was bigger than Godzilla. And if the market believed it, well, then such was reality. Everything on Vandeveer's map was piled up on DeFanti's backbone. Even long-forgotten outfits, like Wife Number Three's little leather-goods store, a toy he'd bought the woman to keep her out of trouble. Here was his older son's ridiculous adventure-canoeing outfit, making some bucks off the yuppie Green idiots who loved malarial jungles in Borneo. Everything. "This son of a bitch knows more about us than we do about ourselves! How the hell did he find the time to draw all this?" "He didn't draw it at all. That map graphs all those connections on the fly." "Nobody can do that." "Vandeveer does it. Van wrote that graphics program himself." "Who is this guy? He's a menace! Where did you find him?" The Dot-Commie was hurt. "We're a gifted generation, all right? Van was my roommate once." The Dot-Commie brandished his MIT Beaver graduation ring. "I hooked Van up with his girlfriend—his wife, that is. Mrs. Vandeveer. Dr. Vandeveer that is, because Dottie has a Ph.D., too." The Dot-Commie smiled in the bluish light of the laptop. "They're very sweet people." "Do we have anything useful on this guy? Like a leash, for instance?" "Tom, please! Van is _on our board._ Van gets big comps and preferred stock. That's a very sweet deal for a little guy like him. He never does board work for anyone else. He joined us as a personal favor." "Okay, so you kissed this hacker on the lips. And for that he gives us _this_?" "We need this! This is what he does! Van would never cross us. Van's a straight-arrow R&D type. He's the classic white-hat hacker." DeFanti scrolled across the tangle with angry flicks of his thumb. The map was a marvel. Not a marvel for himself, though. It was a marvel for federal investigators, industrial competitors, or divorce lawyers. It had unbuckled DeFanti's pants and dropped them round his ankles. And not just his own pants, either. "Beelzebub.darpa.mil." What clown was naming their servers over there? The Dot-Commie's sleek face took on a gloomy look of serious adult concern. "Van has done us a big favor here, Tom. With this traceroute map, we can secure our infrastructure, plug our leaks, and eliminate a host of wasteful redundancies." "What exactly is he trying to sell us?" "Van's got nothing to do with selling. His R&D lab at Mondiale has a twenty-million-dollar budget and they let him do whatever he wants. He invented this! Tom, this is a unique competitive advantage for our outfit." DeFanti set the laptop aside. "Okay, so give me the deliverable. What specific action are you recommending?" "Okay then!" The Dot-Commie straightened alertly. "Cleaning up our own house, that comes first. That's a major capital expenditure, I admit that. But we have to do that, because living that loose is risky and just bad for business. "Once we clean up and button ourselves down with a decent security policy, then we've got the whip hand over all those old-school hacker slobs. We can make real money there. We'll make our money by revealing this bad news to all these other people who were once linked to us. Their networks are buck-naked. We know that, and they don't know that yet. How much is that worth, Tom? You tell me." DeFanti grunted. "That won't make us popular." "I'm figuring this turns into a nice little sideline business all along our supply chain. Every outfit that you ever M&A'd or divested since the birth of the Internet. Every address squatter, every Internet freeloader . . . They've gotta pay us. That's only right. And, Tom, it's incredible how much just plain _junk_ we're still running. Computers that we own and operate that _nobody ever looks at._ We plugged 'em in long ago and we forgot 'em. We need to yank them out of the garages and just dump them. The software they are running is years old and it's never been patched. They're very dangerous." "Without this Vandeveer guy, this so-called threat wouldn't even exist." "Obscurity is never security, Tom." "It sure as hell is if no one ever looks." "Machines will look. In cyberspace, everything looks. They'll program some net-bots to look. It's just a matter of time, that's all. We're stuck now between the old crappy Internet anarchy model, and a serious, big-time commercial industry. The only responsible course is to take appropriate steps. Before it comes apart on us, right at the seams." DeFanti sighed. "Have you budgeted this?" "No. I didn't. I really wanted to. I e-mailed our CIO. With a screaming yellow zonker red alert. The CIO told me to grow up and come back in ten years. That attitude won't do, Tom. That guy's due for retirement right now. Not ten years from now." DeFanti struggled to remember the name of the Chief Information Officer. He knew the guy's face. He had a thick brown beard and he wore bad waistcoats that his wife stitched for him. DeFanti had rescued him from the financial wreckage of a dying mainframe company, and he was very loyal. He was seasoned, reliable, and lacking in ambition, everything the Dot-Commie was not. Small wonder the kid wanted his scalp. "So what do I do for another CIO? Are you telling me you want that job?" "Of course I don't want that job. But I'll tell you another thing, Tom. Van's connection map here is already out-of-date. Because my own network people have already cleaned house on my holding company, my Bangalore suppliers, those Chinese rocket people, and all of my e-commerce interests. Those are just baby companies, obviously. They're fresh start-ups and they don't have your legacy problems. But I don't want 'em stuck in that briar patch with all those open back doors and those misconfigured routers. That is just unacceptable." "What is it you really want from me, kid? You want me to fire my CIO? That makes you happy?" "No, Tom. That's not enough. You've got to fire the CIO, and the system administrators, and the whole crowd of good-old-boys who make such a habit of ignoring computer security. We need to run the networks in a better, more solid way now. Vandeveer doesn't know this, but he's given me a new management tool. We can replace all these high-salary geeks with some young engineers from India who will follow secure procedures, and work on a B-1HB visa for one-fourth their salary. That's what this traceroute map is telling me, Tom. Because that is this industry's future." DeFanti's laptop broke the silence with a pinging sound. "Well, here we go then," DeFanti said. "The Iridium flash already? That's great." DeFanti glanced into his laptop and rattled off coordinates. "How do I input those over here?" said the Dot-Commie, at his scope. "Do it manually." "Do I _look_ like I do things manually?" DeFanti stepped across and aligned the bigger telescope as well as his own. The two of them pressed their heads to their cold rubber eyepieces. "Been to Sri Lanka lately?" DeFanti said. "Nope. Should I go there? The jet's all warmed up." "I sent e-mail to Dr. Clarke there. The 'Father of the Communications Satellite.'" The Dot-Commie jerked erect from his eyescope. He was stunned. "Arthur C. Clarke? _The_ Arthur C. Clarke?" "Yes, and Dr. Clarke answered me. He was very polite." "Tom, that is _fantastic._ What an honor! I saw _2001_ when I was three years old." They shut their glowing laptops to help their eyes adjust to night vision. "Are you seeing that haze up there?" DeFanti asked. "It's pretty clear tonight, Tom. It is truly tremendous out here. What a treat." "That's wildfire smog. Two years of drought in Colorado. Fires and fire alerts everywhere. The sons of bitches lit up that public park like Coney Island. There are state and county dark-sky ordinances, but they're feds, so they just ignore us. 'Sue us,' that's their attitude. A bunch of arrogant, wise-ass, brass-bottomed jacks-in-office . . ." "I saw a flash!" the Dot-Commie yelped. DeFanti switched eyes at his rubber eyepiece. No use. You had to be there just at the instant. "It was like the flash off a rearview mirror," the Dot-Commie reported. "Metallic. Brief, yet intense." "Back in the good old Wild West days, the U.S. Cavalry used heliographs," DeFanti said as he fruitlessly searched his patch of sky. There could be three, or even four flashes if the bird's attitude-control was going. But he was seeing nothing but stars. "The Cavalry once sent a flash of sunlight off a mirror that was visible for ninety miles. The British Army used signal mirrors in Afghanistan. Can you imagine that? An army fighting with mirrors in Afghanistan." "Afghanistan's not a consumer market," said the Dot-Commie. "Will there be more glints?" "Maybe," said DeFanti. They waited. "No," he said finally. He straightened his aching back. The Dot-Commie opened his laptop, woke the screen, and punched at keys. "So what do you make of our problem, Tom? I know it's a lot of money. But we can do that. We've got loads of market money now. Buckets." "Okay, straight from the gut, kid. Here's the deal. You can't turn an enterprise around on the word of one guy from R&D. It doesn't matter if he's brilliant or even if he's technically correct. The middle-level people just won't go for that politically." "Truth and technology will win over bull and bureaucracy, Tom. That's the story of the New Economy." "No, kid, the truth does not win. For a couple of quarters the truth gets somewhere maybe. If everybody's real excited. But never in the long run, never." DeFanti shrugged. "The common wisdom always wins. Consensus, perception management, and the word on The Street. The markets, kid, the machine. The markets will go ape if we get all sweaty about some obscure security problem and start firing our established personnel. That move is panicky. It's just not professional." "You're not Getting It here, Tom." "Kid, I knew you would tell me that. I'm not so old that I'm blind and deaf yet. I know that it's a dangerous situation. It's dangerous like mixing Deep Black intelligence and also owning the media. But I do that anyway, because dangerous is what pays. Dangerous has got a high rate of return. Robert Maxwell mixed spies and media just like I did, and he jumped off his own yacht and he drowned. I knew that guy, Robert Maxwell. I knew him personally. I even knew his yacht." "So we just drown our problem, that's your solution? What about Vandeveer? He's on the board." "I've got nothing against Vandeveer. I'm glad that guy's inside our tent. You keep him in the dark and feed him lots of gold. I want him kept real happy. Him and the wife—Ditsy?" "Dottie." "Right. Nice, sweet, technical-weirdo people. I'll give 'em the personal gold star. The big chairman pat on the back. Very appreciative. All the proper steps. All expenses paid trip to Finland for him and the missus and kids. We need some guy like him to go winkle out those little Finnish cell phone sons of bitches—what was their name again?" "Nokia." "Yeah, them. Nokia. God, I hate those people. A full report to the board about those instant-messaging apps. Six months, eight months, whatever. Keep him busy for us." The Dot-Commie rustled in the darkness turning back to his telescope. "Van is plenty busy already. He's a VP for Mondiale. Van hates junkets, he only likes big toys. Fancy router hardware for his lab, that's what Van wants out of his life. I can shut Vandeveer up and I can sit on him if you want, there's no problem there. But I've got to tell you something, Tom: you're making a major mistake. We're in a high-tech revolution right now, the biggest thing since the invention of fire. If it's even halfway possible, then it's gonna happen." "I know that you think that. But you're wrong." "Okay," said the Dot-Commie. "If that's your full, considered judgment, I guess that's it, then." "That's it, kid. So give me your fallback position." The Dot-Commie pulled the thin plastic hood from his head. A dark night wind had come up and he smelled of hair gel and sweat. "Okay. Vandeveer wants to install some honeypot sites for network intruders. That way, if we are penetrated, at least we can trap the hackers." "It's good to hear he's got some common sense. And that costs us?" "Not much. Peanuts. He'd do it for us as a favor. He builds them for the FBI all the time." DeFanti rubbed his stubbled chin. "This guy is a Bureau consultant, too?" "Van lives on Internet time. He's thirty years old and he's got _students_ who are in the FBI." The Dot-Commie abandoned his telescope and turned his pale face to the zenith. "Well, I'm glad we hashed that issue out, at least. It's a load off my mind. My God, Tom, just look at all those stars. They've got _colors._ Look at that detail. You never see that near a city anymore. Nowhere in this world." "This is the last place in the continental USA where a man can see truly black skies." "You ever get the aurora borealis down here? I see them on over-the-pole flights. I see fantastic things, unbelievable." "No. I don't." DeFanti paused. "What the hell is all that?" "What? Point." DeFanti raised his arm. "I'd be guessing Cassiopeia, right?" "No, I mean that flickering up there. That flickering looks auroral." The Dot-Commie's voice dropped an octave. "You say, there's some 'flickering,' Tom?" "There's _rotation._ And it's red . . ." DeFanti began to tremble. It was some kind of object . . . It was round . . . it had thickness and depth, and it spun and it sparkled . . . He was witnessing a cataclysm in his beloved sky. It was a Flying Object, floating in the sky, an impossible creature of red dancing light. "Look up there at that damn thing," he croaked. "I'm not getting this, Tom. What exactly do you see up there?" "It's flying and it's made out of lights. And it's _bi_ _g_!" "You're serious about this?" "It's _getting closer_! Look at it!" DeFanti flinched and ducked. "Look out!" "I'd _love_ to see it, Tom. What are you talking about?" "It tried to hurt us!" DeFanti shouted. "Now it's really moving! Oh, my God, look at the _speed_ of that thing!" Awe, terror, wonder fought within DeFanti. Good Lord, to have _seen_ a UFO, to know that the real world really held such things, not any joke, not a dream, _space travelers,_ that alien spacecraft were true and real, just like hammers and hamburgers were real . . . But that would burst the limits of the world. It meant total loss of control. The Dot-Commie cleared his throat politely. "Tom, did you say this thing is 'made out of lights'? I only ask because, well, there are often good explanations for unusual visual phenomena." "You can't see it at all? Look, it's wheeling around! It's coming back right at us!" "No, Tom, I don't see it. I do see that it's getting a little hazier up there, as you said. So maybe it's just car headlights, Tom. It's reflections off low clouds." "Kid, that thing is _flying._ I see a flying object!" "Car headlights can fly. Their lights move up and down on hillsides. Wait, Tom! I've got it! It's those giant windmills." "What?" "It's flickering, right? They're setting up megawatt windmills down in the valley now. Those windmills are huge. Light could flicker off their giant blades." "Are you crazy? It's a flying saucer! I can see it." "Okay," the Dot-Commie said calmly. "Okay, I guess you're right. So then, it's got to be an artifact." "An _alien_ artifact?" "No, an artifact of your perceptions." "You're telling me that I'm a lunatic." "No, Tom. I'm telling you that you're shaking like a leaf, and you're saying things that make no sense to me, and I can't see any reason why you should do that. And that's got me very, very concerned. This UFO you're witnessing, is it still up there?" Of course the UFO was still up there. It wasn't there like a piece of aircraft metal—it was there like a terrifying bloody haze, occult, supernatural. "Yeah. It's still there. It's hovering. I think it's watching us." "Tom, I never thought I would have to use this with you. But I learned this in the chill-out tent at Burning Man. Tell that thing to move, Tom. Give it an order, out loud. Speak right to it. Because if it's all in your head, then it'll do whatever you say." "That proves I'm crazy." "You're the boss, Tom. Tell that thing where to get off." DeFanti craned his neck and stared. He was encountering a UFO. He didn't have many choices. "Move left!" In all its uncanny majesty, the intruder slowly did as he said. It crawled across the zenith like a jellyfish. "Move north!" DeFanti screamed. The disc flickered in and out across a screen of distant stars. DeFanti broke into sobs. The Dot-Commie put both his hands on the trembling rawhide fringes of DeFanti's shoulders. "Tom, let's go inside now, all right? It's just no good out here." DeFanti's teeth were chattering. Cold tears ran down his face. "Help me." "We've got to talk about the medications, Tom." "I need something bad . . . I need . . . I need a cigarette." "Back to the ranch house, okay? Can you ride the back of my bike? You're really shaky! Hey whoa! Let me help you up!" CHAPTER **ONE** NEW JERSEY, SEPTEMBER 11, 2001 **W** ith eager screams of hunger, little Ted Vandeveer drove his parents from their bed. Dottie slipped a rubber-coated spoon between the infant's lips. Baby Ted blew out his chubby cheeks. Porridge spurted across the table. Dottie scanned the mess. Her eyelids flicked upward meaningfully. "Where's the au pair?" Van hedged. "She didn't come in last night." Van rose from his white plastic chair, and fetched a white paper towel. With the wisdom of experience, Van tore off a second towel for Ted to use as backup. Van still felt giddy inside his mansion's bright new kitchen. The new kitchen featured deep steel sinks, thick red granite counters, and a chromed fridge the size of a bank vault. When he'd signed up for a house renovation, Van hadn't known that New Jersey contractors were so enthusiastic. At least, Van thought, Dottie approved of the changes in their house. The mansion's original kitchen had been a nightmare straight out of H. P. Lovecraft. Dottie's new kitchen was now the only place in the Vandeveer home where the plumbing worked properly. On a corner of the new stove, a small TV played WNBC out of New York City. Van had hooked the set to a pair of rabbit ears. The township of Merwinster, New Jersey, lacked cable television. This was a serious blow to the Vandeveers, who were dedicated fans of _Babylon 5, Red Dwarf,_ and _The X-Files._ But Mondiale was the little town's biggest employer, and Mondiale was in the broadband Internet business. Mondiale despised all cable TV outfits. Van toweled up the baby's spew. Baby Ted enjoyed this fatherly attention. He kicked his chubby feet and emitted a joyous string of syllables. "He said 'dada,' " Van remarked. Dottie yawned and stirred the baby's porridge, propping her head on one slender hand. "Oh, Derek, he's just babbling." Van said nothing. As a telecom expert, Van knew definitely that his son's vocalizations had contained the phonemes "dada." Technically speaking, Van was absolutely correct. However, he had learned never to argue with Dottie about such things. Van dropped the dirty towel into a shiny kick-top wastebasket. He sat again in his plastic picnic chair, which popped and squeaked under his bulk. Van accepted this embarrassment quietly. He knew that it was all his own fault. He, Dr. Derek Vandeveer, famous computer scientist, owned a decaying Victorian mansion that had no proper furniture. Historical Merwinster, New Jersey, was a gabled, colonial village, woody and surrounded by horse farms. It also boasted the third-biggest clump of fiber optics on America's Eastern Seaboard. Merwinster was a superb place for advancing high-tech research. Van routinely put in sixty-hour weeks inside the Mondiale R&D lab, so he was forced to live in the town. Dr. Dottie Vandeveer spent her days in Boston, at the Smithsonian Astrophysics Lab. Van had bought the two of them a house in Merwinster because it seemed wrong to Van for his baby, their new third party, to have no home. Besides, Van had to do something practical with his money. Van was making money, and not just a lot of money. Van was the VP for Research and Development at Mondiale. Van was making a weird amount of money. The TV muttered through a headache commercial, obscuring baby Ted's eager slurps from Dottie's rubber spoon. Van tapped at his trusty ThinkPad and checked the titles of the 117 pieces of e-mail piled up for him behind Mondiale's corporate firewall. With an effort, Van decided to ignore his e-mail, at least until noon. Because Dottie was home with him. Dottie was sleeping with him, and lavishing her sweet attentions on him. Dottie was cooking and cleaning and changing diapers. Dottie was wandering from room to dark decaying room inside the Vandeveer mansion, and wrinkling her brow with a judgmental, wifely look. Today, furnishing the house had priority. So far, in his rare moments outside of the Mondiale science lab, Van had managed to buy a crib, a playpen, a feeding chair, a Spanish leather couch, a polished walnut table for the breakfast nook, a forty-six-inch flat-screen digital TV with DVD and VCR, and a nice solid marital bed. Van had also installed a sleek, modern Danish bedroom suite upstairs, for Helga the au pair girl. Helga the au pair girl was Swedish and nineteen. Helga had the best-furnished room in the Vandeveer mansion, but she almost never slept in. According to Dottie, when she and Helga were alone together in Boston, the girl was always gentle, very sweet to the baby, and was never into any trouble with men. But in quiet little Merwinster, Helga went nuts. Helga was hell on wheels with the local computer nerds. She was a man-eater. The geeks were falling for blond Swedish Helga like bowling pins. Van sometimes wondered if he should charge them lane fees. Dottie put the baby's yellow goop aside and got up to make toast and eggs. Van took rare pleasure in watching Dottie cooking for him. Dottie was not a natural cook. However, she had memorized an efficient routine for the creation of breakfast. Dottie fetched the brown eggs out of their recycled-paper carton and cracked them on the edge of the white blue-striped bowl, hitting the same spot on the rim, precisely, perfectly, every single time. This sight touched something in Van that he lacked all words for. There was something silent and dark and colossal about the love he had for Dottie, like lake water moving under ice. The pleasure of watching her cooking was much like the secret pleasure he took in watching Dottie dress in the morning. Van loved to watch her, nude, tousled, and bleary, daintily attacking all her feminine rituals until she had fully assembled her public Dottieness. Watching Dottie dressing touched him even more than watching Dottie undressing. Baby Ted was eleven months old. Ted had some major abandonment issues. Deprived of his mommy and his rubber spoon, Ted jacked his chubby knees in his high chair, with a wild, itchy look. Van watched his baby son intensely. The baby was of deep interest to Van. With his shock of fine fluffy hair and his bulging potbelly, baby Ted looked very much like Van's father-in-law, a solemn electrical engineer who had made a small fortune inventing specialized actuators. Baby Ted packed a scream that could pierce like an ice pick. However, Ted changed his mind about howling for his mother. Instead, he picked intently at four loose Cheerios with his thumb and forefinger. Van sensed that picking up and eating a Cheerio was a major achievement for Ted. It was the baby equivalent of an adult landing a job. Van ran his fingers through his thick sandy beard, still wet from the morning shower. He set his ThinkPad firmly aside to confront an unsteady heap of magazines. Junk-mail catalog people had gotten wind of Van's huge paycheck. For them, a computer geek with a new house and new baby was a gold mine. Van didn't enjoy shopping, generally. Van enjoyed mathematics, tech hardware, cool sci-fi movies, his wife's company, and bowling. However, shopping had one great advantage for Van. Shopping made Van stop thinking about Nash equilibria and latency functions. Van had been thinking about these two computer-science issues for three months, seriously. Then for two weeks very seriously, and then for the last six days very, _very_ seriously. So seriously that even Dottie became invisible to him. So seriously that sometimes Van had trouble walking. However, Van's network-latency analysis had been successfully completed and written up. The white paper would be widely admired by key members of the IEEE, and cordially ignored by the Mondiale board of directors. So Van had given himself some time off. Dottie, slim and delicious and barefoot, was silently reading the instructions that came with her new toaster oven. Dottie always read all the instructions for everything. Dottie always studied all the safety disclaimers and even the shrink-wrap contracts on software. Back at MIT, classmates at the lab had teased Dottie about her compulsive habits. Van, however, had noticed that Dottie never made the dumb beginner's mistakes that everybody else made. Dottie was pleased to have this quality of hers recognized and admired. Eventually Dottie wrote her own vows and then married him. Van leafed through slick colorful pages and discovered a Fortebraccio task lamp. The designer lamp looked both spoonlike and medical. It had the robust, optimistic feeling of a vintage Gene Roddenberry _Star Trek_ episode. It rocked totally. Van ripped the lamp's page from the catalog, and dumped the rest into the recycling bin at his elbow. Van's next catalog was chock-full of chairs. Van, his attention fully snagged now, settled deeply into the problem at hand. He was sitting uncomfortably in a lousy plastic picnic chair, one of a set of six that he had bought on a hasty lunch break at the nearest Home Depot. That situation just wouldn't do. Dottie repeated herself. "Derek! You want seven-grain bread or whole wheat?" Van came to with a start. "Which loaf has more in the queue?" "Uhm, the whole wheat loaf has more slices left." "Give me the other one." Logically, that bread was bound to taste better. As a serious programmer, Van used an Aeron chair at his work. The Aeron was in some sense the ultimate programmer's working chair. The Aeron was the only chair that a hard-core hacker lifestyle required. Van hunched his thick shoulders thoughtfully. Yet, a family home did require some domestic chairs. For instance, an Aeron lacked the proper parameters for breakfast use. Spattered baby food would stick inside the Aeron's nylon mesh. Van winced at the memory of the three FBI guys who had shown up at his Merwinster mansion, seeking his computer security advice. The FBI G-men had been forced to sit in Van's white plastic picnic chairs. The Bureau guys hadn't said a word about the plastic chairs—they just drank their instant coffee and took thorough notes on yellow legal pads—but they got that dismissive FBI look in their eyes. They were reclassifying him as a mere informant rather than a fully qualified expert. That wouldn't do, either. Dottie didn't know about the FBI and their discreet visits to the house. Van hadn't told Dottie about the FBI, for he knew she wouldn't approve. The interested parties from the Treasury Department and the U.S. Navy Office of Special Investigations had also escaped Dottie's notice. This was some catalog. It had chairs made of black leather and bent chrome tubing. Chairs like baseball mitts. Chairs like bent martini glasses. Chairs cut from single sheets of pale, ripply plywood. Dottie slid a breakfast plate before him. Dottie's new toaster oven had browned Van's toast to absolute perfection. Van had never before witnessed such perfect toast. It lacked the crude striping effect that toast got from the cheap hot wires in everyday toasters. "Derek, can you open this?" Van put his manly grip to an imported black jar of English jam. The enameled lid popped off with a hollow smack. There was a rush of aroma so intense that Van felt five years old. This was very good jam. This black British jam had such royal Buckingham Palace authority that Van wanted to jump right up and salute. "Honey, this stuff is some jam." "It's blackberry!" Dottie sang out from behind her copper frying pan. "It's your favorite!" Even the baby was astounded by the wondrous smell of the jam. Ted's round blue eyes went tense. "Dada!" he said. "He said 'dada' again." Van spread the happy black jam across his perfect toast. Ted slapped his spit-shiny mitts on his feeding tray. "Dada!" he screeched. "Dada!" Dottie stared at her son in awe and delight. "Derek, he _did_ say it!" She rushed over to praise and caress the baby. Baby Ted grinned up at her. "Dada," he confided. Ted was always good-natured about his mother. He did his best to mellow her out. Van watched the two of them carrying on. Life was very good for the Dada today. Van wolfed down all eight pieces of his toast. This was a caviar among blackberry jams. "Where on earth did you find this stuff, Dots?" "Off the Internet." "That'll work. Can you get a case discount?" "You want more?" "You bet. Point, click, and ship." Van leaned back and slid his toast-crumbed plate aside, increasingly pleased with the universe. Dottie sidled over, bearing a plate of fluffy scrambled eggs. Van lifted his fork, but then his gaze collided with yet another catalog chair. The spectacle unhinged him. "Holy gosh, Dottie! Look at this thing. Now that's a chair!" "It looks like a spider." "No, it's like an elk! Look at those legs!" "The legs, that's the most spidery part." "It's made out of _cast magnesium_!" Dottie took away Van's jar of jam. "Paging Stanley Kubrick." No way, thought Van. Kubrick's movie _2001_ was all 1968! Now that it really was 2001, all that futuristic stuff was completely old-fashioned. Van sampled his scrambled eggs. They were very tasty indeed. "Magnesium! Wow, no one in the world can tool that stuff, and now it's in chairs!" Dottie set her own plate down, with dabs of food on it that would scarcely feed a sparrow. She heaved the restless baby from his high chair and propped him on her slender thigh. Ted was a big kid and Dottie was a small woman. Ted flopped back and forth, flinging his solid head at her like a stray cannonball. "How much does it cost?" she said practically. "Six hundred. Plus shipping." "Six hundred dollars for one chair, Derek?" "But it's magnesium _and_ polycarbonate!" Van argued. "They only weigh seven kilograms! You can stack them." Dottie examined the catalog page, fork halfway to her tender mouth. "But this chair doesn't even have a real back." "It's got a back!" Van protested. "That thing that grows out of its arms, that is its back, see? I bet it's a lot more fun to sit in than it looks." Dottie poured Van fresh coffee as Ted yanked at her pageboy brown hair. "You don't like it," Van realized mournfully. "That's a very interesting chair, honey, but it's just not very normal." "We'll be the first on the block to have one." Dottie only sighed. Van stared at the awesome chair, trying not to be surly. Six hundred dollars meant nothing much to him. Obviously Mondiale's stock wasn't at the insanely stellar heights it had been when he had bought the mansion, but any guy who bought his wife emeralds for their anniversary wasn't going to whine about a magnesium chair. Van couldn't bear to turn the catalog page. The astonishing chair was already part of his self-image. The chair gave him the same overwhelming feeling he had about computers: that they were _tools._ They were _serious work tools._ Only lamers ever flinched at buying work tools. If you were hard-core you just _went out and got them._ "This is a Victorian house," Dottie offered softly. "That chair just doesn't fit in here. It's . . . well, it's just too far-out." Dottie took the catalog from him and carefully read all the fine print. "That chair is not that weird," Van muttered. "It's the whole world that's weird now. When the going gets weird, the weird turn pro." He picked up his wireless laptop. "I'm going to Google the guys who made it." "You really want this thing, don't you?" "Yeah, I want ten or twelve of them." "Derek, that's seventy-two hundred dollars for chairs. That's not good sense." Dottie sighed. "Tony Carew keeps saying that we should diversify our investments. Because the market is so down this season." "Okay, fine, fine, we're not stock freaks like Tony is, but folks still need wires and bits." Van shrugged. Van owned Mondiale stock because he put his own money where he himself worked. His work was the one thing in the world that Van fully understood. Whenever it came to the future, Van would firmly bet on himself. That had certainly worked out for him so far. Dottie smoothed the glossy magazine page. "Derek, my grant expires this semester. That's not good. I've got everything publishable that I'm going to get out of that cluster survey. The peer review people are saying we need better instrumentation." She wiped at Ted's spit-shiny chin with Van's spare paper towel. Van struggled to pay attention to her words. Dottie's lab work meant everything to her. She had been working for four solid years on her globular cluster study. Dottie had colleagues in Boston depending on her. Dottie had grad students to feed. "Derek, it just didn't break wide open the way I hoped it would. That happens sometimes in science, you know. You can have a great idea, and you can put a lot of work into the hypothesis, but maybe your results just don't pan out." "People love your dark energy nucleation theory," Van said supportively. "I've been thinking of spending more time here at home." Van's heart leapt. "Yeah?" "Teddy's going to walk soon. And he's talking now, listen to him." Dottie stroked the baby's wispy hair as Ted's jolting head banged at her shoulder. "A little boy needs a normal life in some kind of normal house." Van was shocked to realize how much this idea meant to him. Dottie, living with him and Ted, every single day. He felt stunned by the prospect. "Wow, being normal would be so fantastic." Dottie winced. "Well, Helga is never around here for us when we need her. I think maybe I made a mistake there." "We could put out an APB for her." Van smiled. "Aw, don't feel bad, honey. We can make do." "I should do better," she muttered. "I just don't look after you and Teddie the way that I should." Dottie was plunging into one of her guilty funks. The oncoming crisis was written all over her. Pretty soon she would start lamenting about her mother. Dottie only allowed herself these painful fits of insecurity when she was really, really happy. It had taken Van ten years of marriage to figure that out, but now he understood it. She was spoiling their perfect day because she had to. It was her secret promise to an ugly, scary world that she would never enjoy her life too much. Normally this behavior on her part upset Van, but today he felt so good that he found it comical. "Look, honey, so what if you got some bad news from your lab? What's the worst thing that can come out of all that? Come on, we're rich!" "Honey bear," Dottie said, looking shyly at the spotless tabletop, "you work too hard. Even when you're not in your office, you let those computer cops push you around all the time." She picked up the other catalog again. "This funny chair you like so much? It's waterproof. And we do need some kind of porch chair. So get this one, and you can keep it outside. Okay?" "Two?" Her mouth twitched. "One, Derek." "Okay then!" One chair, just as a starter. One chair would be his proof-of-concept. Van beamed at her. The television grew more insistent. Dottie glanced over her shoulder at it. "Oh, my goodness! What a terrible accident." "Huh." Van stared at the smoldering hole in the skyscraper. "Wow." "That's New York, isn't it?" "Yeah. Boy, you sure don't see that all the time." Van could have walked to the little TV in three strides, but on principle, he spent thirty seconds to locate its remote control. It was hiding in a heap of catalogs. Van turned up the TV's volume. An announcer was filling dead air. Some big jet had collided with the World Trade Center. Van scowled. "Hey, that place has the worst luck in the world." Dottie looked puzzled and upset. Even Ted looked morose. "I mean that crowd of bad guys with the big truck bomb," Van explained. "They tried to blow that place up once." Dottie winced. It was not her kind of topic. Van fetched up his ThinkPad from the floor. He figured he had better surf some Web news. These local TV guys had a lousy news budget. Covertly, Van examined his e-mail. Thirty-four messages had arrived for him in the past two minutes. Van flicked through the titles. Security freaks from the cyberwar crowd. Discussion groups, Web updates. They were watching TV right at their computers, and instantly, they had gone nuts. Van was embarrassed to think that he knew so many of these people. It was even worse that so many of them had his e-mail address. Van examined the television again. That television scene looked plenty bad. Van was no great expert on avionic systems, but he knew what any system-reliability expert would know about such things. He knew that it was very, very unlikely that FAA air traffic control at Kennedy and LaGuardia would ever let a jet aircraft just wander accidentally into a downtown New York skyscraper. New York City had a very heavy concentration of TRACONs and flow control units. So that couldn't be a conventional safety failure. However. An unconventional failure, that was another story. An ugly story. Van had once spent a long, itchy three-day weekend with FEMA in Washington, watching information-warfare people describing the truly awful things that might be done by "adversaries" who "owned" federal air traffic control systems. Since there really was no such thing in the world as "information warfare," information-warfare people were the weirdest people Van knew. Their tactics and enemies were all imaginary. There was a definite dark-fantasy element to these cyberwar characters. They were like a black flock of the crows of doom, haunting an orc battlefield out of Tolkien's _Lord of the Rings._ Van was reluctant to pay them any serious attention, because he suffered enough real-world security problems from hacker kids and viruses. Van did recall one soundbite, however. A bespectacled infowar geek, all wound up and full of ghoulish relish, describing how every aircraft in the skies of America would "become a flying bomb." Air traffic control was a major federal computer system. It was one of the biggest and oldest. Repeated attempts to fix it had failed. The guys in the FAA used simple, old-fashioned computers dating to the 1970s. They used them because they were much more reliable than any of the modern ones. FAA guys had very dark jokes about computers crashing. For them, a computer crashing meant an aircraft crashing. It meant "a midair passenger exchange." It meant "aluminum rain." Now, Van realized, he was watching "aluminum rain" on New York's biggest skyscraper. There was no way this was going to do. Not at all. Van drew a slow breath. There was a bad scene on the TV, but he was prepared for it. He had been here before, in his imagination. In 1999, Mondiale had spent over 130 million dollars chasing down Y2K bugs, with many firm assurances from security experts that the planet would fall apart, otherwise. Van had believed it, too. He'd felt pretty bad about that belief, later. When computers hadn't crashed worldwide and the world hadn't transformed itself overnight into a dark _Mad_ ___Max_ wasteland, that had been a personal humiliation for Van. At least the Y2K money had really helped a big crowd of old programmers who had never saved up for retirement. Van's New Year's resolution for the year 2001 had been to never panic over vaporware again. So Van stilled his beating heart as the blasted skyscraper burned fantastically on his television. He was living way ahead of the curve here. He was already thinking in tenth gear. Calm down, he thought. Chill out. Be rational. Nothing really important was going to happen unless his phone rang. Some flurry of e-mail from his most paranoid and suspicious acquaintances, that did not mean a thing. Internet lists were no more than water coolers, nothing more than a place for loudmouths to shoot off. His home phone number was extremely private. If that phone rang, then that would mean big trouble. If the phone did not ring, then he was much better off not saying anything to Dottie. Let her be happy. Let Ted be happy. Please, God, let everyone just be happy. Look at that sun at the window, that oak tree out in the lawn. It was such a nice day. Uh-oh. There went the other one. CHAPTER TWO NEW JERSEY–CALIFORNIA, SEPTEMBER 11–14, 2001 **A** ir traffic had shut down. Van was living in a world without airplanes. His Frequent Flyer cards were useless plastic. Van finally understood why he had bought himself a Range Rover Sport Utility Vehicle. Van climbed into the Rover, parked at curbside as usual, for his Victorian mansion had no garage. He drove a few hundred yards from the village, parked in the colossal lot that had taken over a former horse farm, and walked through Mondiale's brown Plexiglas entranceway. Then he raided his lab for equipment. His coworkers asked him no questions about why he wanted so much hardware, or where he was going with it. At Mondiale's R&D lab, Van's friendliness to federal agents had never gone unnoticed. The mood at the lab was shattered and jittery. Mondiale had lost a branch office inside the World Trade Center. While most of the Mondiale staff had retreated from the burning building in good order, two fatalities had been entombed in the giant disaster site. To have dead colleagues horribly killed by terrorists, that was very bad news, but the physical damage to Mondiale's telecom system was a stunning calamity. When Manhattan's two tallest buildings collapsed, New York's microwave capacity had been gutted. Wrist-thick fiber-optic cables, safely buried deep in the WTC's subway, had been snapped, burned, and drowned. Bursting debris from the falling towers had crushed a telephone switching station in another building a block away. With cell-phone relays buried in the rubble, only one call in twenty was connecting. The landline networks were overwhelmed, with call volumes off the scale. Cops, feds, journalists, even professional system administrators, were reduced to using Blackberry pagers. New York's telecom companies were howling for hardware, manpower, and emergency permissions from the FCC. They were struggling with closed bridges and streets thick with ash and debris. It was the worst emergency of Van's career. It wasn't just a question of his company taking it on the chin. Feds wanted his advice, by e-mail, fax, and phone. Lots of feds wanted him. Law enforcement, military, infrastructure protection. Feds were calling him from agencies he had never heard of, and Van had heard of plenty. Van's future was swinging like a broken window in those smoking, ash-laden winds. Van was not panicking. He felt grim confidence that he could manage. Cops were dead, firemen were dead, but Van was not dead and he was in no mood to play dead, either. He understood that his life had been profoundly changed, and that from now on his services would be needed in new ways. Everything would be different, harder, uglier, tougher, and more dangerous. He just needed a few good, solid ideas about that situation, that was all. He needed some genuine wisdom, from someone that he trusted. He needed a point of view that was solid and simple, that would settle him down. So, for very powerful, very personal reasons, Van had to travel right away from Merwinster, New Jersey, to Burbank, California. Dottie understood this need of his. She never asked for many words from him. As foul black clouds spread across the television screen, Dottie went into a trance of efficiency. Her bright eyes went keen and hard behind her little round glasses. She packed up the baby, and herself. She even managed to find Helga the au pair. Van packed three PCs, a laptop, a printer, three toolboxes, eight car batteries, five cell phones, and a satellite dish. Van's car was a sixty-thousand-dollar truck with fifty-eight cubic feet of cargo space. This was the Range Rover's finest hour. He also removed the rearmost seats and packed the futon from his office, for the sake of catnaps. No matter what Van was going to be doing, he was sure he would be doing it around the clock. Van wasn't keen on lugging Helga all the way to California. Helga was nineteen years old, and pretty, and a foreigner. For Helga, the United States was one big Disney World where sweet older men showered her with gifts. Real terrorism made Helga really terrified. Helga sobbed miserably as she climbed aboard the Range Rover. She couldn't stop weeping. Van was an excellent driver. Dottie was a careful, methodical driver. Helga was a lousy teenage driver who lacked even an international driver's license. But Van made Helga drive the Rover anyway. The work made her stop sniffling. As the miles rolled beneath the Range Rover's Michelins, Dottie comforted baby Ted and tried to doze, saving up for her time at the wheel. Dottie wasn't allowed much sleep. Time and again her Motorola tri-band sprang to shrill, bleeping life. Dottie's astrophysicists in Boston regarded Dottie as their den mom. Dottie was the only one in the lab who knew where they kept the whiteboard markers and the Coffee-mate. Van had never overheard Dottie dealing at such intimate length with her colleagues. During their married life, she had usually spared him this ordeal. Van was guiltily aware that he had never been a good faculty spouse for Dottie. They had a two-career marriage where neither party self-sacrificed. They were hugely respectful of each other's gifts and ambitions, so whenever somebody's personal sacrifice became absolutely necessary, they would hire somebody else to do it, and pay them a salary. On I-470 near Columbus, Ohio, Van's third phone rang. Of the five he had packed, the batteries had already died in two. "Vandeveer." "Van, that was not a hack attack." This was a familiar voice for Van. A growl, really. Orson Welles with a Texas accent. A man who weighed three hundred pounds and always talked straight from the gut. Van knew Jeb's voice well, but there was a new quality in it since those towers had gone down. "How do you know that?" Van said, scowling as he sat cross-legged on his folded futon. "Did they check the avionics boxes?" "Al Qaeda can't hack avionics. They're too dumb for that. That was a Moslem suicide attack. The biggest one ever." Van considered this. Moslem fanatical terrorists, crashing American jets into giant skyscrapers, with themselves still aboard. This was absurd to him. It was a nutty thriller-fantasy straight out of Hollywood blockbusters. If Jeb said it was true, though, then Van was willing to accept it as the working hypothesis. Jeb had the best contacts in the business. Van cleared his throat. "So how did they do that?" "They used box cutters to seize the cockpit. We think they trained their kamikaze pilots on flight simulators." "So they knocked down two skyscrapers with razor blades? And the Pentagon, too?" "That's the story, Van." "What is with these guys?" Van barked. "They have got to die!" "You haven't heard the good part yet. The fourth plane missed the White House. That was their last target: economic, military, and finally political. They missed the White House because the passengers attacked them inside the fourth plane. Their families got through to them on cell phones." Jeb lowered his growl. "That is gonna be the _future_ of this story, Van. It's phones versus razors. It's our networks versus their death cult. For as long as that takes." Van was in a rage. His ears thumped with each heartbeat. "It's a real good thing they like dying, then." "Van, I need you on my team. Has anyone else called you?" "Oh, yeah, lots," Van blurted. Jeb had called first, it was true, but since then he had heard from the Bureau. The Commerce Department. The CIRC. The OMB. Several Air Force outfits he had never heard of. Even the Bureau of Weights and Measures. "Lotta headhunters out there all of a sudden," Jeb agreed cordially. "But where were they when the screen was blank, huh?" Van said nothing. Jeb had been the very first cop to take serious, practical notice of Van's talents. The state and local cyber-cops in California were so hip that they ran their own user's groups. Silicon Valley cops met a lot of white-hat hacker kids, and tended to think they were cute. But when Van had encountered Jeb, Van's life had changed overnight. Young Derek Vandeveer, a dewy-eyed comp-sci student with an intellectual interest in security issues, had suddenly met the maven's maven. Jeb had collared Van and dragged him right behind the curtains. Suddenly there were special, classified courses for Van in FLETC and Quantico, with behind-the-scenes briefings from panting, sweaty computer emergency-response teams. Jeb had shown Van the ropes, put him in the know, enrolled him in the big-time show. He'd shown Van the realities of federal information technology: awesome levels of screwup that only a superpower could create or afford. "Situation Normal: All Fouled Up." If a SNAFU remained a superpower, it was due to guys like Jeb. "In my outfit," Jeb promised, "we actually know what we're doing. That's what's so different and refreshing about us at the CCIAB." "Jeb, I've got to talk to a consultant about all this." Van glanced up guiltily at the passenger seat. To judge by that stricken look in her eyes, Dottie knew very well what he was doing. Dottie knew about Jeb and Jeb's world. But Dottie was not his "consultant." Dottie was just his collateral damage. Dottie had the look of a woman in a _Titanic_ lifeboat, watching the black icy water come up over the bows at the man she had left behind. Van had never been able to hide anything important from Dottie. He had married a woman with an IQ of 155. And besides, New York was on fire. "I knew your father, Van," Jeb said. "We never had to ask him twice." "I told you I needed seventy-two hours to make up my mind." "You just call me whenever you reach a decision, Van. I'll be here in the Beltway." Jeb clicked off. As he labored on his computers in the back of the truck, Van thought darkly of the various times in his life when he should have felt terrorized. Basically, there weren't any. He'd had some strange experiences, here and there. Van could rightly say that he had been blooded out in the field. He was a civilian computer expert from a large, aggressive corporation. He'd taken part in five hacker raids with joint federal-state investigation teams. American computer cops often took large crowds with them when they raided computer hackers. This made it clear to the other, more everyday cops that kids sitting alone in their bedrooms really were committing crimes. So Van had been there when muscled Secret Service guys in their tasseled shoes and Kevlar armor were stomping from attic to basement, menacing Mom and Dad with drawn guns. Mom and Dad were always pretty terrified by this. Van just concentrated on the bagging-and-tagging, hauling Junior's piece-of-junk hotrod PC out to the white Chevy vans. Van rather liked that part of the assignment. Especially that look on the face of the code kid when he realized that he knew nothing about the people who really owned and ran the Internet. The hacking scene was pretty brainy as crime scenes went, but it did have down-and-dirty sides. Hacker kids were an ankle-biting nuisance, but the scene also featured ugly grown-ups who stole real money. Van's counsel had often been sought in such matters. Van knew more than anyone should know about the bad programming habits of Russian bank hackers. Vietnamese computer-chip theft rings were certainly no shrinking violets. A crime family of crazy, shotgun-toting hillbillies in West Virginia had preyed on Mondiale for years, stealing mile after mile of copper telephone cable and selling it for junk. The thought of their criminal lives and attitudes gave Van a metallic tang in his mouth. Van had never spent much brainpower on ethics, law, or philosophy, but Van could taste evil. Cops knew this about him. Cops regarded Van as a stand-up guy. Cops bought him beer. They respected the difficult things that he told them about network security and computer forensics, and they took the technical steps that he recommended. Van's software and his advice worked out pretty well for cops. Arrests and convictions followed, and cops liked that a lot. Since cops were underfoot and on the phone so much, Van had taught himself to speak the language of cops. He kind of liked the way that cops cut the crap. When people became cops, certain delicate, fussy, annoying parts of them got scraped off. Van understood this much more keenly after the events of September 11, 2001. The size and scale of what had happened . . . it had freed him from some complicated doubts and hesitations. Van was not saying much about these new perceptions. He was trying to figure out his proper place in the world to come. He stared at his wife as she cradled her infant and her phone with the same overloaded arm, the kid's noggin nudging her glasses up her cheek. Van was dragging his wife across America, from sea to shining sea, and Dottie could not tell her friends why she had left, or where she was going, or what it was all about. Because it was secret. Dottie understood about secret lives, because she had married a Vandeveer. She had met Van's father, mother, and even his grandfather, and got along with them better than Van did. The women in the Vandeveer family always caught on about the nature of government secrecy, even when their men never said much. But in the ten years of their marriage, Dottie had never had to deal hands-on with any serious secrecy, not like this. Cops, Dottie could handle: she was always very polite to cops. Dottie never cheated on taxes or broke any traffic laws. For her own peace of mind, Dottie had read the statute books of both Massachusetts and New Jersey. Spies were more secret than cops. Sometimes the spook world did lean in on Van. Spooks were getting very into cyber-security and infowar. The NSA had always been into computers, and the rest of the spook crowd were finding that world to be more and more sexy. Van had never looked for any spooks voluntarily. But people he knew intimately had lived in that secret world. They had been transformed à la _Buffy the Vampire Slayer._ Cops changed, but spooks really changed. Spooks could be totally alone, at home, asleep in some warm, dark room, and cold, curling dry-ice fumes would pour out from under their sheets. Government secrecy was already changing Dottie, right before Van's eyes. Van had a dark, interior, cavernous feeling, as if his life had crumbled at a touch. He stared at the passing Ohio landscape, annoyed to find it so Ohio-like. He badly missed his e-mail. There was no e-mail available to him inside the Rover. Once he got them both online again, Van figured, he could send Dottie a nice reassuring note. He loved Dottie, but he and Dottie always got along best by e-mail. E-mail was how he had first asked her out. E-mail was how they carried out their professional lives and coordinated their schedules. They often sent each other e-mail over the breakfast table when they were living inside the same house. They'd decided to have a child by e-mail. They'd been talking over e-mail about having another one. Van stubbornly assembled his hardware in the back of the truck, using racks and plastic cable ties. With the rear seats hauled out and left behind in New Jersey, the Range Rover was cozy for him, about the size and shape of a grad student's office cubicle. With the ongoing network crisis in Manhattan's pipes and antennas, Van figured that no one would notice his physical absence from Mondiale's Merwinster offices. Not as long as he stayed on the Internet around the clock. Van's life's work was software. Although he had seen it done, he would never splice a cable down a manhole. In smoldering Manhattan, Mondiale was trying to call-forward thousands of local numbers, porting them from a smashed and charred facility into underused third-party switching stations in Queens and Hackensack. The FCC was freaking out, so it was willing to let this strange experiment happen. Van knew that Mondiale's routing algorithms for "local number portability" were not going to scale up. Van knew that the porting code would break. It would break in some interesting ways. He might understand how it had broken, and where. He might figure out how to patch it. That would be nontrivial programming under tremendous time pressure, the kind that very few people could do. It was the most useful emergency service he could offer to his company. But to be available to his stricken coworkers, Van needed fast, efficient Internet access, all across America. This sounded pretty simple. But it wasn't simple. It was impossible. Most of the East Coast was okay for high-speed Net access, except for lower Manhattan, which was on fire now. If Van phoned ahead and called in some favors, he could drive in to campuses and computer centers, to hook up on the superfast Internet2 grid. Van was a regular veteran at the Joint Techs conference, the cabal of geeks and wonks who were building the Next Generation Internet. The sysadmins of Internet2 were very much Van's kind of people. Van had taught at Stanford before Mondiale had made him their world-beating business offer, so the West Coast was even friendlier to Van and his digital needs. There were also big islands of advanced technical sanity in places like Austin, Texas, and Madison, Wisconsin. But out here in Range Rover land, the Internet was a shambles. Van was rolling across America with two women and a baby, and the United States was huge. Van flew across America quite commonly, but he'd never rolled across it before. The USA had cyber-free boondocks that Van had never imagined were there. Cell phones worked for data delivery—sort of. Dottie was fitfully hooking her Motorola into her laptop, using power from the Rover's cigarette lighter. That might do for the occasional brief e-mail, but that certainly wasn't Van's idea of access. For Van, cell phones were like breath mints. Even on America's major interstates, which were spiked with cell-phone towers from coast to coast, those breath mints had big holes in the middle. Any dip in the highway could drop you right out of a download. Wireless laptops running on Wi-Fi worked only in Wi-Fi hot spots a hundred yards across. That left Van only one way to angle it: the zenith angle. Satellites, straight overhead. Internet access direct from Space, the Final Frontier. Van had never before used a satellite Internet service. He certainly knew that such things existed, but he lacked any reason to mess with them. Van had broadband Internet2 in his office and two T-1 trunk lines into his house. He needed to be practical, though. Outer space would just have to do. Dottie understood this, so she let him work. Dottie needed serious Net access even worse than Van did. Astrophysicists were the world's heaviest users of scientific broadband. When an astrophysicist wanted to "send a file," that meant some colossal mountain of data that would simulate the entire atmosphere of the gas-giant Jupiter. Astronomers had such ferocious need for bandwidth that they were up for any scheme that might get it for them, no matter how far-fetched. They even hooked millions of PCs together, in giant volunteer networks, that combed the galaxy around the clock for alien radio signals. Van was doing his best for the two of them. It was a family matter and a question of professional pride. Through misplaced company loyalty, Van had hastily found and grabbed one of Mondiale's "Cosmoband" Internet satellite rigs. Since the Cosmoband product was commercially available and sold off-the-shelf to Mondiale's customers, Van had assumed he would just hook up the dish and get going. But Mondiale had told the world an evil lie. Van's PCs worked. His Ethernet worked, after some effort. The batteries worked, until they ran out. The Cosmoband satellite rig was an alien from outer space. Like most commercial space companies, Cosmoband was battered and humbled. To the awful surprise of its starry-eyed investors, Cosmoband had lost hundreds of millions of dollars. Cosmoband's little fleet of leftover satellites were scraping the bottom of the cosmic barrel, haunting the niche markets, doing automatic meter-reading and freight-truck asset tracking. The crippled Cosmoband had been snapped up in one of Mondiale's legendary acquisition frenzies. This treatment only added to Cosmoband's troubles. Mondiale's brass ignored the company, because it lacked any go-go stock-booming growth rates. All the original Cosmoband rocket engineers had run away. Cosmoband's remaining people were a rabble of cheap hucksters. They offered their so-called Interplanetary Internet in tiny back-page ads in _Popular Mechanics_ and _Scientific American._ They had no service guarantees. No service person anywhere ever answered Cosmoband's phones. And their klutzy old software didn't mesh with Microsoft's new releases. Van wanted to punch a big metal hole through the top of the Rover, to install the Cosmoband dish on a truck mount. Dottie, who loved the truck, hated this idea, and worse yet, to do this was no use. No satellite dish ever worked on a car or truck that was moving. The least little bump or pothole always knocked satellite dishes right off their signal. Marveling at this gross stupidity, Van studied his blurry satellite documentation, badly printed in distant Korea. Baby Ted filled his diapers and shrieked until the Rover's walls rang with his rage. No one had explained to poor Ted why he had to spend forty-four hours and thirty-nine minutes strapped into a crashproofed car seat. Ted had turned from yuppie puppy into a mobile papoose in bondage. Ted was into a straight-out raw deal. At a darkened roadside stop near Springfield, Missouri, Dottie pumped gas, her delicate hands clutching the ridged nozzle and heaving Arab oil into the Range Rover's 24.6-gallon belly. Van was alarmed to find himself actually setting foot in the state of Missouri. He'd flown over the state dozens of times and had never touched Missouri in his life. But Missouri had Coca-Cola and gasoline. Missouri had a stop-and-go mart with a nice clear view of the southern horizon. The mart had heavy-duty power plugs on its outside walls. No one was watching them to see if somebody borrowed a lot of electricity. So Missouri would do. Yawning Helga, the peevish baby, and a frowning Dottie vanished in search of bathrooms, beef jerky, and Hershey bars. Van parked the Rover in a grimy corner of the tarmac, next to a dripping drain hole and a rusty Dumpster. He plugged in. Then he hauled out his big plastic satellite dish and a tangle of multicolored cables. He set up under moth-clouded streetlights. Passersby honked at him. The skeptical people of Missouri were laughing at him and his weird satellite gizmo. Cosmoband's mobile Internet dish looked like a half-melted white surfboard welded to a chrome bar stool. Van was a grown man with a beard and a bad temper, wrestling a _Star Wars_ Storm Trooper contraption. Shaking with road jitters, Van booted the ground-control positioner. The Cosmoband receiver whined and labored grumpily. Then, with dim, mechanical reluctance, it connected. The dish's target was dusty, old-fashioned, and underused. It was one-fifth the size of Van's Range Rover. And it was orbiting twenty-three thousand miles above the Earth. Van triumphantly sucked e-mail from the sky. Dottie appeared. "Honey bear, you want a Slurpee or something?" "Nope." She examined the cables. "Can I log on now?" "Yep. Right through the LAN." A smile broke. "That's great, Derek!" As the Rover rolled on, Van read all his mail. Then they stopped the truck again, he hauled the dish out, and grabbed fresh work out of a sequence of Mondiale internal Web sites. He struggled with Mondiale's broken router code. He spewed more mail back into the sky. Then he did this again. And again. He did it under the stars, and at dawn. Then he slept on the futon. Then he did it again. When they reached Burbank, Van was driving the Rover, the only one left awake. He was six hours ahead of schedule. They had crossed four time zones and broken speed laws in eight states. CHAPTER THREE BURBANK, CALIFORNIA, SEPTEMBER 14, 2001 **E** xcept for his bone-weariness and persistent itches inside his stale clothes, Van had no problem driving around Burbank. He had spent a lot of time in Burbank with his grandfather, in summers and on holidays. For a time, during his marriage to Grandmother Number Two, Elmer "Chuck" Vandeveer had owned a weekend ranch up in the hills, not far from the Ronald Reagan spread. The times spent on the ranch were Van's happiest childhood memories. He had much enjoyed falling off horses, setting fire to bales of hay, and shooting rats and rabbits there. Grandpa Chuck was one of the world's top aerodynamicists. As a jet designer, he tackled his toy ranch as a make-or-break project: feverishly digging post holes, efficiently splitting firewood. Even Grandpa's relaxation was high performance. Grandpa's only true home, the place where he logged all his overtime, the source of his deepest passions in life, was a windowless, two-story concrete bunker, near the Burbank airport. It had lead-lined rooms for antisurveillance. It was frequented by the Air Force elite and the CIA. Grandpa belonged to the Lockheed Skunk Works. The city of Burbank had exploded since Van's childhood in the 1970s, eating every orange grove and rolling up the hills. The palmy streets near the airport were still vaguely familiar to him. Van sensed that he himself had transformed even more radically than the town of Burbank. From a little kid with a popsicle stick, a stammer, bad allergies, and a plastic _Star Wars_ X-wing fighter, into a big, quiet, bearded geek with black glasses, smelling of sweat. Something wasn't adding up here. Van thumbed at the Rover's GPS, alarmed. He had input the proper street address, but he didn't recognize the neighborhood at all. This was not his grandfather's elder-care facility. Van had rarely seen his grandfather during the long hectic frenzy of the dot-com boom. Since he'd left Stanford, he'd scarcely seen his grandfather at all. Old folks' homes were far from cheerful places. Phone calls, e-mail, digital Christmas cards, and digital photos of the baby. That was pretty much it between himself and his grandpa Chuck. But now the GPS had guided him to a completely unknown destination. It appeared to be a private home, a cheap stucco duplex. Worse yet, it was only 6:17 in the morning, local California time. Van pulled to the overgrown grassy curb and stopped the Rover. He got out, and gently shut the solid door, with care for his sleeping brood. When he stretched, his cramped spine popped loudly in three places. Carpal tunnel twinged in his overworked wrists. Feeling lost and absurd, Van approached the front door. Duplex A belonged to "C. Chang," while Duplex B listed a "J. Srinivasan." Van had rushed headlong to California to find his grandfather mysteriously replaced by two immigrant families. And he had no other address for Elmer Vandeveer. Van dismally pondered his next move. It was past eight o'clock on the East Coast. He might call his mother in Georgia, and ask her if she knew anything about his grandfather's strange disappearance. Van's mother was long-divorced from his father. She had settled down with a gentlemanly Southern dentist, who spared her the impossible treatment she had gotten from Van's father. Van had never liked explaining difficult things to his mother, on the phone or off of it. Van and his mother were from two very different worlds. Van's world was serious and technical, while her world was just plain messy. Even though his mother meant well and tried to listen, she always ended up taking offense. For Van to call his own father was completely out of the question. Van never knew his father's phone number, or even if his father had a home or a phone. Not only did they not talk, they had nothing to say to each other. Van certainly wasn't going to call the local cops in Burbank and ask around for Missing Persons. The cops would page the NCIC database, and even twenty years into retirement, a top-secret engineer who built spy planes was not the kind of guy who ought to just go missing. That situation could get ugly fast. Van might, conceivably, ask Jeb for help. In the world of federal databases, Jeb knew everybody who was anybody. Jeb had been there on the ground floor, literally laying the pipes. But Jeb would be ticked-off that his star recruit had lost his own grandfather—and lacked the smarts to find him. Van decided to case the joint. That was risky and probably dumb, but at least it was practical. It didn't feel much worse than raiding some teenage hacker punk's house as the family snoozed. It was dawn, birds were twittering, and the place looked quiet and sleepy. Van opened a rusty wrought-iron gate thick with bougainvillea. He tiptoed warily down a narrow, weedy brick path, clustered with wet pink blooms. Was there one loose doorknob around here, maybe? Just one window left open to the California breezes? Any open entrance around here? Any system vulnerability where a nearsighted computer scientist, six feet one and putting on weight, might illegally break-and-enter the home of some total strangers? Had he gone completely insane? What the hell was he thinking here? At any moment Van expected the white flick of a motion-sensor light. The frenzied barking of a Doberman. The cocking of a shotgun. Van peeked warily through a barred window and around an untucked curtain. The Srinivasan home featured brightly patterned carpets, a sandalwood screen, a wicker couch with thick colorful pillows, and a silent TV. Dusty yellow garlands hung around a dead man's framed portrait on the far wall. Battling his sense of despair, Van cleaned his glasses on his shirttail. Then he sidled around the house. He heard a voice. Van edged closer and peered through another window, this one damp and grimy, with rusting iron bars and a warped sill of cheap aluminum. He had found a kid's room, a boy's, to judge by the cheery sports wallpaper and the sky-blue ceiling. The ceiling was hung with a dozen dusty airplane models, dangling on stout black threads. They were World War II fighters: a snarling P-51 Mustang, a Messerschmidt with the Iron Cross, a red-dotted Zero. A kid's wooden desk had a full set of modeling tools. Testor's enamels, brushes, tweezers, a big square magnifying-glass lamp, and a very odd kind of glue gun. A half-completed model was pinched by alligator clips in a jointed metal armature. The voice came from a gumdrop-colored Macintosh computer. Van disliked Macintoshes. First, because they were cute toys for artists rather than serious computers. Second, the female Macintosh voice that read error messages aloud sounded eerily like Dottie's voice. Not Dottie's normal voice, but the voice Dottie used when she was really upset with him. When Dottie was being very, very clear with him about something. The Macintosh was reading a text file aloud. The bedroom's faded walls, wallpapered in yellow race cars, were piled with battered white filing boxes. Many of the boxes had ruptured, spilling thick heaps of blue-stenciled engineering paper. Van's grandfather, wearing ratty pink slippers and a pale blue terry-cloth bathrobe, came shuffling from the open door of the bathroom. He settled himself with painful care on a plain metal stool in front of the desk. Then he clicked at his candy-colored one-button Macintosh mouse. "Step one," the Mac said in its female voice. "Attach C-1, Instrument Panel F, and C-2, Instrument Panel R, to A-1, fuselage top." Van's grandfather raised the arm of the lamp and made its beam hover over the desk. It threw thick shadows over the model's jigsaw bits of gray plastic. Van tapped at the window. It was no use. The old man was hard of hearing. His eyes were going, too. His hair was gone, a few untrimmed snowy wisps. The muscle had shrunk from his spindly legs. His once-thick neck was bent and baggy, and his face, once so round, so red and beefy, was pale and creased and liver-spotted. Van was gazing through the window into a time machine. It promised him a painful future of bypass surgery, of bellyaches and Rogaine. Van reached into his cargo pants and found his laser pointer. He beamed the laser's red dot through the window. The old man caught on. He rose from the metal stool and teetered to the iron-barred window. Van waved at him. Grandpa Chuck turned down the cheap window latch and tugged at the dew-spotted frame. The window was jammed. Van got a purchase on it with the screwdriver blade of his Swiss Army knife. The window jerked open an inch and a half. They gazed at each other through the bars. "How are you, son?" said the old man. "I'm fine, Grandpa. You?" "Not too good, not too bad." Van's grandfather scowled. His scowl was scary. He had been an important man, once. A man who gave orders and had them obeyed. "I know why you're here, son," the old man said, his pale eyes slitting under pouchy lids. "It's about those Boeings. The ones that hit those skyscrapers." "That's right," Van admitted. "So the CIA wants you back now, Robbie? I always said those spooks would have to come running back to you, didn't I?" "I'm not Robbie," Van blurted. "Robbie's my dad. It's me, Van. I mean, it's Derek." The old man's face gaped. "Little Derek? Robbie's little Derek? Derek the computer kid?" "Yeah, Grandpa. The feds are all over me. They want me to take a job in Washington." Grandpa lifted a liver-spotted hand and smoothed the remains of his hair. "Well, you'd better come in here, then." Van shook the iron bars. They had been poorly installed, tucked into the stucco with cheap Phillips-head screws. Five minutes with a power tool would have them all down. "Did you ring the doorbell?" the old man said patiently. "Mrs. Srinivasan should be making her congee now." Surprised, Van retreated. He brushed dew from the hems of his pants and rang the doorbell to Duplex B. It was answered by a stout older lady in a Hawaiian blouse, purple slacks, and rubber zoris. "Oh," Mrs. Srinivasan said, looking him up and down. "You must be Chuck's boy. I've heard so much about you." "I'm his grandson." "You look just like him." "Could I talk to Dr. Vandeveer? It's urgent." She opened the door politely. Van stepped inside. A glossy Hindu calendar with a technicolor goddess flapped gently on the wall. The place smelled of cone incense, Lipton tea, and tandoori. "Sorry to be so, uh, soon," Van said. "He's no trouble, darling," Mrs. Srinivasan said cheerily, leading Van down a scruffy, beige-carpeted hall. "We keep him in my son's old room. He wanders a little. He wanders a lot, don't you know." "I heard about that." "Sometimes he is also very stubborn, your grandfather." Van nodded. "Yeah." "Please don't let him smoke." Mrs. Srinivasan pulled a house key from a chain in her hefty bodice. She unlocked the door. His grandfather's cell smelled like a plastics refinery. He'd been using hot glue on his airplane models, something pungent. Worse yet, he'd somehow managed to set fire to his mattress. The narrow wooden bed frame had a long scorched scar under the wrinkled sheets. Van hugged his grandfather. The old man was stooped and bony, with the empty flabbiness of old age. "Little Derek," he said. "I brought my son here, Grandpa Chuck. Your great-grandson, Ted. Ted's out there in a truck." "Oh, wow." The old man stared at him peaceably. "Grandpa, I think I need your advice." "My advice, huh? Okey-doke!" The old man sat on his metal stool, and with a careful, visible effort, he crossed his legs. "Shoot!" "So, did you see what just went down in New York? And the Pentagon?" "I saw the President's speech on the TV," said the old man, growing livelier. "That kid is all right! He's not like his dad. Old George Bush, he used to come out to Area 51 when we were launching Blackbirds. Back when George was Company. 'Fifty thousand dollars an hour,' George Bush would say. No vision thing! He was a bean-counter! Anywhere on earth, any Sunday, a Blackbird could bring back pictures! High detail, too, shots the size of bedsheets!" "Great." "We never lost a pilot." "Right." "First ten pilots inside the Blackbird, nine of them became Air Force generals!" "Right, Grandpa." "Surveillance shots straight from Eastman Kodak, the size of dang tabletops! With a handful of planes. Every one of 'em handmade in Burbank!" Van had no reply to offer. An ugly thrill of weariness shot through him. He sat on the old man's reeking bed. It scrunched and shot a cloud of dust into a beam of morning sunlight. "Made out of _titanium_!" The old man brandished his glue gun. It was big, hollow, and shiny, with fins like a Flash Gordon ray gun. Van sat up. "Titanium, huh?" Van's grandfather quickly hid the titanium gun inside his desk. He forgot to unplug it, though, so the bright red cord simply trailed from the desk to the wall, an obvious trip hazard. "Robbie, if I say anything I'm not supposed to say, you just forget that. All right? You can just forget about all of it." He waved a hand at the crumbling boxes on his walls. "Don't look at all this." Van looked. "What?" "They ordered us to _destroy all the documents._ They ordered us to _break all our tools._ " The pain was still fresh in the old man's eyes. "That was the worst part, Robbie: when the politicians make you break your dang tools." He looked at the slumping wall of boxes. "The D-21, that's what this is. A cruise missile we built in 1963. Well, ol' Kelly Johnson had all these boxes stored in his garage in Alameda. He was supposed to burn 'em all. Burn every blueprint! But in Alameda? There woulda been an _air quality report_!" The old man chuckled wheezily. "Couldn't break those federal rules and regulations now, could he? The EPA wouldn't like the _smoke_! They'da sent ol' Kelly straight to Leavenworth! Ha ha ha!" "Why did they break your tools?" Van coaxed. "So we couldn't pull the D-21 back out of mothballs when the White House changed hands. Breaking the tools, son, that's the only way to kill a secret federal program and keep it dead. We built 'em a cruise missile twenty-five years before its time. Fifty Lockheed engineers and about a hundred union guys in our machine shop. We made that bird with our own hands. We fired it over Red China four times. At Mach 3. The Chinese never knew a dang thing about that." "Did it work?" "Radar signature the size of a Ping-Pong ball . . ." The old man lost interest suddenly. He groped at his bathrobe for a missing shirt pocket. Van recognized the gesture. He was missing his lighter, and his cigarettes. They'd made him stop smoking twenty years ago. "They make you burn everything," he groused, still patting at himself. "Then they give you a secret medal for doing that. What's the name of that new cartoon? That comic strip? That good one. The one with all the engineers in it." Enlightenment dawned. "You mean 'Dilbert'?" "That's right, that's the one!" The old man rose and teetered to the tiny closet. He opened the warped veneer door with a squeak and picked at a loose heap of uniformly colored golf shirts. None of them had any cigarette pockets in them. "Good old Dilbert. Well, in the Skunk Works, nobody ever had to be the Dilbert. Because Kelly Johnson wouldn't suffer a damn fool around for seven seconds. Whenever Kelly lowered the boom, the Air Force brass ran back to NORAD to cry in their three-percent beer." Grandpa Chuck chose a shirt and a loose, baggy pair of elastic sweatpants. Then he carefully sat on the narrow, stinking bed. He went through the extensive effort of pulling his baggy pants on, one leg at a time. His knees trembled pitifully. His back was very stiff. Van wanted to help his grandfather put his pants on, but there was something far too intimate about that. "Grandpa, the feds want me for some kind of cyber Skunk Works. It's really small. It's secret. It's elite." "Do they have a decent R&D budget?" "Well, yeah, that's what they tell me." "Take that job," his grandfather said. He tugged the stretchy waistband up over his bony hips. "Son, you never know what you can accomplish until you're in a Skunk Works. You pull that off right, and a Skunk Works makes big things happen. Big new things, son, genuine breakthroughs in engineering. Things competitors wouldn't believe. Things the _Congress_ wouldn't believe." The old man dropped his bathrobe and fingered his golf shirt, sitting there bare-chested. "The enemy believes it, though. The enemy, they pretty much always believe it. They even believed in Star Wars!" Van had never directly worked for the federal government. Occasional consulting as a favor to Jeb and his friends, sure, but no official title, and certainly no money ever changing hands. To get himself full-time, paying federal work, there were legendary ethics hassles. And the feds didn't pay well. If he went to work for Jeb, Dottie and he would lose a whole lot of money. "I'd have to leave my day job. Mondiale is a great company. They're building the future." "Son, can you do this job your country is asking you to do?" Van considered this. It surprised him that his grandfather would doubt his competence. He wasn't cocksure about dealing with Washington insiders, but he knew for a fact that he had few rivals in his own line of work. "Yeah, I can do it. If anybody can." "Who's your boss? Is he decent?" "Well, it's this new board for the, uh, National Security Council. There's a bunch of NSC Advisers, and one other guy. That's the guy who wants me on board." "You're working _direct for the Presiden_ _t_?" "I guess so. Sort of." Van blinked. "It's software." The old man closed his dropped jaw. "You'll grow into this, son! It'll broaden you! You _need_ some broadening. Computer people get way too specialized." The old man laced his veiny hands in a big knuckly knot. "No man should ever get too specialized." He took a breath, gazed at the wall with a fixed expression, and recited something. "'A human being should be able to change a diaper, plan an invasion, butcher a hog, design a building, write a sonnet, set a bone, comfort the dying, take orders, give orders, solve equations, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.' " "Who said all that?" said Van, impressed. "A great American writer. Robert A. Heinlein." The old man looked watery-eyed at his glowing Macintosh. "Are there any Heinlein e-books these days? Something this machine can read out loud to me? I can't handle that fine print anymore." "I'll get some for you, Grandpa," Van promised. "I tried to make Kelly Johnson read himself some Heinlein, but Kelly never read a novel after those Tom Swift books of his. _Tom Swift and His Airplane._ " The old man snorted. "Kelly Johnson decided to build airplanes when he was twelve years old." Twelve years old, mused Van. For him, that meant 1981. He had been eleven when his father brought home the Commodore Vic-20. He'd been twelve when he rebuilt it. "Son," his grandfather rasped, "if you'll be working for the feds, you do need some advice. Yes, you surely do. And I can tell you something real useful. That is, how to run a Skunk Works. Once you do that right, you can't ever forget." The old man was brightening. He looked many years younger now. "The right way is one way that gets results. Are you listening to me, son?" Van nodded soberly. "These are simple things. They're the principles. You gotta listen, that's number one. It's more important to listen to your own people than it is to tell 'em what to do. Decide, that's number two. Make your management decisions whenever they're needed. You can figure out later whether they were right or wrong. And believe. Don't ever try to build a project that you can't believe in. Because otherwise, when they cut your funding—and they will cut it—you won't be able to tell 'em with a straight face why they should go straight to hell." Van felt grateful. "Oh, yeah. This is the right stuff." "Son, government programs are just like people. They get slow as they get older. They get very stuck in their ways. That just won't do for a Skunk Works. You've got to be quick, you've got to be quiet, and you've got to be on time. You had your three principles, and those are your three rules." "Okay." "When I tell you 'quick,' that means small. Small teams, the best people, very restricted. Ten or twenty percent of the people that normal outfits would use. No long reports, ever. Never read a long report, and if a guy writes you one, fire him. No long meetings. You want to keep 'em all working close together, no distractions, focused on the project all the time. Everybody stays hands-on with the tools, everybody stays close to the aircraft. Stick with the machine, never back off. That's how you get results quick." "Should I record all this?" "Just _pay attention,_ dang it! It took good men a lifetime to figure this stuff out!" The old man was breathing harder. "When I say 'quiet,' that means no talking. You don't brag about what you're doing. Ever. You just do it, and you never demand any credit. If nobody ever knows who you are, then nobody knows what you did. Except for the enemy, of course." The old man cackled and coughed. "Every day, Russki spy-sats counted every car in our parking lots! Those spies in Moscow, they knew a lot more about my work than my own family ever did." There was a painful silence. This was by far the longest, frankest talk Van had ever had with his grandfather about work. Of course, he'd always known that his grandfather built jets, but a fine haze of Vandeveer family silence had always hung over the details. Van examined the yellow wallpaper. It was cracking and peeling in spots. "My second wife knew quite a lot about my work," the old man said defensively. "Because Angela was my secretary. So was my third wife. Well, Doris was not a secretary exactly. Doris was a headhunter from Northrop." The old man sighed. "I should never have jumped over to Northrop, but Ben Rich had the top job at the Skunk Works sewn up, and I just couldn't stand to work on civilian subsonics." "Give me the 'on time' part," Van prompted. "That was it! Right! You got to be on time! You got to do it when there are stars in their eyes about it! Before they get all bureaucratic, and start counting every nickel and dime! Timing is the hardest part, son: you gotta know when good enough will do. You gotta know when to quit." The old man tunneled his bony arms through his golf shirt. Static left the remnants of his hair like a windblown thistle. "Me, I got out. I got out at last. I should have got out earlier." "Why, Grandpa?" "Because of the Grease Machine." The old man made a bitter, money-pinching gesture. "The Grease Machine never needs maintenance, son. That Japanese Minister and his crooked payoffs . . . Lockheed was never the same. A Skunk Works is finished, once the Grease Machine takes over. Once the money beats the engineering, that's the end of it, son. Once the money beats the engineering, it's all just chrome and tail fins, after that." Van felt a pang at the depth of his grandfather's sorrow. He'd been all of seven years old during the Lockheed bribery scandal. Except for family reasons, Van would have known and cared nothing about it. It was just some obscure scandal from the Watergate era. In his later life, though, the subject had come up once. That was when a Japanese guy from DoCoMo had tried to explain to him why Japan was in so much trouble. Why Japan, with the world's best engineers and hottest products, had fallen into a hole. In the eighties they were on their way to running the world. In the nineties they were going nowhere. Somehow Van had always just known that defense contracting was a crooked business. How could anybody have any illusions there to get disillusioned about? Luckily, he himself was from the world of computers and telecommunications. A very different world. "Well . . ." that old man said. "That's it, son. That's all you need to know. Now you can go home and fix yourself a drink." Van's grandfather wandered restlessly back to his worktable, and discovered the red wire of his glue gun, hanging from the drawer. Surprised, he pulled the shiny gun out and set it carefully on the desktop. "Now don't you look at this," he said. "Grandpa, I've seen a hot-glue gun." "Not as hot as this one, kiddo. The boys in Burbank made me this when we got the Blackbird shaped and annealed. Titanium was Blackbird skin, it'll take Mach 3 when the shockwave's hot enough to melt lead!" He brandished the ray gun. "Here, let me turn this on." Van noted with alarm that the cheap wall socket was discolored and half-molten. "You shouldn't be melting any lead in here, Grandpa." "Oh, I can melt any kind of solder in this gun, no problem." His grandfather began searching through the dusty junk in a desk drawer. "Grandpa, let me have that thing." "This gun's too old for you. The boys made this for me back in '63. Chuck Vandeveer's Buck Rogers ray-blaster!" He smiled in delight. "That was a dang good joke, too. They were such great, funny guys." "Grandpa, I'll buy you a fresh glue gun at Home Depot." "But you can't have this gun. This one's mine. You really need this solder gun, boy? Why?" Van had no good reason to offer. The old man narrowed his eyes. "You can't tell me, huh? It's classified? It's electronics." "Oh, uhm, yeah." "Lotta hard soldering work in electronics. Vacuum tubes and such." "Sure," Van said gratefully. "Yeah." "You keep it then, Derek, son. You can keep it as long as you need it." "Thanks a lot." Van hastily unplugged the glue gun. Then he ripped some Velcro loose and stuffed the dangerous contraption into his baggiest cargo pocket. At least now the place wouldn't burn down. He waved his free hand at the walls. "Grandpa, how did you get in this place?" "I'm hiding out here, that's how! After I broke out of that damn nuthouse!" Grandpa Chuck tapped the thin skin on his skull. "Old Kelly, he never knew when to leave when the time was right! Hardening of the arteries up here, that was Kelly Johnson's problem . . . I used to see ol' Kelly laid up in his hospital bed, all crippled-up and cussing-out Allen Dulles, when Dulles was already dead . . . His mind went! Now my boy Srini, though . . . He's just this young kid, Srini, but he's a good engineer, one of my best . . . He fixed up this computer for me, to read things out loud for me . . . A lotta contract work now, he's a busy boy . . . This was his room." "He sure likes planes," Van observed. "I pay his mom room and board, you know. His mom, she's a widow now. Family values, that's a good deal." The old man turned back to his desk. He looked with resigned confusion on the clutter of small plastic parts. "Now this here was the P-38 Lightning. Kelly Johnson's first classic design. America killed Admiral Yamamoto with those P-38s." He tapped the plastic fuselage with a mechanical pencil. "So much for your Pearl Harbor, huh, Admiral? Welcome to hell!" One of Van's phones rang. He pulled it from a hip pocket. "Vandeveer." "Where are we?" came a plaintive cry. "Where are you?" It was Helga. "We're here now. We're in Burbank." "But there's no one in the street! I looked everywhere! I'm scared. Why don't these phones work better? I forget which big numbers to dial first." "I'll come get you," Van promised. "Is Disneyland in this town?" "I'll just come get you, Helga." Van opened the bedroom door to leave. Surprised, his grandfather came after him in a shuffling old man's hustle. The old man swung his arms. "I never got to work on the Lightning. That was before my time. But that's your future, boy! That Pearl Harbor business!" He bared his irregular teeth. "Dang, I'm hungry." Once in the hall, Grandpa Chuck briskly turned the wrong way and hastened to an outside door. He clawed at the round brass doorknob, his fingers slipping. The doorknob clicked, but the door was firmly locked at the top with a cheap brass bolt. Grandpa Chuck never looked up at the bolt. He never thought to do it. He just pawed at the round brass knob, muttering in frustration, while Van stared at him in dismay. The old man gave up at last, and tried to look jaunty. "How's about some breakfast, son?" Van followed his barefoot grandfather into the kitchen. Mrs. Srinivasan was there, quiet and polite. She fetched the old man a box of bran flakes, some whole milk, an indestructible metal bowl with a big wooden spoon. The old man sat at the corner of the Formica table, scowling at her. "Television," he snapped. She obediently clicked the set on. Van left Mrs. Srinivasan's duplex and fetched Helga from the street. Helga was overjoyed to see him. She chattered at him nervously. Van put up with this. Helga was tall, shapely, and gushy. Van knew that for some men she had a lot of sex appeal, but he had never understood why. She was not his type at all and he had never felt even a twinge of chemistry. Van was pleased that Helga was good with infants, but basically he felt about Helga the way he might feel about a tame llama. Inside the duplex, Mrs. Srinivasan and Helga stared at each other as if they had come not from Sweden and India, but from Venus and Jupiter. They both seemed like decent women to Van, or at least okay women, but they couldn't get the remotest grip on one another. They kept addressing each other through Van: "Ask your blond girl if she wants to sit down," "Ask the nice lady if she has a real bathroom here, you know, with a toilet." Irritated, the old man turned up his morning cable news show. The TV blared war and terror, headache pills and paper towels, suicide and revenge. Mrs. Srinivasan's phone rang. It was her neighbor, Mr. Chang. Mr. Chang was surprised at all the morning ruckus. He wanted to make sure that she wasn't being robbed. Mrs. Srinivasan was an Indian widow with an elderly man in her care. She seemed very reliant on Mr. Chang, who was the retired owner of a Chinese grocery. There was nothing for it but to have Mr. Chang come right over. He did. He was small and gray-haired and bent, with pants belted high above his waist. Mr. Chang examined the visitors. He sat on Mrs. Srinivasan's lavishly pillowed wicker couch, and rolled himself a cigarette. Mr. Chang put such luscious handiwork into this that it was clear that smoking was his full-time occupation. Mrs. Srinivasan set out green tea. Another of Van's cell phones rang. Dottie had awoken inside the truck. She arrived with the baby. The arrival of little Ted broke Grandpa Chuck's foul mood. Van helped Grandpa Chuck to the wicker couch and put Ted on his bony knee. The two of them together looked postcard-cute. Even Mr. Chang was forced to smile. Van felt stunned. His grandfather and his son looked eerily alike, same round faces, same blinky, distracted stares. Dottie plucked Ted free from the old man before Ted's uneasiness could grow into sobs. Using her baby as a wedge, Dottie swiftly broke the ice between Helga and Mrs. Srinivasan. Soon the three women were clucking over Ted in a happy international hen party. Van's stomach rumbled and his mood darkened. Van realized that he was starving. Clearly Mrs. Srinivasan lacked the provisions to feed this sudden crowd of adults. "Kentucky Fried Chicken?" Van hypothesized. His insight met with swift approval. Mrs. Srinivasan was vegetarian, but not on special occasions. For Mr. Chang, Kentucky Fried Chicken was the height of luxury from the Red Chinese cultural thaw. Helga loved American fast food. Grandpa and Ted could suck on the crusts. Van left in the Rover and fetched a big family bucket of extra crispy. Driving the Rover again, even for a few more blocks, was like having sunburned skin rubbed. When Van returned to the duplex, two more strangers had arrived. One was a middle-aged, olive-skinned woman, in a tailored black pants suit and a hooded khaki jacket. The other was an older, distinguished man, in designer jeans, with a gold earring and graying blond ponytail. The man was his father. A sudden hush fell. "Is that Kentucky Fried Chicken?" his father said at last. "Uh, yeah, Dad." "For breakfast?" "Yep." Van set the cardboard bucket down defiantly. His father took a breath and emitted a quotation. "'Let me prescribe the diet of the country; I do not care who makes its laws.' " Van felt a familiar despair. Why was his father always like this? Why didn't he just say whatever he meant directly? Why did he have to dig into his big, 1968-hippie head, and come up with some kind of weird, senseless, semipolitical quotation? Van's dad was a former Rhodes scholar. He was ruinously gifted. Van's father was literally the only human being in the world who spoke both Afghan Pashtun and African Bantu dialects. He was also the only man Van knew who carried on conversations, in real life, using semicolons that you could actually hear. Van looked at his father glumly. His father looked bad: piratical, slick, and never to be trusted. But he didn't look quite so bad as he normally did. He was, for instance, sober. His father offered Van a brisk, cheery "Your dad is here, all is well" smile, a smile as thin, flimsy, and phony as individually wrapped lunch meat baloney. How had his father found out that Van was in California? How had he shown up here at this building? Without a word, a phone call, an e-mail, or a whisper of permission! The guy was impossible. "It's more of an early lunch," Dottie offered kindly. In the rare moments when her erratic father-in-law drifted into her life, Dottie loved to play the peacemaker. "This smells good!" declared Helga, eagerly helping herself to the chicken bucket. Then everyone went for the chow in a merry outburst of chattering, except for Van, who had lost his appetite. To cover his pain and confusion, he gave an extra-crispy thigh to his grandfather, who seemed lost in the crowd now, tired and bewildered, forgotten. Van could not understand why his painful personal problems were suddenly the business of Swedes, Indians, and Chinese. They seemed pretty pleased with the fast food he had brought them, but how could such a thing have ever happened? "Son, this is Rachel Weissman," his father said, introducing the latest girlfriend. "Hi," Van told her reluctantly. Rachel half curtseyed to grab up her chicken from the cardboard bucket. There was something very wrong with her hip. "Where are you from, Rachel?" Dottie asked her. "I'm from Bogota," Rachel lied. "I work in oil." "Rachel and I have a beautiful residencia north of the city," his father aided and abetted. Dottie blinked at them. "So you're really at home in Colombia now, Robert? To stay?" "It's never like it sounds in the media. 'Nature gives to every time and season some beauties of its own.' " Van's father gave Rachel a warm, protective look. Rachel was in even worse trouble than Van had imagined. Rachel was obviously Jewish, but she wasn't Colombian, Van concluded. His father looked much more Colombian than Rachel did, despite his blondness and his hefty bulk. Van's father was solid as a bear, but even before he had joined the CIA, there had always been something spacey and strange about him. When they'd finally shunted him into Counter-Narcotics, that dead end of any intelligence career, that was when his pride had broken down. During the eighties, Afghanistan had cheered him up for a while. He'd shaped up physically, patched up the marriage, and even taken Van camping and fishing in the California mountains. But in Angola, he'd done something indescribable. Generally the CIA never gave its top agents Third World assignments that risked malaria and guaranteed diarrhea, but Van's father was a charmer. He had a genius for working himself into situations where he was unwelcome, unneeded, unwanted, and way too smart for the job. In Angola, Van's father had crossed some line, into some mess he just couldn't mentally manage. Something oily and permanent had stuck to him for good in Angola. He'd returned from Angola with unblinking eyes like two saucers, quoting more poetry than ever before . . . Nightmare episodes in Van's adolescence, when his mother would scream in betrayed anguish, and his father would storm into his home office, to snort cocaine and translate Walt Whitman into African dialects. Those were the moments when Van would quietly shut his bedroom door, warm up the modem, and vanish deep, deep, deep into his computer. In some sense, Van had never come out. Dottie was doing all the talking for the group. Her lips were moving rapidly as Van stood there, moored in his silent crisis. For the first time Van realized what Dottie was actually saying. She had had a lot of time to think in the car, and she had bravely made up her mind about something. Dottie was talking about quitting her lab post in Boston and taking up an entirely different job. "So it's the perfect time for me to undertake a transition, if Derek is also switching careers," she confided to everyone. "Mmm-hmmm." His father nodded unhelpfully. "I do have a standing offer. Because Tony Carew . . . have you ever heard of Tony Carew? Tony is the only friend of ours who's really famous. The Davos Forum, the Renaissance Weekend . . ." "I've certainly heard of those," said Rachel, looking interested for the first time. "Oh, I see," said his father. "So then, Derek. Tony must be that good friend of yours who works for Thomas DeFanti." Van saw that a response was required of him. "Sort of." Rachel bored right in. "Have you ever met Thomas DeFanti, Dr. Vandeveer?" "Yes," Van and Dottie chorused. They both always answered to "Dr. Vandeveer." "That'll be my new research post in Colorado," Dottie said. "With one of Thomas DeFanti's foundations. He's always been a very big supporter of astronomy." This whole business was very like Dottie, Van thought sadly. If he chose to mess up their fragile, tender status quo, then she would not fight with him about it. No, she would cooperate fully, by messing up their lives even faster. Would Dottie really move all the way from Boston to the Rocky Mountains while he'd be moving from New Jersey to Washington, and working for Jeb's outfit? There would be nothing left of their life together. Well, there would be e-mail. Helga happily chowed down on her chicken wing. Helga didn't realize it yet, but soon, very soon, Van would have to fire her. He didn't have any place to keep her. Her nicely furnished suite in Merwinster would be history. Van pulled a chunk of chicken from the bucket and jammed it in his mouth. He gnawed silently as the rest of them chattered happily. Then Van dumped his bare chicken bone and went out to the Rover. He beeped it open and fetched the Iridium phone. It was heavy and shaped like a brick. Van hadn't yet had a chance to try out an Iridium phone. The phones were clumsy, expensive, and didn't work indoors. The Iridium satellite network had gone broke—but at the last minute, the new post-bankruptcy owners had been rescued by the U.S. Defense Department. The U.S. military had suddenly realized that it might be pretty handy to have phones that worked off-road in places like Afghanistan. Now Van would take the plunge for the first time as well. A fatal announcement like accepting Jeb's job was worth the ridiculous Iridium charge of two dollars a minute. His father hastened after him. He had a bleak, naked look on his face. "I know that they want you in Washington, son! But you don't have to go through with that. There's no need for it!" Van shrugged sheepishly. A teenager's gesture. "Think about it. What are you going to get out of this? Do you want a Christmas card from Henry Kissinger? Son, I _know_ people from al Qaeda. I've met them. They don't matter in this world. The only way they can matter is to kill themselves inside our jets and buildings. Al Qaeda can't build anything. They can't invent anything. But you can, son. You're a builder, you're an innovator. People like you are making people like them matter less every day." "Look, Dad, I write software, okay? Don't get all philosophical. I'm never going to shoot anybody. But computer security matters." Van sighed miserably. "That scene is just so bad. You don't know what it's like to run those networks. Nobody knows who hasn't done it. It's a much, much bigger mess in there than any normal person imagines. It's been neglected way too long." Van's grandfather appeared at the door of the duplex. No one had been watching over him. He took off down the sidewalk at a brisk walk. "Every big outfit gets like that, son," his father insisted. "If he wasn't in jail now, I'd take you to meet Aldrich Ames. That son of a bitch is the poster boy for the crisis inside the Company." His father groaned. "He sold out every asset we had inside Russia. And no one in the Congress even noticed that Ames did that, ever! We had brave people dying who were never missed." "Dad, the Internet gets kicked flat by teenagers in Canada. That just won't do." The two of them apprehended his grandfather. "I'm going out for some Marlboros," the old man protested. "I want you to have a happy life, son," his father insisted, taking a firm grip on his grandfather's bony upper arm. "You have everything, Derek. You're a big success, you're enjoying your life. She's a sweet girl who loves you, that's a wonderful baby. Do you know what you're risking there? You'll never get that back." "I don't get off that easy, Dad. They need me. Because they know I can help. Everybody else has screwed it up." "Derek, if you work inside the Beltway, the people who screw things up are gonna become your best friends. They're going to be your best war buddies. You're gonna encounter people worse than you can imagine, with problems that don't bear thinking about. There's no reason for someone like you to become one of them." "No, there's a very good reason, Dad. I know I can make a difference, so I have to try. If nobody ever tries to fix the world of the Internet, the future will just turn into . . ." Van broke off. This was a very long speech for him, and his father wasn't getting it at all. He realized that his father thought of him as a soft, dreamy person, from a lucky generation, leading a charmed life. Van didn't know whether to feel rage or pity, so he felt what he always felt with his father: gloomy confusion. He began to shout. "The Internet turns into hell! Some awful, total mess! Where every single decent company goes broke. Viruses and worms breaking everything. Lawsuits everywhere you look. Where crazy people from the very worst places on earth try to rip you off with bank frauds and drugs and filthy pictures . . ." His father looked at him with alarm. His grandfather was totally bewildered by Van's outburst. Van sounded wild and crazy, even to himself. Why let on about the nightmare cyber-scenario? He should never have opened his mouth, he thought. He was crushing their cherished, old-fashioned ideals. There were horrors in the world beyond their understanding. CHAPTER FOUR CHECHNYA, NOVEMBER 2001 **T** he American agents inside Chechnya were rapidly improving their disguises. The Americans would never seem at home in the Caucasus, though. They didn't have lice, nor did they stink. The Colonel was sharing a rocky, blasted ledge with the American agent called Kickoff. The two of them were very close, so close as to be quite intimate. Kickoff wore a black fur hat and crumpled Soviet combat fatigues. To that extent, Kickoff looked normal for Chechnya. Yet his teeth were white and perfect beneath his salt-and-pepper beard, and his skin was uncannily clean. Silky mountain-climbing underwear kept his precious American body toasty from wrist to ankles. Kickoff wore strong, beautifully knitted socks. He even wore sock _liners._ Thin, magical membranes that kept the painful rot of trench foot away. They were like condoms for his feet. The Colonel himself stank badly of sweat, fear, boredom, vodka, and strong cigarettes. But his personal reek was lost in the awesome stench from a dead donkey's rotting haunch and fetlock. Endless skirmishes had been fought over this vulnerable run of the Chechnyan pipeline. The shallow little cave the Colonel shared with Kickoff was a well-known bandit lair. It was routinely scourged by passing federal helicopters. Every once in a while the lightning-sticks would blow a smuggler's donkey apart. Tonight he and Kickoff would be killing bandits. Not all of them, of course. Just enough to prove a concept to Kickoff's employers. There were not enough soldiers in all the world to guard all the world's pipelines from all the world's thieves, saboteurs, and vandals. That task would have to be automated somehow, for those pipelines were the arteries of all the world's machines. Like clouding mosquitoes, human bandits had learned to pierce those pipes and drink deep. So, in return, the threatened machines would have to learn to seek, hunt, and kill. Kickoff handed the Colonel his heavy, brick-shaped satellite phone. "Hello again, Alexei," said the phone in Russian. "Hi sexy," said the Colonel, his morale improving at once. It no longer seemed odd to the Colonel that he talked on a satellite telephone to a distant woman in Bethesda, Maryland, merely in order to communicate with Kickoff. Kickoff knew no more than a dozen words of Russian. Yet Kickoff was a practical man. If he couldn't haul his translator into a killing zone, he would simply phone her. "We've grown so intimate in such a short time, my dear," the Colonel said into the phone. "Yet I understand we'll be parting soon." "I'm sad about that, too. But it's the nature of their business, dear Alexei." Kickoff zippered open his dappled weapons bag. He produced a marvelous, long-barreled sniper rifle, made of carbon fiber, polished fiberglass, and dense white plastic. He then seized the phone and barked into it. The Colonel accepted the phone once again. "That was a whole lot of stupid technical crap about his big gun," the woman said. "Are you interested in that? Should I bother?" Kickoff was ex-American military—he had a soldier's eyes—but he was officially a civilian consultant. This was the first time the Colonel had ever seen Kickoff handle a weapon. Kickoff's lethal machine was a Western .50-caliber rifle, privately produced. Pampered special-ops gangs carried toys of that sort when, unlike Russian troops in Chechnya, they were not killing Moslem terrorists in the mud and blood every single day. "Darling, I'm interested if you're interested. You tell me all about it. Just how wonderful is Kickoff's big gun?" "Oh, in bed, I suppose you mean. Well, he's wonderful in bed," said the woman coolly. She was an American, and completely lost to modesty. The Colonel liked her very much for this. It was so refreshing. "He's in good condition, with a handsome face," the Colonel told her. "Such good teeth Kickoff has." "His name is not 'Kickoff.' His name is Michael Hickok." The Colonel mulled over this correction. "Hickok, Kickoff." For the life of him, he couldn't hear any difference there. And why would that matter anyway, when they never spoke except through her, their translator? Women had such odd priorities. "Does he love you at all?" the Colonel asked. "Does that matter to him?" "Not one bit does he love me." She was bitter. "He doesn't even know what that means. 'Have a nice day,' that is what he tells me. Oh, and he buys me cheap, sexy underwear." "My dear, how is it that we human beings forgot how to love? How did the world even come to such a state?" said the Colonel, warming to his theme. "Since this may be my last chance to ask you, may I seek your customary good advice in an intimate matter? I must decide what to do about Natalya." "You shouldn't even ask me about that, Alexei. I never have any luck." "If I leave Natalya here, the bandits kill her for being my mistress. If I take her home to Petersburg, the mafia kills her because she is dark. If we stay here in the Caucasus, then they kill both of us, eventually. And then there's my wife, of course. What on earth is to be done?" "All right, I'll tell you. Get some money and leave Russia. My mother emigrated to New York in 1978. So my dear mother is finally free of Russia, and I, her only beloved daughter, now I have hopeless affairs with crazy American mercenaries." The woman sighed in pain from the far side of the world. "At least 'Executive Solutions' got me this great translator job. They've got medical, dental, everything. I could get liposuction." Kickoff brusquely seized the phone again. "Now he wants you to look through his big rifle's telescope," the woman reported. "He's also angry that you spend so much time talking to me, while you hardly say one single word to him." "That's because you are so wise and charming, while he is merely a professional killer. Can we discuss something truly important now? My Natalya is the only happy woman in Chechnya. That is the truth. There is something so profoundly erotic about surrendering yourself to a deadly enemy . . . Natalya has a holy, abject quality, very feminine . . . It's as if she absorbs me . . . I'm bewildered by it, it's a spiritual calamity . . . I used to rage at her, helplessly, confusedly . . . I love her so much that I can't even drink anymore . . ." Kickoff gestured impatiently at the enormous rifle. Wearied by his duty, the Colonel lowered himself to his elbows and obediently gazed through the black rubber-cupped eyepiece. He had seen night-vision goggles before. Alfa troops had them. But never a device like this. This was fantastic. The rifle's scope opened up the Chechen evening like the eye of an owl. Now Kickoff was growling into the phone at the embittered woman in America. The American's corporate sponsors had sent Kickoff here with a huge stack of war toys and no language skills. Kickoff had ventured into the wilds of Chechnya with three little toy robot airplanes, six videocameras, a hundred delicate wind gauges, satellite phones, solar panels, a shatterproof military computer in a camouflaged gunmetal case . . . Kickoff bore a stack of cash, and many discreet documents issued by various oligarchs and moguls. Tyumen Oil and ConocoPhilips, LUKoil and ExxonMobil, Sibneft, Halliburton and ChevronTexaco. The signature of Igor Yusufov of the Energy Ministry was much in evidence in Kickoff's papers. Alexei Kuznetsov, Thomas DeFanti, Mikhail Khodorkovsky. There was even an importation permit signed by no less a man than Vladimir Putin. It was not that Kickoff knew these important men personally, or that they would ever need to know him. However, they seemed to feel some need for the services Kickoff provided. When Kickoff declared that was he not a spy, but an American working legally on contract from civilian companies, he was probably telling the truth. The Colonel shifted Kickoff's weapon on its bipod and trailed the eerie scope across the wrecked and glowing landscape. Repeated bombings had reduced the local storage tanks to fragments of riveted steel. Spindly trees, ten years old, grew from the tortured heaps of black tarmac and bad concrete. The hotter surfaces glowed vividly in the scope's computer lens. It looked uncanny, surgical, as if the veins of the earth had opened and bled. Why was such visual poetry restricted to the mundane work of shooting pipeline thieves? The Colonel daintily twiddled a diopter. The crescent Moon grew huge in the rifle's crosshairs, blooming in a square rush of pixels. Now the Moon looked big and cheese-orange, like a rind of fancy pizza from Moscow's finest Pizza Hut. Machine analysis worked its magic inside the rifle's optics. The blazing crescent of the Moon toned down, down, and the vast dark plain between the lunar horns emerged in the Colonel's vision. This was, thought the Colonel with holy awe, the Moon shining gently back at him in light reflected from the Earth. A small red glow winked at him within a lunar crater. The Colonel was pleased; the way that red light splashed brought the Moon's rounded qualities into startling life. A moment later it occurred to the Colonel that there should not be any lights visible on the Moon. There should be no lights on the Moon at all. After all, it was the Moon. A second red light splashed and flickered, this time within another crater. The Colonel pulled his eye from the rubber lens cup and stared at the Moon bare-eyed. To his human gaze, the Moon was a small, distant crescent. The red light was far too faint to see with the naked eye . . . But no, this was an infrared scope. He was seeing _heat_ on the Moon, not light. His wondering eye sought the rifle yet again. The red spark was playing steadily, frolicking across the Moon's surface, a shimmer and a glow. The Colonel grabbed the phone. "Please tell Kickoff that I just saw something bizarre on the Moon. Volcanoes, I think." "What? I can't translate that." "Lunar volcanoes! Red eruptions on the Moon! I saw them through the sighting-scope on his rifle." She laughed. "Oh, that? You mean that digital thing? That thing is _digital,_ Alexei." Excited tension drained swiftly from the Colonel's neck. Of course. Just a fault inside the stupid equipment. Were there really space aliens up there, live volcanoes on the holy Moon—or just a pixel or two, turned red inside some screen? What foolishness. Kickoff tugged at the Colonel's sleeve. Kickoff gestured at his laptop. His tiny airplanes, hidden in the night sky, were sending him fresh pictures. A Toyota pickup truck, spanking-new and doubtless Saudi-supplied, was working its way up the gorge. The Colonel held up his leather-gloved fingers: two. There would be two trucks, for there always were. There would also be bandits on foot to escort them, with rifles and walkie-talkies. Kickoff shook his head and made a throat-cutting gesture. Kickoff didn't care to wait for the chance of bagging both the trucks. That was not necessary to Kickoff's technical purposes. His assignment, it seemed, was merely to field-test the equipment and the support system. Kickoff gently plugged a small video wire and jack into the side of the rifle's scope. He blew dust from a flat plastic wafer and inserted a fresh, spotless disk from a jewellike case. Then he urged the Colonel on. The Colonel nodded and bent to his labors. The first .50-caliber round, a thumb-sized lozenge of spinning steel, flew through the Toyota's hood and completely through its engine block. As the truck lurched to a stop, the Colonel put two more rounds through the exploding glass and metal of the cab. The spidery white gun kicked very gently on its bipod. There was a high-pitched hiss of escaping gas. And yet, no burst of visible fire from the long black barrel. The rifle was gentle, surgical. The rifle almost fired itself. A glowing human figure burst free of the shattered truck, and the Colonel missed him as he fled. The fourth round struck him true, though. The oil thief tumbled instantly into two hot glowing pieces: a ruptured carcass, and a severed, spinning arm. The Colonel sought the phone. "Tell him that we need to leave this cave now. There will be other bandits. They are never afraid of us, and they will want this weapon very badly." Kickoff listened politely to the anxious squeak from the phone. He made an air-circling gesture. The Colonel leaned in toward the mouthpiece. "I don't care how many toy airplanes he has, or what they can see. We're in the dark, next to bandits on foot, moving under cover. They will fire rockets on us from far up the slope, above the cave. Oh, and tell him it's a lovely gun." Kickoff listened to the reply and made an extensive prepared speech. "Alexei, he says to thank you for the compliment. He also says he's coming home to see me." She was excited. "And he's taking our satellite phone away, my dear?" "Of course he's taking our phone. But he's not taking that gun, Alexei. He's not supposed to carry it inside America. He says that you should keep it. He says he knows a good soldier can use a good gun. He wants you to know that he appreciates you." "He's a generous man with a gift, your big friend here." Kickoff was giving a soldier a fine weapon, instead of some mere sordid bribe of dollars. That was very tactful of the American. The Colonel was touched. A handsome gift like this was a clear hint that the two of them would meet again in the future. That seemed probable enough. There certainly wasn't likely to be any shortage of oil thieves. "Trust me, Alexei, he didn't pay for that gun himself." "Oh, no. Of course Kickoff didn't pay for it." Yet others would. A fancy rifle like this was worth a great deal of money. Especially in the right set of wrong hands. The Colonel winced a little at that thought. Young Russian troopers, bewildered, conscripted, doomed, their flesh flying apart under those silent ferocious impacts . . . But only one side in Chechnya was awash in cash. That was not his own side. His side was merely a national army, not a global conspiracy. His side was always broke. The thought didn't bear contemplation. And yet, and yet, Natalya. Yes, if fate demanded it, he could do a thing like that for Natalya's sake. Because love conquered all. CHAPTER FIVE WASHINGTON, D.C., DECEMBER 2001 **T** all yellow cranes were digging black wreckage from the Pentagon. American flags the size of basketball courts covered the walls of federal offices, Old Glory the Battle Flag as a kind of angry wallpaper. Truck bomb barriers, strangely disguised as concrete flower pots, bloomed right, left, and center. The streets around the White House had become empty asphalt malls, where jittery tourists lurked in ones and twos. The newly formed Coordination of Critical Information Assurance Board met in the Old Executive Building, under the sponsorship of the Vice President. The badly overcrowded conference room had leather club chairs, steel coffee urns, lots of dented mahogany, and an ancient oil painting of an elder statesman named John C. Calhoun. Mr. Calhoun didn't look happy. Neither did the crowd. If Van didn't know all the faces, he knew the institutions. Every major federal bureaucracy had some kind of stake in computer security work. The Justice Department with the FBI, the Treasury with their Secret Service. The Department of Defense had a Defense Information Systems Agency. The Air Force was high-flying and enthusiastic, while the Navy worked to keep up steam. The Commerce Department, the National Institute of Standards and Technology. NASA was there. The Computer Emergency Response Team, the Federal Law Enforcement Training Center. Even one lonely computer whiz from the Railroad Retirement Board. The National Security Council, Van's new employer, had sent out the invitations. This was their first big dance. If this shindig worked out, then a lot of things might work out. If this didn't work, then Van had just blown his career for a swift bureaucratic fiasco. With a thirty-year career in computer crimebusting, Jeb was a living dinosaur of computer security. Jeb had trained a lot of the people in this conference room, and most of them owed him favors. Van had a gold-star reputation as a coder, but was a personal stranger to most of these people. Most of them were strangers to one another. This was the cyber-version of a larger story happening all over the federal government, from Pennsylvania Avenue, to Quantico, to Fort Meade, to Pentagon City. Since 9/11, all federal security agencies had been suffering a scary process that they called "melting stovepipes." People who had spent their whole lives inside narrow institutional channels were forced to network with other feds that they'd never met. Who were these strangers from distant, scary wings of the U.S. government? Were they rivals? Allies? Neutrals? No one even knew. The new Homeland Security empire was going to eat up any number of proud, independent agencies. Some said six, some said twelve, and some said twenty-two. This meant that no one's turf was safe anymore. It also meant something more promising, though. It meant opportunity: the biggest federal re-org in forty years. It meant that the right bunch of computer-security geeks, in the right place with the right tools and attitude, might break out from obscurity. Bold nerds from some mainframe garage in the Commerce Department might end up giving marching orders to the Secret Service. Jeb was the kind of man that computer people naturally turned to in a crisis. Jeb rather resembled Jabba the Hutt, if _Star Wars_ characters had been cops from Texas. Jeb's mood, always dark and cynical, had ratcheted up several notches to grimly militant. Jeb had the rigid-eyed stare of a man who was summing up his life's work and laying it right on the line. Jeb had shaved his cherished beard, revealing a nest of pale double chins. Jeb had even found somebody in Washington willing to cut him an enormous blue serge suit. Van had never seen Jeb answer to "Dr. Jeremijenko" before. Jeb Jeremijenko didn't even have a real doctorate. No one ever used his unspellable last name. Jeb had learned his computer security as a street cop who had stumbled over a UNIVAC in Houston in the 1960s. Banging a mahogany table with the meaty flat of his hand, Jeb hushed the chaos in the room. By getting together in this very, very quiet way, Jeb bellowed, they could get some useful progress made in the stupefying mess that was federal computer-security policy. In other words, they could finally settle down and cut the crap. No one objected to Jeb's frank assessment of the work at hand. American federal agencies had owned and used computers longer than anybody else in the world. That was bad news rather than good, for it meant that the federal government had the world's oldest, creakiest, cruftiest, most messed-up systems. Everybody who knew anything about the reality behind the scenes knew that it was awful. Computer security was obscure, ultra-technical, underfunded. It was scattered and amateurish. There was nobody in charge. There were no firm policies and no accountability. And the budgets? Laughable! However: after September 11, a day of reckoning had finally arrived. Jeb knew it. The crowd knew it. Congress knew it. Anybody who watched the news or read the papers knew it. The old lazy, scatterbrained ways just weren't going to cut it anymore. Every great crisis was also a great opportunity for people with the guts to dare and win. Now, Jeb declared, was the vital moment to level with each other, get a strong sense of the will and abilities of the computer-security community, and to really clear the air for solid, effective action. Van knew that this sermon of Jeb's meant big trouble. Jeb was positioning the CCIAB to become a kamikaze high-tech outfit that played fast and loose with the old rules. Van was okay with that risk. Realistically, there wasn't any other choice. If he, Derek R. Vandeveer, was ever going to become an effective federal security official, then Washington was going to have to ditch old rules by the bucketful. Some busybody think-tanker from the Competitive Enterprise Institute went trolling for Van: "Does our Stanford professor concur with Dr. Jeremijenko's unorthodox approach?" "Be quiet!" Van roared back. "Be quick! And be on time." Nobody had any idea what Van meant by this, but the startled conference room went silent for twenty-five seconds. Nobody else asked Van another question, which was great. Van hated meetings. He never did at all well in them. He knew that he was there as a potted plant for Jeb to exhibit: one bona fide, certified computer genius, pulled in from the best R&D lab in a top company. It made no sense for him to try to out-politic federal bureaucrats. Van had invented a solid program for his new career. Since he had to be a potted plant anyway, he'd be a cactus. Think tough, look tough, talk tough. Real security pros were never chatty, chummy guys. Van listened awhile, glaring at people at random, while caressing the keys of his laptop. Then he lost interest. They were obviously blue-skying it, these people. They weren't making progress; they were sounding each other out and trying to cover their butts. They clearly had no idea what the hell was really going on. They were scared for themselves and their futures. They were politicking. Because this was Washington. There was nothing Van could do but put up with that. After two agonizing hours, Jeb confronted the subject of the CCIAB's own hardware. The mood in the room shifted instantly. Everyone in the room, without exception, was very interested in the subject of computer hardware. Obviously, an outfit whose business was coordinating computer security for the rest of the federal government would need an internal system that was top-end, heavy-duty, and very impressive indeed. At this point, Van, who had been feeling sorry for himself and was badly missing his infant son, perked up a little. As a professional computer researcher, Van secretly hated computer security. It was boring and beneath his true talents. Making him work on security was like asking a top Olympic cyclist to make bicycle locks and bicycle chains. Nevertheless, this was now his duty. Plus, Van kind of liked the idea of building a genuinely advanced, secure system, from the ground up, from sound theory and practice rather than implementation hacks, and without any absurd interference by stupid market vendors. If he got to do that job by himself, that would be pretty okay. Van knew he could do it, it was honest work if dull, and at least he could set a good example. Now he had to tell a room full of people how this was going to work. Van struggled with his stage fright. Stage fright was a very old demon for Van. He knew how to beat it, though: he beat his demon with confidence tricks. Like pretending that they were just another Stanford undergraduate class. But they sure as hell weren't. Or pretending they were all wearing red underwear. Beltway bandits in expensive suits were not exactly a red underwear crowd. He could reach into his shoulder bag, and stick 'em up with his grandfather's ray gun. A titanium ray gun! Leveled right at their heads! The very last thing in the world they would ever expect! That thought did it for Van. He was just fine now. Van opened his laptop. "Well," he told them, "Jeb says we should be frank." He threw up a colorful PowerPoint screen to keep them happy. Then he read aloud from his script. "As this shows you, today's security industry will tell you certain very predictable things. They will tell you that a federal agency needs to buy their products. Secure servers, secure routers, firewalls, crypto, authentication, all brand-new out of the box . . . That is the conventional wisdom." Van switched PowerPoint screens, to a nicer one with a lot of colored bars and arrows. "But even for us, a small coordinating bureau, those purchases would set us back sixteen million dollars. We don't have that money." Another screen. "In the CCIAB, we can't wait the standard eight months to install conventional secure equipment. We need to be up and running, effective yesterday. We can't afford the time and money for security products. But we do have to meet a very serious security need. You reconcile those two vectors, and that means only one thing." Van switched screens. This new screen took a while to refresh. To his vast relief, PowerPoint did not crash. "We have to create a brand-new breakthrough system. Thinking way outside the box. Really quickly, really quietly, using about one-tenth the number of normal staffers. With radically innovative hardware and code." The room had a holy hush over it. They were totally with him. Jeb was beaming in the PowerPoint screen glow. "In the CCIAB, we do have one great advantage. We don't need to rely on anybody's lame industry vendors, because, in the CCIAB, we actually understand code. So we can build, and we will build, our own Grendel supercluster. Grendels are made from obsolete PCs, but clustered in parallel without any von Neumann bottlenecks." Another nice screen. "For about a hundred grand, we will own a new federal system with more raw computational power than the entire Commerce Department. And, in the short term, that system will be very, very secure. Because no hacker anywhere has invented or found any security holes for Grendel distributed supercomputation code. There are maybe ten guys in the whole world who understand that code. They are all loyal American computer-science academics, and they are all real, real busy." A hand went up. It was a late arrival, a skinny younger guy with a battered laptop on his knees. "May I ask a question, sir?" "What?" "You, Dr. Derek Vandeveer, you're one of those ten guys?" "Yeah. And I know the other nine. Who are you?" "Well, I'm a Web journalist, and—" "Meeting adjourned!" Jeb bellowed, lurching to his feet. Van was lying in bed, staring at the ceiling, and thinking hard about streams. Van had always wanted to do something useful and important with streams, because streams were inherently superior to the conventional structure of files. Van was planning to implement distributed streams within the Grendel. That was overkill, really. There wasn't a kode-kid, cracker, hacktivist, or even intelligence agency in the whole world that could break into a Grendel. But a Grendel running _streams—_ man, that would be beyond all coolness. Blinking occasionally, Van thought about streams. He thought about streams seriously, and then, very, very seriously. Eventually, Van became aware that someone was pounding on his apartment door. Surprised, he sat up and pulled on his pants. Van had rented his Washington apartment point-and-click off a real-estate Web site. Van had been in a big hurry to find a place in Washington, and the street was close enough to a telecom central station to get himself an ADSL line. The rooms had looked okay in the GIF file. In real life, the apartment was tiny and reeked of insecticide. Van's apartment had ugly walls of exposed yellow brick, a lot of peeling Formica, and a foul layer of oily grime on the kitchen walls and ceiling. The toilet wobbled in the bathroom. The Web site hadn't talked at all about the neighborhood, either. Van's neighborhood was sinister. Van now kept his grandfather's ray gun handy beside the door. The people who knocked on Van's door usually wanted to sell him crack cocaine, or themselves. Van removed his glasses and placed his right eye to the peephole. Out in the dim, ratty hallway stood a skinny girl with a big nose, dark eyes too close together, and black, frizzy hair. She wore a strange little frock of greenish-looking, all-organic, undyed cotton, and carried a shapeless fabric purse. She looked like a Girl Scout who'd sold all her cookies and taken up panhandling. Van undid three large brass locks and opened the door on a length of steel chain. "Dr. Vandeveer?" "Huh?" "I'm your new secretary. Can I come in?" Van considered this. It was unexpected. "Can I see some ID first?" The woman showed him a plastic-coated mag-stripe card with an embedded photo. The card had a nice red lanyard. The card identified her as "Fawn Glickleister, Executive Assistant, CCIAB Technical Services." "Huh," Van said. Fawn held up a different badge, still in fresh shrink-wrap. "I brought your badge, too, uhm, Derek. These badges are new. You haven't been to work in three days." "I _am_ working," Van insisted, stung. "I just can't do any meetings with anybody right now." "Can I come in please? It's kind of scary out here!" Van undid his rattling chain. Fawn came inside. She studied the big plastic weight-lifting bench, which dominated Van's small apartment. The grimy wall behind the bench was covered with posters of Full-Contact Karate champions, guys with staring eyes, flying sweat, and feet swathed in red plastic gauntlets. "Is all this yours?" "I just moved in." The apartment's previous tenant had abandoned everything he owned, including his thong underwear, his girlie mags, and his size-twelve kung-fu shoes. Van was pretty sure the guy had gotten shot or arrested. No one seemed to know or care about that. "Wow," Fawn marveled, "that is one really cool chair!" The magnesium chair was the only piece of furniture that Van had managed to bring from Merwinster. He'd grabbed the chair on impulse and thrown it into the Range Rover. His plan was to junk everything in the Washington apartment and replace it all—the Korean landlord said that would be just fine—but he had lacked the time. Fawn Glickleister was definitely older than twelve. She was older than Helga, Van's sad little fired au pair, but she was as restless as a sixth-grader. Her lips were badly chapped and her brown eyes looked red and puffy. She had a high, squeaky voice. "This chair doesn't outgas any toxins, does it?" Van stared at her. "How could magnesium outgas?" Fawn sat down daintily. "Wow, it's a lot more comfortable than it looks!" She pulled a thick pair of wireless specs from her canvas purse. An ominous silence fell as she looked around the apartment. "Can I tell you something, Derek? It's even scarier in here than it is out in the hall. Are you sure you're a computer geek? I know a whole lot of nerds, and most of them aren't, like, weight-lifting, scary karate guys in the ghetto. Hey, wow, what happened to that kitchen?" "You just sit in that chair for a sec," Van commanded. He opened the door, stepped into the gloomy hall, and slammed the door behind him. "Jeb," said the phone. "Jeb, what the hell is it with this girl you just gave me? She's twelve years old, Jeb. She looks like a Muppet." "That would be Fawn Glickleister." "I know her name. If I need help, I know where to get it." "Glickleister!" Jeb insisted. "She's not twelve, she's twenty-six. She's Glickleister's daughter." Recognition dawned. " _The_ Glickleister? Hyman Glickleister?" "Do you know any _other_ Glickleisters?" Van took a breath. Hyman Glickleister. Legendary computer visionary. ARPANET. Packet-switching guru. A man thirty years ahead of his time. Glickleister had spent the last fifteen years of his life in a wheelchair, dying of some obscure neuromuscular disease, and that had only made him concentrate more fiercely. Van had been crushed when Glickleister had died. It was as if some vast blazing bonfire had gone out. There ought to be bronze statues to Glickleister in front of every router station in the world. Van mulled it over, shaken. So weird to think that Hyman Glickleister had actually reproduced. Some woman had married Glickleister and borne Glickleister's child. Once would pretty much do it for that activity, Van guessed glumly. "Okay, so she's his kid," he admitted. Fawn looked just like Glickleister. Jeb was eager to soft-pedal the situation. "Now, Van, you taught at Stanford. You get it about today's young people. Fawn is bright, she's a quick study. You can mellow her out." Jeb was old-fashioned. He still thought that college students were wild, crazy kids. Van's students at Stanford had been sober workaholic Indian and Chinese software engineers with astronomical SATs. "Jeb, I don't want her. I don't like her." "Then I can get you another secretary. Some old lady from the Defense Department with her hair in a bun and a pencil through it. And you know what she's going to do to you, Van? She's going to tape all your phone calls to Monica Lewinsky, and she'll betray you to some political operative. People do that kind of thing in this town. I'm trying to protect you here, Van. We raging supergeeks don't have a lot of friends inside the Beltway. You're my Deputy Director for Technical Services. You're my top boy and I want to kiss you, but somebody has got to answer your phone. Because you don't do that. So Fawn will. Because Fawn is one of us. Fawn was born one of us. We can trust her." This was a crushing speech, but Van resisted mulishly. "How about Jimmie Matson from Mondiale? He was my executive assistant in the lab. Jimmie can get it done. He's great." "You recommended Jimmie Matson to me already. We did a background check. Jimmie Matson is a gay guy with a substance problem." "Jimmie is gay?" Van was stunned. "And he's on dope. This isn't the private sector, Van. Fawn passed a security clearance with flying colors. Glickleister's daughter is more secure than you are. Lots more secure." Van's phone beeped with an incoming call. Van decided to take it because he was losing his argument with Jeb so badly. "I'll get back to you," he said. The other call was Dottie. "Hi!" he said, startled and pleased. "Are you in Washington?" "I'm in Colorado," Dottie told him. "Are you being mean to Fawn?" "Honey, I'm not being mean." "Fawn can cook," Dottie coaxed. "She cooks Szechuan. Fawn found me on Google and we talked over all your problems. She's very sweet." "I don't have any problems. I don't need a secretary or a cook. Besides, the class 'secretary' is not congruent with the class 'cook.'" Dottie's voice sharpened and lifted half an octave. "Derek, what did you eat tonight?" "A TV dinner," Van lied, caught out. He hadn't thought to eat at all. He had been thinking very seriously. "What kind of TV dinner?" "A Salisbury steak," Van blurted hastily. And it was true. He actually had eaten a Salisbury steak TV dinner. He had forgotten about doing that, so he had lied to Dottie by accident. Twenty minutes after Grendel first went up, the system received its first hacker attack. It was a port scan, and of course it got nowhere. A Grendel running streams didn't have any "ports." Van had installed emulators that vaguely resembled ports, in the way a Venus-flytrap resembled a nice little red flower. Triggered by this assault, Van's pager went off, vibrating his right knee in the cargo pants. Van had guzzled so much coffee during the past twenty-four hours that at first he thought the jittery vibration was happening inside his own leg. Van fetched out the pager and then logged on, wondering. An attack within twenty minutes? How was that even possible? He watched the intruder fanatically typing. Then he called Jeb. "Jeb, come over here right now. You have got to see this." "I'm having a dogfight with the Air Force, Van." "To hell with the Air Force, come look." By the time Jeb arrived in Van's office, the would-be intruder had already filled five screens with gibberish and back spaces. Van paged the terminal, up and down silently, through the long list of line commands. "Is that who I think it is?" Jeb's froggy eyes bulged. "It is! It's him! This is kind of an honor, really." Fawn left her desk, where she had been cleaning up spam while listening to a book on tape. Fawn favored the fictional works of someone named Kathy Acker. Since wearing earphones at work seemed to calm Fawn down some, Van overlooked her strange habits. "What is it?" Fawn said, chewing the end of a Sharpie. "'It' is The Weevil," said Jeb solemnly. "Look at that guy. He is going through all top twenty of the biggest vulnerabilities for Windows systems. And he'll do each one of them ten times." "But we'd be crazy to be running a Windows server," Fawn objected. "Big Bill's got more holes than baby Swiss cheese." "The Weevil _is_ crazy," Jeb said. "He doesn't even know what Windows is. He doesn't know what UNIX is, either. But when he runs out of all of the Windows holes he knows, then he'll start in with his complete list of UNIX vulnerabilities." "I heard The Weevil used an Apple hole once," Van offered. "Probably an accident." "What does he do once he's inside the system?" said Fawn. Jeb shrugged. "He gets root." "But what does he do when he gets root?" "He makes himself superuser, covers up the intrusion in the logs, and looks for some other machine to get root on." "Oh." Fawn scratched the side of her nose with her pen. "He's one of those, huh?" "The Weevil is _the_ one of those. He doesn't know any programming. He'll never know. He only wants to knows holes and vulnerabilities. He collects them for their own sake. He has long lists of them. And he tries them all, cookbook style. Manually! Look at him backspacing there." "Wow." "Twenty-four, thirty-six hours straight sometimes. Day after day. Weeks. From his laptop in the toilet," said Jeb. "Did you ever _see_ The Weevil, Van? He's been raided about thirty times." "I saw a pic of him," Van said. And of The Weevil's den, or whatever one called that impossible, filthy hole where The Weevil lived. At the FCIC Reunion in Phoenix in '96, they'd had a slide projector. They ran some slides of The Weevil's raid photos during their beer bust. Van could still remember those computer cops howling. "I met him once," said Jeb, wincing at the memory. "In a halfway house in Tacoma. I just had to go see The Weevil. I mean, this was the bad guy who took control of over four thousand computers. Mostly federal. One by one. By hand. Even back then, he had carpal tunnel so incredibly bad . . ." Jeb paused thoughtfully. "I think they call that 'degenerative osteoarthritis,' really. Hands like two big hockey gloves." "No," said Fawn. "Yes, Fawn." Jeb offered Fawn a gentle smile. That fatherly expression looked strange on Jeb's big face, but Jeb had known Hyman Glickleister really well. Fawn's penny loafer scuffed the federal shag carpet in her doubt. "Really?" "Yeah, Fawn, really. I'm not kidding." Fawn believed him. "So, uh, what do we do about a guy like that?" "Well, he's mentally ill. The FBI profiled him as extreme obsessive-compulsive, and . . ." A summary thought struggled to burst out of Jeb. "This is the face of our enemy," he said at last. "I mean, he's not al Qaeda, but he's truly of that kind. There is just no reasoning with this guy. There's no possible diplomacy we can use with him. There's no compromise or common sense. We can't scare him off, or buy him off, or give him anything that he wants. He's got a value system so totally alien to ours that he's like a _Star Trek_ Borg." Van tugged at his beard, hard enough to pluck a whisker. "How does The Weevil even know we're here? The only feed upstream of us is the NSA!" "Man, I sure don't like _that,_ " Jeb said. Van watched the screen. The Weevil was an awful typist. Small children typed better than The Weevil. He was, Van realized, using two fingers. Maybe two stumps. Van had had two hours' sleep and three pots of coffee, getting the alpha rollout of the Grendel system in shape. The project was turning out better than Van had imagined. In fact, it was working out in a rather interesting fashion. It was elegant and he was proud of it. Working with Grendel was worthy of his talents. The work was consuming him. Van was living alone. He was under great pressure to perform. He was sore all over from lifting weights every night, so as to collapse and get some sleep in his cold, lonely, lumpy bed. Then, as Grendel's very first "guest," way before any legitimate user ever logged on to admire Van's handiwork, here he was already, instantly, this . . . creature. Of course The Weevil wasn't getting anywhere against Van's secure system. It was like watching a termite trying to chew through a concrete block. But, as long as it just kept chewing, chewing . . . "We've got to get rid of this guy," he realized. "He'll never get inside Grendel." Jeb shrugged. "He's a lunatic." Van lowered his voice. "We have got to get rid of him _just because he is him and we are us._ " "Good people have already tried that," said Jeb. "Any district attorney takes just one look at The Weevil. It's like: you want me to put THAT in front a jury? It's almost blind! It has no hands! It can't even talk. It's never held a job in its life. It has no life. I'm not even sure it can read." "How does he eat?" said Fawn. "He's got some kind of family in Canada. They send him cash, I think. They're okay people, that's what I always heard. They're just really happy that The Weevil lives far away." Van pulled off his glasses. "The Weevil is _Canadian_? He's a _foreign nationa_ _l_? I never knew that." "Yeah. So?" "Oh, man! That's it! Game over! Illegal combatant! Enemy of humanity! Into the razor wire! Guantanamo Bay, Jeb. Into the steel cage." "Take it easy, Van." Van stabbed at the screen with a finger. "Jeb, _look_ at this! He's _attacking the National Security Counci_ _l_! You know, _us_!" "Huh." Jeb cleared his throat. "Well, you've definitely got a point there." "This is his last hacker 'sploit! He is _ove_ _r_! We _own_ him now!" "Van, the NSC isn't supposed to directly involve itself in operational activities in the field. And we're just a board of the NSC. We're a policy coordination group." Van boiled over. "This punk-ass chump is screwing with us, and you're going to let him _wal_ _k_? He's notorious! Everybody in our business knows who he is! Are we wimps in this outfit, are we the _victims_? Give me his address! He lives in Oregon, right? I'll drive over there right now! I'll kick his door in and kick his ass myself . . ." Van let his voice trail off. Fawn and Jeb were staring at him. They had both gone pale. "I'm overdoing it," he realized. "Uh, yeah," said Fawn. Van touched the monitor gently. "But, Jeb, you know, this is my baby here." Jeb took a while to nod. "Maybe I shouldn't be saying this. But I do get it, Van. You've got the right gut instinct about this issue. We need to take some steps. I'm gonna keep you in the loop here." "Okay." "We need you here with this new Grendel system, Van. We can't have you leaving us to run any field assignments." Now it was Van's turn to stare. Jeb really believed that he, Derek Vandeveer, would lock and load, drive across America, and physically raid some bad guy. Take him down. Maybe shoot him. Van watched more tortured letters wriggle across the screen. He would do it, too, Van thought, in a stunning leap of self-knowledge. He was aching to go shoot The Weevil. He would sleep better for doing it. Where was Dottie, where was Ted? Where was his bed, his home? He was in a bad way. "I'm thinking visa problems," rumbled Jeb, thunder gathering in his face. "Emigration violation. I'm thinking 'cyberterrorism.' I'm thinking a personal call to John Ashcroft and a serious ton of bricks." "Did they even pass that statute yet?" said Fawn. "Patriot Act? Honey, they're gonna pass all kinds of stuff." Van's apartment in Washington was grimy and dangerous. His NSC office in Washington was makeshift and dull. But Van's second office, four hours away from Washington in a place they called the "Vault," was so awful that he almost liked it. It quickly became his favorite place of work. On CNN and MSNBC, the Vault was always known as the "Undisclosed Location." Dick Cheney was supposedly in there a whole lot. In point of fact Van had never seen the Vice President wandering around the Vault, but the Vault had an interesting crowd. Someone with a very odd checklist had tried to figure out what kind of people would be necessary to run the United States of America if Washington was destroyed in a terrorist nuclear attack. That was the big concept behind the Vault: the lively possibility that D.C. might turn, without any warning, into a weapon-of-mass-destruction field of black slag. Washington would be instant rubble. Then five minutes, maybe six minutes later, the Vault would come online. The survivors stashed away in the Vault would become the American post-nuclear government. The community in the Vault kept bubbling, in constant turnaround. Nobody really wanted to stay in the eerie Vault. They all much preferred to lead real lives, even at the risk of getting killed by nukes, sarin, or anthrax. So the Vault was a very mix-and-match place. It was the Melting Stovepipes business all over again, only to a factor of ten. The inhabitants of the Vault all slept in similar steel bunks. They had the same military card tables and folding steel chairs. You never knew, day to day, who your new neighbors would be. Federal Emergency Management Agency, Army Corps of Engineers, U.S. Postal Service even . . . They'd show up with plastic-coated briefing books and bewildered expressions, to spend two weeks hiding underground. The Vault had been built in 1962, in a nation still queasy from the Cuban Missile Crisis. It stayed secret because it had been built quietly, in a big hurry, by a very small group of top-notch fallout-shelter contractors. The Vault was located in the Alleghenies, just over the border of West Virginia. It had a rather delightful and well-equipped hotel sitting on top of it, to camouflage it from the Russkies and the American press. The Vault had successfully stayed unknown to the world for forty solid years. The West Virginians who ran the hotel were a clannish lot. They had never breathed a word about the giant warren lurking beneath them. The Vault had huge steel blast doors and its own coal-fired power plant. The coal plant doubled as the Vault's crematorium, in case anyone died of A-bomb radiation injuries. All the telephones were red plastic with rotary dials, straight off the set of Kubrick's _Dr. Strangelove._ The biggest open space in the Vault was a small gym, so the last men on earth wouldn't go completely bats with jail fever. Van spent a lot of time in the Vault's gym. He'd become a workout addict in the grim celibacy of Dottie's absence. His neglected hacker's body yelled out for attention: decent food, sex, sleep, a long vacation. None of those things were remotely available to Van. Ferocious exercise was pretty much it. That attitude fit the military tone inside the Vault, though. These guys brought heavy private burdens to their fifty-pound barbells and Nautilus racks. Every Vault rat had to be emotionally troubled. The whole point of being in the Vault was that everything you knew might be blasted to ashes overnight. There was even one big, doomed soul in the Vault's gym who lifted his weights with a security briefcase permanently tethered to his wrist. This top-secret courier never said a word to anyone, but he was a hard guy to miss. Tall, dark, silent, chiseled-looking, very buff. Van took an interest in this mysterious stranger. Day after day passed, but no one ever set the courier free of his burden. The chained briefcase was waterproof and apparently blastproof. The guy even showered with it. Van, of course, never asked him about the briefcase. There was something way too personal about that subject. The Vault was a barracks, and had stark, simple, military routines. The cafeteria line fed everyone three times a day, on big community tables. All the federal foodstuffs had tough-guy military nicknames, like "elephant scabs" for the veal parmigiana and "bug juice" for the orangeade. When the lights went out at night, nobody stayed up to party. The Vault went as black as a tomb. Van and his CCIAB people became extremely popular in the Vault. Within two days, Van had installed securely encrypted broadband Wi-Fi. Thanks to Van and his fellow cyberwarriors, even the most bored, lonely Vaultie, stuck in a sealed cell with a cheap khaki blanket and a laptop, could securely surf news portals. Van expected someone in authority to complain about all this free Internet access from within a secure facility, but no one ever complained. They just accepted Internet access as a modern force of nature. Van lived much better inside the Vault than he did in his Washington apartment. The Vault was cramped, stony, and smelly, but at least he was fed and watered regularly. Van felt safe from the outside world. Most other federal employees in the Vault sheepishly feared an apocalypse that would destroy everything they knew. Van, however, was getting one. Van's world was literally being destroyed, in newspapers, magazines, and television, day after day. It was hard to believe—Van would never have imagined it—but Mondiale, the mighty Mondiale, was dot-bombing. Mondiale was coming apart at the seams. This brave, heroic, visionary, cutting-edge company—the bear market was beating it to death like a cheap piñata. This made no sense at all. Mondiale was not some flimsy e-commerce Web site with a make-believe business model. Mondiale was the necessary basis of modern civilization. Mondiale was a telecommunications giant that owned real property: cables, microwave relay towers, optical switching stations, long-distance voice franchises, big chunks of regional local loop, and even satellites. Mondiale was a highly profitable business that was laying fiber-optic pipe around the planet, uniting the world in efficient globalized prosperity. Mondiale was the future. It was insane to think that a society in an Information Age was not going to need Mondiale and its skills and capacities. But the world had stopped believing in that. The Bubble was the Terror, just like that. And the stock had cratered. Van's own holdings, his fortune, his net worth, were nose-diving day by day, relentlessly. Van was helpless. There was nothing he could do to escape the collapse and save himself. As a federal employee, he had placed his holdings into a blind trust. Doing this had never bothered him. He had never been the kind of guy with any time to dabble and meddle in stocks. Of course he knew people who lived that life—one of them, Tony Carew, was his best friend. Knowing Tony well, Van had always known better than to try to outhustle the IPO hustlers on Wall Street. Van didn't mind putting his Mondiale holdings into a locked federal box. Van had confidently figured he would just leave his stock there, as a classic, sensible, long-term investor, until the big emergency was over, and Mondiale took him back. But Mondiale was eaten by the Terror. Everything that the common wisdom had urged Mondiale to do had turned, overnight, into poison. Everything Van had discovered and assembled for them—golden vistas of research potential, a host of raw possibilities, shining ways forward . . . nothingness. Vaporware. The abyss. It felt very good to work inside solid bombproof concrete, then. Van was wiped out, but not quite totally. As the Deputy Director of Technical Services for an NSC board, Van had a federal salary, paid promptly every month. Van was paid about as much as a senior FBI agent, which was to say, he was paid peanuts. FBI agents never made a dime until they quit the FBI. Former FBI agents could do pretty well, when they went to work as well-paid private security people. Former FBI guys commonly went to work for big, serious-minded, major commercial outfits. Like Mondiale. Even Tony Carew, the proverbial dot-com rich kid, had hit hard times. Tony never said a word about red-hot market opportunities anymore. Tony was fiddling with science projects in Colorado, he was angling for high-tech defense work. Tony had lost more money than Van knew how to count. And he still had to live out there. Inside the Vault, though, a guy could get along on powdered eggs and grits. Creditors would never find you there. You didn't have to watch financial news on TV or glimpse the stocks in a newspaper. The Vault had hot macaroni and cheese. The Vault had dry yellow cake. There was no beer or alcohol of any kind allowed. There was grape juice. That was what there was. That was all there was. That was the Policy, and it was the federal government. You didn't have to think about it. It got worse. Federal procurement systems were notoriously sluggish. When he and Jeb had gone over the stats for the Grendel system, they had discovered that it would take eight times longer to pay for Grendel than it would to simply build it themselves. They could wait for a procurement check to be cut, but by that time, they would have lost the critical first-mover advantage that had led them to plan a Grendel in the first place. So Van had paid for Grendel's hardware himself. Van still knew that this was the sensible choice. He knew that the baby CCIAB would quickly die if they didn't prove their serious chops as go-to technical people. Jeb had promised that the feds would be good for Van's money sooner or later. As the legendary Admiral Grace Hopper had often told Jeb, it was always easier to apologize to a bureaucracy than it was to get permission. Jeb did not have the necessary money, himself. Jeb had spent most of the last twenty years as a federal law-enforcement instructor. So, Van personally tasked Fawn with buying 350 used PCs on eBay. As a bridge loan for the CCIAB, Van sold his Range Rover. The Range Rover was in big trouble parked in his Washington neighborhood anyway. It was smarter to sell his truck than to have it carjacked. Ironically, after selling his Rover, Van had no problem at all requisitioning a posh federal limo. In fact, the black limo driver was a neighbor of his. So Van slithered around Washington in a bombproof stretch limousine with smoked windows, a vehicle often used by the Secretary of State. Then he went home to sleep in a slum. Fawn was a practiced eBay hand. Fawn bought most of her clothes there, from tiny New Age retailers who made anti-allergenic clothing. Now Fawn bought herself a set of fake eBay IDs for "security reasons." Soon she was elbow-deep in a web of electronic transactions that Van had no time or energy to oversee. The 350 used PCs showed up very quickly. Most of their hard disks were crammed with pirate software, viruses, and pornography, but that posed no problems. Van stuck the 350 PC motherboards into hand-welded frames. He installed a completely new operating system that turned them all into small components of a monster system. Grendel was installed in a spare Internet rack in the bowels of the Vault, directly connected to all-powerful servers in the NSA's Fort Meade. Days later, Van's office furniture arrived. Van hadn't asked for new furniture—he had been working off metal folding chairs—but Fawn took matters into her own hands. She bought a discontinued office suite from a defunct dot-com and boldly had it crated and shipped to the Vault's secret mail drop in West Virginia. The CCIAB's cheerless chunk of bunker blossomed with leopard-dotted Leap Chairs and strange, hexagonal, filmy office sets, featuring spandex light shades and tiltable desks. Fawn's flamboyant gear was a major hit within the Vault. Such comforts were unheard-of in federal employment. Envious Defense Department drones would come by just to steal Fawn's golden paper clips and her teakwood thumbtacks. The CCIAB won a lasting nickname: "Those Cyberwar People." Once again, Van expected someone to lower the boom on them for being too bold, but nobody ever lowered the boom on small boards of advisers that worked for the National Security Council. Except for the President himself, there just wasn't anybody in the federal government with direct authority to fuss at the CCIAB. Even the President himself would have to create a Special Review Board just to review his special boards, and in times of war, that was out of the question. The CCIAB was not really a federal agency. Like the National Security Council itself, it was a small, make-do work gang of close colleagues that was trying to steer huge federal bureaucracies into the latest and trendiest policy directions. Like a president, the CCIAB was just a temporary passerby in the federal system. Except for Fawn herself, who had had no job when she begged Jeb for a favor, there was no such thing as a career CCIAB person. Every bureaucrat in the CCIAB was seconded-over from other careers in other bureaucracies. Karl Bowen, their top policy analyst, came from Los Alamos National Lab. Brian Coon, their chief investigator, was from the Office of Criminal Investigations of the IRS. Herbert Howland, the public relations guy, was from the Navy Broadcasting Service. And so forth. Jeb's game plan for the CCIAB was to create a realistic policy for National Cyber-Security that the President, Secretary of State, DoD, CIA, NSA, and Joint Chiefs of Staff could all sign off on. The pitifully vulnerable federal computers had to become less sleazy and less easy. Through their own good example, sheer panic, and grim threats, the CCIAB would beat, beat, beat the bureaucrats into line. Whatever could budge would be made to budge. And the devil take the rest. During the Christmas season, the political pace slowed down. Vital people simply vanished from Washington. Contacts did not answer e-mail. Van was glad for the chance to concentrate. His emptied head was buzzing with hot new technical ideas. Back in his Washington apartment, Van was waiting for his latest batch of code to compile. Living in a high-crime area had brought Van useful insights about real-world security. In real life, if you had a solid wall, then you could lock the door. If one lock wasn't enough, it helped to install five or six locks. But computer networks didn't have walls. So the "firewall" metaphor was just that, a metaphor. A far more fertile approach would be a computational _immune system._ After all, the vast majority of serious computer attacks were not carried out by outside hackers. Hackers did not "break in" through anything that could "break." Most real-life computer acts-of-evil were carried out by crooked insiders already _within_ the firewall. Thieves or double agents, people who knew the system already. Usually, they knew very well what they wanted to corrupt, erase, alter, or illicitly copy. So a better security model would not "lock" or "wall away" anything. Instead, it would scan constantly for evil processes inside the machine. It would hunt for bad acts inside the system, in the way that the bloodstream fights germs. This was an exciting new paradigm. It offered fruitful ways forward that resolved a host of the day's knottiest security challenges. The concept was a generation ahead of its time. Maybe two generations, given the awful state of the computer market. All the more vital, then, that the CCIAB should pioneer a serious breakthrough like that. They could run it within the Vault, an ideal place to start a working demo for a core audience. A streaming distributed supercomputer, on broadband wireless, featuring a pilot, alpha-rollout immune system. This inspiration set Van's brain afire. It was fantastic. And it was really likely to work, too, that was the best part. The CCIAB didn't have a whole lot of money, but they did have the attention of the top experts in the field. There was no competition in creating computer immune systems. There were no stovepipes. There were no established industry vendors trying to protect market share. So they could farm the project out just like Open Source, develop it quickly, quietly, in closed modules, on a need-to-know basis. So while Jeb was struggling with the state of federal security in his political, bureaucratic way, he, Van, would be literally building and assembling the future of computer security. Hands-on. The real deal. Proof-of-concept. Wow. Van's son flickered onto his laptop screen, the size of a postage stamp. Ted's creche in distant Colorado featured a webcam. Both Van and Dottie commonly watched Ted's webcam during their workdays, though nothing much ever happened there. The day care was run by a bouncy, well-scrubbed Buddhist feminist from Boulder, a thirty-something woman in braids, who wore denim overalls and a head kerchief. She commonly sat cross-legged in her Timberland boots as her little charges crawled all over her. Sometimes she read them non-gender-specific fairy tales. Ted seemed to find this treatment more or less okay. He definitely looked a little bewildered sometimes. Sometimes Van would touch his son's flickering image on the screen and murmur a few words. He couldn't help himself. On the day after Christmas, Van squinted through the peephole of the apartment door and was stunned to see Tony Carew. Van undid three locks and two chains. Tony slipped inside, with a final wary glance down the gloomy hall. Tony wore a pale, tailored trench coat, a spotless snap-brimmed hat. He looked very Washington. He'd never looked that way before, but he sure looked it now. "Van, you're a hard guy to find. Don't you answer your phone?" "No. Not anymore." Tony confronted the apartment. He summed it up and dismissed it in disbelief. "Is this a safehouse? If so, it's not very safe. I brought a bodyguard and a chauffeur to this part of town. I'm really afraid somebody's going to hurt them out there." Tony put his black shoulder bag on Van's peeling Formica counter. He unzipped it and displayed a newly purchased bottle of brandy and Benedictine, still in a paper sack. The B&B bottle was two bottles really, double-necked and welded together. Glass twins in green and yellow. In their teenage undergraduate days, Van and Tony had considered brandy with Benedictine to be the height of sophisticated drinking. It was, of course, illegal for them to be drinking at all, and doubly illegal to do it on campus, which made a doubled form of booze even tastier, somehow. They each had elaborate theories on the exact proportions of brandy and Benedictine necessary to get properly hammered. The sight of the two crooked bottles gave Van a warm nostalgic glow. There had been such innocent joy in his life then. Tony had been such good fun. Tony Carew was the guy who had found Van the best fun he had ever had: a serious girlfriend. Van had never before had a roommate who could match him in intelligence. And it hadn't hurt Van's feelings any that Tony was witty, fast-talking, and great around girls. Tony took off his brand-new hat and placed it on top of his bag, so that his hat would not have to touch the disgusting countertop. "I don't suppose there's such a thing as a 'snifter' around here." Van fetched them a couple of jumbo disposable foam cups. He'd been meaning to buy himself some glassware, but had never found the chance. Tony set to work to open the bottles. Van checked the Casio strapped to his wrist. It was only 6:00 P.M. "Are you drinking, Tony?" "How could I not?" Tony said. "I just came back from a rotten little holiday emergency in the bowels of the FCC." "Oh." "No, Van, it's even worse than that. I strongly advise you to join me immediately in a heavy boozing session." "All right." Van knew that Tony had a point. He knew it all too well. Tony poured their potions. He clowned around with the flimsy cups, acting drunk already. Tony wasn't genuinely wasted yet—Van pretty well knew what Tony looked like under those conditions—but Tony definitely had that first, lit-up look. Tony had brought a burden with him. It couldn't be just the awesome, industry-smashing train wreck in federal telecommunications policy. Tony would not have come here personally just for that. Tony's priorities shifted around some, but Tony was always Tony. Tony Carew was into money, women, technology, and status games. Tony Carew was a very charming guy. He was fluent and persuasive. Van had never competed with Tony in those aspects of life. That was why Tony trusted him. Like most overachievers, Tony had personal burdens that weighed on him like anvils. But Tony's idea of burdens—the big money, the fast women, the struggle for status—those things fell on Van like a light refreshing rain. From their first day as friends, Van had been able to drink in Tony's problems. Van didn't judge Tony, he didn't scold. He couldn't even say that he sympathized. He needed Tony to trust him, somehow. He needed to be trusted with those things. Van offered Tony the magnesium chair and sat on the weight-lifting bench. Tony stroked the shining chair. With Tony inside it, it was a throne. "Wow! You should get a dozen of these. They stack!" "Great idea." Van tilted his flimsy white cup and sipped his B&B. Instantly, its familiar velvety burn made him feel nineteen years old. Tony studied the apartment's bare walls. Van had managed to rid himself of the kung-fu posters, along with all the previous tenant's possessions. He had kept the weight-lifting set, though. The weights were his consolation prize. "Van, couldn't the NSC get you a furnished apartment?" "It _was_ furnished, Tony. I threw everything out." Tony's eyes narrowed. "So you swept it all for bugs, huh? Yeah, I've seen that done before. Man, that really wrecks the place." Van shrugged. "Van, I can't believe they made you into a fed. I know you've got the right family background there, but that line of work doesn't seem much like you." "Times change." "But why are they wasting your valuable time? Why you? You're the computer-science gold standard, man. Can't they FedEx their little password crypto puzzles over to Merwinster? You've got a decent place up there." "I'm selling my house." "No way! It can't be!" Tony blinked. "Mondiale is cratering that hard? Mondiale, too?" Van nodded. "On a federal salary, I can't pay the real-estate taxes on that place. I'll be lucky to sell it. I wish I knew who could buy it. The whole town's been turned inside out." Tony's face fell. Tony was a rich kid from a wealthy family, but the money issue between them had never much bothered Van. Dottie's dad was also pretty well-to-do, and Dottie was just fine. "I knew your scene up there had a serious downturn, but . . . Did you tell that to Dottie?" "She can do math." "You didn't tell her, then." Van said nothing. He and his wife kept separate bank accounts. When Van's salary and stock had begun skyrocketing with the Internet boom, that didn't seem the proper time to confront Dottie with some strange demand that they change their usual financial arrangements. That was too much like one of those creepy post-nuptial agreements. Van was never going to dump Dottie Vandeveer for some puff-headed trophy wife. Mondiale's other VPs might like to pull such stunts, but those clowns were just money people. "You been out to see her lately, Van?" "Not lately. We called at Christmas. Talked a lot." "Seen her ever? Since she moved to the Facility?" "Well, no. We're both working like crazy." Now Tony was truly shocked. "Look, Van. Maybe I shouldn't comment here. But I've known Dottie even longer than I've known you. I've seen her in Colorado, I dunno, five times in the past two months. And you can't fly out there to the site? You married her, fella. What is the problem?" "We trade e-mail every day." Tony topped up Van's foam cup, a pitying look on his face. "My man, look at this dark place you're in. You really sleep in here? Are you a fifth-level federal Dungeons and Dragons troll? Are you a kobold now? Are you Gollum? She's never seen you in this awful place, am I right?" Van nodded. "Well, thank God for that." Tony sighed. "I'd better cut to the chase right away. It's up to me to take you two in hand. Van, she is sensitive. She is lonely and vulnerable. She'll never call you first. She has that kind of proud shyness that really bright women get. She would rather be shot first. You've got to tell her that you want to see her. You've got to insist, Van." Van blinked. He lowered his voice. "Well, man, it's kind of hard to just go and do that . . ." Tony touched the vest of virgin wool within his trench coat. "Van, was I right before? Ten years ago, I told you all this. Word for word. I _made_ you call Dottie. I practically _beat you_ into making that first call. Was I right?" The brandy was hitting Van now. There was a hot rush to his bearded cheeks. "Yeah, Tony. Yeah, you did that for me. Yeah, you were right." "So. What is your deliverable, then?" "Well," said Van, "I guess maybe . . . There is this big conference coming up for the CCIAB, out at this big farm retreat in Virginia . . ." "Which one? Coulfax? Erlette House?" "Erlette House, yeah, that's the place." "Oh, yeah. That would be perfect. CIA, DoD, Bell Labs, DARPA, they all do big seminars there. The food is fantastic, beautiful landscaping, ponds, swans, arbors, flower gardens, man, the wine cellar's two hundred years old! Erlette House is where every undersecretary takes the sexy intern." Tony laughed. "End of your problem, my man." Van sat up straighter. That did sound pretty good, really. The Erlette House event wasn't till early spring, but by March the CCIAB would be delivering its recommendations. And he, Van, would be leaving the little board for some heavy-duty, long-term, permanent federal post. Or else contemplating sudden unemployment. Either way he should have Dottie with him. To celebrate with him, or commiserate, or . . . No, just to be together. He owed her that. "You're gonna thank me," Tony promised. "I'm thanking you already." "You should fly to Colorado to see her as soon as you can," Tony said, bearing down. "Do you have any idea what we've got going on out there? We are a world-class facility. We are bringing astronomy right into the e-world. We've got the biggest Internet2 node west of the Mississippi." "Yeah, Dottie seems pretty pleased with the job." "It's a great job for her. It's the future of her profession. You don't just _look_ through a digital observatory, pal. Everything that it senses is archived and fully accessible on Internet2." Van smiled. "Is this your best new toy now, Tony?" Tony sipped his cup, raised a brow, and added more Benedictine. "You know, back in the Boom, I wondered why I spent so much time and energy on some stargazer project. That was old DeFanti's baby, and I was just his chief cook and bottlewasher. But after the hell I've been through lately—hey, now I know why he needed a real big hobby way outside the business world." Van nodded. "The old folks get it about these ups and downs. That's part of life, that's all." "Oh, I knew I'd see a market correction," Tony said grimly. "I never guessed I'd see anything this insanely bad." "Don't take that to heart, Tony. Time is on your side. You'll be back. You'll be back with bells on." This was the best thing Van could think to say, and he meant it sincerely, but he saw from Tony's wince that he had overdone it somehow. Maybe it smelled too much like pity. "I shouldn't tell you this," Tony said, "but, you know the way router prices have crashed lately? Well, DeFanti had a standing order in to purchase those below a certain price level. Pal, we have got _unbelievable_ numbers of routers in that facility. Barns full. We _are_ Internet2, man, we can handle all the lambda from Juneau to Los Angeles." "No way." "Yes way. There's nothing new about an NSF hub being a major Internet backbone. Enron was gonna move hard into that niche, in a Bush administration. They were gonna marketize Al Gore's broadband. We were with that idea way ahead of the curve. We would have made a fortune with DeFanti's old pals from Houston. We coulda run a dozen observatories off that kind of revenue." "How is that holding up now?" "Oh, the price-point on routers will come back soon. It's just kind of a bridge loan to the industry, really. But in the meantime, we've got _loads_ of routers. I'm thinking your Grendel thing could do with some routers. Am I right?" "Sure it could, but, Tony, I can't buy any hardware from you." "I could practically pay you to take 'em." "We're friends. I'm a fed now. That's not ethical." Tony was nettled. "Do I look five years old? How long have you been in this town? Of course I wouldn't 'sell' them to you. You wouldn't 'buy' them either. It would never show up as a financial transaction at all. You're NSC, and I'm NSF. Plus, we've got the NSA, for heaven's sake! How do you think _they_ buy their hardware? They don't even damn exist." Van shook his head. "My boss hates the NSA. They're all over our turf. They killed all the crypto initiatives. They made security bad and kept it bad, just so they could spy the easy way." Van put his cup down. "They suck." "Yeah, sure they do, but the NSA has got black budgets that make Enron look like a bookie joint. Okay, never mind the hardware. That was one option, that's all. How about you coming out to lecture us next spring? We know how bad security is out in the networks. We're hosting the next Joint Techs conference out on DeFanti's dude ranch. Next April. Why don't you fly out there and bring us some of the noise from inside the Beltway? You always do Joint Techs, right?" "That's true." Everybody at Joint Techs was a personal friend. That was the only way that the Secret Nerd Masters of the Internet knew how to invite you to Joint Techs in the first place. Everyone who was anyone went. "Yeah, Tony, I'd go there for you." "You could tell Joint Techs the new party line from your boss the Jebster." "Yeah, I'd demo Grendel for 'em." "Oh, man. That would rock so hard. Why don't you _build_ a Grendel at Joint Techs? We'll get you a truckload of crap PCs. We'll wire 'em up real time. Joint Techs will go ape." That would definitely work, thought Van. Such a showman's stunt would never have occurred to him, but Tony was absolutely right. The guys at Joint Techs would be totally thrilled by a hands-on confrontation with k-rad streaming hardware. They would forget how to breathe. He beamed on Tony suddenly. It was impossible not to love the guy. Van could barely remember how lousy he had felt twenty minutes ago, how grim and committed and full of fortitude. Now, with Tony in this sorry little room with him, there were suddenly some bright shining lights in his future. Days that would be full of sunshine for him. And happiness. Future days that would be _really cool._ The guy was light and magic. Tony silently reached to pour himself more booze. The happy moment passed quickly. There was an anvil on Tony's back. "What are you up to, Tony? You got plans to turn it around, right?" "Well," said Tony, who was definitely not okay, "you mustn't lose sight of the end goal, Van. After a stock market bubble, people are just as irrational as they were before. But now it's all about the terror, instead of all about the greed. They are _more_ irrational now, because they can't see any future." "You've got money troubles?" "It's not that simple. By the way, I'm really sorry about your board of directors gig for DeFanti's holding company. You were right to resign before you turned fed, but, well, I wanted to make that thing work out a lot better for you." "That's okay, Tony," said Van, and it was, because Van hated corporate board meetings even more than he hated federal ones. "They never got it about what I told them about real security, that was clear." "When you're a master-of-the-universe like Tom DeFanti, sometimes you just plain lose track." Tony's face twisted. "You heard all about what happened to Tom, didn't you?" "I know that he retired. The board never talked much about that. They kept it real hush-hush." "Oh, everyone knew Tom was getting erratic, that part was all over the media, but . . . Well, Tom finally, completely crashed. Basically, Tom is a prisoner now. They wouldn't send a guy like that to just any mental clinic, you know. They _built one around him,_ the way they did for Howard Hughes. Tom is delusional. They've got him trapped inside a wing of that farmhouse. The Chinese wife looks after him . . . He talks about Martians, Van." "Oh, jeez. You mean that?" "I know it. Tom met a UFO. Among other things. It's like the _Heaven's Gate_ thing. Spaceships and Martians. He's really bent in the head. It's been a total nightmare for all the associates." Tony emptied his cup and slumped in the shining chair. "The very same powers that made Tom so great are tearing him apart. The acuity, the imagination. The mental daring. I think it's the very worst tragedy that I have ever witnessed at first hand." "My God," Van said. "I had no idea it was that bad." "Van, listen." Tony was passionate now. "I have learned something important about people who are profoundly creative. They are unbalanced. That's why they have so much to give. They _have_ to give. They are fighting with some kind of black chasm inside. Great artists, great writers . . . Captains of industry, even. The top ones get much better than any human being ever needs to be. No mere reward could ever make anybody act to that level of performance. Because it's never about the money, or even the fame. It's all about the inner terror." "Come on, Tony." "That is the truth, Van." He was bitter. "I have seen it happen with my own eyes." Van rallied himself. He was feeling pretty good now, the brandy was smoothly taking hold of him, and it was time for him to exert himself for the sake of his unhappy friend. "The work is its own reward, Tony. If you do it right, it feels great. To give is good for you." "You say that because you've got creative power, Van. You are a scientist. You're stable. You can stare deep into the screen and you really engage. I have seen you do that and it's marvelous. You get awards for it. I knew you had a gift the first time I met you. But you're not an artist. You're not a businessman, even. Because you don't have a demon. You're a nice guy." "Tony, come on. If I don't believe in UFOs, there's no way you're gonna get me going about demons." "Who, me? I'm just a deal maker. I'm not a creative. I'm just a glorified hustler." Van laughed. "Tony, buck up. You do okay, man. You do great." Maybe Tony had suffered some market setbacks, but the guy had a private jet. He dated models and actresses. He spent enough on his clothes to feed a village in Kenya. Why was he carrying on like his world had ended? And yet, Tony had always been like this. It was the other side of his charm somehow, that dark urge to put himself down. Tony rubbed at his cheeks, the way he did as his face went numb from drink. "I do assemble my deals in rather remarkable ways, sometimes. Through pastiche and collage, basically. It's very postmodern." "'Postmodern'? You're drunk, Tony, cut the crap." Van rose to his feet. "You know what we should do right now? Bowling. Let's go bowling, Tony, come on." Tony smiled. "You're still bowling? You're gonna kick my ass, man." "No way, Tony. You are _the_ bowler. You are _Mr._ Ace the Split." "Look at your damn arms," Tony objected. "What have you been doing to yourself? You've got arms like two tree trunks." "Two tree trunks," Van repeated carefully. As a child with a stutter, he would have found those words impossible to say. They were pretty hard for him to say right now, with that brandy hanging on his tongue. "Let's go bowl in the Pentagon. They've got some great lanes in there. I've got a Pentagon pass card." "Now you're starting to interest me," Tony said. "The Pentagon is full of hot chicks." "You are plastered," Tony realized. "Did you eat anything today?" Van shrugged. "Let's just go. This place stinks. Lemme call my limo guy." "Never mind that, I've got a chauffeur," said Tony. He helped Van into his overcoat. The coat was West German military surplus. It was slick green nylon with elastic cuffs, some kind of a European battlefield medical thing. The coat had the many pockets Van always needed for tools, gizmos, and spare bits of hardware, even though it made him look like a secret mad surgeon. Normal people skittered away when they saw him on the sidewalks of Washington. This was one of the coat's major benefits, actually. Plus, the coat was warm, and it was cold outside. On his way out the door, Tony noticed the ray gun. He snagged it from its holster on the wall. He sniffed the barrel. "This is a hot-glue gun." "Yeah," said Van. Tony rapped the hollow barrel with his knuckles. "So, you've got a Flash Gordon ray gun that melts glue? What is this, aluminum?" "Titanium." "I _thought_ that was titanium. But, man, nobody can machine titanium. Even Steve Jobs can't machine titanium. Where on earth did you get this thing? It's insanely great!" "I keep it to scare off the crack pushers." Tony reverently wrapped the electrical wire around the glue gun's butt. "You wouldn't believe what I went through at the FCC today," he said. "It was truly awful. It was bloody blue ruin. But _this_ thing, Van." He burst into whoops of laughter as he put the gun back in the wall holster. "You, my man. You have just made my year!" Tony really did have a chauffeur, and he really did have a bodyguard. They were two dark, gloomy men with a silent, rent-a-cop, paid-by-the-hour look. They sat in the front of the limo, while Tony and Van sat together in the plush, upholstered back. It had always been their principle never to mix liquor, so Tony opened the limo's bar to retrieve some Courvoisier. The bar supplied them with nifty little translucent green shot glasses. Van downed his shot. This brandy was not just good, but superbly good. It was soul-stirring. It gave him just the jolt he needed to get to the point. "Tony, why did you come to see me tonight?" Tony smacked his lips and poured himself a second one. "Hey, I was in town, man! Tomorrow—well, maybe two days from now, counting the dateline—I'll be back in India. At a New Year's party at a mountain resort, with a very beautiful woman. I should tell you all about dating Anjali, my man. Anjali Devgan, from Bollywood. You would find this story very, very revelatory." "That must be pretty hot." "It is a different world over there. It is an entirely different erotic universe. That woman has ruined me. She has. She is fantastic. Anjali has made me into some kind of centuries-eaten male statue from the temples of Khajuraho. She and I are like water and fire. There are sexual clashes that yaks can hear in Nepal." "What can I really do for you, Tony?" "Nothing, my man! I swear I'm beyond all help!" "Just tell it to me, all right? This is Van here." Tony checked the bulletproof glass between themselves and the driver's compartment. "Okay . . . but I _really_ shouldn't tell you this." "Right." Van started to relax a little. Here it came, then. "I didn't want to tell you. You're forcing it out of me." "Right, Tony." "I shouldn't tell you this because there is money in it. A lot of money. And I've got a lot to gain by that, so I am not an objective witness here. Bearing that in mind." Van nodded silently. "The KH-13," Tony said. A spy satellite. "I've heard of it," Van said. "It is an overengineered, sorry-ass piece of junk." "I heard that, too." "Two years behind schedule. Way over budget, hundreds of millions. A launch weight over seven thousand pounds, so it won't even fit in a standard Titan booster. They cheated DeFanti on that one. The KH-13 is the only U.S. spy satellite in orbit that doesn't have Tom's imaging chips. Tom got beat out in the bidding, and you know, that was a crooked deal, but that's a long story . . . The point is, they are bureaucrats. And they tried to make a new-model spy satellite. They tried to do that and they _screwed it up bad,_ Van. Now, DeFanti could have pulled that stunt off, because he always had this really tight crew of top people—" "Really quiet," said Van. "Really quick. And always on time. Top people, but maybe ten percent of the number of technicians that anybody else would use." Tony put his shot glass on the limo's hanging board. "Yeah. I never thought of it quite that way, but yeah, that's exactly how that worked." "So what is the problem?" "They farmed out the new KH-13 to this bunch of crooked fat cats. So right when America really needs fresh eyes in space, we are screwed. They managed to launch exactly one KH-13, and the stupid bastard is on the blink. It is way too sophisticated and overfeatured, especially in the infrared cameras. The KH-13 is supposed to be able to spot muzzle flashes in real time from automatic weapons in terrorist training camps. That is a _crazy_ thing to ask from a satellite. And whose fault is it that the project is so screwed up? It's anybody's fault! Anybody but the almighty Air Force and the NRO! They are looking for somebody to hang it on. They need a fall guy." Why was Tony telling him this? "Tony, I'm in cyberspace, not outer space." "There is this guy, Michael Hickok." Van waited. Here came the rest of it, then. "Hickok is this black-bag guy who did a lot of dirty work overseas. Chechnya, Central Asia, Kazakhstan where the launch pads are . . . Hickok's a mercenary. The guy is up for anything. He's been hired to find some political cover. So you know what the spin is now? It's all a 'software problem,' Van." "Ah-ha." Van scowled. "Blame the coders for it. Blame the geeks." "Hickok is going door-to-door looking for somebody to pin that satellite's problem on. Don't let that be you. Okay? Because your new outfit is getting some real credibility in the code world. That means that incompetent people will try to drop all their crap problems on you. From a great, great political height." "Tony, we're not looking for any satellite problems at the CCIAB. Trust me here, we've got our own problems to hack and plenty of them." "Van, look out the window, okay? This is Washington! You don't get the luxury of minding your own business in this town. The KH-13 is political. It is the kind of problem that comes looking for you." Van thought this statement over. It had the ugly smack of authenticity. "So here it comes, straight at me and my people, that's what you're telling me?" Tony had turned his face to the passing streetlights. "There's not much I can do for him now, but Tom DeFanti was my people, and Tom DeFanti _was_ the spy-sat business. So I _know_ that problem's coming for you." Van considered this. "But what if I can fix it?" Tony was at a loss for words. "Okay," he said at last. "If it really _was_ just a software problem, yeah, you would probably be the guy who could fix that. But that is not the problem at all. The KH-13 is a boondoggle from start to finish. The U.S. had a huge lead in spy-sats. Nobody ever figured we would really need much better ones. The spy-sat contractors had the fix in, they had themselves a sweet racket. Now they have a flying gold-plated Cadillac with an engine that is Detroit junk. You wanna fix something? Go fix Lockheed Martin and General Dynamics." "Okay, Tony. I hear you." "You're a pretty good guy, Van, but you're not up for fixing the military-industrial complex. I'm not trying to tell you to rush out there with guns blazing and bring me some justice. I would never ask that of you, man. I'm just warning you to duck. That's all I have to say." "Thanks for the heads-up, Tony. I don't forget stuff like this." "I really shouldn't have told you that, Van. You are not properly cleared. We could go to jail for that." Van sighed. "Tony, we're not going to jail. We are going bowling." "Right." "We went bowling together. That is all we did." "Absolutely, man. Totally. Swear it in court." "And you told me all about your hot date with this Indian actress." "Oh, yeah, she's an actress," Tony agreed. Tony was much improved now. "But you know, Van, the actress part is kind of the least of her." CHAPTER SIX AN UNDISCLOSED LOCATION, JANUARY 2002 **J** eb's effort to assemble a federal security consensus had its thornier side. Washington's political establishment cared little for computers. They were completely obsessed with aircraft flight safety. To Van, this strategy made no sense. It was typical of panicky amateurs who couldn't think through security issues from a sensible engineering perspective. Obviously, al Qaeda was not going to repeat their September 11 airplane attack. Terrorists never did that. The element of surprise was vital to them. No crew or passengers on earth would ever again surrender an airplane to attackers armed with razor blades. Not when it was obvious that everyone inside the airplane was going to die. Logically, it was both useless and impossibly expensive to try to protect airlines from razor blades. The airlines would go broke trying that stunt. It was also beside the point. Airports everywhere were still selling liquor bottles. Any hijacker with a liquor bottle had a big glass club full of flammable liquid that could be turned into a deadly glass dagger with one good whack on a bulkhead. A fifth of Jack Daniel's made a much worse weapon than a tiny boxcutter. Where were the priorities here? Why hadn't someone thought that through? Still, Van could understand why politicians obsessed about plummeting airplanes. A falling airplane was one of the few weapons that could kill a large crowd of politicians inside Washington. So the CCIAB was willing to swallow that foolishness, for the sake of political need—but it got worse. If terrorists really did want to use airplanes to assault a center of government, then civilian passenger airliners were a lousy choice for that kind of attack. Civilian airliners were way too slow, too well policed, and had too many witnesses and busybodies on board. The ideal flying assassination weapon for kamikaze terrorists would be a private business jet. Their crews were small, and such jets were easy to steal from a hangar. Then the stolen jet could be packed with explosives, Oklahoma City style. It was a matter of simple physics, obvious once you worked it all out on paper. Stolen business jets were sure to hit much harder, faster, and more effectively than the September 11 passenger planes. But while Joe and Jane Consumer were having their shoes x-rayed at the airport, nobody in federal security was doing anything useful about the stark threat posed by private jets. Private jet owners were America's richest people. Nobody in Congress dared to offend them. American rich people were too rich to get treated like terrorists. Even though Osama bin Laden was plenty rich, and probably the world's best terrorist ever. Shoko Asahara, the nerve-gas yoga mastermind, was so rich he could afford private helicopters. If anybody was a serious terrorist security problem, it was rogue rich people. However, this huge gap in America's air defenses hadn't escaped the attention of the Air Force Office of Experimental Avionic Research in Colorado Springs. These guys, who had the sexy military-style acronym AFOXAR, had been working on the problem with some quiet help from NASA and DARPA. Their first conversion target was the BBJ, Boeing Business Jet, the largest and therefore most dangerous aircraft of the American private jet fleet. Their scheme was to come up with a small, secret autopilot that could be quietly installed inside jets and then triggered remotely during emergencies. Then the autopilot would guide the plane and its baffled terrorists right back to earth, and the waiting arms of fully informed police. This scheme sounded simple enough, but the devil was in the details. Remote control of flying jets posed many daunting challenges, but one of the worst was the software. Because, if some clever hacker ever took over the control system itself, then all of America's private jets could be turned instantly into remote-control flying bombs. The AFOXAR guys had done a lot of career work on remote-controlled surveillance drones. They truly got it about air control and avionics problems, but serious network security was beyond their reach. Jeb had taken on the software problem for AFOXAR, because it was politically useful for the CCIAB to have a hand-in with homeland aircraft security. Though it made little sense from a technical perspective, it would get the attention of congressmen. Van's Grendel project had stabilized for the time being, so Van found himself tasked with retrofitting secure spy-satellite controls for use within private jets. Van doubted that this project was likely to thrive—it would only stay sexy as long as there were headlines about hijackers—but Van was not his own boss. Besides, once he looked at the technical details, it turned out to be very interesting technical work with broad applications. After all, spy satellites were remote-controlled flying objects. They also had some very well-tested crypto communications protocols. Van had never expected outer space to be so rich in supersecret high technology, but in point of fact, it was fascinating. For some forty years an incredible variety of adversaries had tried to "spoof" American satellites. To hack and "own" a supersecret American KH-11 Keyhole or Aquacade in orbit—that would be a huge accomplishment in espionage, a much bigger deal than Falcon, or Snowman, or Jonathan Pollard. Huge enemy effort had been wasted in this. Nobody—not the Chinese, not the Russians, not even the French or the British—had ever touched America's supreme technical command of telemetry, systems acquisition, phase-locked carrier tracking loops, phase-coherent tracking, and stochastic integro-differential hybrid multichannel carriers. Van was truly in his element with this part of his new assignment, and he really enjoyed his briefings. Van was way beyond a mere "Top Secret" clearance now—he had achieved ratings like "Executive Gamma" and "NKR," where his briefing material was brought to him by the hands of couriers, on flimsy, easy-burning sheets of typewritten onionskin. The grumpy, reluctant NSA and NRO techs hated telling Van anything. Their stovepipe was melting awfully. They were dropping their pants and revealing their family jewels. The NSA satellite geeks came from some strange parallel world of computation where everything important had been invented in the 1960s by forty thousand mathematicians under a big hill in Maryland. Van felt a strange respect for them—not for the modern NSA guys, who were sort of lost and snooty and owlish, but for the amazing Cold War rocket state of his grandfather's generation. A lost empire of truly macho engineering, where America's best tech guys just sort of rolled up their sleeves, lit an unfiltered Camel, and detonated hydrogen bombs. Van had lost a personal fortune while working for the CCIAB, but there was no question that he was learning incredible stuff. The NSA was a mystery even to the people who worked inside it. Their secret spy feats were the stuff of distant, mist-shrouded legends. Before their first spy satellites were ever launchable, American spies had used eavesdropping balloons. They'd sprayed toxic metal clouds into the sky that reflected Soviet radio signals from far over the horizon. Fewer and fewer government veterans still remembered any of this stuff. Huge bursts of top-secret ingenuity had just plain been forgotten. It had been nailed into wooden crates and lost inside some warehouse, like the Ark of the Covenant in _Indiana Jones._ The remote-control code that Van was now examining was a direct descendant of that mythical era. It wasn't native computer code, it was space-machine code. His own grandfather had probably had something to do with developing this stuff, as he worked on that lost 1960s cruise missile. It was a living space-age fossil. It was code built entirely for electronic spying, electronic spacecraft, and electronic Cold Warfare. It had crept into the modern cyber-world like a digital trilobite. Still, nobody had ever broken it, because the math behind it was rock-solid. So, Van and his clients in AFOXAR now faced the serious technical challenge of repurposing this satellite control code for use in aircraft. And not normal, everyday aircraft, either. Very fast, low-flying aircraft, stolen or hijacked, skimming the hilltops to stay off Air Force radar, as they zoomed toward the White House or Capitol with a bellyfull of terrorist explosives. The likeliest engineering solution looked like a geosynchronous aircraft-control super-satellite somehow hooked into the satellite GPS system. This was a typically bloated Pentagon-style solution that would pull down sixty billion and take a generation to design, build, and implement. Van was hoping for something much quicker and quieter that might be delivered before he died of old age. He figured the CCIAB's best approach was to repeat a Grendel-style success. Make one working model as a proof-of-concept, and just install it somewhere in somebody's jet. The AFOXAR guys were pressuring NASA and Boeing to get them a nice handy jet they could wreck. AFOXAR guys were a small gang of young engineers that nobody had heard of, but they didn't brag much, they worked fast, and they were very can-do. Van was in his tiny Vault office, deeply engrossed in this problem, when Fawn came swooning past his tangerine-colored cubicle divider. "Ohmigod, it's him! He's here. Elvis is here. Elvis is asking for you!" "Who?" said Van. He was no longer even a little startled when Fawn said something apparently insane. Fawn Glickleister was not crazy. She was just so intensely bright that she cut into reality at a sharp angle. "It's that tall dark handsome dude with that secure briefcase strapped to his arm. He's waiting out in the corridor, Van. He needs to consult with us!" Van came to full alert. "That guy doesn't look much like Elvis." "Well he's Southern," Fawn gushed. "He _feels_ like Elvis. He's just like Bill Clinton that way. Ohmigod, he is such a dreamboat, Van. He's the hottest guy in the Vault." "What is it with you, Fawn? Get a grip." "Let's investigate him!" "Show him in here." Van nodded. His code-wearied brain could use the break. Elvis shouldered his way into Van's tight cement warren. He was wearing a black blazer and a white polo shirt and gray pants and black shoes. Elvis had changed out of his gym clothes, Van thought. This clearly implied that he could unlatch himself from that briefcase somehow. Van offered Elvis the Leap Chair and sat on the ripply edge of his plastic computer desk. The Vault cells were so small that it was like meeting a guy inside a photography booth. "I'm Dr. Vandeveer," Van offered. "What can we do you for?" Elvis crushed Van's hand with a Right Stuff handshake. "I'm Michael Hickok." Van's crushed hand flew straight to his beard. He stroked it thoughtfully. Hickok didn't seem to notice his shock. After a moment, Van had steadied himself. So here he was at last then, Michael Hickok, that hustler, that ruthless mercenary, showing up at the office like a bad penny. Jeez, no wonder Hickok never took that briefcase off—he was wandering around just like that lost atomic lunatic in _Repo Man._ A cynical operator with a thirteen-billion-dollar political liability that he was trying to dump on the first available sucker. And he'd already successfully put the charm on Van's naive young secretary. If Tony Carew hadn't bent the rules to warn him . . . "Nice to meet you," Van lied. "Doc, I'm told you've been cleared Executive Gamma," said Hickok. "That's true. We do some satellite work here at the CCIAB. Communications software and protocols." "I can't understand that sort of thing myself," drawled Hickok. "But my employers are real, real anxious to have some experts doctor their sick bird." "I see." Van was fully prepared to lower the boom on the guy. Close up and in person, though, Hickok gave off the spooky vibe of a Delta Force karate master. It looked like he could break every object in the room with his bare feet. Why rush anything? Van thought. Surely it would be much cagier to study Hickok's technique. Politely lure him in with a pretense of innocent cooperation. "So tell me about it." Hickok reached into his pocket and removed a lethal-looking folding knife with a dangling set of keys. "I'll have to open this secure briefcase now." Van glanced up. "Scram, Fawn." Fawn's eager face fell. Fawn was not cleared Executive Gamma. "But . . ." "Shut the door, and shut the outer door. Stand in the hall. If you see anybody strange, let me know right away." "Yes, sir," said Fawn, who never called him "sir." She left. Hickok opened the briefcase with a small gray key. The case held a set of common-looking Pentagon-style folders, the sort used for weapons procurement programs. Van had seen more than his share of these Pentagon folders lately. Through fifty years of military bureaucratic ritual, the Pentagon had created its own unique paperwork style, with everything initialized through chains of superior officers, and documented in quintuplicate. Van recognized the folders he was confronting as a classic "Pearl Harbor file." Whenever a big-ticket project went sour, paperwork escalated as the guilty parties tried to cover their asses from the investigation that they knew was coming. The folders began to bulge, dent, and rip. There was wear and tear as the evidence got tossed from hand to hand like a hot potato. There was no way Van was going to waste his life working his way through this huge stack of self-serving gibberish. It was time to move this farce right along. "I see we have a big opportunity-cost here." "That's the truth," said Hickok, "but my employers are willing to be more than generous with resources. That's a ten-billion-dollar project you're lookin' at there." Van knew for a fact that the KH-13 was a thirteen-billion-dollar boondoggle that had been budgeted for eight. Van waved his hand around the junk-towering walls of his tiny office. It was densely crowded with hopeful toys of the infowar trade: solar-powered outdoor spycams, shirt-pocket-sized anthrax sniffers, biometric access gizmos that stared into eyeballs and sucked users' thumbs. Ninety percent of them were useless, but someone responsible had to look at them and throw them away. "As you can see, we have other proj-ects here, more in line with our core tasking." Had he really just said "core tasking"? The sense of fear and threat that poured off the sinister Hickok was really jazzing him up. "Look, doc, I wouldn't be coming here to y'all if there hadn't already been investigations," said Hickok, producing a much slimmer folder in a different shade of blue. "The bird worked fine on launch—just a few shakedown bugs. She didn't start acting serious weird till a year ago. Believe me, we had plenty of people watching her." Van looked at the light blue folder without touching it. Something deep in him was hooked by this situation. His curiosity had been set to tingling. Van sensed something peculiar here. Michael Hickok was a very scary guy, but he just didn't feel like a smooth political operator who was out to play pin the tail on the donkey. Hickok just didn't seem bright enough to be capable of a scheme that complicated. Maybe Tony Carew had never personally met Michael Hickok. Just possibly, there was some big, dumb, simple mistake here. Something that had gone wrong a long time ago, that Van could put right. "So, is the bird tumbling?" "Nope. She's solid as a rock." "Noisy links? Bandwidth too tight?" Hickok shook his handsome head. "She can talk to the ground." Van had to like a guy who called a satellite "she." "You might have some antenna obscurations. Are you getting a lot of SEU's?" "What's that again?" "'Single Event Upsets.' " "Look, doc, I can follow most of this, but I'm just a simple country boy who is ex-Air Force Special Operations Command," said Hickok. "You want a solid air-to-ground spotter link for a Predator drone in the back end of nowhere, then I am your man. Rocket science, that's a little beyond me. But I can sure see it's not beyond _you._ Let's talk some turkey here. You look to me like the kind of man who can get this job done!" Van was flattered. Then he sensed a trap snapping shut. Oh, yeah, this was the honeypot principle at work here: no overconfident hotshot could resist a sweet appeal to his ego. It amazed Van how good it felt to be played for a real sap. "It's not likely I'll ever repair a satellite for you," he said. "The CCIAB is a policy board." "But there's money waitin' on the table! You could hire people! And people tell me this Grendel machine of yours is twenty years ahead of our time." Now Van knew that he was being played for a sucker. "That may be so, but Grendel also takes a whole lot of my work time. All of it, really. I'm sorry to turn you down." Hickok's face darkened. He was not the kind of man to take a rejection kindly. It was clear he'd had more than his share lately. "It's like that, is it?" "Like what?" Van said. "You can't deliver! You're one of those R&D guys, so you're always chasing the next hot biscuit. You're all velocity and no vector!" Rage flared within Van like a match on crumpled fax paper. "Look, pal, you're coming to me, I didn't come to you. Why should I care? Take a hike." "Why should you care? We're in a war now, Jack! I got buddies of mine freezing their ass off in the 'Stan, and you're sitting here with this faggoty dot-com stuff!" Hickok flicked a finger onto Van's halogen desk lamp with a light aluminum clink. "That is America's next-generation spy-sat, you egghead dork! It could save the lives of American soldiers out in the field! But not you, no, you're too good for that!" With a heroic, life-changing effort, Van got his searing temper back under control. He wasn't going to punch a guest inside his own office. Besides, something deep in him told him he was confronting a very dangerous man here, somebody who could kill him easily. "Look, Mr. Hickok, if I'm not serious about this war, then what the hell am I doing in a damn secret bunker in West Virginia? You wanna tell me my job? Sit down here and start coding. See how far you get." "That's what I'm asking from _you,_ doc." "Go to hell. The KH-13 is a sorry piece of junk. It's gonna fall out of the sky like a bank vault. You want that thing to fall on me and my people? No way. Go find some other sucker." "Look, you don't know all that," Hickok protested, with surprising mildness. He touched his pale blue folder. "You didn't even look at the evidence here." "I don't need to look at your evidence." Hickok's eyes grew round and mild. "You're a scientist and you're saying that to me? Scientists are s'posed to look at the evidence. That's what I always heard." "Well . . ." Van fell silent. He felt pinned down. No option was good in his situation suddenly. "Look, this has got nothing to do with scientific evidence. This folder here, this blue thing, this is a legal trail. I'd have to sign off on it to look at this blue folder. Then your bosses would be all over me. Right away. They'd nail me for it because I was the last guy to touch the hot potato." Hickok narrowed his eyes. "Damn. I never thought about it that way. So that's your big problem, huh? You don't want your nose in a mousetrap." "You bet that's my problem." "That's right," Hickok admitted. "They'd do that kind of thing, too." It wasn't a question. It wasn't even an admission. It was a realistic assessment. "But if you really fixed this bird, doc, they wouldn't have to blame anybody." "I'd love to fix your bird," Van told him. "I'm of a different generation than those guys who built the Space Age. We've got much better methods of computer analysis now, and I like to think that maybe I actually _could_ fix the thing, if I had some time and resources. But they don't want me to fix it. They just want me to touch it." Van shrugged. "Look, I'm not putting my initials on any of that paper. That's too much to ask of me." "I can get it about all that," said Hickok. "Everywhere I go in this world, there's some kind of hell that started long before I was ever born." Hickok had gone strangely stiff. Suppressed fury, maybe. It might even be shame. "Suppose I left this little blue folder under a bench in the gym." Van felt his eyes widen. "That's crazy. That's an NKR document. You wouldn't do that." "I take long showers," Hickok snarled. "You're a tough guy in the gym, right, Mr. Computer Geek? I've seen you in there. Maybe you could skip a couple of your sets on that Nautilus." Maybe I would, thought Van, and maybe I wouldn't. And maybe he would, and maybe he wouldn't. He jumped from the edge of his worktable. "Why not right now?" CHAPTER SEVEN PINECREST RANCH, COLORADO, JANUARY 2002 **T** ony Carew spent his afternoon watching his girlfriend performing in the snow. Anjali aimed to become Bollywood's Heroine Number One, outdoing Aishwarya Rai, Bipasha Basu, and the Kapoor sisters. If flesh and blood could do this, then Anjali had them to give. Anjali lip-synched to the piercing Hindi soundtrack while whirling, fluttering, bumping, and grinding. Repeatedly, glowingly, beautifully. Take after grueling take, on a sunny midwinter day, at a nine-thousand-foot elevation. Indian film fans loved romantic mountain scenes. So much so that the Indian movie industry had worn Switzerland out, and Tony Carew was supplying them with Colorado's mountains, instead. The audience for Bollywood movies was rather peculiar about snow. The core Indian village audience, all billion of them, regarded snow as a mythical, romantic substance, something like fairy dust or cocaine. So Hindi film actresses never wore coats or jackets while dancing in the snow. They had to perform bareheaded and bare-armed in their customary midriff-baring chiffon, brilliantly smiling and bitterly freezing. Between takes, Anjali rushed to the sidelines to drink hot goat's-milk cocoa and breathe oxygen from a black rubber mask. Anjali's co-star, Sanjay, who was also her cousin, was the film's male lead. Being a man, whenever Sanjay was in snow, he got to wear thick boots, long trousers, and an insulated jacket. Sanjay was big, solid, deft, graceful, and wonderfully handsome. The Bombay film clan of Sanjay and Anjali had been breeding movie stars for a hundred years. In Sanjay the family had produced a huge, beautiful animal. In Bollywood, actors weren't just movie stars—they were "heroes." Sanjay was a twenty-first-century Indian hero. Sanjay wasn't kidding about this ambition, either. Like most film-star children, Sanjay had started his film career as a teen romance lead, but he needed those big mid-career payoffs as a tough-guy Indian action star. So, Sanjay had boldly enlisted in the Indian Army. Young Sanjay had been a soldier against Moslem terrorists, on patrol in the blood-spattered mountains of Kashmir. He had driven an Army jeep and carried a machine gun along the dangerous Indo-Pakistani Line of Control. Sanjay had won a huge amount of worshipful Indian media coverage for these patriotic publicity stunts. Pundits in the know were already talking wisely about Sanjay's future political career. The Bharatiya Janata Party or "Indian People's Party" were Sanjay's brand of leaders. The BJP were tough, heavily armed right-wingers who had been running the Indian government since 1998. Sanjay was the BJP's kind of movie star, a modern guy with big modern Indian muscle, great Indian clothes, cool Indian moon rockets, and extremely dangerous Indian atom bombs. Sanjay's violent adventure movies always played well with these tense, nervy Indian superpatriots. Sanjay's dad, who had won huge popularity playing Shiva in a TV soap opera, was a BJP member of the Indian Parliament. Knowing all this, Tony was very concerned about Sanjay, and not in a good way. Tony's wild romance with Anjali had gotten a lot of play in the Bollywood film press. Bollywood always publicized the love life of its film stars, and the more peculiar, the better. Sanjay could break both of Tony's arms like matchsticks. And yet Sanjay had never said a word about the Anjali situation. Tony wasn't quite sure if this dicey situation was just a given, or completely unspeakable. Many, many things in India were both at the same time. Tony had a lot of investments in Bangalore, and offshore outsourcing was one of his major lines of work lately. What Anjali got out of all this was less clear to Tony, but Anjali always went along for Sanjay's hunting trips, no matter where in the world he went. While she was hunting, Anjali was allowed to live without her golden saris, her heavy jewels, her movie cameras, and her greasepaint. Hunting trips were the closest thing to freedom that Anjali would ever be allowed. Tony was also pretty sure that Anjali had been deputized by the family's women to spy on Sanjay. She always went along with the big-game hunter to make sure the family's favored son didn't do anything unpredictable and James Dean-like, such as blowing his own head off. The sudden glamorous arrival of Indian film stars had absolutely thrilled the Indian staff at the Colorado telescope facility. The Indian staffers that Tony had hired were Bangalore software hacks, living in America on business visas. Most of the time, the Indian staffers felt very isolated in the remote Colorado mountains. Sanjay and Anjali had done wonders for their morale. Sanjay and Anjali seemed pleased to tour the wonders of the telescope and to pose for friendly snapshots with the staffers. Bombay film stars took their offshore fans very seriously. With another day's shooting wrapped up and in the can, the film stars drove to Pinecrest to kill some elk. They took a sturdy set of nicely heated Jeep SUVs, with ruggedized tires and the standard Pinecrest luxury tourist provisions. Their driver and hunting guide was a Chinese servant who called himself "Chet." Like all of Mrs. DeFanti's Chinese ranch staff, Chet was so tidy and reserved as to be practically invisible. Sanjay sprawled in the Jeep's toasty passenger seat, wearing a brand-new black cowboy hat and a spotless leather jacket. Pinecrest Ranch had loaned Sanjay an enormous .338 Winchester Magnum. When he wasn't caressing the rifle, Sanjay made a lot of use of his silver hip flask. Sanjay tended to drink steadily while "hunting," also easing the tedium with high-stakes poker games and dirty songs in Hindi. Tony and Anjali also rode in Sanjay's Jeep, sharing the backseat with Tony's smaller, very uncomfortable 30.06 rifle. They were trailed by two other big Jeeps from the Pinecrest fleet, bristling with weapons and crammed with Sanjay's male drinking buddies from the film crew. Being from Bollywood, Sanjay never went anywhere in life without a posse of backup dancers. The Jeep lurched over a boulder in the uphill trail, and Anjali brushed against him. "Tony," she fluted. Tony brushed a wrinkle from his nylon jacket. "What, _sajaana_?" "Tony, you're too quiet. What are you thinking, Tony?" "Why, I'm thinking of you, _maahiyaa._ " Anjali's eyelids fluttered. She was twenty-three years old and had the eyes of a Mughal concubine. Her eyes inspired in men an uncontrollable urge to shower her with jewels. "So, what, my dear, thinking what? That you miss me when I don't see you? Because I miss you so much, Tony. Morning, noon, and night." In a gesture of limpid sincerity, she placed a slender hand against her brassiere. Tony coughed in the dry mountain air. "Baby, sweetie, honey-pie, _terii puuja karuun main to har dam._ " Anjali broke into a musical peal of laughter. She loved it when he quoted her song lyrics. "Oh, you, you lover boy! Just shut up, _yaar_!" The Jeep lumbered into a chilly patch of open air and twilight. The long drought had been unkind to Colorado. A local mountain, federal park territory, had snowy slopes measled all over with big seared patches of black ash. "Your little mountains look so sad," said Sanjay. "They're not the Himalayas, dear boy." "You're absolutely right about that," said Tony. "And your fancy telescope is too low. Lower than India's big mountain telescope." "Yeah, you mean that Indian Astronomical Observatory up in Hanle?" "It's four hundred meters higher than yours." "Two hundred meters," said Tony. "I measured it." Sanjay turned in his seat, throwing back a leather-jacketed elbow. His gazellelike eyes were reddened with altitude and drink. "Is that a joke?" "If you like." "I don't like jokes." "I don't like _you,_ " said Tony. Two heartbeats passed. _"Ruup aisa suhaana tera chaand bhii hai diiwaana tera."_ The Jeep erupted in laughter. Even stony Chet the driver chuckled, relieved to see that Sanjay was guffawing at Tony's wit instead of putting a bullet through somebody. Sanjay was all chuckles now. " _Bindaas,_ " he told his cousin. Anjali lifted one dainty thumb and wiggled it enthusiastically. It was a gesture completely without any Western equivalent. " _Yehi hai_ right choice!" she purred. The Jeep's engine labored as Chet fought the slope. Anjali put her pink-nailed hand around Tony's forearm. "You're so good with him," she whispered. "Am I good for you, precious?" Anjali glanced toward the front seat. Sanjay was sinking into boozy indifference. Anjali drew her tapered finger down Tony's cheek and gently caught and pinched his lower lip. This was her favorite caress. Incredibly, as always, it worked on Tony. It blew every circuit in him. It plunged him instantly, wildly, uncontrollably, into the head-spinning saffron depths of the Kama Sutra. Tony had never believed that such things were possible. When he was away from Anjali—and he spent a lot of time away from Anjali, for the sake of his sanity—he found himself incredulous that such things could ever happen between man and woman. But then she'd be back in his arm's reach, and oh, my God. It wasn't her beauty that had trapped him, or the fantastic sex, or even the looming, steadily growing danger that some angry man in her family would shoot him dead. It was the sheer sense of wonder, really. Anjali Devgan had been Miss Universe 1999. She was quite likely the most beautiful woman in the entire world. Chet pulled the Jeep into a sloping meadow. Sanjay drained his silver hip flask, zipped his leather jacket, shoulder-slung his heavy rifle, and bounded right out the Jeep's door. The other two vehicles pulled up and stopped, crunching through some low-hanging pine branches. Nobody looked eager to follow the great man and his gun. There had, apparently, been some unlucky incidents in the past. These Hindi film guys were good-natured media pros. Unlike Sanjay, they were not rifle-toting assassins by conviction. The hip Bombay film dudes were mostly interested in the nifty contents of their Jeeps, which had been loaded with Teutonic thoroughness for the benefit of German hunters. Big windproof tents, portable tables and chairs, gas stoves, odd German board games, ecologically correct windup lanterns, rope, matches, cases of German beer, latrine shovels . . . In the back of a Jeep, Anjali discovered a thin, silvery NASA space blanket. She pulled it from its plastic wrap. "How pretty." "Yeah, baby, that's for astronauts." With a practiced whip of her wrists, Anjali fluttered the thin silver garment through the air. Then she wrapped herself in it with a well-rehearsed, arm-twisting spin. Instant space-age sari. The film boys looked up and applauded cynically. "It's warm," she told him, eyes glowing. Tony nodded speechlessly. On her, it was so very hot. Anjali shot him a come-on look that burned the marrow of his thighbones. Then she drifted off into the pines, gently trailing her silver scarf, her spotless Timberland boots flashing over the fallen trees. With a steely effort, Tony waited until Anjali had faded from sight. Inflamed though he was, it wouldn't do to run off with Anjali in full, blatant sight of the entire crew. Anjali was a clever and practical girl. She wouldn't run much farther than earshot. Tony fiddled unconvincingly with his rifle while the boys struggled to set up a nylon and aluminum tent. Stalking elk in Colorado snow was the last thing on the film crew's minds. As soon as they could manage, they'd be settling into those heated camp chairs to get right into the German beer and the poker cards. Tony set about to track down his girlfriend. Unfortunately Tony Carew was a dedicated urbanite. Once in the huge, chilly forest, he quickly lost her footprints and all trace of her. A few discreet Nelson Eddy forest love-calls got no response. When Tony searched harder, he even lost the camp and the Jeeps. How had he managed to wander off without a handheld Global Positioning System? He stumbled through the pines in increasing dismay. He heard the repeated boom of Sanjay's rifle. Sanjay had blown away not one, but three elk. The three huge dead animals were lying in a clearing, almost nose to tail, big heaps of bloody meat. Tony emerged from the woods, his rifle in the crook of his arm. "They didn't run," Sanjay told him. "They didn't run?" "No. What's wrong with them? They should run from me." Tony led Sanjay across the brown, snow-choked grass to his nearest kill. An elk was a huge beast, three times the bulk of a deer. It had a lustrous sofalike hide, and a rack of antlers the size of an easy chair. The black skin of the animal's muzzle had a scorched, cracked look. Its eyes were filmed and filthy. Caked slobber was streaked down its muzzle. Tony switched his rifle from one arm to the other. "Nobody's been looking after these animals since the old man went wrong in the head." Sanjay was as stupid and vain as most young actors, but he had flashes of lucidity. "These animals are sick, Tony. They are _very_ sick." Sanjay tipped his black hat back and raised his elegant brows. "They are blind." Tony nodded soberly. "Yes, they are. Do you know of a sickness called 'elk wasting'?" "No. So this is it?" "It's similar to Mad Cow Disease. From the same source, really. It starts in tainted food. Old DeFanti used to feed his elk cattle chow, to keep them sleek during the winter. I always warned him that the cattle chow might be tainted. But he was an old man, stubborn. Sometimes he wouldn't listen to good sense." An ugly smile spread across Sanjay's face. "So that is your story, eh?" "How's that?" "I could make a film from this. I could make an epic. The story of Mad Cow Disease. The story of the West. It first came when the British slaughtered sick sheep, and fed the bone meal to innocent cows. A very wicked practice. For years they tried to conceal the sickness from those who ate the flesh of cattle." Tony shrugged. "Well, everybody really needed the money." "Then the sickness came to America. Not in England's cattle. In America's wild animals. 'Elk wasting,' it gets a new name here." "Well, yes, I guess that's all true, more or less." "And then that Western sickness struck down Tom DeFanti himself! Because the owner of this land fed his animals that evil poison. Then he ate their flesh! Now the madness is inside his own body! The world's great master of high-tech media is a sad, mad beast!" "Don't talk that way about him." Tony tightened his grip on his rifle. "He was my guru." "Sorry, _bhaiyya._ " Sanjay seemed touched. "Really sorry. It's just . . . that is such a wonderful script for a horror movie. Very modern. Very Ramgopal Varma." Tony gritted his teeth. "I never told you that story, Sanjay. You never heard that story from me. Nobody ever talks about Tom that way. Nobody asks or tells." Sanjay shrugged, and fixed Tony with his brown, lambent gaze. "The man is my host! Why would I talk against him? I ate his salt—although, thank God, I never ate his meat." "Right." "I've been around the world many times. I've seen stranger things than the fate of your guru. The world is strange, these days." "Tom's life was always strange." After a moment, Tony decisively jacked a round into the chamber. "Sanjay, all these elk must be destroyed." "What, all of them? Now? Today?" "Yes. Because elk wasting is a contagious disease. It's an unclean herd. The Colorado tourist trade doesn't talk about it much, but for obvious reasons, they're at war with this." Sanjay considered this for a long moment. Slushy snow fell from the height of a tree. "What a beautiful hunting trip you have offered me here in America," he said at last. "Look at the huge head on your fine beast here. What's that word?" "Antlers." "Antlers, yes. Fantastic antlers. Another fine trophy for my hunting club in Ootacamund." "Let the head be, Sanjay. You don't want a taxidermist touching that brain matter." Six more elk, stumbling together in a clump, entered the clearing. The elk had their muzzles down, as if sniffing along. They were thudding into each other's flanks as if they found comfort in it. They were graceless and dirty. Some were drooling. Tony snapped off a shot. It was hard to miss at this range. A cow went down and lay in the grass, thrashing. The herd panicked at the sound of the shot, but they could not see to flee. They just stumbled, crashing and ripping their hides against the underbrush. Sanjay deftly shouldered the heavy Winchester. The rifle boomed again and again and more elk buckled, jerked backward, and collapsed. When the heavy-grain bullets took them at the base of the neck, the elk went down as if guillotined. Sanjay was an excellent shot. One surviving elk thrashed into the undergrowth. It wouldn't be hard to track. Sanjay put a final shot into a crippled cow. He gave Tony a brotherly pat on the shoulder. "You don't worry about this, Tony. Because yes, I understand. I can help you with problems like this." "Just as long as it's quick, Sanjay. And kept quiet." Sanjay swung his chiseled chin in a nod. "We'll get my very best boys! And your very best guns." CHAPTER EIGHT WASHINGTON–COLORADO, FEBRUARY 2002 **T** he CCIAB had a difficult relationship with America's spy satellites. Spy satellites were critical infrastructure of intense and lasting importance to national security. Since the satellite programs also had a huge black budget, everybody naturally wanted in. The little CCIAB was in no political position to make any bold grab for these crown jewels of orbiting spookdom. As Tony Carew had cynically pointed out, the likeliest role for the CCIAB here would be "fall guy." And yet, on a stark, technical level, the KH-13 satellite was badly broken. Obviously, some really gifted technician ought to fix the thing. Nobody seemed to be getting anywhere with it. If the KH-13 failed, that would be a massive disaster. An economic, industrial, technical, and military mess. Van felt that preventing a massive disaster was probably his duty. What else was he good for? Why else had they hired him? What else was he doing in Washington? Van knew that the CCIAB had many pressing problems on its agenda. These were serious political challenges innate to any reform in computer security: the distribution of security-certification logos, the establishment of baseline security standards, a wise judgment of the regulatory costs of compliance, the daunting difficulties of online patch distribution, the rating of potential flaws and vulnerabilities, even the awful discovery of certain flaws "too expensive to fix" . . . The list went on and on. Basically, these problems had one commonality: they couldn't be programmed away or fixed by engineers. They could only be solved through sincere, extensive, fully briefed bargaining and negotiation among the power players. That was why nothing much had ever happened to resolve those problems. This whole situation was the very opposite of his grandfather's rules for technical progress—especially, that burning need to stay close to the machinery. The KH-13 was machinery. Van thought that he could shine there. Van knew that fixing a spy satellite was a long-shot. Realistically speaking, how could one computer-science professor cure an ailing multibillion-dollar spacecraft? But Van also knew that the job was not hopeless. Such things sometimes happened in real life. For instance: Richard Feynman was just a physicist. But Feynman had dropped a chunk of rubber O-ring into a glass of ice water, and he had shown the whole world, on TV, how a space shuttle could blow up. If Van somehow solved Hickok's zillion-dollar problem, that would prove that he, Derek Vandeveer, had a top-notch, Richard Feynman kind of class. Van had sacrificed a lot to get his role in public service. He'd given up his happy home, his family life, his civilian career, his peace of mind, and a whole, whole lot of his money. Van wanted to see real results from all that sacrifice. He wanted to do something vital. The KH-13 was probably the grandest and most secret gizmo that the USA possessed. If Van somehow found the KH-13's busted O-ring, then he would be giving America the ability to photograph the entire planet, in visible and infrared, day and night, digitally, repeatedly, on a three-inch scale. Yes, that really mattered. Careful not to mention the advice he had gotten from Tony, Van broached the matter with Jeb. Jeb quickly understood the implications. Yes, it would obviously get the CCIAB a lot of kudos if they could technically outsmart the Air Force, the Space Force, the National Reconnaissance Office, NASA, and the host of federal contractors who had been working on satellites since the days of the V-2 rocket. It would make the CCIAB look like geniuses and it was just the kind of stunt that really impressed congressmen. Weighed against that was the scary prospect of getting in over their heads, then getting blamed for it. So Jeb, in his own turn, talked the matter over with some old-school technical buddies from DARPA and the Defense Department's Office of Special Projects. A plan emerged: a firewall strategy. Jeb would protect the CCIAB by moving Van one step out from the organization. For satellite work, Jeb had Van "loaned out" from the CCIAB to the "Transformational Communications Architecture Office." The TCAO was a joint effort of the Defense Information Systems Agency, and the Assistant Secretary of Defense for Command, Control, Communications, and Intelligence. The "Transformational Communications Architecture Office" was an easy outfit for Van to work for, because, basically, the Office did not exist. The Office was just an empty box in one of Donald Rumsfeld's ambitious DoD "Transformation" schemes. And even the NRO and NSA were terrified of Donald Rumsfeld. Rumsfeld had once been the boss of the futurists at RAND. Rumsfeld had a horrible knack for asking simple, embarrassing questions that nobody had ever thought about before. Nobody wanted to cross him. Rumsfeld seemed kind of okay about cyberwar issues. Whenever computer security was mentioned at National Security briefings, Rumsfeld made some brisk notes. Tom Ridge's imaginary Homeland Security agency was badly stuck in the mud, but Jeb felt pretty cheerful about Rumsfeld's Department of Defense. Donald Rumsfeld was the closest thing the CCIAB had to a patron in the Bush cabinet. So, like a lot of other policy players in the Bush administration, Jeb had taken to speaking in Rumsfeldese. In return for allowing Van to meddle with the KH-13 satellite, Jeb announced that it was time for Grendel, Van's "project launch," to be "spun out and delegated to a responsible agency that can add some structure." Van was not allowed to whine or moan to Jeb about this harsh decision, either. Instead, Van was told to "avoid overcontrolling" and to "ease that personality bottleneck." It was Hickok who explained to Van what this speech meant in English. "Your boss is taking away your best toy and he's selling it out to the highest bidder, fella. Your Grendel gizmo is bait for the brass hats now, pure and simple. Jeb wants to see those big boys fighting a bidding war to take that thing over, see? That'll improve his bargaining position with them." "But I built it," Van protested. "Plus, I paid for it all with my own checks." "So what? You can't grow it any bigger. You don't have the money or staff around here. So don't you feel bad about that! If some major outfit takes all that hard work on for y'all, hey, that's a big victory!" Hickok beamed on him. The loss of Grendel meant that Van had time to work on Hickok's problem. So, Van won official permission to tinker with satellites. Unofficially, this permission meant very little, because Van was already neck-deep inside the blue folder. Michael Hickok, the man who had leaked it to him, had instantly become Van's best war buddy. The two of them were always close, because Hickok was physically chained to the KH-13's secret documents. Whenever Van examined the satellite's problems, Hickok had to be present with him in the room. Van had never gotten over the burning tingle of curiosity, the technical thrill he first felt as he leafed through the weird, forbidden schematics of the world's most advanced flying spy machine. At first, as Van obsessed over the KH-13's malfunction reports, Hickok just idled around the CCIAB's concrete den inside the Vault. He flirted with Fawn, made cell-phone calls to a series of loose women, and paged through computer security brochures. But Michael Hickok was a man of action. It wasn't in him to waste time. He watched Van's office routines, then he made himself useful. Van's least favorite job was to demo security gadgets for the Vault's many cyberwar groupies. There were packs of gizmos arriving for Van every day. Dongles and decryptors. Peel-and-stick RFID labels. Teflon and Kevlar security cables. Barcodes and asset tags. Ridiculous homemade EMP blasters right out of the aluminum-foil hat set. Teensy-tiny locks on chipsets sculpted right into the microscopic silicon with ultra-high-tech MEMS techniques . . . The CCIAB had become a clearinghouse for American infowar toys. Van spent a lot of valuable overtime reviewing and clearing peculiar gizmos for the Special Forces. The Delta Force, the Navy SEALS . . . they got to carry any kind of gadget they pleased, but they were too small to support their own R&D labs. They had to depend on the kindness of strangers. Hickok quickly got the hang of Van's spiel to Vault visitors. It was basically the same old Frequently Asked Security Questions, over and over again. Van hated this mind-dulling routine. When ignorant people failed to read the manual and asked him stupid questions, this brought out Van's tough, potted-cactus side. After watching Van stammer, bark, and hand-saw his way through these briefings, Hickok asserted himself and just took them over. Hickok did very well at the work. Hickok had a knack for boiling down complex technical issues to a military briefing level that career bureaucrats could understand. With his baritone voice, his soldierly good looks, and two fists that could break solid bricks, Michael Hickok was a top-notch computer-security salesman. He was certainly the best promoter that the little CCIAB had ever had. Hickok scared the living daylights out of people. Once Hickok was through wringing them out, federal officials would leave their business cards with pale and trembling fingers, and beg for emergency help. Van's new best pal was no computer whiz. He was a whiskey-drinking Alabama guy with a high school education. Hickok liked dirty jokes, heavy metal music, and reckless women, except on Sundays, when he was always in church. Hickok was the simplest man that Van had ever befriended. Hickok had few self-doubts. Hickok had no interest in complex ideas. Intellectual puzzles just irritated him. Van found something very refreshing about all this. It took just one more thing to move the two of them from coworkers to comrades. That thing was gunfire. Guns were much more than just a hobby for Michael Hickok. Guns were a basis of Hickok's very life. The two of them went out two times a week, and on Sunday evenings after Hickok's church services, drinking heavily, bowling, and firing advanced automatic weapons. They quit bowling after two Sundays, because Van was an excellent bowler and Hickok really hated getting beaten at anything. So they stopped the bowling, and cut back on the drinking. They settled on just the guns. Van was happy to learn about guns. Hickok knew plenty about them, and Van was a star student. Van hadn't fired a weapon since he'd plonked at rabbits with a single-shot .22 on his grandfather's ranch. In Hickok's company, though, Van put on goggles and ear protectors. He roared his way through Ingrams, Uzis, and Pentagon lab models with no names at all, just acronyms. Weapons like the boxlike "OICW," the "M249 SAW," and a futuristic, four-barreled, 15mm mini-rocket launcher from the U.S. Army's Soldier Systems Center in Natick, Massachusetts. Hickok had incredible contacts in the world of specialized weapons testing. Hickok knew gun nuts who made Charlton Heston look like Winnie the Pooh. Van quickly discovered that guns were extremely interesting technical devices. When Van considered the many ingenious engineering problems that had been solved by master gunsmiths, he was fascinated. It didn't matter to Van that he was myopic and only a middling good shot. Van spent most of his time in the range stripping Hickok's guns down and putting them back together. Left free to get hands-on with guns, Van learned a lot. Enough to know that he could build a gun himself, if he wanted. If he ever built a gun, it would be a digital cybergun. It would be smart, interactive, precise, speedy. It would put every single bullet exactly where it was meant to go. It would fill up graveyards faster than the Black Death. Van found that it refreshed his mind to tinker with lethal hardware. Guns inspired Van, they got him out of his mental box. When Van returned from the firing ranges to bend his full attention onto the KH-13 spy satellite, the satellite problem cracked around the edges. Then the problem started to yield to him. Van tossed and turned, in eighteen-hour days, and in the depths of the night. He labored through blind alleys, made wild leaps of insight. He called in a lot of favors. He gave of his very best. He worked quietly, and he worked very quickly. And then, all in a rush, it went. The truth was that the satellite's so-called software problems had nothing to do with the satellite's software. The satellite's software was incredible. The code was built to mind-boggling, unheard-of security specs. It made AT&T switching station software—the most paranoid commercial code Van had ever worked on—look as loose and scattered as empty Schlitz cans at a beer bust. The satellite's software had been assembled and vetted by three hundred humorless, white-shirt-wearing, avionics-software drones in Clear Lake City, Texas. The KH-13 had three different onboard control computers, each of them independently running 420,000 lines of code. It was belt, plus suspenders, plus a straitjacket. Those 420,000 lines had exactly one fully documented, well-understood bug. This was totally unheard-of. The very best commercial software written to that length would have suffered about 5,000 bugs. The KH-13's software was the dullest, least creative, most focused, most disciplined software that Van had ever seen. It scared him. It was sober, detailed, frighteningly methodical. The code's design specs alone ran to thirty volumes. Every single line of the 420,000 was completely annotated, showing every time it had ever been changed. Why, when, how, and by whom. Every change was rigorously linked to some severe dictation in the design specs. Literally everything that had ever happened to this vast program, down to the tiniest detail, was recorded in a giant master history. And since this code re-used some fully tested code from earlier spy-sats, the reports stretched back some thirty solid years. There was something genuinely nightmarish about this KH-13 code. About its complete lack of inspiration, creativity, and cheerful hacker sloppiness. About its gray, sober, steel bank-vault qualities. Van realized with a sinking in his heart that this was the gold standard for the safety and security that he and the CCIAB were trying to impose on the daffy, geeky, loosey-goosey software world. In a cyber-secure utopia, all software would look just like this. But the satellite's coders, for all their horrifying clerkly skills, were only part of the satellite system. The secret aerospace bureaucracy that had built the KH-13 had worked on a strict need-to-know basis. This meant that no human being had ever understood the KH-13 as a whole. There were still big black patches in Van's knowledge, too. Any device of that size and complexity was just too vast for one human brain to hold. But Van had researched the problem with unusual methods. Van knew that he understood things about the KH-13 that were not grasped by anyone else in the world. Van went to report his triumphant progress to Jeb. He was eager to explain his ingenious solution to someone who could fully appreciate it. Unfortunately, Jeb was not cleared for learning about the innards of spy satellites—that was one "stovepipe" that was still holding firm. So Jeb simply thanked him, congratulated him on the hard work, and gave him a new assignment. Van was now "tasked with creating" a new, bang-up technical presentation for the forthcoming federal computer-security "Cyber-Strategy Summit" in rural Virginia. Jeb was obsessed with this conference, the golden climax of the CCIAB's policy-making efforts. It was absolutely vital, said Jeb, that "America's cyber-security community" should come out of this Virginia shindig with "some broad policy guidance and momentum on the ground." This Virginia retreat would be the CCIAB's last best chance to gather all the major federal players, and get them to line up, see sense, split their differences, dig deep in their pockets, and all sign on together on the same policy page. Then there would be real, true change in the world. Real structure, tasking, and accountability. Finally, American computer security that knew what it was doing. Sensible. Businesslike. Orderly. Realistic. Van had to beg permission from Jeb to report his satellite findings to some proper authority. Finding a proper authority took some time, because (as Van now realized) nobody anywhere had ever expected Hickok to find somebody who could actually solve the problem. When a good candidate was finally located inside the intricate spacewar bureaucracy, Hickok insisted on driving Van from Washington straight to Cheyenne Mountain, Colorado. Hickok's special courier vehicle had a bulging fiberglass shell, a telescoping mast, and nineteen-inch metal racks full of command-and-control hardware. Hickok's Humvee could open links to FLTSATCOM, MILSTAR, NAVSTAR, INTELSAT, INMARSAT, EUTELSAT, and the Pentagon's Global Common Operational Picture. On this cross-country trip, Van's e-mail arrived for him on Navy-sponsored dot-mil satellite channels designed for aircraft carriers. Hickok's professional life was strangely familiar to Van. It was full of small elite teams. Quick, quiet black-ops soldiers who did peculiar things on very short schedules. They never bragged. The American press never printed a word about them. They were very busy guys. They were very much like top-end computer wizards, except for one thing. They were not pale, pudgy hackers wearing glasses. They were cold-eyed athletes with crazy, kick-the-door-in fitness standards. Behind the Humvee's wheel, Hickok was an iron man. Hickok drove like a low-flying aircraft buzzing the Kuwaiti Highway of Death. Hickok's reflexes were so much keener than those of normal drivers that he whipped through traffic with race-car twitches of his fingertips. Van learned to watch the windshield as if it were the screen of a video game. It was much easier on his nerves if he pretended that the two of them could just win some extra lives. Whenever Hickok needed a break, he retired to the Humvee's cavernous backseat. There he amused himself, munching take-out double cheeseburgers, sipping strawberry shakes, and leafing through his usual leisure reading, Christian apocalypse fiction. Hickok had no problem reading novels in a moving car, for Hickok was Air Force Special Ops. Hickok never got carsick. He had the stomach for five or six gees. Hickok was a big devotee of a best-selling series called "Tribulation Force." In tomorrow's post-Armageddon world, the Rapture had carried off all the Believing Christians, leaving all the liberal scoffers, skeptics, and atheists to fight it out with the evil troops of the Antichrist. Hickok liked to read the most ruthless sections of the book aloud, chuckling to himself. "Y'know," Hickok sang out suddenly. Van gripped the Humvee's wheel. Van was dead tired, but it was a lot more relaxing to drive the Humvee than it was to watch Hickok doing it. "What is it, Mike?" "We never really talked about that secretary of yours." "What's Fawn done this time?" "Did you ever clear it with her about those surgical gloves?" "Mike, I'm just her boss, all right?" "What is it with her allergies? The girl is allergic to everything. And what's with that talcum powder? Is that all in her head?" It was pitiful that Hickok asked him for advice about dating geek women. Van already had a geek woman. And unlike Hickok, who was awesomely promiscuous and never thought twice about it, Van badly wanted to keep the geek woman he had. Dottie was the only woman in his life who had ever understood him. Now that Van was out of his bunker office and with his nose out of the briefing papers, he could guiltily realize how much hell he had been through and how much harm he had done to himself. Why was he shooting the breeze with some war buddy when he was a married man? Van knew that Dottie's love for him was large, and generous, and without conditions. But oh, how they were hampered by all those other boundaries in their lives. All those far-sighted, professional postponements, those acts of scholarly discipline, those duties and obligations. They were both so well meaning about it, and maybe that was the worst thing. It wasn't like they really meant to neglect each other. They just arranged their lives so that they always could. They talked each other into it somehow, making nice lists in their e-mail, researching the alternatives, checking out a spreadsheet maybe, wisely agreeing on what was surely best for them in the long run. But the long run never came around for them. They used their smarts and knowledge to lop off all time for each other. There was something inhuman about being dutiful workaholics, something that wrecked marriages, shattered families, and made a man and woman shrivel up inside. It was going to kill them both someday. Without his wife and his child, hinges had popped loose in Van's soul. He could feel that something quiet but vital to his humanity was slowly going down the shredder. Why was it that he could never tell Dottie these things? She never denied him things he needed—when he asked her for them. But when he was worn down like a pencil nub, he couldn't even find it in himself to ask. They were like a couple who talked in sign language, and now were losing their fingers. It just wouldn't do. No. Cheyenne Mountain was just one stupid mountain in Colorado. But Dottie lived in the Colorado mountains now. He was going to see Dottie and try to set things straight. Van had already sent her e-mail. It was a bright, drought-stricken day. The sun gleamed off looming slopes of bare red rock and patches of trapped snow. Cheyenne Mountain loomed so large and bald and frowning that Van had a dizzy spell. The legendary Cheyenne space base was something of a disappointment to Van. Cheyenne Mountain commanded America's ICBMs and it had the capacity to blow up the whole world. It should have been a lot stranger than it looked. Cheyenne was basically a rather typical Air Force base, just stuffed inside a big stone bottle. No grass here, no flagpoles. Bad overhead lighting. Miles of dusty exposed plumbing and ventilation. The entire base was supported on giant, white-painted steel springs. If half of Cheyenne Mountain vaporized in a fifty-megaton first strike, the deep bunker would just bounce on its springs a little. The machinery of America's nuclear vengeance never came unplugged. The security people took away Van's cell phone and his Swiss Army knife. They photocopied his New Jersey driver's license and demanded his social security number. They let him keep his heavy NSC shoulder bag and his cork-lined instrument case. Without his ever-present pocketknife and pocket phone, Van felt both robbed and naked. Hickok had secured an appointment with Major General Edwin A. Wessler. Wessler was a big cheese around the KH-13, but he was not Hickok's boss. Michael Hickok never showed up on anybody's organizational charts, so he never had any "boss." Hickok referred to the various interested parties as his "sponsors." Major General Edwin A. Wessler turned out to be a big, bluff, balding guy with rimless glasses and a Hawaiian tan. General Wessler had just been reassigned to Cheyenne from a missile-tracking base in the mid-Pacific. Wessler was only partially moved into his new office. The place was all beige paint, gunmetal shelving, and scattered blue folders. The screen of Wessler's new Dell showed that he was working on a PowerPoint presentation. Wessler's topic was "GEODDS, Baker-Nunn, and the ASFPC." "GEODDS," Van muttered, rubbing his aching forehead. "Yes, sir!" boomed General Wessler. "GEODDS can spot an orbiting object the size of a basketball!" Van put his heavy bag and case on the floor. His back ached and his wrists were sore. The altitude was killing him. Being at high altitude deep inside a stone cave was somehow much worse. Wessler flicked Hickok's business card with his clean, buffed fingernail. " 'Executive Solutions,' so what kind of outfit is that, Master Sergeant?" "That's a long story, sir. Ever heard of the Carlyle Group?" "I don't need any long stories today," Wessler told him with a thin smile. Major General Wessler had an aeronautics degree, an MBA, and had worked for both NATO and NASA. General Wessler was not just any everyday general. He was a literal rocket scientist. Wessler wore an elastic blue one-piece jumpsuit with starred shoulders and a U.S. SPACE FORCE breast patch. General Wessler looked tanned, fit, and ready to spring right aboard the next Shuttle liftoff. Even though he never did anything spacier than stare deep into a tracking screen. Van found it rather weird to meet a no-kidding, real-life general from a "Space Force." It was weirder yet that America's Space Force had bases all around the world, with forty thousand service personnel. America's Space Force was twenty years old. Why had he never seen any Space Force soldiers in any war movies? Or TV programs, either. Not even _The X-Files._ Van coughed on the dry mountain air. Wessler removed loose books from the metal seat of his office chair. "You'd better take a load off your feet, flatlander! I'll have an orderly bring you a Pepsi!" Van hated Pepsis, but he sat down gratefully. He focused his aching eyes on Wessler's stack of brand-new books. The titles were _War at the Top of the World, Tournament of Shadows,_ and _The Prize: The Epic Quest for Oil, Money and Power._ Their pages were thick with fresh yellow Post-it notes. Wessler barked orders into a bright red desk phone. "I brought you something good here, sir," offered Hickok. "It sure wasn't easy finding it. I had to kiss me a whole lot of frogs. But, sir, I believe this approach might work out!" Wessler lowered his brows in a scowl. He had about a mile and a half of shining bald forehead. "Why'd you leave the Air Force, Mr. Hickok?" Hickok was startled. "Well, it just seemed like the right time for me to move on, sir." "Don't hand me that crap! Why'd we lose an airman like you? And now you're here telling me you think you know how to manage a satellite, Master Sergeant? What on earth is that all about?" "Well, sir," said Hickok, standing straighter, "if you want the truth about why I left the Force, it just got too obvious who was calling the shots there in Kosovo. It was the damn United Nations!" Wessler didn't take that remark at all well. Van was very alarmed. They'd agreed earlier that Hickok would do the talking, because Space Force was a branch of the Air Force, while Hickok was Special Ops, also Air Force. Two wings of the Air Force trying to fly together, how hard could that be? "Mr. Hickok may be a civilian now, sir," Van spoke up. "But I'm NSC." "That's not what your card says, Dr. Vandeveer! This card says you are DoD!" Wessler read it carefully. "'Transformational Communications Architecture Office, Department of Defense.'" Wessler's glasses gleamed fiercely. "That outfit doesn't even exist! It's nothing but a press release!" "Well, we're way ahead of the curve," Van mumbled. Van was saved by the arrival of a young airman with a Pepsi. The drink came in a sixteen-ounce plastic Los Angeles Lakers cup. "Sir," Hickok told the general, "that big space re-org at the Pentagon is not the lookout of me and the computer doc here. So there's no need to bring up the subject of 'space transformation.' If you'll just hear us out a minute . . . We came a long way, and well, we've got some good ideas." Wessler hitched up the elastic belt of his blue jumpsuit and sat by his computer. "I'm listening." Hickok shot Van an urgent look. Startled, Van put his Pepsi on the floor. "Well," Van blurted, "uh, sir, when I first saw those SEU reports, I had it figured for thermal failure. Some kind of heat load. But of course, this bird is the most advanced infrared spotter we have. So if there's anything it would spot, it would certainly be heat." "They tell me you're a programmer." "That's right." "Cut to the chase! What's gone wrong with the bird's software?" "Nothing," Van said, lunging for his cold-sweating Pepsi. "It's the hardware. First, I had to correlate those reported anomalies with its orbital position." Wessler stared at him. "You tracked the bird's zenith angles?" "Well, yes." "That is the one thing no one is supposed to know! The orbital periodicity, that is the most jealously guarded secret we have! If the adversary learns that, then he can do denial and deception!" "It wasn't that hard to figure out," Van said. Other national governments already knew about the KH-13. It was the business of their intelligence services to figure such things out. So Van had used French commercial SPOT satellite photos, easily purchased through the Internet. Using these photos, Van had watched Indian scientists at various Indian nuclear weapons centers busily moving their cars and trucks to baffle the KH-13. The Indians were doing their usual denial and deception efforts against the new American spy satellite, trying to disguise the feverish activity in and out of their nuclear weapons centers. Given the Indians' keen awareness of the KH-13's orbit, it was easy for Van to download a PC simulator program from Dottie's astrophysics lab, and deduce the satellite's orbit by himself. Dottie was happy to help him find the right program, and she had never suspected a thing. "The KH-13 is in a standard American spy-sat LEO/POLAR orbit," Van said. "Apogee 256, perigee 530 . . ." "Never mind that." Van nodded hastily. "So, once I had the orbital periodicity, then I could see these damage episodes are far from random. They only occur when the bird is transiting from the highly charged polar regions into the mid-latitudes." This news put General Wessler right off his feed. Wessler started fiddling nervously with the track-wheel in his mouse. "So, what do you mean to say? That it's surface-charging? That there's an arc discharge?" "Well, that's part of it," Van said. "I had to look at SD-SURF." "Space Debris-Surfaces, yes, we ran that diagnostic almost a year ago." "Yeah, you always run that program," Van told him. "But SD-SURF was written in FORTRAN way back in 1983. So SD-SURF treats the spacecraft's surface contours as a faceted geometry. That simulation's not entirely accurate, because you get these peaks and waves of flux and probability surfaces that are artifacts produced by granularity in the model. That's due to the way the subroutine interrogates the ballistic limit surface . . ." Van's voice trailed off. Hickok and Wessler were both staring at him blankly. He had completely lost them. Van cleared his dry throat. "So, anyway, I rewrote SD-SURF and sent it to some friends of mine over at NCAR." "Do you mean NCAR up in Boulder? Those Atmospheric Research guys?" "Yeah. Yes, sir." "But NCAR is a civilian agency! They're not cleared for any of this at all!" "SD-SURF is not a secret. SD-SURF is public domain. It's free for download off a NASA Web site." Wessler made a quick note on a Post-it. "We'll have to see about that right away." "So, uhm, I had NCAR run my improved version of SD-SURF on their weather-simulation supercomputers. And while I was at it, I also had them search their files for space weather. Solar discharges, photoelectron flux, the works. Everything." Wessler narrowed his eyes. "Oh, ho." "There was no correlation," Van said. "Not at first. To maintain my confidentiality, I told my friend at NCAR to search _everything._ So he also ran through all of NOAA's _conventional_ weather records. And there, a strong correlation turned up. There is a direct relationship between these, uh, damage episodes and storm fronts moving across the western USA." "You mean the weather on the ground." Van nodded. He hated talking this much. It was making his head ache. "Dr. Vandeveer, can I remind you of something? That bird is two hundred fifty miles up!" "I know that, General. But there's a lot we don't know about the upper thermosphere. My friend at NCAR put me in touch with a friend of his at NOAA who's a world expert on sprites and elves." Wessler tugged at his ear. " 'Elves'?" "Sprites and elves. Sprites and elves are huge discharges from the tops of thunderclouds," Van said. "Nothing like lightning. They go _up._ They are very big. Colossal. The Shuttle has photographed them from orbit." Van paused. "Show him those elf and sprite pics, Mike." As Hickok busied himself unlatching the case from his wrist, Van forced a swallow of Pepsi. It tasted even worse than he remembered. Wessler examined the set of glossy NASA printouts. "So, Dr. Vandeveer, you're telling me my satellite was attacked by elves." "That's just one hypothesis," Van said. "But I can tell you, as a fact, that there has never been a damage episode that wasn't correlated with a storm front. When I searched those storm records, that's when I realized that there haven't been just four episodes, as your reports say. There were seven episodes, including three weaker storms with three much weaker attacks. The very worst came with the most violent storm last winter. December 17. Those onboard power anomalies." "That was really bad," Wessler said gloomily. "We really thought we'd lost her that time." The elf pictures had shaken Wessler. Van had felt the very same way when he had seen them. It was truly bizarre to realize that the Earth's upper atmosphere had some gigantic blistering explosions that no one but pilots and astronauts ever saw. Sprites and elves, "Transient Discharge Phenomena." Sprites and elves sounded almost crazier than UFOs, but they were very real. Every bit as real as the northern lights. "That December event," Van said. "Some very similar power surges happened to the Hubble, before the Shuttle crew fixed its Kapton sleeves. The power surges mean that the solar panels were vibrating on their bistems." Van bucked his hands back and forth. "It means that something almost tore the wings off your spacecraft." Van put his Pepsi down. He felt drained. But Wessler had a face like a cross-examining attorney. "We used to have those 'episodes,' as you say. But now we have ongoing operational anomalies. What do you make of that?" Van could handle that question. "That's BUMPER, your space-junk debris collision program. I looked at BUMPER, too. BUMPER has an unexamined assumption in its design specs. BUMPER assumes that debris cannot intercept a spacecraft from more than ten degrees above or below a plane tangent to the Earth normal." Wessler scratched the back of his neck. "Of course. Otherwise that debris would fall right into the Earth's atmosphere and burn up immediately." "No," said Van. "Not if the debris were coming _off of the spacecraft itself._ Not big chunks of space junk, not yet. But a fine haze of debris. Ionized. Ablated. Particles and ejecta from violent surface shocks. You would get a dielectric constant on the spacecraft that would reattract those contaminants and precipitate them onto specific areas of the hull." "You see, it's just like a microwave oven, sir," Hickok broke in helpfully. "You can't ever get smoke in outer space because there's no air up there, but if it got blasted by an elf or sprite or like that, then there would be gas and dust. Kinda like a hot cloud of grease." "I know what the man's talking about," Wessler said tautly. Hickok shrugged. "Well then, you sure got me beat." "I understand it, but there's no reason for me to believe it," Wessler said. "Why do I have to believe in elves, all of a sudden?" "I don't know," Van said. "There wasn't time to fully examine that question. But I do have a working fix for your satellite's problem." "This is where Dr. Vandeveer and I part company, sir," Hickok said eagerly. "Because I _do_ know! And it's no damn little elves, either. We are _under attack,_ sir! This is _spacewar_!" "What?" said Wessler. "How? Who? The Russians?" "Well, why not the Russians?" said Hickok. "I've met some Russians, sir. I know they're up for anything." "The Russians can't launch anything at us! I have personally seen their space centers. The Russian space centers are totally broke! They can't pay their own power bills." Hickok bored in. "The Red Chinese are building rockets, sir! They can lift big payloads! I reckon they're sandbagging us." Wessler raised his brows. "What do you make of that concept, Dr. Vandeveer?" "I don't believe in sandbagging attacks," Van said. "Sand is not an effective space weapon. Fine debris like sand would ionize quickly, then it would fall out of orbit. Besides, a cloud of sand from a Chinese rocket would injure other spacecraft, and we haven't seen any signs of that." Van pulled at his beard. "Have we seen other signs of that, General?" Wessler closed his lips tightly. He had nothing to offer on that topic. Van tried to smile at him. "Let's all be reasonable here. We don't have to bring any elves, UFOs, or Communists into this." He cleared his throat. "Let's just say . . . cause or causes unknown. Then we can focus on patching this problem you have." Wessler's face set like stone. Van knew that it was time to move right along in a hurry. "Can you help me with my case here, Mike?" Hickok opened the cork-lined instrument box. Van removed the extra foam-rubber padding. He was very relieved to see that his breadboarding had survived the rough trip from Washington. Van had had to leave his grandfather's big solder gun back inside Hickok's Humvee. Van had gotten so used to using the ray gun for work that he didn't think he could manage any more with a normal soldering tool. Van sensed that this demonstration was his last chance. "Like I said, about that space dust," he said. "I've got a friend in Los Alamos National Lab who models particle action in dielectric fields." "You seem to have a whole lot of unnamed friends, Dr. Vandeveer." Van's temper sharpened. "General, in the President's National Security Council, we don't exactly lack for helpful contacts." Wessler heaved aside a stack of folders on his desk to make extra room for Van's box. "Please. Do help yourself." Van took a deep breath. "Ionized dust seeks equilibrium, to balance that electric charge. So the dust will settle wherever the fields on the spacecraft guide it." Van removed an extremely secret printout from the case. He ran his finger across the schematics. "That means you're getting a cloud of filth on the KH-13's sensor booms, the edges of the chassis, and especially right about here. This highly charged area, just at the rim of the Mylar insulation. There's a big component there, under the skin of the hull. It's an MIL-STD-1541, Taiwanese capacitor. Just like this component in this case." Wessler gazed into the box. "Where did you get that thing?" "They're pretty standard. My secretary bought it off eBay." Van sighed. "Ideally, I would have liked three milspec control-CDUs in this experiment as well, but that is way beyond my salary." Van touched a switch. "Okay, General, I think we're ready to roll now. I want you to watch this voltmeter here. Mike, fire the model up." Hickok put his hand to a gray plastic crank. There was a faint crackle. "See that needle bouncing?" Van said. "Now look at these SEU records. Bang, bang, beat, beat, blip. Same series, same surges, same rates of decline. That's it, General. This is your bug, that's your ongoing operational anomaly. It's a hardware glitch, and it's in this capacitor. It's got so much dirt on top of it that it is overheating." "You're telling me there's too much dirt on it," Wessler said. "But you can't tell me _why_ there is any dust in the first place." "No, sir, I can't tell you that. But I can tell you how to fix it. You need to spin the spacecraft." "Spin it," said Wessler. "Spin it on the longitudinal axis. That'll fling the loose dust off, and whenever these, uh, episodes happen again . . . well, spinning will spread the stresses evenly across the whole spacecraft. So you won't get that pitting, that, uhm, that sputtering . . ." Van was losing it. Those words he'd just said, "ongoing operational anomaly." That was a regular tongue twister. "You tell him, Mike." "The bird spins like a chicken on a spit, sir. Won't blacken all on one side, turns golden brown, like." "But the whole point of a satellite is to have a steady, fixed camera!" "No," said Van. "The whole point is steady, fixed _images._ You can compute the fixed images from a spinning satellite camera." "That's impossible." "No. It can be done." Astronomers could help a lot with orbiting camera images. Van hadn't breathed a word to Dottie about it, but he knew it could be made to happen. "It's like Hollywood special effects, sir," said Hickok proudly. "We'll just fix it up in post-production. Like _Jurassic Park_!" Wessler rose from his desk and put both his hands in his blue jumpsuit pockets. He had the look of a man who badly needed a drink. "You will lose two, three percent of acuity if you spin the camera," Van admitted. "But you've already lost that much acuity to that so-called CCD fogging. That is not a CCD problem at all, by the way. That is dirt being blasted off your spacecraft and settling on your lens." Wessler was still pacing. "We don't have the fuel to spin that bird. We're not made out of hydrazine up there." "That's right. You'll also lose fifteen months off the expected nine-year life. But at that rate of damage . . . the satellite won't live two years." "Our bird is under attack!" said Hickok, passionately jumping to his feet. "There is something up there, sir! I don't know how it got up there, but it can't be any accident that we have this problem during a War on Terror. Some evildoer is screwing with us, sir. I just know that." Wessler sat down again. "I don't get a briefing like this every day." "No," Van agreed. "Where the hell did they dig you up, Dr. Vandeveer? You're a hell of a guy, and I've never even heard of you." "MIT," Van said. "Stanford. And Mondiale." Wessler stared as if a toad had jumped from Van's tongue. "You're from _Mondial_ _e_?" "I'm from Mondiale's R&D lab," Van said hastily. "I quit to work for the government." "I can't believe this!" Wessler shouted, standing up again. "You crazy sons of bitches, my _mother_ owned Mondiale stock! You're a _phone company_! How did you lose ninety percent of your stock value? You people are completely crooked!" A moan slipped out of Van. "The whole industry is hurting . . ." "I can't go to my best people and tell them to screw up our satellite on the say-so of some goofball from Mondiale!" "I know that," Van blurted, waving his hands in panic, "I know that the company hurt a lot of people. But you don't have to take my word for this! That's not a problem, not at all! I don't want any credit for this, no, no! You just have to _look_ at it. That's all. Look at the bird. See how bad off it is. Shocked or burned. Like that!" "How?" "You can send up the Shuttle." "Do you know the price of a Shuttle flight? And the scheduling? Those old birds are falling to pieces!" "Train the Hubble on it. Search it for burn marks." "Civilian telescopes are not our department." "Just look at it, that's all," Van begged. "Do it from the ground." "No! Observatories are _strictly forbidden_ to image American spy-sats. I certainly wouldn't want them getting started! Besides, they lack that technical capacity." Van had nothing left to say. His wife's new adaptive-optic telescope would certainly have that capacity. But it was two years away from coming online. By then, it would be no use. Hickok stared down at Van, expecting some final wizard miracle from him, but Van realized that he was beaten. He couldn't believe that Mondiale had brought his whole scheme crashing down. But that made a horrible sense, for in the last few months Mondiale had screwed up everything in Van's life. The big shots who had hired him away from Stanford were about to do a perp-walk, in handcuffs, in front of cameras. Guilty of stock fraud. Failures. Disasters. Deceivers. From leaders of a revolution, they had turned into liars and cheats. Van had done his best, but he had blown it. "What the hell's going on here?" said Hickok loudly. "I got your problem fixed, General! And you won't even _loo_ _k_?" "This guy is from Mondiale!" "Like Lockheed's better? That bird could save the life of Special Forces spotters in Afghanistan! You're telling me, what, that's too much work for you? Use a KH-11!" "That's completely outside normal channels." "You're gonna let our adversaries destroy our best surveillance asset while you sit here like some jackass?" Wessler turned beet-red. "Mr. Hickok, you can't push around a Space Force officer by yelling a bunch of saucer-nut crap. We are the _only_ force on earth that has military space capacity. There _is_ no one else. That's not even remotely possible." "Who cares what your fat-cat industry vendors think is possible? That bird is dying up there! I busted my ass, I got you a genuine gold-plated computer genius here! He can fix the damn thing! If you don't fix it, then you, _you,_ are betraying our men out in the field." Wessler's throat was moving. Van realized that Wessler was silently counting to ten. Van had never seen a grown man in uniform do that before. It was very frightening. Finally Wessler spoke. "I believe I've given you two dilettantes all the time that you need." "That does it," Hickok announced. "I quit!" He took a key from his pocket and undid his wrist-cuff. Then he tossed the briefcase on a metal chair. "This turkey of yours is dead meat! I want no part of this! You useless sumnabitches couldn't run a model rocket show!" Wessler looked at him, his reddened face flickering through rage, disgust, and pity. "Master Sergeant, I really don't believe this is your game." Hickok leveled a throat-cutting stare at him. "Oh, so it's a game to you, is it? You can't get your big square head around an asymmetric threat, General! No wonder they hit the damn Pentagon out of a clear blue sky. I'd rather dig ditches in Lebanon than hang out with you pie-eating game-boys. Jesus Christ." "Mike," Van said. "What?" "Let's go now, Mike. All right? We'll just go." CHAPTER NINE COLORADO, FEBRUARY 2002 **H** ickok wasn't the kind of guy to silently nurse his grudges. His first stop outside the Cheyenne base was to pick up two fifths of Jack Daniel's. Van drove the Humvee as Hickok slurped his bourbon and griped. In going to visit Dottie, Van was borrowing Hickok's courier truck. The failure gnawed at Van. He was right, he knew he was right. Why hadn't that worked? Why hadn't he been more convincing? Two reasons, really. The first was painful and personal. He, Dr. Derek Vandeveer, was a geek. He was a classic, bearded-weirdo, introspective nerd. Oh, yes, he could hold his own when people came to him with technical problems. But he didn't have the grit that it took to really kick ass and take names. He should have had that kind of quality. He had nobody to blame for his weakness but himself. His grandfather would have broken that stupid Air Force general like a matchstick. Almost. He'd been so close. If not for that ugly Mondiale business . . . but that shouldn't have mattered. Or, at least, Mondiale was only one aspect of a much deeper crisis. He should never have sold out to private industry in the first place. At Stanford, at MIT, people had high standards. People had intellectual rigor. At Mondiale, nobody cared at all about principles. The method at Mondiale was to build a prototype in R&D. Then throw it over the wall to marketing and product development. That was what Van had just tried to do with this military professional. And it just hadn't worked. Van fiercely gripped the Humvee's padded steering wheel. He was driving a vehicle the size of a living room, through dense Colorado commuter traffic, on snowy, hairpin mountain turns. White-line fever had him totally keyed-up. Phantoms of shame and guilt danced on the snowy road ahead of him. Not only was he not a true leader, he was not truly a scientist, either. That was the tragic core of the whole ugly mess. Computer science was a fraud. It always had been. It was the only branch of science ever named after a gadget. He and his colleagues were basically no better than gizmo freaks. Now physics, now that was true science. Nobody ever called physics "lever science" or "billiard ball science." The fatal error in computer science was that it modeled complex systems without truly understanding them. Computers simulated complexity. You might know more or less what was likely to happen. But the causes remained unclear. When a hard-headed, practical man like General Wessler asked him "why," all that Van could do was helplessly wave his hands. He could have become a mathematician. He knew he had some skill there. Math would have been a much better choice for an ugly man who was shy and retiring. It was only personal weakness that had made him give in to the lure of computers. They called it "software engineering," but that wasn't engineering, either. If he'd been a true engineer like his grandfather, he would never have gone to the Space Force with such a cheap, lousy hack. He had brought them a half-baked notion. A hack was something rough-and-ready, tacked onto the end of a legacy system that was too huge, complicated, and overwhelming to fix. That was why he'd failed and been kicked out in disgrace. Jeb had given him the very same siren song. "This time, we'll really straighten it all out." No. No one could ever promise that about computers, because that was never the truth. It didn't matter how good you were, how smart you were. Nobody ever "fixed" computers. You just threw the old computer out and got another one. Any genuine reform was impossible. The only thing you could do was layer some fresh mud on top of the cracks. That, or just give up. Go into hiding, just hide from the burning shame. Yes, he, Derek Ronald Vandeveer, was a phony-baloney security expert for an agency that didn't even exist. But it wasn't like he could return to his previous life. What had happened to Mondiale and their competitors . . . that wasn't a "bubble." That was a train wreck on top of an avalanche. He, Derek Vandeveer, was part of the worst destruction of wealth in human history. Men he knew and trusted, corporate visionaries building a new and better electro-world, were out on bail. The very guys who used to drop by his lab in Merwinster in their pressed slacks and cashmere sweaters, to ooh and ahhh at the prototypes. Their second homes were auctioned off by bailiffs. Their trophy wives had vanished off the fashion pages into dry-out tanks. Why had he ever, ever believed in that crap? As a last, fatal bottom line, what kind of terrible verdict was that on his own integrity and good judgment? He'd been in the lab blowing money entrusted to his company by widows and orphans. By the mothers of Space Force generals. What possible right did he have to thrust himself into public policy? What was he doing here now? A full nightmare awareness struck Van. An awful vision of the hordes of the cheated, the deceived, and the damaged. Millions of normal people across America, across the whole world, who had no awareness of what he had done to them, what he was trying to save them from . . . Remember that hot stock that you bet on, Mr. and Mrs. America? All those nerds you trusted to bring you a New Economy? Well, they're driving massive trucks in Colorado. Lost, alone. With drunken ex-soldiers. In a War on Terror. Cursing, bewildered, frustrated, violent. In his panicky haste to flee Cheyenne Mountain, Van had abandoned his cell phone and even his beloved Swiss Army knife. His pockets were truly empty now. Nobody would even talk to him. He was doomed. The CCIAB was doomed. The satellite was doomed. Maybe even America was doomed. "You're sure as hell not saying much," said Hickok. "I screwed up bad, Mike. I should have nailed that. That should have worked." "You're the one bitching? I don't even have a job now!" Hickok flung his empty whiskey bottle out the Humvee's window, with an overhand Molotov lob. Then he cracked the seal on a second. "You've got a wife and a kid, fella! All I got in my life is this truck and some Dixie Chicks tapes." "You want a job, Mike?" "That wouldn't hurt me," said Hickok. "What, a job with your outfit, you mean?" The idea amused him. "You're gonna turn me into a true-blue cyberwar freak, Dr. Professor?" "Yeah, Mike. You're hired. Come by my office when you get back to D.C." Hickok peered at the fine print on the whiskey label. "I think maybe I'll drive back straight through Tennessee. Tennessee makes the best damn liquor in this whole wide world!" Dottie's telescope needed black skies. Black skies in America were few and far between. There were some strange and spooky places in the backwoods of Colorado. Mountain people always lived free. The nooks and crannies of the Rocky Mountains had Space Force generals, and ancient hippies, and silver miners, and jack Mormons. "Out here in God's country, we got ourselves some dropouts!" crowed Hickok, drunkenly pounding his leg with his rocklike fist. "The real off-the-grid people! Polygamists. Unabomber types. And there's survivalists!" During the Y2K panics of 1999, Van had come to know quite a lot about survivalists. And what he knew, Van didn't like. Survivalists were people of bad faith. Their faith was that civilization would break down, and ought to break down, and deserved to break down. That no one in charge should ever be trusted. That all authorities were useless, deluded, or evil. The survivalist faith was to abandon everyone and everything. Go into hiding. Buy lots and lots of gas masks. Cement. Water filters. Sacks of grain. Bars of gold. "Mike, do you know any of those survivalist types?" Hickok's lids fluttered. He sat up in the Humvee's backseat. "You bet I do! Us 'snake-eaters' can live right off the land! Escape and evasion under the stars! Cover your face up with dang mud! I used to train around these parts. If I recall myself correctly, there should be a roadside depot yonder. Sell you most anything you need to know!" Van soon found Hickok's depot. The place didn't look like much. A big red barn. He wanted to press right on and get to Dottie's place. Then he saw a glowing yellow roadside sign standing next to some rusty gas pumps. The sign was measled with shotgun pellets. KNIVES AMMO, it bragged. GUNS GUNS GUNS. "Whoa," said Van, hitting the brake. Van arrived late at his destination, pitched out at the end of a two-lane road. The drunken Hickok wheeled his Humvee and roared back down the mountainside. He'd said something about a girl waiting in Fort Collins, but Van was not convinced of it. With that briefcase finally off his wrist, Hickok had the look of a man aiming for a major-league bender. Van was left standing alone in a cold Colorado night, under two pools of amber light that fell from curving, snake-shaped poles. Observatories hated light pollution. So these Martian-looking light poles carried weird LED panels that shed a very thin gleam. Reading by their light was like wading underwater in a hookah. Van set down his brand-new survivalist backpack and stared up at a beautifully painted sign. ALFRED A. GRIFFITH INTERNATIONAL ASTRONOMICAL FACILITY, it announced. This big sign—it was a dignified metal billboard, really—carried eye-squinting little logos for a whole swarm of federal sponsors and private contractors. NATIONAL SCIENCE FOUNDATION. AURA. NOAO. NASA. NORTHRUP GRUMMAN OPTICAL SYSTEMS DIVISION. CANADIAN SPACE AGENCY / AGENCE SPATIALLE CANADIENNE. MAX PLANCK INSTITUT FUR EXTRATERRESTRISCHE PHYSIK. Warning: This Is a U.S. Interior Department Endangered Species Refugium. To Van's right, to his left, stretched a galvanized twelve-foot steel elk fence. It was topped with nasty whorls of razor wire. Too bad nobody had included a doorbell here. There was no way for Van to enter Dottie's facility. It was very clear that nobody ever showed up here who wasn't fully expected. The fences were too tall and sharp to climb. The gates looked built to resist a headlong charge by angry buffalo. There was no intercom and no guard on duty. Van had no cell phone. The winter night was getting colder. Van opened his pack and pulled out his laptop. Another tough break: there was no wireless signal for his laptop's Wi-Fi card, either. As Van was accustoming himself to complete defeat, the overhead light poles winked out. How very bright a million stars were in the mountains, suddenly. Van opened his laptop. The federal dot-pdf on his screen was horribly titled "Draft Reporting Instructions for the Government Information Security Reform Act and Updated Guidance on Security Plans of Action and Milestones." Van did not have to read any more of this awful document, though. Instead, his computer was going to give him enough light and heat to survive the night. Van dug in his pack and wrapped himself in a four-dollar NASA surplus astronaut blanket. He chewed a brick of indestructible NASA-surplus spaghetti. He warmed his hands on the hot battery of his laptop. He'd been in a paranoid mood, back at the survival store. Hooded in his windproof blanket like a silver garbage bag, Van sat on his bulletproof backpack and confronted the glow on his screen. What did it matter if he was alone, cold, lonely, and humiliated on the end of the road? Van had a lot of important office work on his lap. Many unread reports, many policy statements, and important federal white papers. Requests for commentary. Invitations to important seminars. He could achieve a lot while freezing in a wilderness. The air was thin up here, and it got colder yet. Van rearranged and color-coded his many, many files and folders. As he typed, his fingers turned blue. After an hour and forty-two minutes, the black gates spontaneously opened. Van was forced to scramble out of the way or be crushed. A slab-sided white panel truck barreled through. Before the gates could swing shut, Van grabbed up his pack and hustled inside. Van trudged uphill in cold and darkness, under starlight, with his eyes gone big as an owl's. It was a very steep climb. For all his hard work in the gym, the hike had Van huffing, wheezing, and rubbing his thighs. When he plodded his way over a crest, Van could see, lit up like toy ballerinas, a distant nest of gently whirring rotors. Wind power, renewable energy. Out here, those pretty dancing windmills wouldn't smudge their perfect skies with smoke. A deer stared at Van fearlessly and went back to raiding the bushes. The road lifted suddenly. Van found himself walking on an echoing metal bridge. More amber lights loomed ahead. Here was a parking lot, all of it up on pillars. It was filled with silent electric vans and logo-covered golf carts. Van had found Dottie's research complex. The pictures she had sent him didn't do the place justice. It was a whole lot odder than it looked in the brochures. The place was like a Silicon Valley health spa built for mountain hobbits. The complex rose right up a mountain slope, all twinklingly underlit with tiny amber lights. The offices were made of cedar, granite, glass, and aluminum. Lots of perforated grating, pillared balconies, and shiny steel handrails. All these buildings were poised on the mountainside on daintily curved metal feet. Endangered species could frolic right under their floors. Roof gutters caught all the snow and rain and fed it into big cisterns. It looked amazingly pretty, like something out of a kid's encyclopedia. For some touchy enviro-fanatical reason, nobody had been allowed to dig anywhere, to break the tender mountain soil. So all the Facility's water, sewer, and electrical were neatly suspended on pylons, like an Alaska pipeline for toilets. The place was overrun with fat, silver-wrapped pipes. It looked like it had been designed by Super Mario. Van huffed to catch his breath, then clomped straight up a set of toothy aluminum stairs. He opened a double-paned glass door. He walked down a hall floor lined with dark cork. He knocked at Room A37. The door was opened by an old woman wearing rimless bifocals, a colored head scarf, and a lumpy, hand-knitted sweater. "Sorry," Van muttered, "wrong room." "You must be the husband," said the gypsy woman. "Uhm, yeah." "You're late. Dottie had to go. Why didn't you call?" Van made a beeline for Dottie's bedside phone. "I'll call her right now." "Don't do that. She's on television." "At night?" Van said. "Of course at night! It's a telescope!" The talking woke Ted. Ted was sleeping in a plastic crib at the foot of Dottie's bed. Ted hustled sideways on his Disney-cartoon sheets and peered through his bars. He saw Van and shrieked. Van advanced on his son and picked him up. Ted had become huge. Ted's noggin was thick with brand-new blond hair. Ted seemed to have added a full fifty percent to his body mass. When Ted struggled, he really meant it now. In Van's long absence, Ted's marshmallow baby body had turned into muscle. The boy looked ready to jump into his own clothes, grab up his cup and rattle, and get himself a day job. "It's me, your dada," Van bargained. "NOOOOOO!" Ted thrashed his thick legs as if jumping hurdles. He was wearing a long-sleeved red flannel onesie suitable for chilly nights. Ted looked like an infant lumberjack. "NOOoooooOOOOO, no, Mama!" His diapers stank. "I'll tell Dottie you are finally here," said the unknown baby-sitter. She vanished out the door. Van set Ted down on the chilly floor as he hunted down a pack of diapers. Van hadn't changed a diaper in ages, but it wasn't a skill one forgot. Ted resented this brutal procedure. He gave Van a look of bitter, jaded suspicion. "It's all right, Ted," Van lied. He buttoned Ted back up and set him on his pudgy feet. With a determined scowl, Ted gripped the edge of his mother's bed and sidled away from Van. For the first time in his life, Van had some insight into what had gone wrong with his own father. It was guilt. That was why the guy had finally crumbled. Because of burning guilt, dirty guilt, painful, humiliating, fully deserved guilt. There were bad acts in a man's life that could never, ever be repaired. Van sat on Dottie's bed, which was narrow and hard. Dottie's high-tech eco-room was creeping him out. This was like the home of some alternate Dottie from a bad _Star Trek_ episode. Dottie's tight, virginal sheets had tiny blue flowers. Dottie had a small, oval-shaped, Energy Star fridge. She had a hot plate and a pretty teapot on top of her bamboo clothes drawer. Dottie's computer desk was ergonomic and very disturbing. It had many adjustable plastic cranks and was made of swoopy red plastic lozenges. The desk had one special kidney-shaped shelf way up on a tall metal arm. The shelf was poised at a weird, unlikely, Dr. Seuss angle. The tall shelf held one empty, dusty little flower vase. This was a room that was silently screaming for a man's disturbing touch. This room really needed its hair mussed. It was all Van could do not to start hitting things with a bat. "Ted, son, how do you live here?" Ted replied with bitter whimpering. Van persisted. "Hey, Edward." Ted turned his small face toward Van, but he was openly skeptical. Van zipped open his backpack. "You wanna see something really cool? I'm gonna show you my ray gun!" Feet skidded down the hall. Dottie had a new haircut and had put on five or ten pounds. Van stood up. Dottie zipped across the room and gave him a kiss. It was a nice, solid "I am your wife, here are my lips" kind of kiss. "A long trip, honey bear?" The feel of her soft arms around his neck was saving Van's life. Loneliness drained out of him like poison. "This place is the middle of nowhere!" Dottie nodded, blue eyes bright. "It is! It is. But no one ever leaves us." She shrugged out of her padded jacket. "Why not?" "Because the catering is too good! There's Indian food, Chinese food, they had a barbecue chef in today . . . We ate wild elk!" The sight of Dottie meant so much to him that he felt faint. "You look great, honey." "This is my TV outfit." Dottie went to the cubbyhole bathroom and flicked on its fluorescent, eco-correct lightbulb. "There was a crew in tonight from Australian television. I seem to be the big PR person around here now . . . It turned out that I'm pretty good at that. This is not the biggest adaptive telescope in the world, but you know, it really looks great on TV." "No kidding." "This is the only telescope facility ever designed by a major modern architect. Did you see all that fiber-optic out there? We got really big pipes here!" Van sighed. It was hard for him to rally any enthusiasm for another Internet money hole. After the stock crash, Mondiale was doing a scary reassessment of the company's physical assets. Internet routers were in such oversupply that they were worth only twenty-five cents on the dollar. No wonder Tony had stuck some surplus Net hardware up here in the high backwoods. All out of sight, out of mind. Dottie found a heavy quilt. "It gets so cold up here," she said. "They don't like us running the electric heaters . . ." She lifted Ted and put him back into his crib. Ted looked relieved and interested. Ted hadn't seen his parents together in several baby eons, but his mom was happy, and the routine was jogging his memory. For the first time, Ted offered Van a smile. Van put a hand on his son's face and looked deep into his eyes. It was like gazing through a powerful mirror straight into the youth of the universe. "Derek, look, this thermostat has a power meter built right into it, isn't this great? They're in all the rooms." "Why won't they let you heat the place? We're way up in the hills!" "Astronomers get used to that." Dottie tucked Ted into a spotless blanket. "It's a very nice place up here, honey. We get health care. We get paid vacations . . . There's horseback riding. We got workout rooms and massage . . . We get big-screen movies. We get _Bollywood_ movies." "And you watch that stuff on purpose?" "Bollywood movies are great. _Fiza,_ that's such a wonderful film. It's all about a Moslem girl from Bombay whose brother is a mujahideen terrorist." Dottie's voice fell. "I cried and cried." Dottie had been crying and crying, thought Van with a pang. She was being so bright and sweet to him. Two minutes together, and it was as if they had never parted at all. But he knew she had suffered. He had suffered. He had suffered so much he had no idea what to do with his feelings. He hauled Ted back out of his crib and set him on his knee. He couldn't keep his hands off the kid. Ted was such a lively presence that holding him was like licking a fresh battery. "So, who was that babysitter who was here?" "That's Dr. Ludewig. She used to run a radio telescope in Denmark. We get a lot of visiting scholars from overseas here. This place, it's a lot like Cerre Tololo in Chile. For colleagues in Europe and Asia, we're such a big deal." Dottie turned to him. "I'm gonna get some great publications out of all this." "I thought you were still two years away from your 'first light.'" "Sure, we are, but running the telescope is just part of our action." Dottie was always completely serious whenever she discussed her career. "It's all about leveraging digital instruments with the Net. We're building the world's biggest star archives here. Lots bigger than MAST or HEASARC. They're already using us for their backups and mirror-sites, because our bandwidth is so hot. We're the only physical backbone that NSFnet has crossing the Continental Divide. We've got tremendous pipes, stacks of equipment, machines we haven't even unwrapped yet. Racks and racks of numerical simulators. It was 'pre-owned' by the feds, but we're astronomers, so that doesn't matter to us. We're like kids in a candy store." This was a billionaire federal contractor at work, thought Van, with a potent mix of private and public money. It had to get like this, when fewer and fewer ultra-rich people controlled bigger and bigger chunks of America's economy. Peel a few labels off, and the government's suppliers and buyers turn out to be the very same guy. Van understood that well now, because he watched the federal government's "Industrial Base Management" happening every day. Van himself was both Mondiale R&D and CCIAB Tech Support. He was knee-deep in the system, too. Jeb called it "the Smoking Room." Step one: get those heavy operators into the smoke-filled room. Step two: close all the doors and windows. Step three: pick only the contractors who are willing to play the game. When you leave government, then they'll hire you. You'll be them, and they'll be you. The Smoking Room had a built-in revolving door. "Yesterday's Technology at Tomorrow's Prices." That was how the National Reconnaissance Office had gotten itself a marble office complex and the best cafeteria in Washington—even though, officially, nobody had ever heard of the National Reconnaissance Office. They ran satellites. They were real. Real, real secret. The Smoking Room. The Grease Machine. The military-industrial complication. Van's head was swimming. "Mmmm." Dottie was concerned. "Is it your altitude sickness?" "Yeah, honey. Sorry." He hated disappointing her. "Sweetie, you just relax awhile now." She took Ted away from him and put the baby back in his crib. Then she fluffed up a pillow, flopped Van on the bed, and pulled his shoes off. "It's so late. Did you eat anything? You know what? I have some really good Chardonnay. That'll fix you up." Van had to laugh. It was doing him such good to hear her rattle on. "How good is it?" "It'll relax you, you'll fall right asleep." Her blue eyes were full of wifely promise. "Tomorrow, though, we'll do everything." Van accepted a glass. Van didn't much care for sweet, girly chardonnays, but this one was good enough to get him up on his elbow. "Wow, honey, this stuff's great." "I can afford it," she told him. "They pay us a lot and there's nothing to spend money on up here. Housing is free. All our meals are catered. We even get dental." "Wow." She sat on the bed demurely and looked down at him with a tender smile. "You know why it's like that around here? Because it's still the 1990s up here, that's why. When DeFanti set this all up years ago, he thought it would be really hard to get any top technical people to live way up here. After all, we don't even get to have cars . . . So he budgeted us for big dot-com-style perks. Tony would change all that if he could—that guy is such a cheapskate—but that's the way DeFanti angled things with the feds. So it's just stuck in cement. Nobody's got the authority to change any of it." "I thought Tom DeFanti went nuts." "He did, but that doesn't matter now. This telescope is supposed to be his monument. He really, seriously wanted it to last for a hundred years. DeFanti was always kind of strange that way, but . . . Derek, this is such a good place. This is just what life was like when people just like us were really happy. The work is challenging. We get creative freedom. They really pay us. It's a beautiful little campus. The food is fantastic, there's all kinds of cool hardware, there's day care . . . I love it up here." "That's great." Her smooth brow wrinkled. "Whenever I go out of town, to Boulder or Denver, then I see how bad it's getting outside. People out there are crazy now. Everyone is completely terrified." "It's not that bad," Van lied. "Yes, it is." "Yeah, Dottie, you're right, it is that bad." There wasn't much more to say on that topic. It was too depressing. Dottie arranged the sheets and quilt around him. "Honey, this bed is too small for us. Tomorrow we'll go down to DeFanti's ranch. I made us reservations. They've got cottages and a hot tub! Is your head any better now?" "Yeah." A drink always helped Van with his altitude sickness. Alcohol flushed open important blood vessels inside his skull. Van sat up and pulled his pants off. He'd bought new slacks in order to confront General Wessler, hoping to look more professional. As he dropped them to his ankles, his brand-new knife fell out of his pocket. Helpfully, Dottie scooped it up. "Is this a new gadget, honey?" It was a fist-sized lozenge the color of soot. She picked at its thumb lever, and a black, razor-sharp serrated blade slid out. Dottie dropped the knife, scarring the floor. Startled words tumbled out of her. "Oh, honey, this is like some awful thing that people would like murder somebody with!" "It's a hunting knife," Van lied, plucking it up. "Tony always talks about the great hunting up here in the mountains." Hickok had talked him into buying a tactical SWAT knife at the survival store. The knife was blacker than a Gothic ninja. It featured a carbon-fiber handle and a titanium carbonitride blade finish. "You got that thing for Tony?" Van closed the knife and hid it at the bottom of his pack. Van had never mentioned the existence of Michael Hickok to Dottie, because every single thing regarding the KH-13 was so entirely off-limits. A brilliant lie burst out of him. "Nowadays, they never let this kind of thing on airplanes. But I came here by car, so, you know, I'm just holding it." He sipped more wine. Dottie's sweet face clouded. "Why would he want that ugly thing from you? What is wrong with that man? Nothing ever satisfies him!" Van blinked. "What's so wrong with Tony?" "Oh, nothing. Nothing at all, I guess. Except for his nineteen-year-old girlfriend! Derek, he is _buying_ that woman. This Indian movie starlet, this creature with snaky black hair who hangs all over him and has eyes like two headlamps. Does that sound healthy to you?" Van knew very well that Tony's girlfriend Anjali was twenty-three, but seeing Dottie's reaction, he wisely held his tongue about it. "Boy, that's a big shame." "I worry so much about Tony. In all the years I've known him, he has never had one stable, adult relationship. That woman is taking advantage of him, I just know it. He is completely besotted." Van choked back the urge to snicker. "Besotted"? What kind of word was that? The last time he'd enjoyed a talk with Tony, back in Washington, Tony had been rolling his eyes like a cartoon wolf over this little Indian actress. It was very funny to Van that Tony Carew, the poster boy for jet-setters, had finally found the one woman in the whole round world who could lead him around by the nose. An Indian movie star, of all the wild things. It was so like him. Van had been plenty curious about the girl, so he had found one of the actress's Hindi-language movies on an Indian-made DVD. Tony's sex-bomb girlfriend turned out to be this sugary, Technicolor hoochie-coochie girl who didn't even kiss her co-stars. The whole ridiculous thing gave Van a warm, bubbly, glowing feeling. Poor Tony, poor old Tony, that lucky slob. Jeez, at an altitude like this, that Chardonnay had some kind of kick. He patted her hand. "Precious," he said, "we should just let old Tony just be Tony. You and me, we get to be you and me. We can be happy, if they give us a chance. That's what counts." A flush rose to her cheeks. Dottie's shoulders started to shake. Oh, for heaven's sake, she was going to cry. Van's heart smoldered guiltily within him. Well, why shouldn't she cry? She had good reasons. He put a hand on her shoulder. "Honey, it'll be all right now. It'll be good for a while." Dottie only sniffled all the more. Why could he never tell her the right thing? Sometimes he almost got it all straight in his head. But he had a cramp in him that would never let him give her the right words. The baby was asleep again. They were stuck in this small cold room. Dottie was crying and his head still hurt from the thin mountain air. But at least they were alone, and no one was bothering them. Dottie's little room didn't seem so bad once Dottie was inside it. It was lots bigger than his tiny Vault office, and probably much less weird, too. Dottie was here with him, that was the point. He wasn't freezing outside the Facility's gates in the dark. He should be grateful for that. Plus, there weren't any Space Force generals around here. Life wasn't so bad, it was pretty good after all, wasn't it? Yes, life had to be good. He pulled his shirt off. Dottie's eyes widened as she wiped away her tears. Van grinned at her. Yeah, in her absence, he'd really been hitting the gym! He'd shed a lot of flab! Thanks to those Nautilus machines, he'd never been in better shape . . . "What happened to your _shoulder_?" Van glanced at the fading blotch of purple and yellow. He had hammered his shoulder black-and-blue with the bouncing butt of a South African combat shotgun. The thing had a spinning drum magazine that spewed shells as if they were confetti. Dottie touched the bruise in wonder. "Honey, you really got hurt!" Of course the blazing shotgun had hurt him some, but it had been so exciting that he hadn't even cared. "A little accident at work," he lied. He stretched out on the taut, narrow bed. In a moment she had slid in next to him under the heavy quilt. They never shared the same bed much as a couple. With lives in separate cities, they had never fallen into that habit, somehow. This bed was much too small. Dottie clung to him as if they were stuck on a life raft. He was too tired and winded to make love to her, but he was taking huge comfort in the heat of her skin, in the even sound of her breathing. His star girl. A gift to him from the universe. On some silent level of his soul he had felt a profound terror, a deadly conviction, that he would never hold Dottie again. Dottie pillowed her head on his arm, locked a leg around him, and fell fast asleep. The room was very dim. He could barely make out the sweet line of her nose, her cheekbone. How frail the world was. He'd never known, until he stepped behind the curtain of power, that civilization was mostly a matter of keeping up appearances. Up at the very top of the power elite, in the little counsels and committees of the great and the good, even the people who happened to be scientists and engineers had to become witch doctors. Yes, he was a politician now, too. To run the world, you had to find it in yourself to grit your teeth and just fake it. Just stare them down, never back off. That was where he'd blown it with the General. He hadn't come to that man with a warrior's air of command-and-control. "The aura of inevitability." Van closed his burning eyes. Tomorrow, just for once, he had nothing to do but to be together with his wife and child. Why should that seem like such a fantastic privilege to him now? Because he had volunteered for all this. He had willingly turned himself into a weapon. Van hovered at the brink of sleep, his chest heaving at the thin air. The shining image of his grandfather's gun occurred to him. The gun pressed against his mind's eye, heavy with dream-importance. The ray gun had run out of solder as he worked on his doomed KH-13 presentation. That's when he had opened it up, removing four tiny steel screws, and discovered that the engineers of the Skunk Works had built a fake jet engine inside there. When he'd popped off the butt of the ray gun, he was looking right up the round model rocket rump of an SR-71 Blackbird. To make the gun work, you had to shove solder wire up the jet's exhaust, round as a gun barrel. That was true geek humor. Very crew cut and bow tie, very 1960s styling. No wonder his grandfather had always treasured the thing. Wine and weariness came down on him and pressed him flat. At 3:00 A.M. the baby's screams woke them. "Oh, Derek," she said, muddled and confused, "I always let Ted sleep in here with me." There was nothing for it but to jam lonely Ted into the bed with the two of them. The sleepy and irritable Ted wriggled like a flannel otter, wedging his body between his parents and hacking for space with knees and heels. Van, who had been hovering at the edge of altitude suffocation, came wide awake. Van climbed out of the bed, then put all his clothes on, because the room was icy. He wrapped his shoulders in Ted's abandoned blanket, sat at the desk, and woke Dottie's laptop from its sleep. Dottie's room might be neater than a convent, but he had never seen Dottie's computer in such an awful mess. It horrified him to realize that Dottie Vandeveer, his very own wife, was using Windows Outlook Express on broadband without any security enhancements. She'd customized all her icons, too. They were not her usual dainty stars and comets, but icons that a Goth chick would have gone for: bats, UFO aliens, witches' cauldrons. Important files were scattered all over her screen, most of them named with doubled exclamation points!! and shouting CAPITAL LETTERS. Van was staring straight into an X ray of his wife's unconscious mind. The news here was not good. Van had finally reached some kind of peak event in his marriage: he was sending his wife e-mail from her own machine. _Dear Dottie, I never told you how hard this new life would be for both of us_ No, that wasn't it at all, that way was just no good. His words vanished into the left-moving vacuum of her DELETE key. _Dearest Dottie, I can't tell you why this hasn't worked out as I hoped_ _Dottie, I'm not allowed to say just what_ _Dear Dorothy_ There was a sudden electric snapping. Power failure. All the lights went out. Van groped his way back toward the bed in pitch-blackness, and he lay down fully clothed. CHAPTER TEN PINECREST RANCH, COLORADO, FEBRUARY 2002 **D** ottie prodded him flirtatiously with her bare toes. "Well, hero, now you know what you were fighting for!" Van nodded, breathing hot steam. He balanced his cold German beer on the edge of the hot tub. To judge by his surroundings, he was fighting for the right of eccentric rich guys to buy the whole planet. Thomas DeFanti's "cottage" had once been a pioneer Colorado farmstead, all hard rock and tough gray timber. Then some pet architect had transformed the place into a billionaire's secret love nest. It was all done-up inside in black-and-chrome, high 1980s style. It was like Hugh Hefner seducing _The Unsinkable Molly Brown._ Pinecrest Ranch, to judge by what Van had seen of it, was a mix of Hong Kong and Hollywood Western. Mrs. DeFanti, the zillionaire's fourth or fifth wife, was the guardian of the old man and his big spread. Mrs. DeFanti was turning his Ponderosa into a bonsai Chinese ranchero. She was dusting the buffalo, she was grooming the antelope . . . She was a chip mogul's daughter from Taiwan, and she was re-creating Colorado as a Pacific Rim luxury spa. Guest meals were served up in the main ranch house, in a sunny conservatory with a stunning mountain view. Van had started his day with Russian eggs Benedict with spinach and caviar, plus pineapple juice and an inch-thick buffalo breakfast steak. His altitude sickness was banished. The protein, vitamins, and half a gallon of Jamaican Blue Mountain coffee had definitely gotten his motor running. Dottie, who was off the pill, had surprised him with a condom, which they promptly broke. Van was shocked to see her shrug off this mishap, and even laugh about it. She was in a mood he had never seen. The cottage's hot tub was like a little amphitheater, surrounded by black solar-water heaters. The tub gave off a volcanic Jacuzzi sizzling in the crisp winter air. Van had never made love in a hot tub before. As the pulsing currents beat and sizzled against his naked flesh, he got it about the appeal there. It was like having more sex without even needing to move. Dottie sampled her glass of white wine, and tucked her cold hand back in the hot water. "Honey, that was too long apart, okay? I don't wanna be a computer-security widow." "We can meet again at that big to-do in Virginia. And after that, Tony has invited me to a Joint Techs conference up here." Unhappiness crossed her face. He'd given her the wrong answer. She didn't want him to just make some dates. He couldn't tell her the simple thing that she needed to hear. Even though he knew what that was, more or less. It was something like: "Honey, I missed you just as much as you missed me." But that wasn't quite true, and he knew it. Those months apart had brought him an ugly self-wisdom, Van thought as his floating feet bobbed in the sizzling water. There was something wrong with him as a man, a husband, a father, and a human being. He was the only child of a troubled marriage. He came from a line of people who were way too bright. He had an ability to concentrate and work creatively, and he also had a thorny, geeky isolation. And those were not two different things. They were the very same thing. Beneath his shell, his personal armor, he had a vast, galactic gulf of need. It was huge and ruthless, like an autism. It would never be filled. And that wasn't her fault at all, for a thousand loving Dotties couldn't fill it. His heart of hearts lived there in a gulf of darkness, and his love for her was like one single glowing star. If he'd been a poet he could have told her that in some nice way, but Van had never in his life packed a thought like that into words. He might have made a start at saying it—but there was worse. In her absence from his life, in the icy vacuum where her warmth had once consoled him, there was a new and powerful emotion growing inside him. As Van floated there at ease under the big winter sky, looked after, fed, watered, loved, now he could see that feeling, now he could finally put a name to what was going on inside of him. It was rage. He could see that rage within himself as if watching it through a telescope. It was black and hard and dense, like a neutron star. He was someone who read manuals, wore glasses, and typed on a keyboard. About the most violent thing he ever did in his cyberwarrior life was to look for a buffer overflow. But rage was growing in him, because rage was a native part of his soul. Rage grew there in the entirely natural way that grief would grow in a widower. Van had nothing to say to her about this. He couldn't any more wrap his tongue around that than he could lick broken glass. Dottie looked over his shoulder. Then she found her glasses, put them on, and stared. Van found his specs as well. Two men were approaching their cottage on horseback. The first was a young Chinese servant. Van wanted to think of this Chinese kid as a "staffer," but Mrs. DeFanti's Chinese underlings were most definitely "servants." They were around all the time, thoughtful, watching and attentive, but barely there. They made the most self-effacing British butler seem like a brass band. The second man was also humble and ghostlike, but in a very different way. His padded jacket, his tartan shirt, his felt cowboy hat, they were perched on his quiet flesh like the clothes on a cowboy paper doll. The two horses plodded by gently, long heads down, on some very private go-round. Van and Dottie sank deep into the hot water. The servant ignored them serenely, as if two naked lovers in a tub were no more than two pinecones. The old man's gaze fell on them and lingered. He had eyes in a waking dream. They seemed to stare across a thousand light-years. The horses plodded on and carried their human cargo into the pine trees. "I should have stood right up and waved," Dottie said. Van laughed, startled. She swam over and wrapped her chunky little body around him. "We don't have many illusions about that old man," she told him, her lips an inch from his neck. "At the Facility, nobody does. When he was between marriages, he used to go to astronomy seminars and hit on all the women. Oh, boy, the stories you used to hear whenever Tom DeFanti was on the prowl." "How do you know all that? Aren't you a little young for that old guy?" "There aren't that many women in astronomy, honey. Word always gets around." Van gave her a smile. Somehow, it all made sense. "I got myself one of the cute guys," she told him, rubbing his collarbone. "Everybody knows." Van kept his smile up, but the sight of Tom DeFanti had given him a real turn. Van had met a lot of odd and remarkable people lately. He had met the President of the United States. He'd met the Secretary of Defense, the National Security Adviser, and the Attorney General. Once, at an industry junket, he had had a long chat by an elevator with both Bill Gates and Warren Buffett, who were riding up to the penthouse together to drink beer and play poker. Bill Gates had noticed Van's name badge. He had said something nice about how "hard-core" Van might get, working at Microsoft Research in Redmond. Maybe if Bill Gates had caught it in the neck from some huge Enron scandal. If Bill Gates had suffered a total mental breakdown. If Bill Gates was shambling around like some kind of snake-bitten ghost. Then maybe Bill Gates would be as scary as Tom DeFanti had just been. The world's rich people were all getting spookier. During the Bubble, there had never been so many truly wacky people who were just totally, crazily loaded with cash. Up at the very top, they stopped counting their money and they wanted to act just like governments. George Soros had his agents all over Eastern Europe. Ross Perot wanted to be President, and Ken Lay . . . they'd all lost the idea that there was any kind of limit to what money could do to the world. Even Osama bin Laden was a rich guy. It was like they were all staring straight into the sun. "Honey," she said. "What?" "Try to relax, okay? I'm Facility staff, I rented this place. We get to do that with Pinecrest, it's, like, an understanding. They won't do anything. It's all just fine here." "Right," he said. "What do you want to do today, honey? We have our own day just for once, we can do anything we like. Hiking, or horseback riding . . ." "No." "We could go back inside and try out that big waterbed." Van finished his beer. The pores had opened up all over him. He was never going to get any cleaner. All the lovemaking had reset Van's erotic dials to zero. He didn't want to stay around this place anymore. He was ready to put some clothes on and get something serious accomplished. "I've got a great idea," he told her. "Why don't we go see your work?" "Okay. After lunch." "Let's go." "Derek, we're having shrimp bisque at the ranch house. With blackened tuna. Plus sautéed morels in truffle oil." Well then. Maybe Dottie's plans would be pretty much okay. After a sumptuous meal, while his gut was stuffed, his head was logy, and his temples were thudding with coffee, they returned to the Facility. Dottie took an electric cart up the mountain. It was icy, windy, and the air was impossibly thin, but there was a fantastic view. It was the basic business of observatories to have a fantastic view. This one was colossal. Sex, food, and coffee had whipped his altitude sickness. With a sidelong grin at Dottie, Van left her and hauled himself hand-over-heel up the broken slope of a granite crag. He needed to get up there in order to soak it all in. That massive sky. The upended bones of the Rockies were laced with racing clouds and their slope-sliding shadows. Wrinkled peaks dusted with white ice. The long run of green pines. Ancient brown landslides, with old miners' roads crumbled and vanishing. The blackened scars of small forest fires. From the Observatory, the Facility was entirely lost inside its trees: just an aerial, the crisp white rim of a satellite dish. Hovering above the postcard scene was an airborne silver blob. It was an aerostat, on a long striped mooring line. Van had noticed the airship at once, and Dottie had told him about it. This shiny ship was NORAD-surplus, some experimental barrage-balloon radar scheme that the military had never successfully put into operation. DeFanti had reworked the blimp scheme, trying to commercialize it, to repurpose satellite communications, just for local neighborhoods. This wild notion had never caught on in the bigger world outside, but around here in the mountains, a little blimp with telecom aboard did make sense. Pinecrest Ranch, the Facility, and all the smaller local ranches nearby were isolated. They were in a land of dark skies, in a federal area zoned for radio research since the 1940s. Antennas and cable TV were forbidden. So, if the weather permitted, then they could get some connectivity off a floating baby satellite, a cute little Mylar airship. It was technically sweet. A silvery floating jewel for the twenty-first century. A bold proof-of-concept. It was just the touch that this landscape needed. Van's shame and despair had left him. In this huge American sky and these mountains, he found himself light-headed with a golden sense of the world's possibilities. He _did_ like it up here, being with Dottie. It was great. If the stupid war would only end, and if he blew off a few personal bad habits, yeah, he could make a go of it, living up here. The mountains of the West would become his home. He could go native. He'd get barrel-chested, and tanned, with boot calluses on his soft hacker feet. His son would grow up as a mountain boy. Ted would be a skier and a climber. He and Ted would be mountain rockhounds together. He'd get a rifle and a fly-fishing rod. He and Ted would hunt and hike and fish every weekend. Tents and campfires at night, maps and compasses. He would look the kid right in the face and tell him wise, fatherly things about the world. He would make up for everything he was failing to do, failing to give. Dottie waved at him from below the crag, her words to him lost in the keen wind. Van climbed down to rejoin her. Dottie looked strange to him after his reverie. This dainty woman with straight brown hair and unplucked eyebrows, those lips that never wore lipstick. A thick denim shirt and jeans. She was the most precious thing in the world to him. The telescope's round barn was big, but smaller than it looked in its publicity. The dome featured clamshell doors that opened to the zenith. The observatory rotated neatly on gimbals to track the moving sky. The structure had a strangely sleek, sporting-shoe look. It was like a gigantic shopping-mall kiosk. Inside it was still and warm, for the walls were very thick, protecting their precious instrument like a foam cooler full of premium beer. As an astrophysicist's husband, Van had visited more observatories than any man should ever have to. Van was used to the look of serious scientific instruments. He had never seen a telescope half this pretty. Big professional telescopes always looked frazzled, stuck-together, and one of a kind. Here, though, Van knew at once that he was standing in the presence of an old man's darling. This telescope was polished and elegant, bejeweled with buttons, plugs, and switches, like a trophy wife at a Nobel Prize party. It—she—was five stories high. A towering complex of struts had delicately tapered arms painted in designer enamel. Her bottom was a great big mirror bowl of glassy blue hexagons in a green plastic case. All the joins and seams were suspiciously perfect. This telescope was like the Hubble's sexier little sister. The objective of an "adaptive telescope" was to remove the twinkle from the stars. The instrument did that by reshaping the telescope's mirrors in real time, computer-corrected, flexing in subtle response, just as the atmosphere moved. This very cool idea had clearly caught DeFanti's technical fancy. But—Van wondered—was it really necessary to neatly countersink all the bolts? Why was the scope's outer casing snapped together so seamlessly, like some bride in a posh limousine? Then there was the wiring. This telescope had a haywire Medusa wealth of wiring. She was screaming her torrid romance with the Internet. In the mighty effort to bring her online, it looked like the local techs had subjected her to major cosmetic surgery, maybe two or three times. Every glass hexagon drooled out a black Niagara of electronic actuators. There were rafts and banks of fiber-optic lambda just lying there, seemingly abandoned. This baby had enough wiring for a Swiss atom-smasher. No wonder they loved her on TV. "She's real cute," Van said aloud. His voice echoed from the vault. They were alone with this towering instrument, two human beings reduced to the size of Rocky Mountain marmots. Just this sleeping Bride of Science, her control consoles, a scattering of office chairs and wire-bound manuals, some dirty coffee cups and sleeping bags. Scientist clutter. "They had real trouble with the original design," Dottie admitted. "Architects have such big egos. He didn't want any bunch of geeks telling him that ugly things work better sometimes." Dottie spread her hands. "So we're not Keck II or Mauna Loa, okay? But those materials are top-notch, really built to last. As for our bandwidth, well . . . This will be Internet2's only live cyber-observatory. Everything streaming in real time right over the NSF backbone. Tom DeFanti wanted every kid in every inner-city school to see the whole universe. If they couldn't see their sky any more because of all that city glare, well, he'd just give them the universe, free, by the Info Superhighway. And if Al Gore was President now . . . well, he probably could have got a lot of federal money for doing that." "What gives with the bad wire job?" "Oh, well, we call that our Bhopal problem. See, when the original contractors left, Tony hired all these cut-rate Indian engineers . . . They keep coming in here, running expensive tests, putting it online, taking it down again, and rewiring it . . . Nobody ever tried this before, they're fiddling with it day and night . . . He's not the world's greatest project manager, Tony." "I never had Tony figured for that line of work." "Getting this thing built, that was Tony's first big success for Tom DeFanti. It was practically impossible to build any telescope this close to federal parkland with all those regulations and endangered species rules, but . . . well, here it is, Tony arranged all that. Tony always hooks things up in such a clever, Tony-like way." "Like he hooked up you and me," Van said. She looked at him innocently. "What, honey?" Van pretended interest in the complicated bulk of a diachronic beam-splitter. He had almost put his foot in it, right there. "Oh, yeah, Tony used to talk to me a lot about how he got on DeFanti's good side. This scope meant a lot to him." "I found out how he managed all this, you know." She was proud. "See, Tony made good friends with all the people who really hated the project. They were mostly these hippie Green characters from Boulder, real not-in-my-backyard people. So Tony went to them, and he attended their meetings, and he gave them some of DeFanti's money, and he said to them, well, we'll just build it all Green! Everything Green! All renewable energy, everything recyclable, all local materials, and very organic. That was a lot less expensive than fighting their lawsuits. So, I live in, like, a real showpiece for Green construction methods. Most telescope facilities are like Sherpa camps compared to this place. Green people used to come up here in busloads just to gawk at us." There was something else weighing on Dottie's mind. He could see it was something important. "So then what?" Van said. Dottie shrugged. "So then, I guess they just got bored with us after a while. I mean, we're just a bunch of astronomers. Besides, our telescope isn't even up and running yet. We don't even have a proper PR department to do public outreach. I mean, I _am_ the PR department now, basically. That's me." "It's all right now? Those Greenies don't bug you anymore?" "Oh, DeFanti gave them so much money that they put him on their board. They've got some really nice offices in Boulder now that were built by this same guy. He's a really famous Green architect now. They, like, love him in Holland." Insight came to Van in a rush. Tony Carew had gamed the poor bastards. Tony had been their ruin. Because once upon a time, his enemy had been quick, and quiet, and probably always on time. A small, dangerous gang of Green fanatics. But with a warm smile and a big checkbook, Tony had lured them into the system. He made them get official and slow and bureaucratic, so that all these wild-eyed yarn-hat tree-huggers had to put on suits and ties, and play their office game, and totally lose their edge. Nothing left of their wild spirit now but their name and maybe their old logo . . . Was Tony that smart? Yes, of course Tony was that smart. If Tony had the opportunity, if he found a way to angle it just right . . . "What was Tony's angle in all this?" Van said. "Well, DeFanti was just so thrilled. It was Tony's idea to name this place after DeFanti's real father, 'Alfred A. Griffith,' some totally obscure guy who died when DeFanti was seven. That was the best thing that ever happened to us astronomers. Tom DeFanti got this big reputation as this steward of the land . . . That was eight or nine years ago now. A major project like this takes a long time." "Where were Tony's big bucks?" "Do there have to be any big bucks? It's a telescope!" Van tugged at his beard. "You know this is Tony Carew, right?" Dottie winced. "Oh, honey, he's your best friend . . ." "Yeah. I know. That's why I know all this stuff." Dottie was hurt. She looked him in the eye and looked away. "Well, word does get around . . . I don't really know this for a fact, but . . ." "But Tony had an angle," he said. She lowered her voice. "Do you know about pipeline easements?" "You mean like legal permission to lay fiber-optic? Yeah, sure." "Well, Colorado passed a lot of Internet easements once. They were trying to wire up the rural part of the state, you know, equal access rights to the Info Superhighway, and all that. But then, a couple of years later, DeFanti got that law changed in the state legislature into _gas pipeline_ easements. Just a word or two in some state committee, real quiet. Then came that big energy crunch in California. That huge natural gas shortage they had. There were some really big energy companies involved in that. Companies with really big friends." Van grunted. The Grease Machine. Of course. There were only so many ways over the continental backbone of the Rocky Mountains. California's thirst for energy was colossal. If you committted a corporate crime in a forest, and nobody knew it was there, was it even a crime at all? What if you turned right around and gave the cash to charity, like Carnegie did, or Rockefeller? The underprivileged kids of America, noses pressed to their computer screens so they could see their stars . . . Van paced around the telescope, silent, chin up. He stared up at every beam and bolt and crevice of the great machine. She looked so clean. So remote from earthly doings. Van's footsteps echoed from the distant vault. This place was like an opera stage, and here, wired for sound, was the diva. Mondiale had spent billions laying fiber-optic easements across America. Out here, DeFanti found a quiet way to cross the Rocky Mountains, sliding through the wilderness, with a giant firehose of natural gas. Gas pipelines were notorious for exploding. Gas pipelines were very dangerous and dirty, never the kind of thing you could build right out in the open. But that infrastructure had to get built somehow. People needed the energy. Everybody happily used the gas pipes. Nobody faced up to the consequences. So the pipes got built by quiet operators. Guys like Tony. A guy who could do a little sleight-of-hand with those telescope mirrors and the all-natural windmills. Who would ever guess that building a telescope was all about natural gas? Was he being too cruel, too suspicious? His work had changed him. All that dirty work on computer security, stuck inside some bombproof vault. Was he a professional paranoid now? Was he a mean bastard, because he'd spent so much time thinking about terrorists and crooks? Maybe he should have more trust for the motives of big business. Like those fine people of Enron, Arthur Andersen, Global Crossing, and his own beloved Mondiale. Van rounded the telescope. He spoke to Dottie again. "These walls were built out of hay, right? Don't you worry about that?" "It's strawbale, honey. Strawbale is very safe. When strawbale is packed down tight and walled off like this, it can't catch fire. Straw is very light, and it's Green and organic, and it's great insulation. A telescope spins to follow the stars, you know. This whole building spins just like a top." He smiled briefly. "Then it's great." "Everybody asks me that question, about the straw. That's my number one Frequently Asked Question. The straw is great, honey." Dottie drove their electric buggy back to the Facility. Van found himself tired but clearheaded. That ugly failure at Cheyenne Mountain still rankled him, but the sting was fading. Yes, everybody he knew faced a compromise or two. Real life was never made of spun sugar. Was it so bad that he'd blown it, trying to tackle some satellite's bureaucracy? Was it that bad that his best friend politically faked people out, so that he could sell them the power and energy those very same people had to have? Then Dottie took Van into his element. The Facility's Network Operations Center was three stories high, glass-fronted, and nestled right into a cliff. "We never thought we'd have so much telecom equipment in here," she told him. "Our architect built this place for our public relations people. This was supposed to become their office here, a kind of big tourist attraction, but . . ." Van was thrilled. Every Internet2 office he'd ever seen was like a tomb compared to this fantastic place. It didn't even spoil his enjoyment that all the hardware was 1990s vintage. Cisco Catalysts, Juniper T640s, Force10s, and Chiaro optical switches . . . They were up and running, too, their fans were humming busily. They were dumping the power of hundreds of toasters into the February air. Van walked past a glass library of color-coded backup tapes. He skirted open metal cabinets, draped with thick gushes of fiber-optic cable. "Over here"—Dottie beckoned—"there are stairs." "Just a sec," said Van. He had discovered the local network technician on duty. The guy, an Indian, was wearing a bright polyester T-shirt, sky-blue jeans, and joggers. He had a thin hipster chin beard and was leafing through a magazine called _Stardust._ He glanced up politely as Van approached him. "So," said Van. "How's that big Code Red attack working out for you guys?" "Oh, sir! Do I look worried?" The tech chuckled indulgently. "We're an OpenBSD shop here!" Van's eyebrows rose. "Good man! Well then, how about those new RPC vulns?" "Is just not a problem at all! Using 'nfsbug' and patched it all weeks ago." "SNMP traps?" "Oh, no, sir, for already we installed version three! We encrypted the protocol data unit, also!" Van gazed at his new friend in deep satisfaction. "I don't suppose you guys have agent-based packet filtering yet." The tech put his magazine down. " 'Agent-based packet filtering'? Isn't that a _theoretical_ solution to attacks?" "Not anymore," Van told him. "Honey," Dottie objected, walking up. "Should I know you?" said the tech. "I know your face, I think, sir." "I'm Derek Vandeveer." Van stuck out his hand. "You are _Van_!" shouted the tech, vaulting from his Aeron chair. "You are the _Van_! Oh, sir! This is such an honor." He ignored Van's offered hand and lunged straight for Van's shoes. He reverently brushed Van's Rockports with his fingertips. "Oh, sir, I'll never forget your paper on traceroute mapping." "This is Rajiv," said Dottie as Rajiv stood back up. "Rajiv gets a little enthusiastic." Rajiv placed his palms together, beaming. "Oh, Mrs. Vandeveer, I should have known this is him, your famous husband, here at last! Oh, what a joy to meet you, sir. That work with Grendel you have been doing. There's so much to discuss!" Dottie's face wrinkled. She was "Dr." Vandeveer. She hated being called "Mrs." Vandeveer. Van stroked his beard. "So, uh, tell me, would you be that guy, 'Rajiv23,' who posts on Alert Consensus List?" "Oh yes sir, that is indeed me!" cried Rajiv, thrilled to be recognized. "And what a contribution you are making on that list, sir. I forward all your notes to the Bangalore Linux Group!" "So will you be at Joint Techs this year?" "Oh, of course I hope so, sir." "Then let's have a beer, dude. We'll talk!" At Dottie's insistence, Van left him. Dottie trotted up a set of stairs to the building's third floor, Van clomping behind her. She turned and frowned down at him. "I hope you don't mind me boring you to death with my little GRAPE-6 simulators." "Oh, don't mind that guy, honey." Van was hugely pleased with himself. "Derek, I get maybe forty-eight hours with you, and you would have talked to that man all day." "He doesn't kiss like you do, baby." Van gave her a sharp pat on the rump. After a moment, Dottie laughed. Upstairs, things were much busier. Dottie greeted half-a-dozen colleagues, but after scolding him for talking to Rajiv, she was much too sheepish to chat with them about her own work. She settled in next to a console. "I guess I shouldn't show this silly little thing to 'the Van,' but I've been working on this cluster simulation for four years." "Honey, I always love your demos. Just run it." "These GRAPE-6's were designed for n-body problems by a Japanese physics department. GRAPE, that means 'Gravity Pipe.' " "Boot it up, sweetie, come on." "We're directly integrating equations of motion into model globular cluster dynamics," Dottie said smoothly. "We've had n-body codes since the sixties, but we broke loose by an order of magnitude up here. These GRAPE cards do a hundred teraflops. I've got the rest of the system modeling stellar evolution and mass transfer. Oh, and collision models. If we get a cluster core collapse, then the collision model really gets hairy." Van silently watched a black-and-white LOADING bar crawl across Dottie's screen. "We're down to five or six simplifying assumptions now," Dottie said, "and we're spanning fourteen orders of magnitude, from the diameter of a neutron star to the size of the cluster itself . . . Okay, wait, here we go now." Van stared at Dottie's screen, stunned. Of course he had seen Dottie's cluster simulations before. He could remember them from grad school, as crude little X's and O's crawling sluggishly around on a plain green screen. The thing he was looking at now was busier than a swarm of bees. There were stars inside Dottie's box, millions of stars. It looked for all the world like a Hubble photo, but alive. The stars were wildly churning in balletic interactions. Plunging. Knocking into each other. Doing orbital tangos. Looping, kissing, hovering. The round cluster of stars was seething. It was boiling away like hornets at war. It took computers to prove that a jeweled globe of stars was unstable. In any telescope, a globular cluster looked as solid as a baseball, but it was a temporary enterprise. Stars tumbled into the core. They suffered unbearable close encounters there. They got slung like shot out of their family. They flew into the awesome darkness and solitude of intergalactic space. The sight of it set the hair up all over Van's head. What if you were _living_ around a star like that, thought Van, just living on some nice, sweet little planet. What if your daylight sky was boiling with neighboring suns as big as beachballs. And then, oh, my God, what if you flew too low and too close to one. In just a few dozen human lifetimes, the constellations would warp like putty. The heavens would turn against you and your world, and would blow you away at half the speed of light. You and yours, your innocent civilization, expelled into some unbearable icy exile, never to be retrieved. "We call this process 'evaporation,' " Dottie said. "Sooner or later, all the stars have to leave the cluster family. Let me run you this other model, the one with the galactic tidal action." This time the unhappy cluster was taken in hand by forces beyond its ken. What could a little cluster do in the horrendous grip of a superpower galaxy? Clusters were mere golden bubbles. Galaxies were vast flat saucers, cold, spinning, implacable. The uneven force of their gravity bent and tore at the bubbles. There was a mighty tide. Van could see it. The attraction of the galaxy was too much for the globular cluster. The stars peeled loose, they struggled toward exile, clinging fitfully to one another. They were ripped out of the cluster in long trains of refugees. Some fell into the galaxy, alien migrants falling down from high off the plane, strangers from an angelic height, doomed to meet some alien fate. The broken cluster, wrecked into mere rags of gas and dust, hung there, half obliterated . . . "We're talking twenty orders of temporal magnitude here," Dottie told him. "Two neutron stars have a close passage in milliseconds. But the death of a globular cluster . . ." "They die?" Van said. "Of course they die, honey. All stars die. So do all clusters. But here"—she waved at the screen—"my clusters don't die quite properly. The universe is only thirteen billion years old, so I don't have any good observed case studies for a cluster's late-period dynamical interaction. I'm pushing at the limit of this instrument. I'm going thirty billion years into the future." "Oh." "I mean, those numerical errors do accumulate, when I do that." "Oh, yeah." "I really have to fight with that problem," Dottie said. "Thirty billion years, it'll take me quite a while to push that. A long time, maybe. Maybe the rest of my life." Van patted her shoulder. "Baby, honey, you're doing just great!" After a fabulous Szechuan dinner, they took Ted with them for the last night at their Pinecrest love nest. Van was no longer impressed by the place. There was something comical and squalid about this aging zillionaire's bachelor pad. The place was not childproofed. Ted had to live inside his stroller and pen. This was not any kind of home for the three of them, a place like this. Their lives had gone wrong. His wounded pride had stopped hurting now, but he'd made some kind of serious misstep. He could feel it in his bones. At two in the morning, Ted's whimpering woke him. Van got up and stalked across the floorboards. "We're gonna let your mom sleep this time," he told the baby. He changed Ted's diapers and stuffed him into his walker. Ted had a nifty walker that Van had shipped to him in a lonesome moment. It was made of cool cast-plastic, a toddler's bumper car. Ted was clearly thrilled to be up with his dad after midnight inside a brightly lit bathroom. Ted's mother always made Ted sleep, but here Ted was finally getting to do what Ted most ached to do in the wee hours of the morning. Ted wanted to hurl himself around the room with a clash of plastic wheels, gurgling with glee, little arms slapping like pinwheels, a string of eager drool hanging from his chin. Van would be back in Washington by nightfall. He would be forced to tell Jeb that his KH-13 misadventure had gone bust with the Space Force at Cheyenne Mountain. He'd wasted his time, wasted valuable resources . . . To make up for it, he'd have to work twice as hard on the Virginia summit, really dig deep into the rabbit hat . . . Van looked at himself in the mirror, leaning close to take it in without his glasses. He had been a damned fool. He tiptoed away as Ted cooed and burbled. He silently fetched his backpack from the foot of Dottie's bed. He returned to the bathroom with the jet-black SWAT knife. He couldn't fly back to Washington with this throat-cutting pigsticker. Airport security would go nuts over it. But he'd bought it. It was his. It was stupid to not find some kind of use for it. Van grabbed a thick mess of beard and had at it. The knife went through his bristles like they were cotton candy. Six minutes later Van was looking at his bare face while Ted happily sucked on and spat a loose fistful of his beard. The SWAT knife was beyond razor-sharp. It had taken his beard off like a laser. He had thin little paper-cut nicks here and there. No wonder Hickok swore by this knife. Hickok knew his stuff about SWAT weapons. The knife was a jewel. Van hadn't shaved his beard in years. His damp, sleek rubbery face had the pale, surprised look of a shaved head. Next morning Dottie stared at him in astonishment. "Oh, honey," she shrieked, "Oh, look at you! Oh, honey bear, you look so young!" This wasn't the response he'd expected. "Young"? His plan was to lose the goofy hacker beard and look more like a serious Washington professional. "Young"? What about his nose? His nose had grown three sizes overnight. Dottie was experimentally kissing parts of his face that had not been kissed in ages. Bare skin reacted in startled pleasure. "Oh, honey, you look so handsome this way. You look so clean. Look at Daddy, Teddie!" Worn out by his 3:00 A.M. adventures, Ted was fast asleep. "You like it?" Van said. "It's different . . . Of course I like it. I married you, didn't I? Change is good sometimes." "I don't know what they'll make of this, back at my work." "Honey . . ." Dottie paused. "If you only knew what your face looks like, when you talk about your work now." "What do you mean?" "Derek, those people are _torturing_ you. It just hurts me so much. I don't like these people in Washington. I don't like this administration, I don't like this stupid War on Terror . . . I can't even bear to read the newspapers now. They're not our kind of people." "Now what?" Van said. "What do you mean?" "Honey, you don't have to go back to them. You know? You don't have to go back to the war, honey. You can stay right here and live with me. Derek, you hate that kind of work. Security work is ugly, dirty work. Sweetheart, maybe I didn't say this before but . . . things are going _really well_ for me up here. In most campuses, the astronomy people are looking at those awful new budget problems. Nobody's ever seen it that bad . . . But up here, I have only one problem. I have no Derek Vandeveer." "Huh," said Van. "Wow." "We won't have those huge amounts of money anymore, like we did when you were VP. But that only got us in trouble anyway. Derek, you would do great up here. They'll let you use all the network hardware. You can do all those cool, fun computer-science things you really wanted to do. Like, you can finish your paper on Ramsey theorems. No boss and no schedules, honey. You would be so _happy._ " "Do I look so sad to you now?" "Honey, it is written all over your face! I can _see_ your face now. I haven't seen you without a beard in, what, four years? You cut it for my mother's funeral." "Oh, yeah," said Van. "That's right." Dottie wiped at her eyes. "People don't have to _choose_ to have bad lives that we hate. You're such a wonderful person, Derek. You're a good, clean, strong person who means well and has a huge gift . . . There's nobody in that government who is a decent person like you are . . ." She was sobbing. "I want you to come and live with me, Derek. I'm so sick and tired of living alone." Van sat on the bed. His soul was flapping like a blown sail. "Oh, Dottie." "I have a right to you. I'm your wife. Why should we neglect each other? I want you to come live with me. We could have another baby. They didn't draft you. You're not in any uniform. Why don't you just do it?" "I have a title," Van said. "I get paid. They trust me." "You hate that work. It's changing you. You should see what you look like when you're trying to talk about it. Your eyes get so hard and cold. Your face gets sour . . . You look like a big dog guarding the world's last bone." Van did not take this as an insult. He recognized the truth in what Dottie was telling him. He had the kind of face that cops often had. Cops were people who were never just freely happy to see you. Even if they were nice guys, and many cops were, they always, always had to give you that guardian look first, to size you up to see if you were dangerous, or armed, or insane. He'd seen that guard-dog look on the faces of a hundred people in the Vault, and now, yes, he had it, too. He had it because he deserved it. He had earned that face. He had it because he was one of them. "Honey," he said, "there's a lot to what you say. I know that. But I can't just leave. There's a real big deal coming up in Virginia . . . Jeb says . . . well, Jeb says a lot of things . . . but if that all goes well, then it will all be worth it." "What about us? I want you to live here." "It was just a staff job," Van told her. He was really talking to himself. "I never told Jeb I'd make it my career. Even Jeb's post isn't full-time. We were just supposed to . . . paper over the cracks until we can establish solid policy guidance and add permanent structure at a federal level, hopefully cabinet level." "Derek, I never heard you talk like that before. Not when we were happy." "Well, that's how they have to talk." Van groaned. "Honey, I know that I'm overdoing it. I need you to tell me when I go off the rails. When you're not there for me, yeah, the inside of my head gets pretty strange." The suite's phone rang discreetly. Van's limo had arrived. Van dug hastily inside his survival backpack. "I'll miss my plane in Denver if I don't leave right now. But here. I need you to hold on to some things for me. Take this hunting knife. Oh, and take this ray gun." Dottie gripped the ray gun's cord. "You really carried this thing around with you, Derek?" "All over. I need it to solder," Van told her. "It makes a great office paperweight, too. But they're so dumb on planes now that they won't even let me take a thing that _looks_ like a gun. And that bad gig I just did with the Space Force . . . well, I can't tell you about that. But I wasn't happy with that. That really backfired, it was so bad . . . It took me weeks to work on that, and I pulled in help from everyone I knew, but, yeah, you're right, Dottie. I can't fight with you about that. It would have been a hell of a lot better for everybody, everybody in the whole world, if I had just stayed here with you. Maybe watching some sci-fi on TV. Eating that venison sausage. With that cantaloupe. That stuff was great." "They don't have any TV here." "That would have been even better. Some Bollywood movies with the venison sausage, yeah, I want that. I do." She threw her slender arms around him. "We had a great time, didn't we?" "Aw, Dots, it was such a honeymoon. It was just so great. I just wanted more and more. Someday, someday real soon now." "I'll come see you in Virginia." "You send me some e-mail." Van made the mistake of reading his e-mail in the Denver airport. He'd granted himself just three days out of the loop, one brief human chance to eat, and sleep, and maybe kiss his life's companion. Three days, and the CCIAB's office came right apart. It was like reaching out in a blackout to touch a spitting high-power wire. Jeb had forwarded a first-class flame from some Pentagon rat inside the Joint Chiefs. General Wessler hadn't signed off on this bureaucratic nasty-gram himself. Wessler wasn't the kind of guy to be that dumb. Van knew that it had Wessler's fingerprints, though. Stingingly, the complaint didn't even mention Van by name. It was all about "two self-appointed technicians from the so-called Transformational Communications Architecture Office." Van found himself described as "some know-it-all Beltway buffoon" and "that Ivy League professor in his beard and beret." A _beret,_ for God's sake? Most of the rest of Van's e-mail centered on the CCIAB's Virginia event. This was quickly taking on the proportions of a major crisis. The CCIAB was quickly running out of time and leeway. The CCIAB might be one place where the buck stopped, but they were too small and too temporary to function in the long term. Even the National Security Council was not big enough to run the giant federal government. The NSC just talked to the people, who talked to the people, who ran the federal government. Very soon, fatally soon, the CCIAB would be facing the fate of a million other small blue-ribbon boards and small federal advisory committees. Deliver, and die. Jeb had bet the farm on this battle in Virginia. It was going to be the CCIAB's Bull Run and Gettysburg all at once. Strapped like a bondage victim in his narrow tourist-class seat at thirty thousand feet, Van was grim. He never asked Tony Carew for favors, but now his situation was hitting the fan. In pulling Tony, he was going to be pulling his last trump. Tony's ever-eager answering service, a voice-mail jail full of sexy robots, told him that Tony was in Taipei. Van tugged at the aircraft's phone wire and persisted. When Van finally managed to appear at Tony's ear, Tony was very tolerant about it. Jet lag never bothered Tony. Tony was even elated. The reason for this soon came up. The Indian girlfriend had just fled from Tony's hotel suite. Tony was insanely thrilled by her visit. Somehow, against all odds, Tony had stolen her from her watchful family in Bombay for one secret, rapturous night, with just the two of them, and none of her relations, servants, managers, or groomers. Tony couldn't have been prouder if he had magically raised the _Titanic._ Tony granted Van his favor without a second thought. Then he went right back to chew and jaw on his obsession. It sure mattered a whole lot to Tony that this girlfriend of his was supposedly "the world's most beautiful woman." Van scowled. After hearing from Dottie about it, Van had changed his mind about Tony's infatuation. Dottie was right, she was always the voice of good sense. This was not a healthy relationship for Tony, this goofy long-range romance with the constant travel. Tony needed to settle down with a woman that he could depend on. Why was Tony missing the obvious truth about her? His girlfriend was a movie star from a foreign country. It wasn't her business to really care about Tony Carew. If he ever went broke, if he ever got sick, that little fortune hunter would be gone from his life like a shot. Tony ranted on, tirelessly. Van finally excused himself and hung up. He waited ninety seconds, slid a different credit card through the phone, and called Michael Hickok's cell phone. "I'm up in a plane," he told Hickok. Hickok dropped his cell phone with a clatter. Van heard drunken giggling in the background. Hickok scrabbled the phone up. "Gimme a break. I'm with a lady friend and I'm not even wearing pants." Over the roar of the plane's engines, the giggles sounded a lot like Fawn Glickleister. At least, Van hoped it was Fawn. It was pretty horrible to think that two women in the world would both giggle like that, and that Michael Hickok would sleep with both of them. "Mike, you're a pilot, right?" "I've got a pilot's license," Hickok said, yawning. "That don't make me Top Gun." "Okay, you remember that AFOXAR device we were working on? The hijacker interface that overrides and controls private jets?" "I thought you blew that off, Van. You and your big fat boss can't afford to rent any big fat private jet for your big fat shindig in Virginia." "I just found a friend who will loan me his big fat jet." "Oh," Hickok concluded. "So that would be different." "Now I need some guy who can fly a Boeing Business Jet, from the ground, with that little joystick." Hickok chuckled richly. "Hey, you just found your man!" "Can you pick me up at Dulles tonight? I've got to stop by my apartment on the way to the Vault." "What, you mean right now? I've gotta drive some more? I just got here! I broke speed laws in fifteen states!" "I get in at nine," Van said. "If you're still busy, bring Fawn with you." Hickok slapped his cell phone shut with a flat plastic clack. Van's flight arrived late due to weather. Hickok was waiting, and he stared right past him. Van tapped Hickok's shoulder. "Whoa! Van! Where's the beard?" Van shrugged. Hickok squinted. "You gotta do something serious about that long-ass hair now, Professor. You look like the jumbo version of the Little Dutch Boy." Hickok hated leaving his Humvee parked outside Van's Washington apartment. The Humvee was a military super-jeep, but Hickok, with a Southern-boy pride in his wheels, hated the thought of its paint job ever coming to harm. "I can't believe you live around here," Hickok groused. "There's hookers around here. There's crack gangs!" "I'm a security expert," said Van. He avoided a splatter of vomit on his stairs. "Like what, so that makes my car safer?" Van pulled his keys. But the door of his apartment opened at a touch. "Oh, Lord," he blurted. The lamp was lit. Van looked around. Nothing obvious was missing. There wasn't much in the apartment to lose. The keyboard of his Linux machine had been pried open. "They're still in here!" Hickok said tautly. The door of Van's bathroom swung out. A stranger stepped out with a gun. Van was astounded. When leveled at his own chest, the black barrel of a pistol looked as cavernous as a garage. Van had no idea who this intruder was, but he instantly recognized the handgun as a seven-shot, all-electronic, Australian-made O'Dwyer VLE. A really nice gun. A great gun. A real beauty. How could he get killed by some device that he had once taken apart with his own hands? "Yo, Fred!" said Hickok, his deep voice squeaking just a little. "Long time no see!" "Reach for the sky," Fred ordered. Hickok only laughed. "I'm not packing any heat. You're packing heat in here, Fred?" "I'm on assignment," Fred said defensively. "You have any idea who you're aiming to shoot here? This guy is from the National Security Council! Dr. Derek Vandeveer, this would be Mr. Federico Gonzales. Old war buddy of mine." Gonzales scowled. "Why the hell did you have to tell this chump my name?" "We're supposed to be all on one side in the War on Terror, aren't we? You let me know if you changed sides, Fred." "Nope," said Fred. He kept the pistol steady, though, and he spoke from the side of his mustached lip. "You might as well come out now, kid." A second burglar emerged from Van's bathroom. He was tall, stooped, and thin as whipcord. He wore black-rimmed glasses, and had a military haircut. The "jarhead" look. Brown fringe on top, white sidewalls all around. The second burglar carried a black plastic impact-resistant toolbox in one big hand. "Hey, you guys are AFOCI," Van realized, recognizing the hardware. "No, sir, I'm William C. Wimberley." "But that's an AFOCI toolbox," Van insisted. "I helped to vet that thing." "Air Force Office of Cyber Investigation," Hickok clarified. "The AFOCI boys are in and out of the professor's office all the time." "We're not AFOCI," said Gonzales. "I heard of 'em, though." "We're Cyberspace Force," said Wimberley. "Okay, maybe he's in Cyberspace," said Gonzales hastily. "That doesn't mean I have to be in any damn Cyberspace." "You just installed an AFOCI keyboard bug inside my Linux box," said Van, staring at Wimberley. "Okay, yeah, fine," Wimberley told him. "Maybe I did that. Why should you care? You would never have known about that." "Who the hell do you think you're talking to? Of course I would have known!" "Nobody ever looks inside their keyboards," said Wimberley with a sneer. He was very young. "Not even you, Professor. I know who I'm talking to here, okay? If I hadn't pled out, you would have testified at my trial!" Van stared at him. Wimberley looked vaguely familiar, but only vaguely. "So what was your handle?" "Bionic Ninja of 214." An anklebiter. "What, you were like fifteen back then?" "Sixteen," Wimberley said. "The Secret Service broke into my parents' house. My mom never got over that. She still takes Prozac. All just because I borrowed a little long distance from your sad-ass phone company that just lost forty-five billion dollars!" Van took a sorrowful breath. "The Air Force didn't mind your rap sheet?" "The modern United States military loves troubled, aggressive young men with high IQs," Wimberley told him. He had a settled voice and a lethal stare. With an effort, Van stopped his knees from shaking. The hell of it was that Wimberley's bug would have worked. Of course Van would never have looked inside his own keyboard, and the tiny device would have been silently beaming every keystroke he made to some monitoring station blocks away. "Look, I'm NSC, and I know something about your so-called outfit. The U.S. Space Force can't just start up a 'Cyberspace Force' on its own get-go. They've got no policy guidance from the top." Gonzales weighed in suddenly. "The Space Force are the only service branch that can run mil-spec cyber-security," he recited. "No other military outfit has the extensive computer networks or the time-tested technical skills." "Are you nuts?" said Van. "The Space Force is supposed to run satellites! That's got nothing to do with viruses or DOS attacks! The guys tasked with defending military systems are the Computer Network Defense Joint Task Force over at DISA." "Who's Deeza?" said Wimberley. "I never heard of 'em." "They've been at the job since 1998!" Hickok was even more skeptical. "Look here, kid, there ain't no such thing as 'cyberspace'!" "There is if we say there is," insisted Wimberley. "But why did you come here to my place?" Van said. He was genuinely baffled. "I hate to break the news to you, Professor, but information warfare happens inside people's computers! And you, you're trying to sabotage a mission-critical eighteen-billion-dollar satellite project! You don't think important people are gonna notice about that? We know what you're up to." Alarmed, Van turned to Hickok. Hickok just shrugged. "'Important people,' he says." "You're a left-wing professor from Stanford," Wimberley amplified. "You're a peacenik." "'Left-wing'?" said Van, stunned. "'Peacenik'? I just had lunch with Paul Wolfowitz!" "Your wife is in the antiwar movement," said Wimberley. "She was Eastern Seaboard Coordinator for Physicists for Social Responsibility!" "Dottie is from _Massachusetts_!" Van said, outraged. "They're all like that up there!" Wimberley stared back at him. "Don't you ever Google yourself? It's written all over you. Look at that hair and those clothes." "And that's supposed to give you some kind of right to Watergate my apartment?" Van blurted. "Oh, yeah," said Wimberley. "It generally does." "Nobody ever catches us," said Gonzales, shifting his shining handgun and looking at his wristwatch. "You're supposed to be way off in another state. We're supposed to be long gone from here by now." "Yeah," said Wimberley, hefting his case. "We kinda need to be going right now." "Hold on," said Van. "I just happen to be the Deputy Technical Director of the CCIAB." "So what?" said Wimberley. "I never heard of them either." "So I built you that burglar case, you sorry little punk! There's no way you're just walking out of here when you just broke into my own house and tapped my own computer with my own hardware!" Wimberley set the heavy plastic case by his feet and folded his long, wiry arms. "What are you gonna do about it, Dr. Superspy? Call the cops on me?" "I've got a gun right here," Gonzales bargained hopefully. Hickok chuckled. "Aw, come on, Fred." "If you want these cyberweapons," said Wimberley, putting his boot on the case, "then you're gonna have to _take them away from me._ " Blood rushed hotly to Van's face. "You don't think I could do that?" Wimberley laughed in scorn. "Let me put you in touch with reality! I'm not some make-believe warfighter, like you are. I enlisted, dude. I am tomorrow's cyber-military. You're just some flabby-ass civilian professor from some failed telecom company. Plus, you're ten years older than me. So if you attempt to confiscate my weapons here, I will kick your fat ass right up between your shoulders." "You are out of your mind," Van told him. "You're some nutcase punk who called himself 'Bionic Ninja.' I outweigh you by fifty pounds. Plus, this is _my house_!" Wimberley turned to Gonzales. "The hippie here is hallucinating. I think maybe you'd better just shoot these guys." Gonzales snorted. He thumb-jacked the magazine out of his pistol and threw it to Hickok. Hickok, ever-alert, snatched the bullet clip right out of midair. Gonzales sat down cozily in Van's magnesium chair. "Do I look that stupid?" he announced. "One bullet, two bullets, that's not even gonna slow this dude here down. Because, boys, this dude here is Air Force Special Operations, just like me. Mike Hickok and me, we are always 'The First Ones There'!" Hickok burst into laughter. He sat on Van's stained and ragged couch, with a loud thrum of broken springs. "Aw, come on, Fred, this is D.C., man. This is some guy's apartment!" Gonzales put both his elbows on his knees. "The way I see it, these candy-ass computer geeks have got a score to settle." "You're right," Van said. The words startled him as they hit his own ears, but then he realized that he meant them. Rage rumbled through his chest like a rolling cannonball. He was in deadly earnest. Hickok coughed into his fist. "Van, sit down. Let 'em both go. It's all some big mistake." "Your friend Fred here can go if he wants," Van said. "I didn't build him that O'Dwyer pistol. That intrusion case though. That tool case is mine." Wimberley took off his black-rimmed glasses and set them on a table at the foot of Van's lamp. "I can see that I've got to kick this guy's ass now," he announced. He put one fist inside another and loudly cracked his knuckles. "This won't take long." He looked at Hickok and Gonzales. "I just don't want to see you two snake-eater boys start crying about this, or anything." "Are we gonna cry, Mike?" Gonzales asked Hickok. "You ever see me cry, Fred? We were in Bosnia damn Herzegovina." Hickok's face was alight with a greed for battle. "My cybergeek is gonna wipe the floor with your cybergeek." "No way, homey." "Yes way. Because he is smarter, man. My computer geek is like ten times smarter than your geek." Gonzales barked with laughter. "What the hell difference does his brain make?" Van took his glasses off and set them aside. He tried to stare into Wimberley's eyes. Without his glasses, the enemy's eyes were two distant brown blurs. Wimberley's first swing was a contemptuous slap. The slap was a spiritual experience. In one Zen instant, it found the black fury that lived within Van and brought it to roaring life. Van lunged forward. The flying impact of his body knocked Wimberley straight backward and into the magnesium chair. Gonzales leapt free of it, hunched and dodging, and the beautiful chair went legs-up and buckled, with an expensive crunch. Van was suddenly gasping for air. Something had plunged deep into his gut. It was Wimberley's boot. The kid scrambled nimbly back to his feet. Quick, hot impacts. One in the eye. One in the forehead. Van got a clawing hand into his enemy's collar and slung him headlong into the room's single lamp. The lamp tumbled and the room went dark. Van clenched his fists and swung at empty air. Suddenly the enemy was on his back, leaping on him from behind. Van stumbled backward, smashing his assailant against the wall. Wimberley wheezed. Van tore a choking elbow loose from his throat. Wimberley's shoes scraped the wall, and with a powerful kick, he heaved them both away. Van stumbled and tottered off balance, groping wildly. He plummeted. He crashed suddenly, blindingly, smashingly, into the sharp, rigid corner of his computer table. He felt his whole skull cave in. His mouth flooded instantly with blood. With a bestial roar he lurched upright. Wimberley stumbled, scrambling in darkness. Van kicked his legs from under him, clamped a hand on Wimberley's scrawny neck, and smashed his head against the floor. The whole building shook. Wimberley emitted a desperate, catlike squall. Van sank a knee into his enemy's guts and hammered his skull with a fist. Wimberley went limp. There was a sullen sound of liquid dripping. The overhead light came on. Wimberley's unconscious face was spattered in blood. "Get up, Van, Jesus, he's out cold." "He's bleeding," Van mumbled. A piece of his tooth fell out. "No, man, _you_ are bleeding. You are bleeding all over him. Jesus, what happened to your face?" Van put his hand up. He could not feel the shape of his mouth. His cheek. It was all gone. There was nothing there but a nightmare patch of bloody mush. Things were lively at the local emergency room. A man who had merely had his face smashed in had to sit down and take a number. Van held his iced towel against the ruins of his face. He could not touch the damage there without mind-bending pain and a sense of deep, cosmic, nightmare terror. He hadn't merely lost some of his teeth. He had fractured, really smashed, the inner structure of his skull. The gaping wound wasn't about to stop bleeding. The staffers were calling around for a specialist surgeon. The young woman sitting next to Van had red, staring eyes and dirty blond dreadlocks soaked in drying blood. Gore had soaked the shoulders of her white Guatemalan blouse. Blood had spattered her broomstick skirt. "Hey, friend," she said to him. "What's your affinity group?" Van moaned, his tongue thick with blood. The girl opened a woven yarn-bag covered with leftist political buttons. She dug in her bag and retrieved a small digital videocam. "So, you were outside the World Bank with us, right? Did they come after you with those horses?" Van said nothing. "That's when I caught it, from the horses. I sure hope somebody puts all that up on Indymedia. Did anybody tape you? I mean, when the pigs hit you?" Van shook his head minimally. The bleeding girl looked around the chaos in the emergency room. It looked like a campground for derelicts. "I wonder where they put the rest of us. We can't be the only ones." A wave of blackness coursed through the rupture in Van's head. He blinked in silent agony. "Your eyes look nice," she told him. "You didn't get peppergassed." Van nodded behind his blood-soaked towel. "I'm gonna have to get stitches," said the bleeding girl. "They're gonna shave off my hair. But, friend, I don't feel scared anymore. I just don't feel scared of those warmongers. Because the power is in the streets now, man. I can feel the power." She squeezed Van's loose hand, warmly. "Our streets, okay, brother? Our streets! They can bust my head, they can bust your head, but they can't bust everybody's head. Pretty soon America will wake from this nightmare. The corporate media lies, man! They all _lie_!" Van shifted his towel. Some ghastly crust parted stickily into the fabric. The icy numbness came alive with a flare of deep, burning pain. "You know why I feel so happy now?" said the injured girl. "Because there weren't any _chemtrails_ today. I checked again and again. I looked up at the sky and it was clean! No more chemicals up there! So they're just plain running out of whatever that bad stuff is, that's what I think. That poison that keeps the people so passive." Van's eyes blurred over. He was suffering double vision. Double vision had never happened to him before. Now he understood why people talked about it so much. "After 9/11 there weren't any jet trails up there for _three whole days,_ " the girl insisted shrilly. "Not one jet trail across all of America! What does _that_ tell you, huh? Wow, just _think_ about what that means!" A nurse slid her face in Van's field of view. "You're Dr. Vandeveer? Yes?" She slid a blood-pressure cuff over his arm. "We've got to move you now. I think we've found you that ambulance." CHAPTER ELEVEN WASHINGTON, D.C., FEBRUARY 2002 **V** an was in a hospital bed, confronting his e-mail. His damaged face was hot and stretched. The flesh felt rubbery. An inflated tire, a Macy's blimp. There was a very thin strip of surgical steel, securing the ruins of his left canine and bicuspid. His aching tongue could not stay away from that wire. It was like a steel I-beam installed in his head. Dottie had written him such a brave letter. Dottie was apologizing to him for daring to be so lonely and unhappy. She was promising to do better. She said that she was proud of him. As sedatives coursed through his flesh, Van read his wife's electronic sentences over and over. For the first time in his life, he could literally hear Dottie's spoken voice behind her blurry pixels. Van thumbed his way back to the top of the screen again. Some indescribable comfort was seeping into him. In real life, Dottie would not have repeated the same consoling words to him, over and over again, one hundred slow, blurry times. A man in a hospital needed that. Of course, he hadn't yet typed one word to Dottie about getting his face smashed in. What was he going to tell her? What if somebody else told her about it first? He had just gone through a violent, crazy, amazingly painful ordeal, all for the sake of some wild notion . . . so useless, something utterly stupid . . . Van turned his aching face toward the black plastic case of spy tools. Van's burgled apartment was not a safe place to leave a top-secret infowar tool case. So, despite the surprised protests of doctors and nurses, the hardware was still with Van. The case was locked to Van's iron hospital bed frame with a laptop security cable. Come and take it, if you dare. Van had beaten the living daylights out of another American in order to control the tools. Van sank his swollen head into the small, sterile pillow. His face had been smashed in by a computer security policy war. Why not some kind of real shooting war, for heaven's sake? He wouldn't feel half so bad if he'd been mangled while fighting with al Qaeda. Van slid his tongue along the luscious edge of that steel wire inside his head. He was never in his life ever going to fight al Qaeda. Van knew that perfectly well now. Cyber-security was all about computer policy. Infowar was a form of war for high-tech people sitting quietly at desks. Bin Laden didn't surf the net. Al Qaeda were Third World fanatics on low-tech bicycles who talked only to their mullahs and their cousins. Al Qaeda guys got recruited in madrassas and sent to live in Pakistani slums and Afghan villages. They were bitter, freaked-out, culture-shocked men. They existed in such a frenzy of rage and wounded pride that suicide was a blessed relief to them. Being a martyr was so much, much better than being al Qaeda that they leapt at a chance to explode themselves in the midst of much happier people. "We long for death more than you long for life." That was their bumper sticker. Terrorists didn't fight wars. The whole point of terrorism was to kick a government so hard, in so tender and precious a spot, that the government went nuts from rage and fear. Then the machinery of civilization would pour smoke from the exhaust. It would break down. Back to the tribes and the sermons, the blessed darkness of a world without questions. Van looked at the chained black case. So it did matter. Cyberwar had always been about Americans and what Americans chose to do with their tools. Van knew that it mattered, because all he had to do was imagine himself losing the fight. Suppose that Wimberley broke into the hospital room and tried to take the case again. Would Van lie back with a ruined smile this time, let the hardware go? No. Not at all. Van would yank the intravenous feed from his arm, jump up, and fight all over again. After all, he had won. Maybe no one knew how, why, or what the real reasons were, but so what? The world was full of humiliating, secret battles. Van had won in front of witnesses who were used to secret fights. No substitute for victory. He was woozy and scarred in a Washington hospital, but somewhere, a rogue operative had been dragged back to some lair with the crap beaten out of him by a computer-science professor. Message sent. Let's roll. Van rubbed one-handed at his crusty eyes. He slid sideways into a twilight sleep. When he woke the anesthetics had faded. His broken skull smoldered like a fire in a coal mine. Every scrap of flesh, once cold and rubbery, was burning briskly. Dr. Mukherjee was the young surgeon on the night shift who had rebuilt Van's face. Mukherjee had luminous eyes, slender wrists, and a sweet smile full of unfeigned doctorly kindness. Mukherjee set his transparent clipboard aside. He probed the interior of Van's mouth with his white-gloved fingers. "There is no sign of infection," he reported, staring intently and feeling his way over the aching pulp. "The facial bones will knit quickly in a man who is so fit." The latex-coated fingers left Van's mouth. Mukherjee gave Van's solid left bicep a reassuring pat. "You are military, eh? A training accident." Van grunted. His pulpy gums were blazing with pain. Dr. Mukherjee nodded knowingly. "Demerol." Mukherjee made a note on his clipboard with the gleaming steel of a Rotring ballpoint. "Your blood pressure is too high for a young man. You should go fishing, eh? Take leave for a while. Relax." Van moved his shoulders to suggest a shrug. He was sore from kicks and punches in his back and gut. The spreading bruises from those wallops were nothing compared to his broken head, though. "We will discharge you tonight. The breaks were clean and the ducts were not severed. New bone will grow through the bone cement. In a month, the steel comes out. That's a walk-in procedure." Van realized that he was being told amazingly good news. Face smashed in, yet he was out of the hospital in one day. Should he feel grateful? "You will need tomography," said Dr. Mukherjee. "The roots of the teeth, there I cannot tell you. I'm a maxillofacial surgeon. I'm not an orthodontist." "Mmmph." "You need to see an orthodontist, Mr. Vandeveer. In your later life, you might spend much time with orthodontists." Dr. Mukherjee delicately turned a sheet of hospital paper. "If you were not American . . . or if you lived thirty years ago, which is to say the same thing . . . then you would have been badly disfigured last night. Yes, marked for life. Very unfortunate. But not today. No. Today you will be fully restored to quite normal appearance. They do wonderful things with teeth now. Although the lip, the lip concerns me." Van's split and stitched upper lip no longer felt like part of him. It belonged to some distant, remote, legendary being. The Michelin Man, maybe. "You will lisp," said Dr. Mukherjee. "For a while. You might lisp _quite_ a while." Van nodded silently. "There will be scarring. Cosmetic surgery is a possibility. Or you might grow a beard, sir. A beard would look good on you, I think." Fawn brought him flowers. "Nobody knows about what happened," she assured him. "I mean, okay, Mike Hickok knows. So I know. And those two tough guys in your apartment, they must have got a real shock. Because you beat his ass up!" Fawn's eyes shone with sincere secretarial pride. "That was just so awesome. Wow! I told everybody that you fell down the stairs. Was that okay?" Van typed and showed Fawn the screen of his laptop. THAT SHOULD WORK "You look better than I expected. That must really hurt a lot, though." Van spread his hands. The pain of healing was different from the shocking, heart-thudding pain of being wounded. Pain made him simpleminded and sentimental. It made him wildly, totally impatient. "I brought you a good book to read. I know it can get pretty boring in a hospital." Fawn offered Van a paperback. Van took it. An embedded needle twinged in his left forearm. Fawn's book was an obscure, Czech-printed, English-language paperback edition of some plays and essays of Vaclav Havel. To judge by the smashed spine and dog-eared pages, it had spent hard time in the bottom of a student's backpack. Somehow this ludicrously crushed and smashed book gave Van a warm, grateful feeling. This artifact was so much worse off than he was. Fawn blinked behind her glasses. "I spent a lot of time in hospitals when I was like sixteen, seventeen. I mean, a _lot_ of time. That used to drive my dad nuts. Even my mom freaked out, and she was, like, used to our health problems." Van put Fawn's book on the steel roller-tray next to his bowl of mush. "When I got better, I made my parents send me to Prague. Because I heard that Prague was like the coolest place to get away from your crazy parents. Well, Prague was cool, but I was never a cool person. I did make this one cool friend there though. My friend Eva. She's Czech. Eva knew my dad, so Eva was nice to me." Van typed at his screen. "That book's real rare here in America. All Czech stuff is small-press stuff. It's a small country." WHAT'S IT ABOUT Fawn ignored him. "See, here back in the USA, they always talk about Vaclav Havel like he was some kind of saint. Well, he was. He is. But my pal Eva, she's, like, personally related to Vaclav Havel. Eva had to have this saint guy as her President." Van raised his brows, or tried to. The right brow moved. The left one was still numbed from his surgery. "Eva told me, yeah, Vaclav Havel is like this saint, but a saint can't run a government. I mean, very first thing, the country splits in half. Havel is a terrible administrator. His health was bad, all the time. And his first wife, the First Lady everybody really liked, she died of cancer. He married the second wife and nobody could stand her, because she's, like, this hippie actress." Van looked at her silently. Why was Fawn torturing him like this? What on earth was the woman's point? "We've never had a really good talk like this before, you and me!" Fawn said. She removed a pair of latex gloves from her purse and found herself a tissue. "I feel like we're really communicating now!" With a struggle, Van found his tongue. His tongue had not been directly hurt in any way that he understood, but his tongue was really sore anyway. "Thanks," he lisped. "It was good of you to come, Fawn." Fawn's eyes briefly leaked tears. "I don't want you to worry about anything, boss. I'm taking care of all of it for you." "Mmm-hmmm." "I'm gonna get you your money back that you spent on Grendel. Jeb said that should be my number-one priority. And wow, the way you screwed up that requisition process, getting that money back is like a full-time job." Van sniffed. His sinuses were a wreck. "Jeb really admires you. I mean, for a cop, Jeb really knows a lot about computers. Jeb doesn't mind that computer geeks are kind of hopeless idealists. Jeb knows you were really the best." I _am_ the best, Van thought. Was it worth the pain to mention this out loud? No. No use in saying that at all. "I learned so much working with you," Fawn told him gratefully. "Like, it was so cool of you not to say anything to anybody about my stupid little love affair at the office. I had to grow out of that little problem on my own. I always heard that was unprofessional, but you know, until I really did it, with a really stupid guy like Mike Hickok, I didn't know why it was stupid." Van's heart began thudding. "Anyway, now I'm fully briefed about that. So I've just folded that up and put that little subject away." Fawn wasn't kidding. "Van, I just got two great job offers from DARPA and Homeland Security. I can get an important, top-level staff job with a real federal bureau. They know I worked with you and Jeb, and they want me bad. You'd definitely pick DARPA if you were me, right? DARPA, they're Advanced Research Projects, and all." Van nodded. "That's why I'm picking Homeland Security. Security work is a good job for a single woman. Women are great about home and security issues. I kind of stink at advanced research, but home and security, that is all about attention to detail. That's where I shine." Van closed his eyes. He opened them. Unfortunately, Fawn was still sitting there. "I mean, like, when we started whistle-blowing at Enron—that was all us _women_ in the Enron office who were doing that, you know. We women at Enron were the only ones who were _paying attention to the details._ " Van stared at her. "Boy, those big cowboys in Houston sure thought they were hell on wheels. 'Fast Andy' Fastow, Ken Lay . . . They kept dividing the company into these _neat little teams,_ you know, just ten percent of the normal accountants . . . Really quick responses, and all these quiet, secret offshore projects that no one ever talked about . . . I'm so lucky that Jeb found me a federal job after all that. I mean, life after working for Enron . . . I don't even _tell_ people that I once worked for Enron. The weirdest part is, that was like a totally plum job, too. I mean, Enron recruited the top of the top of the class. The best of the best. I was Enron fresh out of college." Van sucked cold air through the gap in his broken teeth. "But thanks to you, I can make a brand-new career. In federal security, I can go just as far as my talent can take me. There's no glass ceiling there! I mean, Janet Reno was Attorney General!" Resignedly, Van adjusted Fawn's bedside bouquet. "Can I tell you one more thing, Van? You look so nice without that beard. You look so normal. I mean, that side of your face that isn't swollen. I like your hair that way, too. It's kind of like Sonny Bono before he became a congressman." Fawn offered him her nicest smile. Then she sneaked a look at her watch. Van showed her his computer screen. WHAT ABOUT THE HAVEL BOOK, THOUGH "You can keep that." Van typed faster. I MEAN< WHAT'S IT ABOUT< FAWN< WHY ME? "You read it, and see if you can find that out for yourself," she said. ERLETTE HOUSE, VIRGINIA, MARCH 2002 Erlette House was an eighteenth-century Virginia estate. It had once been a rival of Mount Vernon or Monticello. It had become a country retreat for the power elite in Washington. Once upon some mythical time, most senators and congressmen had been land-owning squires. They felt most at their ease in the simple, warm hospitality of some big rural farm. In Erlette House, this gentlemanly fiction was still kept up. The hay fields were still raked with teams of horses, even though Erlette House had helicopter pads, a landing strip, and a computer center. Erlette House was surrounded by modern Virginia suburbs, with strip malls and glass office towers. But Erlette House was still a real country estate, sort of. It had livestock, roses, and swans. Van, Dottie, and Ted had been assigned their own rooms in the Erlette House "Lake Cottage." This "cottage," actually a small mansion, featured stone hearths, Federal-style chairs of antique oak, primitive American art, and a four-poster bed with a lovely handmade quilt. The Lake Cottage brimmed over with old-school East Coast Establishment virtue. Every object in its rooms sat there in timeless restraint, polished by good taste, power, and heaps of old money. Except, of course, for Van's and Dottie's laptops, which were like two Martian tripods out of H. G. Wells. Dottie collapsed on the bed. The white feather mattress dented around her like a stick-toasted marshmallow. Dottie was very prone to airsickness. Her long flight to Erlette House on Tony's jouncing private jet had badly upset her stomach. She was pale and greenish. Van popped the lid from a cold curved bottle with an attachment of his Swiss Army cyberknife. "You want a Dramamine, sweetie?" "I'm trying to keep one down," Dottie said in a small, pinched voice. Van put Dottie's Perrier bottle on the bedside table. The bedside table was ancient, wobbly, and dented. The table was very old. It was some kind of eighteenth-century American furniture invention that had never quite caught on. It looked like it had been whittled into shape by Ben Franklin on a bad day. Van sat in a shield-back mahogany chair next to Ted's space-age plastic child-carrier. Dottie's spell of weakness gave Van the tenderest and most protective kind of husbandly feeling. She had been so glad to see him, practically tumbling into his arms off the plane. Although she knew some of the truth by now, Dottie hadn't said one word to him about his crowned teeth, his new beard, or the lisp. Actually, Dottie had said something to him about the lisp. She had said that it made him sound like Humphrey Bogart. Van freed Ted from his plastic seating device. He put Ted on his knee. Ted was cheerful. Ted did not mind air trips at all. Ted was in top condition, as if he'd been shipped from distant Colorado in Ted-shaped foam blocks. Ted looked thoughtfully at his stricken mom, as if logging her vulnerabilities for future exploitation. "You should just go now, Derek," Dottie said, words muffled into the pillow. "I'm sure you and your boss have a lot to talk about here." Van settled deeper into his chair. "I don't care," he said. Dottie turned restlessly. "What?" "I said I don't care, honey. This is my outfit's last big event, and I gave that job all I want to give to it. I don't want to see any of the panels here. I don't care about the speakers or the lobbyists. I don't want to schmooze . . ." Van winced. Van hated the word "schmooze," and with his scarred lip it sounded even nastier, somehow. ". . . schmooze with the presenters. I never liked to speak in public. I'm not gonna talk here. No. They got enough out of me. Enough is enough. It's all political now. We're putting on a big campaign show here. I hate this." "Oh, honey." "This dumb business with Tony's jet. I got hurt, and we ran out of time to do it right. It's not fully proofed and tested. That prototype would never work under real-life conditions, any more than Star Wars missile shields can work. It's vaporware. It's a hoax!" "Oh, honey, if you worked on it, I'm sure it's not a hoax." "Well, it's just symbolic. That's the best you can say about it. I'm a scientist! I'm a scientist, and I'm doing political spin." Van ran his hands over the lengthening bristles covering his cheeks. "Okay, maybe I have to do that. Maybe there's no choice. But that doesn't mean I've gotta do that _to you._ Never to _you._ I want to look after _you_ while we're here. That's what I want, okay? And you, too, Ted. It should be about you, and me, and Ted." Dottie scrunched herself into the pillow. "This seems like a really nice resort . . . But I feel so sick." "Drink that Perrier." Dottie sipped from the bottle obediently. After a moment, she burped. "Oh, God, that's just so awful." "You'll get better," Van said knowingly. "You just rest. Ted and I will go off to the Great House for a little bit. We'll bring you back, like, a nice slice of lime and the fruit plate." Dottie put the pillow over her face. Van left, carrying his son on his hip. They forged across an open field, past a pergola laden with vines, across a rolling hedge, and uphill to a pillared and porticoed historic mansion. It was a warm late March day, smelling of April. The weather was favoring them. Van put his laminated ID badge over his neck. He walked upstairs, past white pillars, carved doors, and a spiral staircase. He entered the ongoing conference. The event was formally titled "The Joint Strategic Summit for Critical Cyber-Security Practice," with a hyphen. It was amazing how much discussion there had been inside the CCIAB about that stupid hyphen. Ted was the only child-in-arms attending the Joint Strategic Summit. Ted immediately became the star of the show. Van was surprised by this. Van had planned to take a very low profile at the event, which was really Jeb's show all the way. But Ted, shiny-faced and gleeful, was upstaging all the pundits, movers, and shakers. Dignified men and women with graying hair and American flag lapel pins could not keep their hands off Ted. It was as if Van had created Ted as a high-tech animatronic toddler. Van had become used to government and industry people sucking up to him a little. He knew that it wasn't personal. It was his job title that got those firm handshakes, those invitations, and all that flattering mail. He was the Deputy Director for Technical Services of the Coordination of Critical Information Assurance Board. For a brief period, mostly while stuck inside a concrete vault in West Virginia, Van had been able to assess some of their stupidest ideas and technologies, and thank God, to quickly get rid of some of them. Van offered Ted a juicy chunk of cantaloupe off a giant cut-crystal fruit plate. Ted, who had a tiny but effective set of choppers now, went after it with gusto. Here was a familiar face. It was Pico Yang. The unusually named Pico Yang had been a Stanford colleague of Van's. He was one of the ten guys on the planet who understood Grendel's operating system. Pico had an Irish wife and four Chinese-Irish kids. Pico didn't seem much impressed by one Ted. Pico had plenty of Teds. "You gotta tell me about this aircraft guidance demo. That sounds like a miracle." Van leveled with him at once. "The flight OS is crap. The latency problems are nontrivial. The multipath effects killed us. It only works on line of sight. That kludge we stuck together doesn't even qualify as an alpha rollout." Pico beamed upon him. "That's great news, Van. For one terrible moment I thought I was forty years behind." "It's possible to build one that works. If you've got a spare fleet of satellites and sixty billion." "California state budget," Pico said. "The school is taking it in the neck. Neutron-bomb buildings all over Silicon Valley. Worst financial crisis since World War II. You left California at a great time, Van. You wouldn't recognize us if you came back now." "It's tough, Pico." "Lots of states. Not just us." "It's _real_ tough." "Plus the war. I couldn't believe it when you went into defense work, but, Van, you were way ahead of the curve. Good for you, man. Real smart move. Great job with the Grendel, too. The streams, Van. Wow. The way you handled streaming, that just knocked me out." Pico gulped heartily from a tapered glass of white wine. "That's a cute kid." There was nothing Van could do for Pico now. Maybe earlier—but not now. They had thrown Van out of the Vault because the CCIAB was on the point of expiring. Leaving the Vault was like getting paroled from federal prison. At the same time, though, for a Vault rat, that message was unmistakable. Go get lost, fella. Uncle Sam no longer needs you. You can go fry now. There was Tony Carew over there, smiling, charming, eagerly pressing the flesh. Tony was chatting with a circle of spellbound federal officials. Tony had crashed the big party on Van's ticket, but Tony looked completely at ease inside Erlette House. Tony looked like he attended Joint Strategic Summits for Critical Cyber-Security Practice every other Tuesday. Van turned away from Tony and Tony's eager new friends. No one would ever cling to him like that. Van pretended to study a large white foamboard announcing the Summit's panel topics. "The Department of Homeland Security: A Historic Creation." "National Milestones for Proactive Software Protection." "A Robust and Resilient Critical Infrastructure: The National Infrastructure Assurance Partnership." "Sharing Vulnerability Analysis Within a Competitive Environment: The Delicate Balance." Van was not going to any of these panels, although he personally knew the vast majority of the panelists. Van had already skipped the event's keynote. It had been delivered by the Secretary of Transportation. It wasn't that these were boring topics or boring people. They were a lot less boring than they had been made to sound. The stark truth was that these panels had nothing to tell Van that Van didn't already know. Now, finally, after months of ceaseless labor in the trenches, Van really understood what he had been up against all along. He understood all the crushing issues that had prevented decent, well-meaning people from ever getting anything useful done in national computer security. Problem number one: there was no such thing as a "national" computer. At all. That was a contradiction in terms, like talking about a black sun or a square triangle. You could put a flag decal on the side of a computer. You could hide it in a military base. You could pay for it with taxpayer money. But talking about "American" computation was like talking about "American" mathematics or "American" physics. It just didn't come with flags. National people were the wrong people to attempt that security job. A nation, any nation, was just too small. Any cable map could show you the enormous fiber-optic pipes that circled the planet. Tycom Transatlantic, Emergia, Americas-II, Africa ONE, Southern Cross, FLAG Europe-Asia. Pipes laid across the planet's sea bottom at fantastic expense and effort. Specifically built to reach distant, extremely un-American places. Places like Santiago, Capetown, Mumbai, Perth, Shanghai, and Kuwait City. Places chock-full of alien computers owned by very un-American people. The whole _point of the effort_ was to become less American. That was why it was called Internet instead of USA-Net. It was possible to build nets inside your own nation that only your nation could use. France had tried it: Minitel. Britain had tried it: Prestel. National networks died horribly. It was like trying to build a computer net that only talked to Milwaukee. It got worse. Even inside American national borders, you couldn't wrap computers in the red-white-and-blue. Eighty-five percent of the hardware was owned by private industry. _Multinational_ private industry. Multinational private industry that _had gone broke._ The computer and telecom industries were on their knees. They had lost legendary, incredible, colossal amounts of money. They had lost diamond-mine, mountain-of-gold heaps of money. They had tried to build a commercial for-profit Internet. There was nothing commercial about the Internet any more than there was anything national. That was why it was called Internet instead of Internet Inc.©‰. The Internet belonged to a world of the 1990s, a Digital Revolution. The people in the 2000s were way over the Digital Revolution. They were deeply involved in the Digital Terror. The nervous system of global governance, education, science, culture, and e-commerce, it was all in a spasm. It had all broken down in a sudden terrible panic in the last mile. The last mile stood between those great, big, fat, global, huge, empty, terrifying fiber-optic pipes, and the planet's general population. The Net had not just broken. It had been abandoned, cast aside in fear and dread. Because the movie companies, and the telephone companies, and the music companies had suddenly realized that their "intellectual property" would not remain their property for one pico-second, when everyday people all around the world could click, copy, and forward all their movies. All their music. All their calls home to Mom. And the people did that. The children of the Digital Revolution were a swarm of thieves. More people had used Napster than voted for the President of the United States. Nobody paid for that music. People didn't pay. The people were free. In a world like that, there wouldn't _be_ a music business. There wouldn't _be_ a movie business. There would be no such thing as long-distance charges. There would be no long distances. There would be no business. Nothing but _it,_ the Net. And the horror of that freedom could not be endured. So the Information Superhighway had just _stopped._ Stopped dead with its sawhorses and construction lights still up, like an incomplete overpass. A titanic physical investment. Dark fiber. Not lit up. In receivership. Gently rotting in the mellow ground. Business could not save itself from the situation it had eagerly brought on itself, this world of free and open access. It could not spare the effort and revenue to reinvent itself as a safe, secure, comforting, for-profit utility. There was no such thing as a computer "business," really. Racing into cyberspace was not a business enterprise, any more than the long-dead Space Race had ever been a business. Money fell out of it here and there, but that was not its point. It was a tremendous, wrenching effort in pursuit of the sublime. People aiming for the Moon, touching it for a golden moment, and being left with massive bills and rusting gantries. There was some software business around. There was Microsoft, which was a monopoly. Microsoft was never secure, because of the hatred. Microsoft was hated everywhere, despised, mercilessly attacked. Sabotaged, tormented, humiliated. Microsoft was a _pathetically vulnerable_ monopoly, because every hacker in the world who knew anything at all about computers understood how to attack Microsoft and its products. Microsoft's operating systems had never been built to resist the focused hatred of every alienated hacker in the whole world. No single system could ever bear up under that level of focused intellectual assault. It was like trying to save Saigon when everyone in the whole world was Viet Cong. There were not just dozens of holes in Big Bill's code but _thousands_ of holes. The patches of the holes wrecked the code, quite often. The patches of the holes had holes. Some of Microsoft's holes were unrepairable even in principle. Bill had more money than anybody in the whole wide world, but Bill didn't have enough money to save himself. Except for the Microsoft operating system—a monopoly—and the Microsoft Office Suite—another monopoly—every other venture Bill had tried lost huge amounts of money. There were a couple of really pretty nice Microsoft computer games that made a little money. That was about it. The biggest competitor that Microsoft faced wasn't even a business. It was a new and terrible thing in the world. It was Open Source, a thing that frightened Microsoft so much they regarded it as a cancer. Open Source aimed to eat away Bill's empire and replace it with a swarming, leaderless ant pile of global hackers. And Open Source wasn't a government any more than Open Source was a business. There was no one to negotiate with. There was no one to cut a deal with. There was no one to regulate. There was no one to bomb. You could bribe them. But you could never bribe all of them. You could sue them, arrest some of them, but that really looked stupid, and besides, they were probably living in Finland. Everyone claimed they wanted secure computers. Everyone was terrified of the consequences of the lawlessness, which were very bad and getting steadily worse. Viruses. Worms. Scam artists. Porn. Spam. Denial-of-service attacks. Organized crime. Industrial espionage. Stalking. Money laundering. The specter of infowar attacks on natural gas pipelines, aircraft control systems, dams, water reservoirs, sewage systems, telephones, and banks. Black horses snorting and stomping in the stables of the Digital Apocalypse. You sat people down and you explained what computer insecurity really could do to them, and they got really, really scared and upset. They wanted something done about it. Until they figured out what effective security really meant for them, what it would do to them. Then no one really wanted secure computers. No one at all. The spies didn't want to fix the holes in computer security. Spies liked to spy on computers. Cops didn't want to fix the holes in computer security. Cops liked to wiretap computers, and to grab them, open them up, and examine them right on the spot. Customers didn't want to fix the holes in security. Customers didn't want to ride a little motor scooter weighed down with a ton and a half of cumbersome locks and chains. Scientists understood how to lock code down, but they hated intellectual property. The military was sincerely good at really securing computers. The military excelled at defense. But they adored attack. The American military excelled at infowar, cyberwar, and electronic warfare. They were always making up horrible new methods of breaking, smashing, subverting, and violently destroying the whole works. Business couldn't do much about it. Business was broke, it had already died at its post. And on the far side of the dead dot-coms, the dead pipes, there was Wi-Fi. If the Internet was the child of Cold War nuclear warfare, then Wi-Fi was the child of the Special Forces. Wi-Fi was all about little military-spec spread-spectrum radios. Secret radios. Tiny radios. The very kind of thing that Delta Force liked to carry way behind the lines of enemies (and allies). Wi-Fi was just getting started, and when Van thought about it, it filled him with chills. Wi-Fi carried data that was _fast, cheap, anonymous, wide-open,_ wireless, portable, great big bleeding menaces to data protection, to intellectual property, to information security, sold in shrink-wrap packs as if they were bubble gum . . . Wi-Fi was a _nightmare._ The stuff coming down the pike was _worse._ It was like it was evolving _on purpose to make a secure life impossible._ Van shifted Ted from his right hip to his left. Someone tapped Van's shoulder. It was Tony. "Van," he said, "want to introduce you." An older man. White mustache. Glasses. Balding. Blue shirt, brown slacks. A conference ID on his lanyard. "Jim Cobb." "Dr. Cobb!" said Van, almost dropping his son in astonishment. There was no such thing as a Nobel Prize for computer science. James Cobb had won a Nobel Prize anyway. He'd had to share it with a Swedish physicist. Everybody knew that when it came to Swedes the Nobel committee had a soft spot the size of Stockholm. "The Bell Labs Concurrent C superset," Van gushed. Cobb smiled. "That's funny. Nobody talks about that much, these days." "I wrote my thesis on that." "The press always wants to talk about the photonics," said Cobb. That was what he had won his Nobel for—he and the Swede, who was his electrical engineer. "You never get the time of day for the work that you loved best." "That superset paper in '79, that was the best," Van said, knowing that it was true. "You know the best way to have truly great ideas?" "How?" Van blurted eagerly. He was talking to a true-blue genius who had had at least seven genuine, world-class great ideas. A phenomenon. "Have a hundred, and throw away ninety-eight of 'em! Haw haw haw!" Cobb was laughing, but Van sensed in his gut that Cobb had never gotten over the anguish of it. Cobb had loved those ninety-eight lousy ideas with just the same passion as the two, or five, or seven, that had saddled him with his immortal fame. "That way you handled synchronization conditions in Grendel," said Cobb. "Yeah!" "Where the capsule structure supports inheritance." "Exactly!" "I liked that," said Cobb. "That was cleverly handled." Van wanted to sit on the floor. James J. Cobb had praised him. James Cobb, who knew the behavior of semiconductors down to the atomic level. A top-notch theorist with "his head right down in the bits." A true grand master from computing's heroic age. In Bell Labs, guys like Cobb didn't even bother with the borders between disciplines. They were the wizards of the coolest, tallest ivory tower around. Guys who did physics at breakfast, electrical engineering at lunch, and programming after dinner. Bell Labs had originated the transistor, plus UNIX, C, and C++, and the Karmakar algorithm. The little R&D crowd at Mondiale could only dream of the colossal achievements at Bell Labs. "Cute kid," Cobb told him. "Where's Mom?" "Oh, Mom's resting awhile," Van said. "This is Ted." "What, so you're feeding the baby, changing the diapers? You younger guys are something else." Cobb lifted a cocktail glass to his lips. Van hadn't noticed any hard liquor at the party. Everyone else was carrying wineglasses. Apparently when you were a Nobel Prize winner at Erlette House, it wasn't hard to find vermouth and olives. "What's your latest project, Dr. Cobb?" said Van. "A year ago," said Cobb, "February 2001, they shut down Bell Labs in Silicon Valley. First time that Bell Labs ever closed a facility." "Right, I heard that." Bell Labs was Lucent now. And Lucent was very broke. "Real focused on short-term research payoffs. I was working on HDTV. Not a lot going on there." "I guess not." "Had my own consulting company for a while, that didn't work out. Just lately it's missile defense." Van tried not to stare. Missile defense? Star Wars? The ultimate in pseudoscience phony baloney? The great Jim Cobb reduced to working on Star Wars? Van glumly supposed that there was money in it. A huge amount of money had been thrown away on Star Wars. "It's not like you think," Cobb lied. He tipped his martini rim below his white mustache. "It's the Airborne Laser project. Air Force." "Oh," Van said with a nod, "the photonic emissions." "To tell the truth, that's not the part they have me working on." Van lifted his brows. The Cyber-Security crowd was getting a bit liquored up and noisy. Ted squirmed vigorously in his arms. Cobb stared emptily over Van's right shoulder. "You have to imagine," Cobb told him, "trying to stuff one hundred and eighty thousand pounds of laser equipment into one 747 cargo jet. That's the Airborne Laser. They need fourteen laser modules to shoot down missiles, and six of them already outweigh any jet's lifting capacity. Chemical laser. Huge, flying tanks of chlorine, iodine, and hydrogen peroxide. The devil's brew, that stuff. It sloshes. Oh, boy, it sloshes." Cobb leaned way back, lifting his free arm. "You are trying to aim that giant, flying chemical laser at a rising missile that is clearing a silo . . ." "It's a death ray?" "Lasers never work well," said Cobb, wobbling back upright. "Lasers are always underpowered. Lethality is in the kilojoule per centimeter range. You just can't do efficient optical coupling in chlorine-iodine wavelengths. There are ways to slide those pulses around, but when it comes to combining them . . ." Cobb started to hand-wave. He looked for a place to set his empty martini glass. He failed to find one. He absently tucked the narrow stem of the glass into Ted's sweaty little fist. Suddenly Cobb was searching in his jacket. He found a business card and handed it over. Cobb's card had an old-school ARPANET address, nothing but dots and numerals. "Mama," said Ted agreeably. Dottie had arrived. To Van's astonishment, she was wearing a short black cocktail dress. Dottie had hose and heels. She had earrings that matched her necklace. Dottie gently relieved Ted of his empty martini glass. "I think I'd better get you a fresh one, Ted." "This is Jim Cobb," said Van. "From Bell Labs. My wife Dottie, Dr. Cobb." "Oh, yes, Bell Labs," said Dottie brightly. "The three-degree cosmic background radiation!" "They thought that was pigeon crap," Cobb told her, blinking. "I beg your pardon?" "That microwave hiss from the birth of the universe. They thought it was pigeon droppings inside the Bell equipment. So they cleaned out the horn. Then they found out that it was the universe radiating right at us." "That's quite a story," said Dottie. "They were looking for crap and they found cosmic significance. The very opposite of most scientific endeavors!" Dottie stared at Cobb. It was a rare privilege to hear Bell Labs humor, straight from the source. "My husband often speaks of you, Dr. Cobb. He's a big admirer of your work." "Love to have you out to the BMDO," said Cobb to Van, slurring a little. "I'd show you that COEA." Tony reappeared. Tony was escorting a woman who was almost certainly the most attractive woman at the event. She turned out to be the wife of a colonel at the Center for Strategy and Technology at the Air War College. She quickly took Cobb in hand, chatting at him amiably. "Your AFOXAR people are still inside my damn plane," Tony told Van. "Meet me there before the demo, all right? We've got to cross some i's and dot some t's." "Tony, I can't do anything they can't do. They're fully trained Air Force technicians." "You and I need to talk, Van." Van scowled. "You're not getting cold feet about this, are you?" Dottie broke in. "He'll be there, Tony." Tony nodded and moved on. Van looked at her, upset. "What was that about? Ted and I were just about to bring you the fruit plate." "Honey, that was over two hours ago. I feel fine now. We have to do the banquet dinner now." Van despaired. "Oh, honey, please don't make me do the banquet dinner." "They got Ted his own high chair. It's all been arranged. They're seating me with the other CIA wives. I wouldn't miss this for anything." Dottie smiled. "It's important, honey. They really want you to go." Van did not want to go to the stupid banquet even the least little bit, but without a Dottie to run away and neck with, there was no point in fleeing. At least the food was good—the food was great, in fact—and he was not required to rise and speak in public. Van wasted many valuable moments of his life listening to tedious master-of-ceremony business. Boring crap about lost objects, departing buses, golfing opportunities . . . Then Jeb rose to speak. It cost Van a pang to see poor Jeb walk to the podium. Jeb was actually walking rather than waddling. The poor guy had lost a whole lot of weight while running the CCIAB. Rumsfeld, who had lived to be seventy-something and was in top physical condition, had been ruthless with Jeb. Rumsfeld had sent Jeb a bullying torrent of inter-office notes, "Rumsfeld Snowflakes," demanding Bethesda checkups and heart-safe exercises. Jeb put on his bifocals to pick through his three-by-five notecards. Van had never seen Jeb so meek and dull and conciliatory. Jeb didn't even start his speech with his customary risqué joke. "The President's board has accomplished, magnificently, the principal goals set for our strategy . . . Speeches, articles, and private meetings have changed the paradigm of the IT buying community. We will never return to the old, careless ways . . . The CCIAB projects already in progress will be making a smooth transfer to the Assistant Undersecretary for Infrastructure Protection in the DHS . . . Quiet but effective work is being done today by the OMB to make our federal government the smartest and the largest buyer of safely configured software and hardware . . ." What in the name of Pete was all that about? _This_ was the big show-stopper Jeb had promised? Where were the tough guys? Where were the antiterror warriors who were going to kick everybody's ass? Trained, efficient, cold-eyed operatives who would crush cyberterror without mercy? To hear Jeb talk, the whole effort had been about procurement issues. ". . . the safe computing benchmarks developed by the U.S. National Security Agency and the Center for Internet Security . . . The National Institute for Standards and Technology's Certification and Accreditation Program . . . the Undersecretary of the Information Analysis Infrastructure Protection Directorate who will oversee collection and storage of the critical infrastructure data in a database . . ." Van's eyelids were fluttering. He looked around the conference room, past the bouquets and sweating ice pitchers. Jeb's audience was drinking Jeb in. This was _normal_ speech to them. Jeb was _normalizing_ the computer world. People who had been howling, paranoid prophets in the cyberwilderness two years ago were getting turned into fully vested bureaucrats. They were _real_ bureaucrats, with real titles and real offices. A little slice of the funding pie there. An undersecretaryship here. Funding. Turf. Accountable responsibilities. Oh, my God. Now Jeb was gallantly name-checking all the usual suspects within the CCIAB. "I can't say enough about the tireless efforts of Herbert Howland, our director of public relations . . . Stand up, Herbert, where are you, take a bow . . ." A pattering of applause. Van's fingers dug tightly into the linen tablecloth. Oh, Jesus. So this was why they had insisted on his being here at the banquet. The ritual applause. Stage fright bit deeply into him. His cheek jumped. Restoring nerves were tingling in there, as they grew their way back through the bone cement in his head. "And the CCIAB's heroic Deputy Director for Technical Services, Derek Vandeveer!" Van forced himself to his feet. To his shock and awe, there was thunderous applause for him. The loudest applause of the night, by far. Frantic, almost. The idiots would not shut up. There was even _whistling._ The whistling was coming from Michael Hickok, who was at a table with the AFOXAR crew. Hickok went on for a good eight or nine seconds when everyone else had stopped. Van sat down, his face flushed and blazing. What was that about? Had he really done that great a job? Impossible. That crushing humiliation with the KH-13 . . . Van looked dazedly across the room to Dottie's table. Dottie looked happy enough to burst. When the banquet broke up, Van sought her out. "Did you hear all that clapping?" he asked her. "Was that just me?" She jounced Ted on her hip. "Oh, honey, Ted and I were just so proud." "Let's get out of here. That was truly weird." "You promised Tony you'd go to the landing strip and help him with the test flight." Van had promised Tony no such thing. "Let's go put our feet up. We'll feed the swans or something." "Oh, no, not now. I've got to go have a drinky-winky on the big verandah with the CIA wives," said Dottie. "They're telling me all these amazing stories about the husband I never knew I had." "They're not 'CIA wives,' honey." "Well, that big redhead sure is. The one who's really looped. I think she knew your mom!" CHAPTER TWELVE ERLETTE HOUSE, VIRGINIA, MARCH 2002 **V** an had no alternative but to walk to Tony's jet. It was a surprisingly long way. Erlette House had actual fields out here, growing tall, peculiar, East Coast historical crops. What was that stuff over there? Flax? Hops? Hemp? He'd never seen the like. The AFOXAR staffers, eager for publicity, had flown in an entire Joint Special Ops command post. It was pushing it more than a little to have tents, briefing boards, spotters' binoculars, laser rangefinders, and spidery spread-spectrum antennas, but AFOXAR was never going to have a better opportunity than this to advertise their services to a crowd of feds. Van offered a vague wave to Hickok, who tapped the side of his ground-contol helmet and gave a thumbs-up. Van walked up the jet's embarkation stairs. Tony's jet was scarily big. It could have held twenty people, if someone had ripped out the love nest's white leather couches and the twenty-three-inch tiltable digital display screens. So here he was inside a fully fueled private jet in Virginia. It really was that easy. If he knew how to fly this jet, he could be smashing into the White House in minutes. Van went up to the cockpit cabin, which had no security door. There was no pilot on duty. There was no one inside the jet but Tony Carew. "Where's your pilot?" said Van. "AFOXAR said they'd put five or ten tech guys in here!" Tony lifted a finger to his lips. "Shhhh!" Van had never been inside a jet's cockpit before. The BBJ had two pilot's seats, tastily upholstered in lamb's wool, plus two black plastic yokes and six bluely glowing digital screens. Big flat planes of glass surrounded Van on three sides. "You're the pilot, Tony?" Van said. "When did you get a pilot license?" "Oh, come on, Van. Who needs one? John Travolta can fly one of these things. Fleabitten al Qaeda guys straight from Yemen can fly them. They're not a big deal. And whose show is this, anyhow? Is this about a bunch of punk kids from AFOXAR? Why let them hog the glory?" Van said nothing. He wasn't thrilled at the way this was going. He scrunched himself into the copilot's seat. He was looking at a gleaming forest of switches and dials. The BBJ had a massive double-handled throttle, like a huge yellow beer tap. His seat had a flip-down pane and an overhead projector. "I flew her over from Colorado myself," said Tony. "That was a milk run. I had to fire my pilot. I'll have to get rid of that leather decor, too. I'm selling this thing, you know. I'm selling her to the party directorate of Bharatiya Janata. In India, she's gonna be a political campaign plane." "No kidding." "Indians can do all kinds of cool things with jets once they're free of the good old FAA regulations. For those village voters in India, a jet like this is pure stage magic. They'll paint her green, white, and saffron. Dress her up like a sacred cow on parade. They can fill the fuel tank with luminescent sparkles and outdo the Navy Blue Angels. Her best days are all ahead of her." Tony patted the instrument panel, his face tinged with sadness in the glow of the altimeter dials. "Why did you sell your jet?" "Why else? I had to. In some other, better world I'm just a dashing tramp flyboy, Van. Maybe I do some milk runs from Bombay to Dubai. I fill this bird up with gold chains and bangles. I settle accounts with some _hawala_ guys and then I can buy another plane. That's how they finance Bollywood movies . . . but, you know, come on. That's a mug's game, it's the smuggler's blues, right? That kind of life doesn't _push the high-tech edge._ " Tony leaned forward in his pilot's seat. "There are only sixty-one of these babies in service in the whole world. And I have the only one that can be flown off a Web page." Tony held up a clipboard. "Really. I mean, here's tonight's little flight plan, okay? Twenty minutes, and it's almost all automated." Van rubbed at his twitching cheek. All automated? No, not exactly. The exact situation involved Michael Hickok standing outside in the gently gathering Virginia darkness with a portable plastic gizmo frankly based on a Nintendo control joystick. Nintendo joysticks worked great, actually. They were extremely dependable interface devices. The engines began to roar. "Van, in politics, people need a damn show!" Tony shouted. "And that's just what we're gonna deliver. Think of the takeaway sound bite we're giving these guys! 'I went to Virginia and Derek Vandeveer grabbed a jet plane right out of the sky!' " Van stared at him. "You know what I like best about this remote-control rig of yours?" Tony bellowed over the engines. "That it's all _invisible_! I mean, if we didn't know better, we'd think we were haunted by spooks!" Tony sent the plane into a taxi run. The engines drank fuel and they picked up speed in a hurry. The jet left the tarmac. They were airborne. "No freight load," said Tony as the roar of takeoff faded. "She's light as a feather with just you and me on board. Stop looking so freaked, Van. I'm telling you, this is totally a picnic. We could go in the back and watch stag films." Van found his voice. "I don't think stag films will go over real well inside India." "People are the same all over, Van. I mean, just maybe, you live in a nation of rich maharajas, influence peddlers, crooked elections, and corrupt accountants. With big software industries, and huge gaps between the superrich and the underclass. Where son follows father in political dynasties, hassled by Moslem terrorists. Is that your country? Really, pick any two." The jet began to bank. Van sneaked a look out the flat black pane of the window. Maybe he was going to survive this. "Let me show you something really cool here," said Tony, scrabbling under his seat. "Look, the pilot's got his own gun." He produced a snub-nosed Smith & Wesson revolver. "Boy, a pilot with a gun, that makes you feel a lot safer, right?" "Put that away, Tony." "It's never loaded," Tony assured him. "Bullets equal zero." He tucked the weapon back in its holster. "But they always ask me about that now. They do, I swear. I've got, like, fifteen Taiwanese chip executives in here for a dirty weekend in Bangkok, and it's like: 'Does our pilot have a pistol in the cockpit?' Like what, you Chinese businessmen are aching to polish each other off inside the fuselage? The world has gone nuts, Van. It's like we're all under a curse." The plane bounced twice, violently. The engines whined. "This must be the good part of tonight's show," said Tony. He took his hands from the controls. "We just got fake-hijacked in mid-air, right in front of your adoring crowd." For the first time, Tony clicked his seat belt. "So," said Tony, stretching, "tell me about your next big step, career-wise." "I don't know," Van told him. "I think I might move out to Colorado with Dottie." Tony was astonished. "What? You're gonna waste time out there with my little telescope? Didn't you hear those clowns yelling and cheering at that banquet? Man, you can have any post you want!" "I don't know what that was even about." The plane went into a terrifying sideways slide. Van clutched at his armrests, heart hammering. "Do I have to spell it out to you in words of one syllable?" Tony said, unperturbed. "I guess I do, huh? Van, you are their hero." "Huh?" "You're their man, Van. You're their ball-breaker, you're their kick-ass guy. What cyberwar people want more than anything in the world is a geek who is genuinely tough. Did you see any 'Cyberspace Force' people in there at that meeting? Did you wonder why not?" The plane leveled out. Then, sickeningly, it began to climb. Tony glanced at his clipboard. "I'm loving these AFOXAR kids. They've got brio. No, Van, the unlikely attempt of Colorado Springs to become the computer-security capital of the visible universe, whoa, that has come to sudden grief. Word got around. When I found out my pal was in a damn hospital, I made some words move around. To the President's political adviser, specifically. He's a busy guy, but he didn't mind when I gave him just a few words: 'illegal bug,' 'National Security Council,' 'rogue operation inside Washington,' some words like that. Major General Wessler has got himself a brand-new field assignment. General Wessler is going to be sucking brown dust in Mesopotamia." The plane dipped violently. Tony whooped in glee. "And that Cyberspace Force, who had such nice brochures . . . They are not even an idea now. They are not even the idea of an idea. They are buried like Pompeii under eighteen solid meters of volcanic ash. What happened there, huh? Dr. Vandeveer happened, that's what." "Look," Van protested, "I know that you told me to stay away from that satellite . . ." "I know, I know, Jeb was real ambitious. You guys just couldn't stay out of the loop on the KH-13. But let me tell you how all that plays to the people at this event, Van. How it looks is, the Cyberspace Force went down and dirty on you, and the CCIAB went down and dirty right back. And there was some kind of encounter. And you came back from that, and your boss kisses you in public. And they _don't_ come back, and their boss gets broken like a breadstick. So everyone claps real loud for you. They clap till their hands get sore. Because they are terrified of you, man. You are their stud cyberwar general. You are the geek who killed and ate some real military. You rock." "That's not at all how it really was." Tony sighed. "Who even cares? You're never going to tell them the truth about beating up some wacky little soldier inside your apartment. And neither am I, or anybody else, ever. The point is that a cyberwar needs heroes. There aren't a lot of cyber-heroes around. In fact, you're pretty much the only one in the world." The ground was coming up outside the window. "Michael Hickok wasn't like you said he was, either, Tony. What you said about Hickok was all hype. I hired that guy." "Van, that was okay, too. I still think that guy is evil, but if Hickok chose to jump ship and join your side, then he's smarter than I thought. Hickok is a goon, but if he's _your_ goon, that's terrific. I can trust your judgment there. When it comes to cyberwar, you're the best around. Really. You just are." Van wiped sweat from his forehead. "Tony, why are you angling this?" "Because your scene is where the action is, brother. This event of yours has been very good to me. The Internet boom is history, but there's still money in security, and there will be a lot more once people knuckle down and shape up. Thanks to you, a ten-billion-dollar boondoggle is finally on the ropes. That KH-13 is facing cancellation. And that is great news. It's a new day now. We're gonna put that kind of bureaucratic bloat behind us, and move right on. Nobody cares about gold-plated Cadillac satellites in a real shooting war. It's all about rapid point-and-shoot now, that's the new trend. It's all about Predators. And, Van, you and I just proved to everybody watching us that we can turn Boeing's biggest private business jet into a giant remote-control Predator. I'm a very proud and happy guy to know you, Dr. Vandeveer. This is working out brilliantly." The jet touched down. It jounced violently and became airborne again. Luggage compartments flapped open and there was a distant crashing from the galley. Then the wheels hit with a screech. The end of the runway rushed upon them. Straps bit into Van's chest and gut. The jet stopped. The engines died. Hot metal cooled and ticked. "Yahoo," Tony murmured. "Yahoo-dot-com." Floodlights flicked over the runway. Van saw to his horror that an enthusiastic crowd was surging toward the plane. Tony laughed aloud. "Van, look at 'em! You are a movie star!" "I'll have to give them some kind of speech," Van realized. "Van, a great tech demo can save any situation. And you just gave them one. This is a victory speech. I'll jot you down a couple talking points." Van was awake inside the Lake Cottage. He felt too elevated to sleep. Dottie was sleeping in the featherbed. A tendril of brown hair was glued to her forehead with sweat. The woman should never take Dramamine and also drink white wine, thought Van kindly. It really made her manic. So funny that Tony Carew somehow imagined that his actress girlfriend was his wild angel. That woman was playing a phony role, that was obvious. While Dottie, who had been married to him for ten years, had found her inner tigress. Van had never imagined Dottie for a gossip, but it seemed that her work in public relations had turned her head around. In just one evening mingling with the Joint Summit crowd, Dottie had wormed out a host of inside stories that Van had never heard or even dreamed of. This stuff was all cocktail blather, obviously, but it was about _himself._ People from outside the CCIAB had notions about him that were wildly divorced from reality. They knew that he lived in a slum, but they thought he had chosen to live there because he liked to beat up crooks. People thought he had a black belt in Tae Kwon Do. They knew for a fact that he carried a high-tech gun. He was supposed to be hacking into foreign computers every week. He was recruiting Special Forces people, breaking into terrorist facilities and installing Trojan Horses and fatal viruses. Also, supposedly, he was having an affair with Fawn. This bizarre tittle-tattle might have upset Van, except that Jeb was catching it even worse. Jeb had a whole set of legends attached to him, like a shark followed by remora fish. Jeb had heart arrhythmias. He had advanced diabetes. He'd had a fistfight with Donald Rumsfeld and Condoleezza Rice had had to break it up (this was the best story, actually). Jeb got anxious phone calls three times a day from Larry Ellison. Jeb had a Republican Party slush fund. Jeb had hired Cuban exiles to wiretap the French Embassy. Jeb was addicted to Halcion pills. Jeb was secretly gay. He, Derek R. Vandeveer, had become the toughest, scariest cyberwarrior in Washington. It made Van wonder if he had ever understood anything about any other human being in his life. Was he delusional? Maybe, when it came to computers, _everyone in the world_ was delusional. On a number of occasions, Van had met the President of the United States. This poor guy even had his own military acronym: POTUS. In real life, Van had met an affable Texan baseball fan in his fifties who liked nothing better than eating pretzels and watching a few innings on the ol' boob tube. He had twin teenage daughters who gave him a lot of grief. This was the President of the United States. Somehow this was the very same guy as the remorseless military war chief who was relentlessly crushing the world's most feared and respected mountain bandits. And now he had even met James Cobb. Van opened his laptop bag and retrieved Cobb's business card. For Van, this had been the true highlight of the Virginia Summit. It had moved him deeply that a man he had once idolized had recognized him as a colleague. Up popped Cobb's Web site. It wasn't a site at all, just a series of retrievable files, like in the good old days when the ARPANET had been the info highway for engineers. No spam then. No porn. No commerce. No viruses. The watering hole for tech wizards. ARPA, Stanford, MIT. Bolt Beranek and Newman. UCLA, Xerox PARC, IBM, and RAND. Those were just labels really. Labels for the same few dozen tech guys, little teams of ten and twenty scientists, nice and quiet, really quick, supplying what was needed whenever the need came up . . . All those Cobb papers from the seventies and eighties . . . In his heyday, the guy was publishing like crazy. He was throwing off ideas like a blowtorch spat out sparks. Conference proceedings on three different continents. James Cobb was literally all over the map. Not just in one discipline, either. Cobb was making connections that no one before him had ever thought to make. He was using systems analysis and information theory to slice through the rest of human knowledge like a layer cake. It was like he had three brains inside one head. Van could still remember the mind-blown tingle he and Tony Carew had felt in their MIT dorm as they looked through Cobb's work. They would sit up together at night, getting steadily drunker on the new intellectual frontiers this guy was violently forcing open . . . And in looking at the papers, Van realized with an adult shock that most of them had gone nowhere at all. Cobb had had a whole lot of really sexy notions that just did not play out in the real world. Van himself was older now. He could recognize the work of Cobb's youth as a young man's fancies. Van had a further insight. It crept up on him like a kind of dread. For the first time, he recognized a kind of emotional distress in what Cobb had done. These ideas were not just freely pouring out of Jim Cobb. They had been squeezed out of him. There was something primal and animalistic about Cobb's huge burst of creativity. Maybe it had satisfied him, maybe he took pride in it, but his act of mastery had hurt him, it had cost him. James Cobb had paid a human price for his science. He had paid some pitiful, heavy dues, like a master of the blues guitar. Van looked at his watch. It was almost 2:00 A.M. Suddenly he wanted to drop everything. He wanted to seek out Jim Cobb as he slept in his Erlette House room. He wanted to wake Cobb up, to tell him that he had achieved enlightenment. He was no longer a student. He truly _understood._ He wanted to become the man's friend. Van looked at the computer screen, his heart thudding with inspiration. Of course he could not find Cobb's peaceful room, pound the door in, and wake him up, shouting frantically. No, that would be senseless. He would send Cobb a professional e-mail. Nothing frantic, nothing weird and geeky. The master addresses his fellow master. Very cool. Very considerate. A technical note. That would do it. Something that he and Cobb could share together. Co-authoring a new paper, maybe. Wow. A great idea, that would be fantastic. After all, the guy had practically invited Van to help him. He could breathe fresh life into something that Cobb had left on the side of the road. It would be like a Festschrift tribute. That should be easy. There was so much there to choose from. Van's fingers hovered over his keyboard. Cobb, James A. (1981) ADAPTIVELY PULSED LOW-POWER EMISSIONS IN MASSIVELY PARALLEL COLLIMATION. _Prospectives in Tunable Bandgaps,_ Conference of the Max Planck Society, Ringberg Castle, Germany. He clicked on it. What was this paper, again? Doing something weird and off the wall by tuning laser bandgaps. It seemed to him that maybe Tony had spoken of it once, ages ago. Tony had always had a fondness for Cobb's wildest, most out-there notions. Very weak photonic clusters. Digitally packetized. Reflectively collimated in real time into massively parallel beams . . . Half an hour later, Van left Dottie sleeping in the suite and walked out under the quiet Virginia stars. He opened his cell phone. Hickok answered at once. It was almost 3:00 A.M., but there was massive party racket in the background, and Hickok was drunk. "Hey, Van! Come on down and join us by the pool! These AFOXAR guys love you!" "Mike, I know it's late, but I need you. Right away." Hickok was crestfallen. His voice had sobered. "So, what, you didn't like my piloting today?" "Mike, this is spacewar." CHAPTER THIRTEEN THE ALFRED A. GRIFFITH INTERNATIONAL ASTRONOMICAL FACILITY, COLORADO, APRIL 2002 **L** ook, it's simple," said Hickok. "Van is the strategic leader. I am the tactical leader." "Dr. Vandeveer's a civilian," Gonzales objected. "Cyberwar is our brand-new kind of war, dude. I'm a civilian. You're a civilian. He's a civilian. The enemy are civilians. We're all civilians." "I didn't even _want_ to be a civilian," said Wimberley. "I got a dishonorable discharge. You know what that did to my job prospects?" The four of them were sitting at midnight, in the mountains of Colorado, in the back of a rented camper-truck. The camper was parked off-road and hidden under a camouflage net. Van wore a black silk shirt, black cargo pants, a black leather jacket. He had a black shoulder bag, black socks, and black Rockport walking shoes. Van didn't normally dress like a New York humanities professor, but it would do. If he was caught breaking into the premises of the Alfred A. Griffith International Astronomical Facility, he had a good cover story. After all, he was Mr. Dottie Vandeveer. He was an old college buddy of the guy who ran the place. There was nothing in Van's shoulder bag that couldn't pass close inspection. Black gloves, black woven hat—well, it got cold up here. Earpiece and mike—that was just a cell phone. Digital recorder, videocam, big deal. Laptop, he always had a laptop with him. He was a computer scientist. The other three cyberwar infiltrators looked like the Mutant Ninja Turtles from Mars. Hickok, Gonzales, and Wimberley were impossibly scary. Van was used to it now—it had been his idea—but he could hardly bear to look at them. Their monster helmets had inbuilt night-vision goggles. They were big pointed Cyclops snouts with matching counterweights in the back. They had faceless black ski masks of fireproof Nomex. They owned the night in their shapeless black battle jackets, black combat pants, black Kevlar gloves, and black lace-up SWAT boots. They had great big black humpbacked ALICE packs. They looked like three giant black plastic action figures. Any normal man who saw these three trolls stalking past him in darkness would assume that they were hallucinations. The odd part was that none of it was even official U.S. military gear. It had all been bought or rented off the shelf, from various mil-spec commercial suppliers. None of it was even secret. Except for the loaded AFOCI burglar case that Van had brought from Washington. "Sure you don't want to take the case with you?" Van asked Wimberley. The kid was looking shaky. "We could bungee it right to that ALICE pack." "I don't deserve to carry it," Wimberley sniveled. "I got my ass kicked over that fair and square." What was it gonna take to cheer this kid up? "There's fifteen grand waiting for you in a bus locker in Boulder." "That helps," Wimberley admitted. "That's gonna help me a whole lot." Van was spending the down payment on a house in order to invade, burgle, wiretap, and hack his wife's workplace. Van wasn't quite sure why this cyberwar operation was worth forty-five thousand dollars to him, plus the rental for the gear, the truck, and the airline tickets. Van had almost crawled out from the shadow of total financial disaster. This misadventure had put him right back in. Not to mention that agent-running his own unapproved black-bag operation was eighteen different kinds of illegal. It was just—he had to know. If he did not learn the whole truth about this evil weapon and its capabilities, he would never have another quiet night in his whole life. Don't call it war. Call it science. "This is only a recon mission," he told his three employees, for the tenth time. "No rough stuff from you tough guys. We're here to be the eyes-on-target. We infiltrate. We observe activities, intentions, and capabilities. We record and we verify. We plant remote sensors. Then we exfiltrate. Nobody sees us. Nobody hears us. Nobody gets hurt. Nobody gets shot. Because this is real, live cyberwar." "I never pack heat," said Hickok. "We don't get caught this time," Gonzales agreed. "If we get caught, will the President pardon us later? Never mind, man, okay, I got no guns anyway!" "Okay then," Van said. "Let's go ahead and roll." He tucked the headset into his right ear. The four-man team did not have to roll very far. Following their highly detailed satellite maps, they left their rented camper and strolled through the pines to the edge of the Facility's fence. They found a ragged valley where the builders had run their fence under an old, sickly-looking box elder tree. The night was dark and gusty, with thin overcast. Wind tossed the spreading tree limbs. Box elders had weak wood. It wasn't much labor for four men to throw a grapnel rope up in the tree, time their heaves with the wind, and rip the old tree apart, nicely crushing the fence. No alert defenders rushed over with any Jeeps and machine guns, because, after all, they were just astronomers, and it was just a tree falling in the wind. The four intruders climbed up the fallen tree limbs and over the smashed fence. Van was careful not to snag his civilian clothes. "Loan me that oxygen mask," said Van to Hickok. "This altitude's killing me." "Can't you carry this tank yourself?" said Hickok, rubbing under his black foam kidney-pad. "I got enough gear, that's for sure." "No I can't carry it. An oxygen bottle looks way too much like a detonation bomb." Van huffed at the plastic mask. Relief flooded his body. As planned, the four of them split into pairs. Gonzales and Wimberley, the B team, were tackling the Network Operation Center. Van and Hickok were going uphill to covertly inspect the Weapon of Mass Destruction. Hickok set to work to hijack a small electric golf cart for the long ride up to the observatory. This wasn't hard. The astronomers had quite a lot of golf carts, and most of them still had keys in them. Hickok detached his helmet mike. "You know what I miss in a cyberwar gig?" he said. "I miss the air support. No Pave Low, man. No C-130s. For Air Force Special Ops, man, that is hard." "I was completely crazy to hire those two Cyberspace guys," Van mourned. "No you weren't," Hickok said. "I hate to say this, but nowadays, most all the 'special' in Special Ops comes from the private sector." "I'm crazy because there is nothing up there, Mike. I'm doing this because I am paranoid. There is no weapon up there. We're not gonna find anything. That is a half-completed telescope." "No it isn't." They drove the electric van silently, in darkness, slowly and without opposition, up to the site of the observatory. They manhandled the cart out of sight, down a talus of construction debris. Van threw a camouflage net over the cart. Van was new to handling camouflage nets. There was a real art to it. Hickok produced the folding, spindly antenna of a multiband burst-radio net. He pointed it down the hill toward the Facility. Gonzales came in at once, clear as crystal. "We got an incoming vehicle now," Gonzales reported. "A big black limousine. I'm making four—no, five occupants. Wow, this thermal imaging rocks!" Wimberley was breathing heavily into his helmet mike. "It's quiet inside the dorms. Just a lot of sleepy astronomers. That Network Operation Center, though. A whole lotta lights on up there." They heard the whisper of his rubber-soled boots as Wimberley moved closer to his surveillance target. "I'm gonna unlimber this shotgun mike." "That would be Carew inside that place," Van told Hickok. Hickok pulled down his Nomex mask. His face, already hard, grew harder still. "You guys copy all that noise here?" Wimberley reported. His sensitive shotgun mike was picking up the rubbery thud and falsetto vocals of London-style Indo-disco. Bhangra music. "That's sure not like any kind of music I know. Lemme see if I can filter that noise out." Odd digital muffling. A woman's shrill voice emerged faintly, her words strained like spaghetti in a metal colander. "You cannot talk to a lady like that, Tony! You dare not say a thing like that to me—" Van broke in. "Wimberley?" "Yes, sir." "Never mind the subject's personal life. Go use your thermal imaging on the electrical station. I want to see if he is routing any wind power through those big fiber optics tonight." Gonzales spoke up. He was calm and focused. "My limousine people are heading straight for that network center. I think we're gonna have ourselves one big party." Van examined the big door to the observatory. It was stoutly padlocked. It was a simple brass padlock, but there wasn't need for more security than that. This Facility was very isolated. And, after all, they were just astronomers. Van set after the padlock with a digital pick from Hickok's utility vest. This pick was new, and British. It was the size of a large fountain pen. It used fiber optics to probe the inside of the lock, then calculated the shape of the ridges on the key. When the computation was over, the butt of the pick slid out a nicely formed piece of stiff wire. It was awful what MI-5's new e-gadgets could do to the security inside conventional mechanical locks. Van really hoped it would be a good long time before normal thieves caught on to this. Van carefully scraped the lock open. When his hands stopped trembling, he enjoyed more oxygen and had a gulp of Gatorade from Hickok's canteen. It was windy and freezing up here. He put on his gloves as well as his black hat. Wimberley reported in. "Those generators sure give off a lot of heat! How much power is in those windmills?" "Half a megawatt each," said Van. Wind power was intermittent—sometimes a little, sometimes a lot. That made wind energy particularly easy to steal. Who would notice if you shaved off some electrical power in a big storm passing through the western U.S.? "Four people left the chauffeur behind in the limo," reported Gonzales. Gonzales was puffing a little after hefting his ninety-five pounds of rucksack cybergear uphill, at a dead run, after a moving car. The effort didn't seem to bother him much. "Subjects were two men, two women. I'm at the Network Center now, and I'm making nine people in the ground-floor room behind this wall. If this millimeter radar works." "It was working okay when I left Washington," Van told him. "Then it needs improvement," said Gonzales. "The limo has Colorado license plates. It's registered to Pinecrest Ranch." That was quick, thought Van. And so far, it had been really quiet. Maybe they would actually get this operation done on time. Van pulled hard at the observatory door. The weather-stripping popped open with a hermetic smack. Van stepped inside the observatory's vault. The place was empty. It was delightfully warm. "Real toasty in here," said Hickok. He unbuckled his helmet. The telescope—that diva of the skies—looked pretty much like she had last time Van had seen her. There had been some additions on the ground, though. A new set of a dozen stacking, folded chairs. Coffee mugs and a big coffee decanter. A new, large designer desk—a multishelfed thing with power strips, big enough to call a console. And, standing near the door, a handsome little Japanese telescope. The little scope was some top-end toy for a rich stargazer hobbyist, sitting on a sturdy tripod. Van walked to the big desk. It held a scattering of CDs and technical documents. He looked under it and behind it. A set of travel bags had been stowed under there. A black fabric rifle case. The hunting sure was great around here. Hickok rounded the giant telescope in awe, his nozzled head tilted back. "Check this thing out!" "I've seen it," Van said. Hickok pulled off his helmet. "I meant with these infrared scanners." Van slipped Hickok's too-tight Kevlar helmet over his own ears. The bridge of his glasses crunched up against his nose. Then the diva showed him her true colors. The Lady wore a bloody crown. A glassy ring of pulsing light. Ten thousand photo-multipliers, the sensors meant to lift the faintest glow of distant stars from the surface of the mirror. They had become a spider crown of red-glowing eyes. In the infrared of Hickok's heat detector, they winked, they twinkled. They were red-hot. The optic pipes that carried light away could also bring light in. And the mirror that brought light down from the zenith could also shine light up into the sky. Van gave Hickok his helmet back. "You know what chaps my ass most?" said Hickok. "That son of a bitch had the guts to build a spacewar weapon in Colorado. Hell, that's where they _train the Air Force._ " Gonzales reported. "The party is breaking up. I'm painting them with the spotter. You copy that now, Team A?" Hickok opened his command-and-control laptop. The map on his screen was like a little military sandboard. Four blue triangles. A little cluster of unsuspecting red squares. "I copy, B." Two red squares veered off from the others. A blue triangle zipped after them in pursuit. "I'm gonna move in to catch these two with my parabolic mikes," Gonzales said. Van adjusted his earpiece. Stolen voices swam into his head. Tony Carew. "There were sixteen carts out here tonight," Tony remarked. "Now there are only fifteen." "You _counted_ them?" said a woman's voice. "No, honey. I've got an eidetic memory. It's my gift." "It's so cold and windy out here! Let's take the limo. Make those stupid Chinese take these ugly little carts." "These delicate roads won't hold up the weight of their big limousine," said Tony. "That's why we use all these carts. Anjali, it's a sensitive matter to demonstrate the capabilities of my instrument. You don't see nice old Mr. Liang or nice old Mr. Gupta complaining about this." "Your stupid clients don't have to wear sleeveless dresses." The cart's tires crunched. The voices faded out of range. Gonzales came back in. "The male and female just departed in a Facility vehicle. They are riding up toward your telescope, Team A. Okay, I am painting two more groups now. I am making . . . four men in that first party. Two men, two women in the second party. Hold on here, whoa. We have got two bodyguard types inspecting the vehicles." "Those bodyguards brought guns," said Hickok knowingly. "We don't know that," Van protested. "No professional would do this sort of thing without a gun," said Hickok. "I don't care if they're Chinese, Indians, or goddamned Martians." "I'm running this operation," Van pointed out, "and I don't have a gun." Wimberley broke in with a yelp. "Hey, I don't have a gun either! Everybody said not to bring any guns!" Hickok sighed. "Would it break y'all's heart if I'd brung along one little Beretta in my ankle holster?" "Hey, I can skip back to the truck and fetch us two MP5s and a Mossberg twelve-gauge," said Gonzales eagerly. "Wouldn't take me ten minutes!" "No, no, no!" said Van. "Keep your eyes on the prize!" "The boss man's right," said Hickok. "We came here to play cyberwar. Fred, you break into that party room and bug it. Kid, I want to see you break into that Network building. Get real busy with those desktop Tempest bugs. Me and the professor are gonna plant audio up here. Then we all retreat outside the structures. We hide out under our camou tarps. We just listen and we record. That is the Policy. We stick with the Policy." The Policy was good and sensible. The Policy did not involve any sudden trips to an emergency room. Hickok slapped his translucent Wi-Fi bugs to various discreet surfaces. Van tuned the bugs into audio channels on his laptop. Then, with time ticking for the arrival of their guests, Van and Hickok went outside to shut and lock the observatory door. The instant Van shut the observatory door, the audio signals from within the building completely vanished. "I thought you said this structure was made of straw," said Hickok. "Looks like they used some copper mesh in that straw." Sensitive instruments needed electrical shielding. "Then if we want to overhear 'em when they're inside there, we gotta improvise," Hickok said tightly. "We gotta go back inside there and hide ourselves." "That leaves nobody outside here to lock this door," Van pointed out. "If they find this place unlocked, then they'll know we're in there." Hickok froze in confusion. He looked at the padlock, and then he gazed down the mountainside. "I can see those headlights coming fast." Hickok began to pray under his breath. "Lord, I, your soldier, am called upon to perform tasks in isolation, far from familiar faces and voices. With help and guidance from my God, I will never surrender, though I be the last. If I am taken, I pray that I may have the strength to spit upon my enemy . . ." "I'm going inside," Van told him. "You run the team awhile, okay? If they catch me, I was just curious." Van slipped inside the observatory. He ran across the floor, kicked some heavy luggage aside, and hid himself beneath the big console desk. It took Tony some time to key his way through the jiggered lock. Distant conversation. Van stuck an earpiece into his ear and turned down the light on his laptop screen. The audiobugs worked splendidly, sending him six different audio streams. It was like he had six ears. "Try to be nice to Mrs. DeFanti," said Tony. "She's been through a lot of emotional pain over all this." "Why don't you call her 'Katrina' to me?" said the actress girlfriend viciously. "It's 'Katrina' you are always calling her, so sweetly, face-to-face!" "Honey lamb, if the former 'Li Huping' wants to be 'Katrina DeFanti' now, why is that a problem? Give me the word, and you could be 'Angelie Carew.' That would look great on a nice new American passport." "You are lovers with her." "Look, she is twelve years older than I am," said Tony, pleading. "Mrs. DeFanti is completely devoted to a much older man who is mentally ill. Katrina and I have useful talents for each other. It is very possible for an adult man and woman just to be good friends. Really, it is!" "You are _lying_!" The actress drew a sharp breath. "Or you are abnormal." "Okay, fine, I'm abnormal," Tony said. "I prefer 'extraordinary.' 'Brilliantly talented.' 'Fantastic.' 'A dream boyfriend.' But okay, 'abnormal' will do. Just be nice to Katrina for one evening. That's all I ask! There is a lot of money at stake. Crores and crores, and lakhs and lakhs, of rupees." Tony's voice faded in Van's earplug. To Van's astonishment, he saw that Tony was suddenly standing right next to him, at the edge of the outsized desk. Tony set down his black shoulder bag. It brushed the edge of Van's black shoe. Van looked up, and saw Tony's pale, strained face. But Tony did not look down. Tony's special guests were arriving. As the observatory door yawned open, Van's earpiece caught a faint cross-talk of radio chatter. The cyberwarriors outside the observatory sounded real busy. Tony left to face his guests. Van quickly opened Tony's shoulder bag. Tony's bag was a rat's nest. Crumpled business documents. Headache medicines. Indian gossip magazines. A laptop. A set of Bollywood DVDs. A titanium ray gun. Tony's customers entered the observatory for their demonstration. There was a babble of voices and the clatter of portable chairs. Someone wandered into range of the fifth audio bug. Van turned up his audio stream. "I can't like a man who lies to a hunting companion," said a male voice. "Yes, I might buy a jet from him, but I can never be his friend." "I hate what he did to my husband's elk," said a woman. "He never asked my permission to blind them and scorch them with his laser beams. Those poor creatures!" "How could poor animals hide from a reflecting balloon in the sky?" said the man. "It's just not sporting. Such an ugly business happening there, when your American plantation is so pretty and beautiful. My film crew and I, we so enjoyed our stay at Pinecrest. That suite was just like the Raffles in Singapore." "Oh, you noticed," said the woman, pleased. "I've been to Singapore so many times." "Look at Carew moving those chairs. Can't he let the guards do it? He's so busy, busy, busy all the time! He's like a servant!" "They all are," said the woman thoughtfully. "Always. But I've come to like them, the Americans." "They are lovable, in a strange way?" "All right, I don't love them. But I love _being_ American. Everyone on earth should be American. I put on my sunglasses. I go to Denver. I'm just a woman, I'm just a normal American woman. No one makes a bother of me, they just sell me whatever they have. 'Have a nice day.'" "I also like America very much," the man confessed. "They know me too much in Bombay, Nairobi, and London. In America no one knows my face yet." "They must have noticed that you are very, very handsome." "Thank you so very much. But why would beauty make a man happy, Katrina? _Duty._ Duty is what makes a man happy . . ." Van listened as Tony set to work to entertain his special guests. Tony's audience did not fully understand his American English. This forced Tony to speak very slowly. His taut, ranting voice echoed from the top of the observatory vault. "You are about to see . . . the single most astonishing . . . and significant technical development . . . in the modern Revolution in Military Affairs . . ." The dome's great double doors opened to the black night sky. The observatory's strawbale walls spun as lightly as a carousel. Van hastily picked up another squawking earpiece. The open roof had hit the right vector. He was getting a signal from his cyberwar team. Wimberley's frantic voice. ". . . burst of electrical down there! When that wind picked up, they really . . ." Then Wimberley's signal vanished, and Hickok and Gonzales were still blocked out. "Now that our roof to the stars is open, I suggest we make our Iridium calls," said Tony. "Mr. Gupta, you may call your home offices at the Research and Analysis Wing in New Delhi. And, Mr. Liang, perhaps you'll be kind enough to call the Second Department Analysis Bureau in Beijing. It's time for a joint understanding." An icy mountain draft rushed down from the black night sky. It chilled Van's flesh as he crouched below the desk. Overhead lights faded. New lights flashed on, stagily. Van dared to press his belly to the floor and sneak a look around the desk. The Lady was beautifully lit now, a diva poised in creamy pools of light. Van climbed to his feet in the thick gloom. His head pounded with the altitude. Tony and his guests were completely seduced by this gizmo. They had no idea that he was standing in a pool of darkness, watching them. Van silently opened the fabric rifle case. He removed Tony's gun. An elk rifle. It was loaded. There was a huge brass round already in the chamber. Van leaned his elbows on the ergonomic desk and stared down the rifle's scope. He picked their human faces out from the darkness, his crosshairs dissecting their heads. They were civilian targets. Utterly unsuspecting. A Chinese functionary. He was an older man with thinning hair, a big gut, and a carpetbag. A younger Chinese man at his elbow, some flunky gopher and interpreter. His bodyguard had the stiff back and humorless scowl of an old-fashioned Red Army commissar. Katrina DeFanti was a pleasant, middle-aged Chinese woman with nicely done hair and a roomy pink Chanel suit. She looked exactly like the kind of woman who should never, ever be shot at. An Indian film star. Another Indian film star, even prettier. A much older Indian man, with an accordion-sided valise, a white Nehru jacket and whiskers. An impassive Sikh bodyguard, who looked like he was cut from solid teak. Van had spent time in shooting ranges. He had learned a lot about rifles. He felt confident that he could put bullets into each one of them. But, as a professional cyberwarrior, he also knew that such crude behavior was counterproductive. Why had Tony bothered to hide a rifle inside this building? What on earth did he expect to gain by that pitiful tactic? For a struggle of the kind happening inside here, a simpleminded rifle was an admission of defeat. It was worse than stupid. A rifle was pure despair. Van climbed back under the desk and returned to his surveillance duties. "Whenever a great power achieves a spacewar capability, this creates a whole variety of remarkable technical spinoffs," Tony told his guests. "Through our methodical exploration of this weapon's capabilities, we've discovered its peripheral features. When combined with laser reflectivity from a Mylar aerostat, we can refocus effective heat beams over a seventy-five-kilometer radius. In early Star Wars parlance, that beam was known as 'The Finger of God.' Space-based lasers have never been put into practice. They are simply too heavy to launch with conventional rockets. Even airborne lasers need a chemical power plant bigger than a 747. However, this ground-based laser, combined with an airborne mirror, can dominate the horizon. It can hit settlements, moving vehicles, any target chosen." The Chinese translator spoke up. "Mr. Liang would like to ask a question." "Of course! Ask me whatever you like." "Mr. Liang would like to ask a question of Mrs. DeFanti." Tony was startled. "I, uh, yield the floor." "Mrs. DeFanti, please tell us something. Is this strange device responsible for the many unsightly forest burns that we witnessed in your husband's rural properties?" "Yes, Mr. Liang," said Mrs. DeFanti in English. "The laser here caused forest fires on my ranch, and elsewhere. There were a number of incidents. The laser also burned up two of the communications blimps." "One can't expect pinpoint accuracy from an airborne blimp," Tony said. "But that's one feature only! Much more remarkable is the laser's fantastic ability to project colossal holograms. Here one combines the laser beam with an airborne chemical compound that fluoresces in infrared light. Spray that chemical across the sky, and you have psychological warfare effects previously undreamed of. Imagine the effect on the morale of enemies unprepared for an illusion of that size!" Now it was Mr. Gupta's turn to object. "How do you place these pollutants up into the sky?" "That's a very simple matter! Jet exhaust! Chemtrails!" The Indian actor spoke up. "You put adulterated fuels in that jet? You never told me you had spoiled the jet's engine with contaminants." "I didn't harm the jet," said Tony, shocked. "It's not a Space Shuttle. Boeings can burn anything." "But it's a matter of principle," said the actor. "You did not disclose to us that you had subjected my property to unclean fuels! The Bharatiya Janata Party will have to reduce its price accordingly." Tony was angry. "Sanjay, you're letting this go to your head! I know you've taken pilot training, and I know that's rather hard to get in America, these days. But the condition of the Boeing Business Jet is completely a side issue. I think Mr. Gupta and his superiors in New Delhi can speak for themselves." Mr. Gupta removed his bristly ear from his brick-shaped Iridium phone. "Oh, no, no." He chuckled richly. "Sanjay Devgan is not merely our movie hero, don't you know? Inside the Research and Analysis Wing, Sanjay Devgan also happens to be _our hero._ Our brave young colleague has our fullest support!" Mrs. DeFanti spoke up. She seemed irritated. "Gentlemen, I know you are all jet-lagged. But if you squabble in this way, we'll be up here all night. I want to see this ugly matter resolved. My husband is too troubled a man for such complex affairs. I want this situation liquidated." Liang ran this speech through his Chinese interpreter. Then he replied. "We Chinese are not interested in some remote device in the rural mountains of America. We do have some interest in the plans and the hardware. Could you ship?" Mrs. DeFanti grew peppery. "All right. I am merely a housewife. It's not my fault that we Chinese suffer a Two Chinas policy! I am very weary of having my family in Taiwan required to sabotage visual imaging chips, just so that major heat sources in a narrow band of laser wavelengths cannot be detected on the ground by spy satellites. It was very tiresome and difficult to get those Taiwanese chips designed, bought, and installed in American spysats, just so that this spacewar laser would not be visible. If the American spies seek other chip suppliers for their later spacecraft, then it will be senseless for any of us to build spacewar lasers at all. Your lasers would be spotted instantly by American spy satellites, and blown to shreds with American cruise missiles. So you must deal with us now, and pay us now, or else this entire laser effort is useless!" Tony cleared his throat. "Well, as Katrina points out so aptly, there you have it. It's our way or the highway. The very good news is, we _have_ successfully defeated the KH-13 satellite. Using this weapon, we burned the KH-13 so effectively that it will never be trusted again. We have proved that, with this telescope, we have a covert device which is also the world's first and only effective spacewar weapon. With this laser capability in place, we can defeat any craft that any space power ever puts into orbit." "Into _low_ orbit only," said Mr. Gupta skeptically. "You cannot damage any spacecraft in the valuable geosynchronous Arthur Clarke orbit." "There's nothing that far out but some harmless comsats," said Tony. His wristwatch bleeped. "We need to wrap this up now all right? It's time for our product demo." Electro-actuators kicked into life beneath the Lady's great blue mirror. The digitized mirror was clicking and flexing, moving in tiny increments of a few wavelengths of light. The digital telescope sounded like a roomful of typists. Tony spoke again. "I didn't mean to interrupt our valuable negotiations, but it's necessary to time this demonstration with care. We are about to attack the Iridium spacecraft that is carrying your phone signals, gentlemen." "How can you prove that?" said Sanjay. "You'll be able to hear the attack happening in real time," Tony promised. "And so will your sponsors at home in your nations' capitals." "You might be simply changing the phone signals inside this observatory building," said Sanjay silkily. "So that proves nothing at all." "I was aware of that objection," said Tony. "As you all know, my personal associate inside the National Security Council is extremely well placed in American cyberwarfare circles. It will be simple for Dr. Vandeveer to get the outage reports from the Iridium's new owners. I can forward those reports directly to you. That will prove the power of my antisatellite capability." The spies listened silently to their satellite phones. "The Iridium satellite is not being destroyed," Mr. Gupta reported at last. "We hear only a faint crackling! We have not even lost our phone connection to New Delhi!" "It's an overcast night," Tony explained. "The damage is mild. The ideal conditions for our laser are clear nights with a strong storm front through the local windmill farm." "Wind there, and yet no clouds here? How often do you get those weather conditions?" "There is very good visibility up on this mountain. After all, this is a telescope." "Snow, rain, then they make your laser weapon quite useless?" Tony tapped busily at his laptop for some time. Then he spoke again. "Of course it takes some time for a silent beam of light to destroy a metal satellite. We do not have enough wind power to destroy satellites instantly. Besides, it would be very foolish to detonate satellites, for then the Americans would know the truth at once. Think of this fact, though: we could attack Iridium satellites, weather permitting, very stealthily, for years. A reputation for bad technical performance would finish Iridium off for good. Then we could short their stock and buy Iridium competitors, such as Globalstar. That would be so profitable that it would easily pay for this telescope." "Globalstar loses money already," said Mr. Gupta gloomily. "If satellite phones made money, our Indian ISRO would be launching telephone satellites! Millions of Indians have never made a phone call." "Maybe you would do that," said Tony. "More likely, you would become a customer of Mr. Liang. China already has a financially sound commercial space-launch service." "Why is it getting so hot in here?" said the actress suddenly. "So cold, and then so hot in here! Where is my coconut milk? Did you bring only coffee?" "When do you begin your so-called satellite attack?" said Mr. Liang's interpreter. "Our phone line to Beijing is still working perfectly!" "We _are_ attacking that Iridium satellite," said Tony. "Right now. There is no visible beam. It is a very energy-efficient process. The adaptive beam has to penetrate miles of atmosphere with as little signal loss as possible. We don't even generate the laser pulses locally. We amplify them and collate them. We are beaming Internet traffic up into the sky, from the telescope, right now. Those Internet signals come from all over the planet." "Don't the people miss their Internet when you throw it up into outer space?" said Sanjay. "It's all spam." "No." "Yes, I am attacking a satellite with laser spam." "No." "We are running a major Internet backbone across the Rocky Mountains here," said Tony patiently. "We have spam filters. Nobody ever asks where the spam goes. We beam the spam into outer space." "You are an evil man," said Sanjay simply. "I don't like you. I never liked you." "Why are you selling this laser weapon to us?" demanded Mr. Gupta. "Why don't you sell your weapon to the Americans? They are the ones obsessed with space violence." "Because India and China are the planet's two emergent space powers," said Tony passionately. "China is about to launch its first manned mission. China is only the third nation on this world that is able to launch men in space. And India has an unmanned moon rocket planned for 2008. You Indians, you Chinese, you _need_ this space capability to diminish America's overwhelming space power. The Americans don't need laser weapons. Not at all! If the Americans want to attack your Indian and Chinese satellites, they can _fly up with a Space Shuttle and bring them down whole in one piece._ " There was a long silence as the listeners consulted their satellite phones. "It makes no sense for us to purchase American weapons on American soil for use against American satellites," insisted the Chinese interpreter. "Your proposal is absurd. We do have some interest in the hardware and the technical plans. A very mild interest." "You _don't have any choice,_ " Tony shouted. He tried to calm himself. "Look at the geomilitary realities here. You are the two oldest civilizations in this world. You have a billion people each. But the Americans completely rule your air. The Americans have more advanced fighters and bombers than all other nations combined. The Americans completely rule your seas. The Americans have nine supercarrier battle groups and whole fleets of nuclear submarines. On land, the Americans have nine thousand Abrams tanks with the world's most accurate fire-control systems. Nobody else even has the _experience_ of the American armies—since 1985 the Americans have been the only military that still fights genuine wars. The Americans are taking over your planet by force of arms. And now, after one terrorist incident from some small cult of fanatics, the Americans feel completely justified in attacking anyone, anywhere, at any time! And with space dominance to leverage all those other military assets, the Americans _can do that._ The Americans can strike with total speed and accuracy on every square meter of this globe! If you don't move into space warfare, your militaries will be completely irrelevant." "No space weapon will ever harm the many American submarines," said Mr. Gupta wisely. "Nor would this one trifling weapon be of much use against the vast host of American satellites. However, I concur that this weapon has one important use. This weapon might be of great use in harming the Chinese space program. We Indians could rent this laser and attack Chinese photoreconnaissance assets. For instance, we could burn up the orbiting Tsinghua surveillance system, a considerable irritant in our Indian nuclear development efforts. May I ask my esteemed colleague Dr. Liang what he thinks of that prospect?" Liang engaged in consultation with his interpreter and his telephone. "We Chinese would consider that a very hostile, provocative act from the Indian nation, likely to create a nuclear crisis between our two great powers." "I fully agree with Dr. Liang. May I further ask if Dr. Liang considers it necessary to beg foreign technical assistance in order to sabotage India's peaceful space program?" More consultation. "We Chinese are entirely aware of India's space ambitions. We Chinese feel entire confidence that indigenous Chinese space technology will conclusively prove China's superiority to India's halting efforts in this regard. 'Begging' is not necessary for us. 'Begging' is more of an Indian skill." "May I point out to my esteemed Chinese colleague, as a matter of record, that India has an English-speaking population, vigorous democratic institutions, a market economy, and is rapidly becoming the planet's software powerhouse? May I further point out that Indian engineers are so very common in the United States that this _very space war weapon_ is manned by Indian engineers? China has a manufacturing capacity that we respect—but it is Indian genius that is going to lead South Asia into the twenty-first century!" "We are entirely aware of the bellicose Hindutva sentiments of Dr. Gupta! We are glad to consider outer space one area of peaceful competition, in which the Indian government does not feel driven to repeat the gruesome atrocities of Kashmir and Gujarat." "My esteemed Chinese colleague should not think that the genocidal sufferings of the Tibetan people have escaped our notice—" "Seven hundred and fifty million dollars!" Tony shouted at them. The two fell silent. "That's all! Just seven hundred and fifty million dollars was all it took to cripple a thirteen-billion-dollar American spacecraft," said Tony. "Can't you people see the amazing financial leverage in that? I didn't even ask you for that money in a lump sum!" "The Indian ISRO can send a spacecraft all the way to the Moon for seven hundred and fifty million dollars," said Gupta indignantly. "That amount of money is absurd." "No Chinese moneys will be forthcoming to you," said Liang's translator, with finality. "We Indians could build an infernal machine like this with our own strong, skillful hands," said Gupta. "We built atomic bombs and we tested them successfully in defiance of the entire world! Let no one think we Indians lack the ability and resolution to build space weapons. We scorn to do that. That is the truth: we scorn to do any such wicked thing." Gupta rose to his feet. "These negotiations are at an end." Van looked around the desk. It was true. Tony's guests were leaving. They simply opened the door and walked out in a body. Tony was abandoned there with two women: Mrs. DeFanti and the little actress. "Don't look so sad, Tony," said Mrs. DeFanti. "That was all a negotiating ploy. You are a technical genius, you have them completely dominated. Those people are mere spies, not entrepreneurs like you and Tom. What can they do but play psychological games? The Indians and Chinese can never think like Americans think. They can't treat a billion dollars like fast food. You astonished them here, Tony. Really, you amazed and impressed them very much. They'll consult with the home offices, and talk to all the elders. Then they'll come back to you." "But I can't wait while they stall for time," Tony said hollowly. "I'm past waiting. I really need to make this sale. There's nothing else left, Katrina." "I'm taking my limousine home," she told him. "Stop fretting, darling. You've always got a place with Tom." She kissed him on the cheek. Mrs. DeFanti left the observatory. Tony looked hopefully at his girlfriend. "Well, honey, by pulling that sad little snit like that, those suckers missed the very best part! I guess that situation looked pretty bad, but you know, I'm not too surprised by what they did. No, I'm not. They don't appreciate me, that's all. They can't grasp the scale of my achievement here. But you know what I'm going to do now? I'm going to do the most amazing thing that any man has ever done for a woman he loved! I am going to write your name on the Moon." Anjali Devgan didn't seem much impressed. "What does that mean?" "You'll be able to see it happening, right through this beautiful Japanese telescope. This used to belong to Tom DeFanti, and I brought it here just for you. I am _literally_ going to write your adorable name, with a laser, on the surface of this planet's satellite. A-N-J-A-L-I. That process will take about half an hour. If we get some overcast cirrus, we might drop a few pixels here and there. But, honey: it's the Moon!" "You're writing my name on the Moon in English?" "Why not?" Tony paused. "Honey, please don't do this to me. I don't have a font in Hindi." "I know that Chinese woman is your lover. She kissed you on the face in front of me! She called you 'darling.' " "I can _get_ you a font in Hindi. I just can't get it tonight." "You have no soul, Anthony Carew. You are a decadent Western intellectual. You never think of anything but your power and your money. I am sick and tired of being your concubine, Tony Carew. I don't care how many toys you give me. You are unworthy of my love. You have no home. You have no warmth of elders in your house. You cannot marry me properly as a man should marry a woman. There is no husband's mother to properly send me my sargee. You want only love without commitment, and sex without children. You have no future!" "Honey, people in the modern world can work out little issues like this." "I'm going home to marry Amitabh. That's what Bapuji wants from me." "Anjali, you can't marry that guy. Amitabh? Even as Bollywood star-children go, Amitabh is as dumb as a racehorse." Tony recoiled from her scalded look. "Okay, fine! Go marry Amitabh, have his kids! I'm willing to look right past that!" "I hate you, Tony Carew. You are evil. I should never have erred and sinned with you. My audience will forgive me my vamp roles when I give them children." Anjali looked at her jeweled watch. "I'm never going back to that ugly Chinese woman's stupid ranch house! Never! I am flying away from you in Sanjay's jet. I have a three-night engagement to dance in London. Bipasha is there, Kareena is there. I want to talk to my star sisters! They understand the sorrows of life!" "Oh, come on, _sajaana_ ___._ ___._ ___._ " "Our love affair is over, Tony. I don't love you, and I never want to see you again." She left him. Tony stood immobile. Then he turned and ran headlong for the desk. He scrabbled at the black fabric rifle case and unzipped it. He stood the rifle on its wooden butt. Trembling all over, he jammed his chin against the muzzle. Van stepped into the light. "I disarmed your rifle, Tony. Bullets equal zero." Tony glared at him with red-rimmed eyes. "Oh, for God's sake. You? What good are you to me now?" "I'm no good to you, Tony. I am the end of you, pal." Van leveled the ray gun. "What's with the titanium toy? Am I under arrest or something?" "No, Tony. You are not under arrest. I hacked you and I own you. You are an illegal combatant. It's the steel box in Cuba for you, you son of a bitch." Tony made a sudden break for it. Van cut him off, grabbed his jacket, and punched him twice in the head. Then he dragged Tony bodily across the floor of the observatory. He threw Tony headlong across a tumbling heap of metal chairs. He opened a chair. He picked Tony up and sat him down. "Now what?" said Tony, wiping his split lip. "I guess you can beat me up. What does that prove?" "I am not beating you, Tony. I am interrogating you. Are there any other ones?" Tony was stunned. "What?" "Are there other laser weapons like this telescope? Anywhere on planet Earth." "Would I _need_ another one?" said Tony. He gestured wildly. "Look at her! This is the most fantastic weapon in the world! I _built a death ray,_ man! I built a no-kidding, working death ray in the very same world that's got bubble gum and _Hollywood Squares_ and Chee•tos! I can _fry spacecraft_!" He drew a sobbing breath. "Okay, so they don't blow up all at once! Maybe it takes me a few months to destroy them! Sometimes the orbit isn't quite right, sometimes the weather is wrong. But I am _bigger than NASA,_ dude! I could take down a Shuttle." "You are a traitor, Tony. You wrecked a spy satellite for money. And you just outed me, to Chinese and Indian intelligence agents, as a part of your rotten conspiracy." Tony looked up wearily. "Van, would you stop pointing that ray gun at me? That's just really geeky. The thing melts glue, all right? It's not even plugged in." Van reached down and plugged the gun into a power strip. Van looked up in time to see Tony nerving himself to leap on him. "Forget trying to kill me," Van said. "I led my cyberwar team here. We have surveilled and recorded everything. You're toast, Tony." Tony laughed hollowly. "That's a good try, pal. You are a glorified computer clerk for an advisory board. Real military people are never gonna move one inch without clearance from SOCOM and the Joint Chiefs of Staff. I could be in Tahiti by the time those morons shuffle their paperwork." Van looked at him in wonderment. "Tony, you sold out." "Why would you even wonder at that?" Tony said passionately. "That was the whole point of living in the 1990s! Did I ever _ask_ to be born under some particular flag? I could live in Bombay. I _wanted_ to live in Bombay, the action there is amazing. I could live in Shanghai! Shanghai has got skyscrapers that make New York look like a bombed-out rathole! So what if I sold out the USA—what about the USA selling _me_ out? I don't even recognize this country since 9/11. It's mean! It's vindictive! It's aggressive! It's broke, that's the worst part. And it invades places! Your country is like a giant Serbia. The people who run it are moron oil company people. I'm a dot-com guy. I am thirty-two years old. I was right on top of the world. Then I went from genius, to bum, to bankrupt in eighteen months! I was right in the middle of the fastest, most potent, the best technological revolution in human history. I was making that happen, I was a true-blue revolutionary. It's been no time, Van, and I'm already history. I'm obsolete, I'm invisible. The sons of bitches vanished me. It's just like I was never there at all." "Tony, you used me in an act of treason. I swore an oath. I'm in the government." "What, you're wrapping yourself in the flag now? Is this Hollywood, are we cuing the violins? Me telling the Indians about you, that was just my bargaining ploy. Those Chinese didn't sign anything. It was all just an ad pitch." Tony looked at Van's face searchingly. "Come on, pal. You were never a top venture-capital guy, but you were definitely one of us. Don't you know how much you've lost already? What's left of your life?" Tony wiped at his bleeding lip. "Do you even know why I had that stupid ray gun in my stupid bag? I was going to mail it to you. From wherever. I was never gonna come back here to this creepy little version of America. I don't have to, and I don't need to. I can make another life in a better place. Let me go, Van." "You're not going anywhere." "Anywhere will do. I'm an inventive guy, I've got a big imagination. I'll just reinvent myself overnight, okay? It doesn't matter wherever you send me, because I'm global. I'll go live in some stupid leper camp in Thailand if you want. Then I'll bring the joy of broadband connectivity to the planet's illiterate masses. Wouldn't that make you happy?" "How, Tony? You angle all that, and then I do what for you? What is it you want from me this time?" "Nothing! Nothing, really! You just let me be free." Van moved his chin in a nod. "You see that large, black creature standing in the doorway over there? Standing in the only exit? Between you and all that freedom?" Tony glanced over his shoulder and yelped. "That is one of my cyberwarriors, Tony. I ordered them here so that I could demolish you." Tony stared at Van in astonishment. "What the hell are you talking about?" "Tony, al Qaeda is only fifteen years old. American Special Ops commandos have been dying in secret wars ever since John Kennedy turned them loose in 1963. These are my guerrillas, and we just defeated you and your spacewar scheme. I need to know something now, Mr. so-called Space Warrior. Your only way out of here is through my soldier. Will you kill him?" "Is this a trick question?" "Yes." "Kill him with what, exactly? You took my rifle away." "You might use this ray gun that I am pointing at your chest, Tony. Because I put one of your rifle rounds inside of it. And then I plugged it in." Tony looked at the ray gun skeptically. "You're kidding me. What the hell kind of weapon is that? You plug it in, you turn the heat on, and sooner or later a bullet explodes and somebody gets killed? That's your big concept here?" "That's cyberwar, Tony." "Look, Van, I don't want to play your weird ray gun game." " _Now_ you don't want to play it, Tony. Because I play it better than you do." Tony bent to look up the gun's barrel. "You really put a real bullet inside that cool little toy?" "Cyberwar is real." The ray gun exploded: Carew catapulted backward out of his chair. A 250-grain elk cartridge was designed to take down a bull elk at four hundred yards. It ripped a hole through Carew. Van looked down at a stinging pang in his arm. A blackened shard of metal had lodged in his flesh. There were perforations all through his black shirt. Little dust-sized bits of titanium shrapnel. He could feel the bigger ones dribbling fresh blood. Hickok walked up from the black doorway. He leaned down without a word, grasped the shard of metal, and yanked it out of Van's arm. Van gritted his false teeth and said nothing. "I'll get a field dressing on that wound," said Hickok, opening his pack. "I can't believe you just shot this bastard. Those Cyberspace boys are being so good down there. They didn't hurt even a fly." "Mike, listen to me. In information warfare, a shooting never counts for much. Media is everything. We're going to vanish this guy and all his works. We're gonna break all his tools. Nothing that happened here ever really happened. So the public never learns." "I get you, sir," Hickok said. "Those foreign techs in the Network Operation Center? Five minutes ago they were a bunch of engineers on visas. From now on they are a covert cyberterror cell. If you have to shoot them, that's fine. If they run and hide, good luck. If Ashcroft gets them, God help them. It's time to phone in some backup." "Hoo-ah, sir." Hickok dressed the bleeding wound in Van's arm with comradely tenderness. "Who exactly do we telephone about a situation like this?" "That would be the Homeland Security Computer Emergency Response Team. Oh, wait, they don't exist yet. Who's closest over here? The Air Force in Colorado Springs? Phone the damn Air Force, Mike. Get me the black helicopters." Van winced as Hickok tied off the bandage. "Demerol," Hickok said knowingly. "Yeah, Demerol," said Van. "That's wonderful stuff." Hickok examined the spreading stain of blood under Tony Carew's corpse. "Boss, we got ourselves a very dead rich guy here." "I'm ahead of the curve with that. We've got to sanitize this whole area. I've got a plan." "I knew you would have a plan, Dr. Vandeveer. Can I tell you something now? I have seen a lot of people killed. A whole lot. I stopped counting back in 1998. Nintendo wars, yeah, air strikes, yeah, collateral damage, yeah. But in all that time, I have never killed a bad guy with my own hands, no, not ever." Hickok looked Van in the eyes. "You are one tough bastard, boss. You are the true pro." "The evildoer goes straight into his weapon of mass destruction," Van said. "Aw, no, Van. Jesus." "Yes. We dump his body into the telescope. We override his weapon's operating system. We turn up those laser amps to eleven. We shut the gates to heaven. We lock that door from outside. Then we vanish this terrorist. Utterly. He is less than history, he is less than ashes. He's going to vaporize. This is an airtight building made of flammable straw. When the heat and pressure builds up in there, we are going to blow this gizmo into bits." Hickok scratched beneath his helmet. "How do we do all that, again, exactly?" "You don't do that, Mike. I do it. You stay near here and you put it all on video." Van drove the cart one-handed, in the dark, down the mountain slope. Van had a fully loaded elk rifle, a sling for his wounded arm, and an open laptop. Hickok had attached the oxygen mask to his face, rigging him an improvised black harness for the tank. With fresh oxygen inside his lungs, Van literally had a second wind. Van had blown right past fear, loathing, rage, and exhaustion into a state of battlefield glory. It was two o'clock in the morning. He had killed. He had been wounded in battle. He felt not one atomic particle of remorse or doubt. His mind had never been clearer in his life. He was exalted. The truth was, he loved war. He had never been in war before, but now he recognized war as his home. He loved war more than he loved women, food, or sleep. He would grind his teeth when cyberwarfare was denied him. In moments of peace, he would miss his dear war gone by. He would miss it so. Wimberley was waiting inside the operating center. He was standing over an unconscious technician. He was tapping at a mouse. Van set his rifle aside. "So what happened to the weapon's operator here?" "I sprayed nonlethals on his keyboard. All over his fingers, Dr. Vandeveer. That spray-on stuff is voodoo." "Too bad. I was planning to interrogate him." "No need for that, sir," said Wimberley. "I set Tempest bugs on his monitor. We got every screen shot. Every keystroke. I'm just resetting these system preferences so we can push this laser past the limit." "Can we get enough wind power to surge this weapon past its red line?" "I do think so, sir," said Wimberley. "And that power-console guy looked real surprised when I busted in there and knocked him cold." "How'd you do that?" said Van. "I used a chair leg, sir," said Wimberley. He stared at Van's wounded arm and tactfully said nothing. Another Internet technician appeared at the far end of a tall set of blue cabinets. He was carrying a hunting rifle cradled in both arms. Van made a one-handed lunge for his own rifle, but Wimberley just turned his black-helmeted head. "U.S. Cyberspace Force!" he shouted from the keyboard. "Freeze!" The technician dropped his rifle with a panicked clatter. Van heard an exit door bang open. He heard shoes rattling down a set of stairs. Wimberley returned to Van with the abandoned rifle. He checked the action expertly. "No round inside the chamber. Safety still on. He busted the scope when he dropped it, too." He returned to his screen. "You were right about the no-guns rule, sir. Guns, that's just not our way." "What does a giant laser death ray run under?" said Van. "OpenBSD. And X-Windows." "Awesome." Van had another huff of oxygen. "I can run this console. I'm controlling all the enemy's software. You know what, sir? I'm about to blow up a spacewar weapon. I'm gonna save an American satellite. Me. William C. Wimberley. This is the most important thing I'm ever gonna do in my whole life, and I'm only twenty-one years old." Wimberley looked at Van and blinked. "You didn't have to give me another chance, sir. I broke your head in." Van shrugged. "I am such a screwup. I've always been a loser. When your phone call came for me to do this, I was drunk and I was crying in my beer. I just thought, maybe he'll give me some money. I'm a pretty smart kid, Dr. Vandeveer, but I never knew who I was, or what the hell I was doing. I'm finally gonna do something here that really, really matters." Van nodded. He had heard about such things before, but he had never before seen it happen. He was seeing a troubled young man rehabilitated by his military service. "The past is over and we're gonna set it on fire," Van told him, waving him on with his free left arm. "You carry on." Van watched his laptop screen for Hickok's video surveillance. The observatory's round wall was bulging. The building warped and began gently smoldering. It was very strange to witness a weapon being demolished on a screen, thought Van. He had just been physically inside that place. He had ordered all the buttons pushed to smash it, but the resulting mayhem could have been anywhere on the planet: North Korea, Iran, Iraq. Plumes of red light. Boiling gas was squeezing itself through the curved doors to the heavens. As the gas hit fresh air, it caught in thin, livid flames. There was violent flashover as all the laser-blasted fumes within the structure ignited at once. The explosion was sudden and elegant. The walls of packed hay splayed out like a giant child puffing a dandelion. The observatory blew its top. The rounded dome tumbled headlong down the mountainside, twirling like a tossed coin. Tufts of flaming hay swirled across the blackened foundation. Bouquets of flame stuck to the molten instrument consoles. The Lady was in agony. She was blackened, on her knees. Her very bones were going. The mirror of Venus, stamped flat by the boot of Mars. When dawn broke, the black helicopters had already been and gone. The local civilians were standing around the wreckage of their telescope. Their prized handiwork was a total, tragic loss. Some of them were spraying bits of flaming hay with fire extinguishers. Most were just wringing their hands, mourning in small groups. It was an awful thing to lose a major scientific instrument. It was a cultural calamity. Gonzales offered Van a pair of binoculars. Van refused them. Van didn't care to look at people as the smoke rose from their hopes and dreams. One of them was almost certainly Dottie. "You gotta try this MRE, Van," said Hickok. "A man who's lost some blood needs to eat a meal. You learn that in combat." "Is that dogface chow?" said Wimberley, sniffing at it. "No, man, this stuff's brand-new. It's civilian MRE. Made in Brazil! Got this sort of pork loin and pineapple thing going, these really spicy black beans . . . and it's self-heating!" Van put the food across his knees. He used the fork left-handed. The food tasted great. In Brazil, people could really cook. Why did Brazil never have wars? he wondered. Brazil was a really big country on a big American continent. How come Brazil had no enemies? It didn't make sense. Brazilians didn't invent much. Well, that explained it. Van had more oxygen. His tank was low. "Here comes the enemy plane," said Gonzales. "Okay," said Hickok, climbing to his feet. "Now this is the part that an Air Force boy likes best." The Indian actor was flying his newly purchased jet plane. He had just taxied off from the DeFanti airstrip. It seemed a little odd to Van that two groups of Chinese and Indian spies would fly off across the Pacific Ocean together, all polite and collegial, inside the same aircraft. But they were people of two practical nations, thought Van, and the trip here hadn't been their idea. For a moment, Van suspected that the Boeing was out of range of the overriding radio signal. But when it came to forward air-controlling operations in the mountains, Michael Hickok knew his stuff. The jet banked hard left and roared over them so sharply that the mountainside shook. Birds exploded from the forest. Wimberley had taken off his helmet to eat. He jammed his hands over his ears. Hickok caressed his joystick. The captured jet spewed black smoke and rose in a steep arc. "Looka that," crowed Hickok. "I got 'er. Boys, this is sweet." "Okay," said Wimberley in a stunned, small voice. "You just used that black box and you pulled a jet out of the sky." Van and Hickok exchanged wary glances. Wimberley and Gonzales had not attended the Summit in Virginia. The general public was not at all up to speed about cyberwar projects to control civilian jets. "Yeah, I did that," Hickok told him, grinning. "Now watch me put 'er into a slow loop over the telescope ground zero there. That aircraft is chock-full of Indian and Chinese space spies. Can you imagine the nerve of those clowns? They're supposed to hate each other! Everybody knows they hate each other! But here they are, infiltrating our own country, and picking on my favorite satellite. I have got them right by the throat!" Wimberley stared at Van. "You can really grab jets out of the sky?" Van nodded. "Who the hell are you?" Wimberley demanded. He was shaking. "Where did you come from? What world is this?" "As long as he's on our side, what difference does that make?" said Hickok. "It's time to settle the hash of the Space Invaders here. Hey, Fred! Did you make that Indian Special Ops guy, that actor with the pecs and the biceps?" "I saw him," growled Gonzales. "Those Indians sure like 'em pretty. I hate a pretty spook." "That actor is the pilot up there. Check this out." Hickok slapped at his joystick. The jet careened violently. "He's a real hot dog, isn't he? He loves to push the envelope!" "No need to be cornball," said Gonzales. "Special Ops are 'the Quiet Professionals.' So fly them straight out into middle of the Pacific. Fuel runs out, then they go straight into the drink. That's quick and it's quiet." "The middle of the Pacific is way beyond radio range," said Hickok. "And that's too slow. I'm thinking a fast power dive straight onto the top of that mountain yonder." "We are letting them go," Van told him. "What?" Hickok demanded. "Then why did we just catch 'em?" "We are letting them go because only punk-ass al Qaeda losers crash airplanes. We caught them to show that we can catch them. We have destroyed the space weapon here. They see that. We own them. They know that. They have no idea who we are. They only know that we are in America, and that we own them. If we kill them now, that sends a message. It says that their resistance matters, so we want to kill them. If we send them back to their bosses, then they _become_ our message." "What the heck kind of message is that?" said Hickok. "Can't we just wipe 'em out? That would do." "That message is: Our command of technology is beyond conventional military resistance. The conventional military struggle between nations no longer matters. We are the agents from a new geopolitical arena. It's time to carry out our struggles in a new, improved way." "What kind of cockamamie war doctrine is that?" Hickok demanded. "It's cyberwar!" said Wimberley. "It's information warfare," said Gonzales. "It's like media spin or something. Am I right?" "They are human beings in there," said Van. "We need to convince them of something important right now. They need to believe that it's cyberwar or it's bloody-handed terror suicide, and those are the only kind of wars that get allowed. Now we can make that distinction clear to them. Let them fly back home, Mike." "Okay," said Hickok. "I know that you know that. What I wanna know is _—how_ do you know that?" "I was inside that plane once," Van said. "That's how I know." PENTAGON CITY, SEPTEMBER 2002 Van woke up. It was his birthday. He stared at the cigarette-stained ceiling. This was pretty sure to be the worst birthday of his life. The federal refund money for the Grendel system had finally come in. That was the pool of cash that he and Dottie were both living on. This was a small miracle, and he was grateful for it, because the CCIAB no longer existed. Quick, quiet, and done with its work, it was not even a Washington memory. Just another blue-ribbon panel, offering wisdom to power. It was as if Van's labors had never been. Van had never expected such a strange reaction from Washington's establishment. He had run a black-bag operation, shot a man, blown up a multimillion-dollar scientific instrument, and captured and released highly placed agents from two foreign intelligence agencies. Van had imagined that they might either arrest him, and put him on trial, or they would give him a secret medal. It had never occurred to Van that he would blow their minds so badly that they would do nothing at all. The ruined observatory was, officially, the victim of an accidental fire. Officially, Tony Carew had vanished. Better yet, he had vanished in India. Strange news about Tony was all over the Bollywood film magazines. According to the tabloids, he had vanished on a hunting trip to the Himalayas. Nobody had gone to India to look for Tony. Nobody seemed to care about a ruined entrepreneur from the Bubble. He'd been a star's plaything and once she had dumped him, there was nothing left of him but a kind of black vacuum. Derek Vandeveer was also a nonperson. Jeb had a new job handling security with eBay. Fawn had a nice federal post. Michael Hickok, as a policy, never explained to anyone what he was doing. Van was left alone. Van's phone did not ring with eager job offers. His e-mail bore no pleas and flattering invitations. Van wasn't looking for any job in computer security, anyway. Van wasn't exactly looking for much of anything, really. He was searching. He was running a small Web log. Nobody seemed to understand Web logs yet. Van had one. It was a quiet, fast-paced Web log. He used it to absorb and spread ideas. Van's Web log involved genuine issues. The genuine issues were the issues that political people lacked clichés for. Web logs interested Van. There was no money in them, yet, and the political campaigners were just catching on. Web logs were in combat for attention. That was the most interesting thing about them. Combat for attention. War of ideas. In his deep exile, Van was doing a lot of reading. His field of study was war. He was reading Clausewitz. Clausewitz was a dolt. He was reading Lidell-Hart. Lidell-Hart was full of himself. He was reading Miyamoto Musashi. Musashi was a New-Agey Zen mystic. He was reading Sun Tzu. Sun Tzu had some rather interesting stuff going on. Official Washington was avoiding Van. Van understood this. He was no more welcome to the official power structure than Watergate burglars and Iran-Contra conspirators. Washingtonians avoided such people while the heat was still on them. The wheel moved back around, eventually. Then the malefactors became talk-show hosts. Van was earning a little pin money by working on a rollout of Bastille Linux. He was also drinking rather a lot. It was hard for a warrior not to drink when he was kept away from the action. He had discovered a fondness for big pint cans of Foster's Lager. Once he had been bright, whimsical, inventive. Now he was dark, dangerous, inventive. The loss of her telescope had brought Dottie's career to a shattering halt. She left Colorado and brought Ted with her to share Van's life. The family was broke, and living in a tiny, unfurnished duplex in Pentagon City. They had no careers, few prospects, large tax debts, and a host of personal humiliations. They had no offices, and both had to work underfoot in the grimy nook that called itself a living room. That was also where Ted had his playpen. If times were hard in computer science, they were brutal in astronomy. Dottie's people were cutting budgets past the bone. Dottie's blighted résumé included a lot of public relations work for an astronomical facility that had somehow burned down its telescope. Through no fault or intention of her own, Dr. Dottie Vandeveer had wandered into a world of hurt. Dottie looked pale and drawn lately. Her face was lined, her brown hair showing strands of gray. Van rose from the bed. He showered, ignoring the mildew in the grout. He went into the soot-stained kitchen in a T-shirt and underwear. The four new chairs in the kitchen had red bows on them. "Happy birthday, honey," Dottie told him. "Wow," Van blurted. "Magnesium chairs!" "You like them?" "They are the best!" "I got them secondhand for you!" Dottie crowed. "Barely used! They were so cheap!" Van sat in one of the metal chairs. His ass felt metallic and cold through his white cotton underwear, but the chairs had always been a lot more comfortable than they looked. "Four of them, wow!" he said loudly. He sipped his instant coffee. "That's just great! You are so good to me, babe." He nibbled some burnt toast. Dottie perched in one of the chairs. "Derek," she said shyly. Van looked at his wife. He knew instantly, in his gut, that Dottie was about to tell him something dreadful. She was using her kindest, sweetest voice, the kind she used when tactfully urging him toward something that would have great rusty fangs like a bear trap. Dottie looked pained and greenish—she'd hardly been eating in the mornings, maybe a sip of coffee, a nibble off a stale doughnut. He had married a proud, shy, lonely, vulnerable young woman with an intellectual gift. And now, in his care, and due to him, she was reduced to . . . what? She was a soldier's wife, he thought. A woman who made do. He was one of the world's secret soldiers. They had become hard, gritty, wounded people with bitter lines around their mouths. What did the future offer them? "Derek, something important has happened . . ." Van moved to the edge of his new chair. "What?" "You're going to have me around a whole lot. You're going to have me on your hands all the time." Dottie rubbed her forehead. "This is my birthday present for you, but you're really going to have to put up with me now, honey . . ." What on earth was the woman rattling on about? Why didn't she cut to the chase? "Derek, I'm pregnant." Van absorbed this input. Where was Ted? he thought instantly. Ted really needed to hear this news. This was going to be of enormous importance to Ted. "I know this is a bad time for us to have a baby . . . But, you know, the only job offer I've got is in Denmark . . . Oh, God, Derek, I've been so careless and stupid . . . I can't believe that happened. It just ruins everything. After all this, things are so bad for us, and now I'm pregnant." Dottie burst into sobs. Van felt something extraordinary happening within him. A dead black crust was breaking open. He had known no word for that feeling until it began to lift away from him under tremendous internal pressure. But now he knew what that feeling had been. It was grief. It was grief. Now the black grief was receding from him. It was blasting away from his heart at half the speed of light. Something inside him that had been tiny and sparklike and bitterly embattled was expanding like a vast red star. He was huge inside. He glowed and burned. He had gravity. "Baby, that is great news. You are saving our lives here." Dottie lifted her head. Her morale was in visible ruins. "I get so sick, with that morning sickness. I get so helpless . . ." "This is the best birthday gift I've ever had." She blinked in disbelief. "You really think so?" "I don't think so. I know so. Four people in our family, that is like a little squad. We'll get really quick, and stop complaining so much from now on. We'll change our lazy habits. We'll get things done whenever they need to get done." "Derek, this will ruin our careers." "No it won't. Your career will move right on. You will take that job in Denmark. I will look after our kids." Dottie's eyes widened. "We're moving to Denmark?" "Yeah. We're gonna sell everything here and we'll move to Europe. Right away." A hectic flush rose to Dottie's cheeks. "What, even these chairs? But I just bought us this furniture." "Honey, Europe is well known for its furniture. These are European chairs." "What about _your_ career, Derek?" "I know what I'm doing. Honey, it is senseless for intelligent people not to have children. Why would I want to vote against the future? What we need is a good strategy. And I've got one for us. You will work. I will stay home with the children." "Really?" "Yes." "You'd make that sacrifice for us?" "What sacrifice? I love the idea of two kids. I need this. It'll be broadening for me. Am I nailed here in Washington, for any reason? I can hit a RETURN key anywhere in the world." Though it was his birthday, Dottie needed consoling. He lavished some on her. That worked. Dottie was still weeping in happiness as they lay in bed together. Van stared silently at the ceiling. It was a very good move for him to get out of Washington. A lateral move, very Liddell-Hart, very Sun Tzu. When power avoided you, a counteravoidance move lured power back in. His wife didn't need to know this, but the Administration had way too many people like himself, wandering loose. Now that Van had learned, by startling counterexamples, something about sound and competent governance, he was very aware that the Terror was just the Bubble by another name. It was just as wild, just as turbulent, and just as unlikely to last. No government that was not desperate and totally winging it ever, ever would have asked Dr. Derek Vandeveer to become a warrior. And yet he had done just that. Odder yet, he had grown to understand the war. He had the scars to prove it. He had become the kind of person who could shift a world's destiny through acts of organized violence. He had become a professional. And his profession was always going to be something that didn't quite exist. The profession of cyberwarrior was always mostly going to be about lying low. The indirect approach, as Liddell-Hart liked to put it. The leak. The putsch within darkness. The patient stalking. The compilation of databases. The cybernetic awareness. The brief and devastating strike. And the silent exfiltration. And the wait. The Terror was merely an overexcited phase, and like the Bubble, it was going to burst of its own hype. And when it did pop, it would be a rather good thing not to be visibly holding the bag. To be, say, a low-key house husband living in distant Europe. Raising two little kids. Two days later, as he was watching the bidding for his possessions on eBay, Van's phone rang. "Vandeveer." The voice on the phone was distant and laggy. "Van? Kind of a blast from the past here. This is Jimmie Matson! You remember me? We used to work together!" Van paused. He could place the voice before the memory came. Of course. Jimmie Matson at Mondiale. His top lab exec. Why hadn't Jimmie from Mondiale just said "It's me, Jimmie from Mondiale"? Of course, Van realized, Jimmie had his reasons not to say such things. Nobody from Mondiale ever said "Mondiale" now. "Of course I remember you, Jimmie. What's up?" "So, I just saw on your Web log that you're thinking of moving to Denmark! Well, I'm here in Switzerland." "How come?" "I got a post here, a kind of liaison committee . . . The WIPO and the World Telecommunications Union . . . plus some WTO people . . . Well, it's hard to explain in a few words, Van, but policy here is a major mess." "Try me." Jimmie sighed into the phone. "Van, I so wish I'd gotten that great post you wanted for me at the CCIAB. But the feds weren't having any of me, for security reasons I guess . . . Anyway, it is just so impossibly bad up here on the global level . . . You would never believe what is going on behind the scenes here in Geneva . . . The French and Germans really get it about the American hyperpower thing, they are all over our case diplomatically . . . All the delegates here hate each other, Van. They hate each other, they can't speak the same language, and they are crooked. Plus they have no idea what they are trying to do, technically. That is the worst part. They've got nobody to fill this job of technical director." "Right." "I thought of you for that job, somehow. I mean, it's an international bureaucracy job, not much for a guy of your caliber, but there's health insurance and a nice subsidized apartment . . . Beautiful headquarters building right on the lake. Really pretty. You've got to hand 'em that." "They need someone there to knock heads," Van said. "Uh, yeah. Officially, this post calls for an executive with advanced technical skills who has had private-sector international telecom experience and has also served in an advanced capacity in a major government. There's just one hitch. There is no such guy. And if there was . . . Well, no guy in the world who had done all those things would ever want to come and get involved in this. This is like trench warfare." "I just did all that. I'm used to it." "I gotta warn you, Van, this scene feels pretty hopeless!" "Hope is not a feeling, Jimmie. Hope is not the belief that things will turn out well, but the conviction that what we are doing makes sense, no matter how things turn out." Jimmie said nothing for a long moment. Then he spoke in a new voice. "Van, how long have you been reading Vaclav Havel?" "Oh, President Havel has been a favorite of mine for some time now," said Van. "Could you fly over here right away, please? I mean, like, _right away._ " "I'll be doing a lot of commuting to Denmark." "They've got great trains in Europe," Jimmie said. "Fine. You make arrangements. I'll be bringing a small child with me, so book me two seats." "All right. Can you take the next plane?" ALSO BY BRUCE STERLING The Artificial Kid The Difference Engine (with William Gibson) Distraction Globalhead A Good Old-Fashioned Future The Hacker Crackdown Heavy Weather Holy Fire Islands in the Net Schismatrix Tomorrow Now Zeitgeist This is a work of fiction. Names, characters, places, and incidents are the products of the author's imagination or are used fictitiously. Any resemblance to actual events, locales, or persons, living or dead, is entirely coincidental. A Del Rey® Book Published by The Random House Publishing Group Copyright © 2004 by Bruce Sterling All rights reserved under International and Pan-American Copyright Conventions. Published in the United States by The Random House Publishing Group, a division of Random House, Inc., New York, and simultaneously in Canada by Random House of Canada Limited, Toronto. Del Rey is a registered trademark and the Del Rey colophon is a trademark of Random House, Inc. www.delreydigital.com Library of Congress Cataloging-in-Publication Data is available from the publisher upon request. eISBN: 978-0-345-47832-0 v3.0
{ "redpajama_set_name": "RedPajamaBook" }
1,509
My dearly beloved daughter, let it be known that death has no power over those of Mine, whose faith has sustained them right up to their last breath. These souls have no fear of physical death because they know that Eternal Life begins at that time. I await such souls with open arms and they run like little children towards the Light of My Love. I embrace them and take them into My Kingdom, awaiting each and every such soul in the presence of the Hierarchy of Angels and all the saints – then great rejoicing takes place. I reunite them with their families and there is much joy, love and excitement. No more tears. No memories of the sufferings, which they endured on earth, remain. All worries, sadness and despair are wiped away and forgotten, in an instant. Death opens the door for those who die in a state of Grace as new life begins. For every soul who is welcomed into My Kingdom, there are different levels, and each one is accorded their reward, based on the Glory, which they have given to God. For souls who die in a state of sin, know that I Am All Merciful and, after their purification, they will be welcomed into My Kingdom. Always pray for such souls because they cannot pray for themselves at that stage. Your prayers will be heard and I will await these souls with open and loving arms. It is important for every child of God to understand one important thing about life after death. You must ask Me, Your Jesus, to forgive you; your failings; your weaknesses and your iniquities, before you die, for it is then that My Mercy is at its greatest. If you do not believe in God, you reject Eternal Life. Without love for God, love cannot be yours after death. I Am Love and without Me, you will feel nothing but pain. Separation from God is to be feared. If you feel confused about My Existence, then you must simply ask Me to show you a sign of My Love, and I will respond. Do not cut yourself off from Me. If you do, there will be great weeping and you can never be consoled, for I will be unable to help you. My Kingdom will give you Eternal Life but you must ask Me for My Help by reciting this prayer. Jesus help me to believe in Your Existence. Give me a sign so that my heart can respond to You. Fill my empty soul with the Grace that I need to open my mind and my heart to Your Love. Have Mercy on me, and cleanse my soul from every wrongdoing, that I have committed in my life. Forgive me for rejecting You, but please fill me with the love that I need, to be made worthy of Eternal Life. in every beautiful Gift which You have given the human race. Help me to understand Your Ways and save me from the separation and the pain of darkness that I feel in my soul. Amen. Do not allow human pride, intellectual analysis or opinion to sway you from the Truth. As a child of God you are very precious to Me. Do not let Me lose you. Come. I Am Here. I Am Real. Let Me fill your soul with My Presence. Once that happens you will find it difficult to ignore Me. I love you all. I bless you. I await your response.
{ "redpajama_set_name": "RedPajamaC4" }
6,584
Chicago: "Ten O'Clock News," 08/15/1989, WGBH Media Library & Archives, accessed April 18, 2019, http://openvault.wgbh.org/catalog/V_A0CDEA7C4DC34769B51080E66561DAA8. MLA: "Ten O'Clock News." 08/15/1989. WGBH Media Library & Archives. Web. April 18, 2019. <http://openvault.wgbh.org/catalog/V_A0CDEA7C4DC34769B51080E66561DAA8>.
{ "redpajama_set_name": "RedPajamaC4" }
2,769
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.prometheus.client.utility</groupId> <artifactId>jvmstat</artifactId> <parent> <groupId>io.prometheus.client</groupId> <artifactId>utility</artifactId> <version>0.0.9-SNAPSHOT</version> </parent> <name>Prometheus Java Instrumentation Helpers for Hotspot VM's jvmstat</name> <url>http://github.com/prometheus/client_java</url> <description> The Prometheus Java Instrumentation Helpers for Hotspot VM's jvmstat </description> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> </license> </licenses> <scm> <connection>scm:git:git@github.com:prometheus/client_java.git</connection> <developerConnection>scm:git:git@github.com:prometheus/client_java.git</developerConnection> <url>git@github.com:prometheus/client_java.git</url> <tag>HEAD</tag> </scm> <developers> <developer> <id>mtp</id> <name>Matt T. Proud</name> <email>matt.proud@gmail.com</email> </developer> </developers> <dependencies> <dependency> <groupId>io.prometheus</groupId> <artifactId>client</artifactId> <version>0.0.9-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <encoding>UTF-8</encoding> <docencoding>UTF-8</docencoding> <linksource>true</linksource> </configuration> <executions> <execution> <id>generate-javadoc-site-report</id> <phase>site</phase> <goals> <goal>javadoc</goal> </goals> </execution> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>release-sign-artifacts</id> <activation> <property> <name>performRelease</name> <value>true</value> </property> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.4</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <!-- Before fiddling with this profile settings here, please carefully read the Javadoc contained in JvmstatMonitor. It explains that the use of this Maven module requires the HotSpot/OpenJDK tools.jar to be included in the classpath. Since this is required for use, it is also required for compile-time validations of this module; thusly, we have included it here. --> <id>default-tools.jar</id> <activation> <property> <name>java.vendor</name> <value>Oracle Corporation</value> </property> </activation> <dependencies> <dependency> <groupId>com.sun</groupId> <artifactId>tools</artifactId> <version>1.4.2</version> <scope>system</scope> <systemPath>${java.home}/../lib/tools.jar</systemPath> </dependency> </dependencies> </profile> </profiles> </project>
{ "redpajama_set_name": "RedPajamaGithub" }
3,288
The Mirafit Multi Gym Lat Pull Down Machine is a really versatile piece of kit and allows you to perform seated rows, arm curls, push downs and weighted ab crunches, as well as lat pull downs. Adjust your weight load easily for precision training. Please note: tools required for assembly are not included. Amazing piece of kit for the money. The cables run smoothly through the runners and you can add plenty of weight. Took me around 2 hours to put together and is very sturdy. I would certainly recommend this for anyone looking to put together a gym at home. You can also buy attachments online which will widen the range of exercises you can do on the machine. You can work back, biceps, triceps and shoulders so it's a no brainier really. The instructions to put this together are not the best, they could do with a update. Didnt take too long to put together. The only issue i had with this bit of kit is the fact i needed to go buy some solicone oil to lube the runners etc. It will not run perfectly smooth like you typical commecial gyms but with a small smount of silicone oil should help. Otherwise youll feel where the pulley likes to stick in places. In my opinion they should put a small 10 ml bottle of oil with this product so you have some knowledge of using it in the future. Overall this is a 100% perfect purchase for your home gym as its a needed bit of kit. This is a really well put together bit of kit yet highly understated! An example of this is "arm curls" are mentioned above. I do overhand and underhand curls and hammer curls (with rope attachment). With an inexpensive length of chain overhead tricep extension are done (burny triceps).
{ "redpajama_set_name": "RedPajamaC4" }
1,737
The St. Louis Blues are the 2019 Stanley Cup champions and we're just as surprised as you Written By Jackie Spiegel (Getty Images) https://images.daznservices.com/di/library/sporting_news/14/f2/blues-with-the-cup-061319-getty-ftrjpg_116ixdfzmkt6g14maawcyflagu.jpg?t=1333590899&w=500&quality=80 The St. Louis Blues are the 2019 Stanley Cup champions. I repeat, the St. Louis Blues are the 2019 Stanley Cup champions — and, just as we were on March 29 when they clinched a playoff spot, we're a little surprised. Craig Berube on clinching a playoff spot: "It's a big thing, where we were and where we are now, but we're not finished." #stlblues pic.twitter.com/87ImXARqO6 — x - St. Louis Blues (@StLouisBlues) March 30, 2019 Why, you may ask? Well, before games were played Jan. 3 — yes, Jan. 3, 2019 — the team from Missouri was last in the NHL and 11 points behind the Anaheim Ducks for the last wild-card spot in the Western Conference. Now, St. Louis is bringing Cup back to its home state. MORE: Get Blues championship gear What a long strange trip this season has been for the Blues: Before we can even start with how this happened, we need to go all the way back to November with the firing of coach Mike Yeo and the promotion of associate Craig Berube . "Chief" took over a team that was 7-9-3. At the time, people thought Joel Quenneville, who was let go by the Chicago Blackhawks two weeks earlier, would be tapped, given that he had previously coached the Blues for parts of eight seasons (1996-2004). Nope. Quenneville was enjoying tailgating with Bears fans and looked content to be off the bench, so Berube was chosen to fill in and finish out what was looking like a lost season. If things couldn't get any worse for St. Louis, teammates fought at practice. Not a good look for a team well outside the playoff race and losers of eight of their last 11. Robert Bortuzzo and Zach Sanford dropped the gloves at #STLBlues practice today. (via @Avery_188 ) pic.twitter.com/7rLxpies6g — Sporting News Canada (@sportingnewsca) December 10, 2018 Robert Bortuzzo, who fought Zach Sanford, reflected on the incident March 25 with Blues radio analyst Joey Vitale on "The Late Shift" "It's something that happens in our game. It's nothing I'm proud of and something that I don't want to be doing," he said. "But it had nothing to do with (Sanford). We're good friends and it was just a sequence of events that led to something unfortunate." As stated above, the season was looking grim on this date. Before games started that Thursday night, St. Louis was 15-18-4 (34 points) with a minus-21 goal differential and dead last in the league. That night, the Blues went out and beat the reigning Stanley Cup champion Washington Capitals 5-2. Sure, one game doesn't turn the tide, but maybe Bortuzzo dropping the gloves with Tom Wilson — who was suspended earlier in the season for 14 games for a dirty hit on Oskar Sundqvist — played a role. MORE: How 'Play Gloria' became the Blues' rallying cry St. Louis recalled 25-year-old goaltender Jordan Binnington from San Antonio (AHL). Two days later, he made his first start of the season and his career. The rest has been history. Beginning with his 3-0 shutout of the Philadelphia Flyers on Jan. 7, the 2011 draft pick has posted a 21-5-1 record with an impressive 1.78 goals-against average and .932 save percentage. Jordan Binnington of the @StLouisBlues became the 35th goaltender in League history to register a shutout in his first career NHL start and the eighth to do so in the past 15 years. #NHLStats pic.twitter.com/XipaVcRYIQ — NHL Public Relations (@PR_NHL) January 8, 2019 Jordan Binnington notched his first NHL start and shutout on the same day he was announced @theAHL player of the week. You could say last week was pretty good to him 👍 pic.twitter.com/R4hUT5UHav — San Antonio Rampage (@sarampage) January 10, 2019 Binnington, who eventually took over the No. 1 spot from Jake Allen, has had his name thrown into the Calder Trophy and, dare we say, Vezina Trophy debates. He has earned Player of the Week honors twice this season (second star on Jan. 14; first star on Feb. 11) and was the NHL's Rookie of the Month for February. Jan. 23-Feb. 19 Twenty-eight days. In just 28 calendar days, the Blues changed their season. After losing 4-3 to the Kings on Jan. 21, St. Louis went on a tear, winning a franchise-record 11 consecutive games. After going from a game under. 500 (21-22-5) to 10 games over (32-22-5), the Blues were suddenly in a playoff spot and poised to make the postseason for the 42nd time in franchise history. The streak included wins over the Tampa Bay Lightning (1-0 in overtime) and Toronto Maple Leafs (3-2 in overtime) and back-to-back victories over the Nashville Predators (3-2 in regulation and 5-4 in overtime), who, as of now, look to be the Blues' first-round opponent in the playoffs. Over the course of those 11 games, St. Louis went 493 minutes and 42 seconds without trailing. Rookie sensation Binnington won nine in a row — tied for fifth-most by a rookie netminder in NHL history. The team's points leader, Ryan O'Reilly, scored 12 points. Vladimir Tarasenko notched an awe-inspiring 20 points (10 goals, 10 assists). Tarasenko, whose name was in the trade rumor mill in the beginning of January , was named the NHL's third star of the month for February. Things were looking up even more when Brayden Schenn was activated March 6 from injured reserve after missing the previous six games with an upper-body injury. Just a day later, things took a turn and the Cinderella season looked to be in peril. Leading goal-scorer Tarasenko suffered an upper-body injury during a 4-0 victory over the Los Angeles Kings in which he scored the 28th goal of his season. The team announced he would be out for 10 days . The Blues went 1-2-2 in the five games he missed and were outscored 13-11, with five of the team's goals coming in the lone victory, 5-1 over the Pittsburgh Penguins. The Blues got healthy. Tarasenko returned, and as if in direct correlation, the team won four in a row, including victories over the Lightning and the Vegas Golden Knights. Just three nights before Tarasenko's return, David Perron returned to the lineup after missing 24 games with an upper-body injury. In the seven games since his return, he has seven points (four goals, three assists). He also closed out a remarkable streak in his fourth game back, March 21 against the Detroit Red Wings. David Perron recorded the fourth instance in @StLouisBlues franchise history of a player recording at least one point in 17 consecutive appearances, joining Brett Hull (25 GP in 1991-92, 20 GP in 1989-90) and Blake Dunlop (19 GP in 1981-82). #NHLStats #DETvsSTL pic.twitter.com/yvSRpeYMU2 — NHL Public Relations (@PR_NHL) March 22, 2019 Welcome to the 2019 Stanley Cup playoffs, St. Louis! You did it! WE'RE IN!!!! https://t.co/aAjs9kXe6a #stlblues pic.twitter.com/eYrWzpq7Om Despite losing to the New York Rangers on March 29, the Blues clinched when the Arizona Coyotes lost to the Colorado Avalanche in a shootout. Since that key Jan. 3 date, St. Louis went 30-10-5 to close out the regular season and become the seventh team since expansion in 1967 (which was also when the Blues joined the NHL) to make the postseason after being in last place after New Year's Day. Those 30 wins were also the second-most in the NHL since Jan. 1. It took 49 years — or exactly 17,908 days since May 10, 1970 — but the St. Louis Blues are back in the Stanley Cup Final. As it so hapens, the last franchise they faced in the Stanley Cup Final is the same one they'll face this time — the Boston Bruins. The moment that's a half-century in the making! pic.twitter.com/Ws9k3WrYxV — St. Louis Blues (@StLouisBlues) May 22, 2019 After defeating the Winnipeg Jets in six games, the Dallas Stars in seven and the San Jose Sharks in six in the West playoffs, the Blues are just four wins away from the first Stanley Cup championship in franchise history. The Blues lifted the Cup for the first time after getting that fourth win, a 4-1 Game 7 triumph over the Bruins in Boston, the city where Bobby Orr broke the franchise's young hearts 49 years earlier. This time, St. Louis took a 2-0 lead in the first period and never let the B's get back into the contest. They iced the title with two more goals in the third. Every season has a Cinderella team, a team with an amazing story. Worst-to-first St. Louis was the team this year. The glass slipper fits. SN's Tom Gatto contributed to this report. Contact Privacy Policy DAZN Group Careers Shop
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
1,247
{"url":"https:\/\/math.stackexchange.com\/questions\/2365031\/the-banach-tarski-paradox-and-the-notion-of-measure","text":"# The Banach-Tarski paradox and the notion of measure\n\nWas reading through this question and the answer given by @triple_sec lists some mindboggling results that are implied by the axiom of choice.\n\nSpecifically:\n[Geometry] Banach\u2013Tarski paradox. (The axiom of choice makes it possible to cut an object into a finite number of pieces in such a weird way that you can reassemble two copies of the same object of the same size!)\n\n[Measure theory] Existence of sets that are not Lebesgue measurable.\n\nHow do we make sense of the Banach-Tarski problem? The reason I pointed out the existence of non-measurable sets made me think perhaps the paradox from Banach-Tarski theorem arises because we are \"incorrectly\/inconsistently\" [I am not entirely sure how to formalize this notion] measuring these pieces of the ball.\n\nWe can't take a ball of chocolate and cut it up and re-assemble it into two balls of chocolate, both as large as the ball of chocolate was to start with, can we? Of course not!\n\nQuestion: Is AC necessarely the culprit? Is the paradox invariant w.r.t the definition of measure (area\/volume?) of a set?\n\n\u2022 What are you asking exactly ? \u2013\u00a0user171326 Jul 20 '17 at 13:39\n\u2022 AC is the culprit because we need AC to show that there are non-measurable sets, which are in turn the culprit of the paradox. The paradox is not invariant with respect to the definition of measure, but Lebesgue measure is an analog of physical volume\/area\/whatever, so that's why the paradox can be phrased in terms of a physical object and size as a sort of loose description. \u2013\u00a0Jonathan Hebert Jul 20 '17 at 13:47\n\u2022 I don't think you should try to relate Banach-Tarski and the real world, as the first one is a purely mathematical phenomenon without any connection to the real world. If you want to get a feeling for Banach Tarski, the big point is that this is true for the free group with two generators. Once you know it, you can prove that there is a group of rotations which generate $F_2$ and finally apply axiom of choice for \"cover\" the sphere by lot of copies of $F_2$ and picking a representant in every copies. \u2013\u00a0user171326 Jul 20 '17 at 13:50\n\u2022 We can't cut a ball of chocolate to five pieces and assemble two. But we are not mathematical objects nor a chocolate ball is a perfect continuous ball, nor reality as we experience it is continuous, but rather very much discrete and finite. \u2013\u00a0Asaf Karagila Jul 20 '17 at 13:53\n\u2022 The problem is that you cannot really measure all sets in space in many models of set theory. AC does not allow it, nor does CH, etc. it's not the inconsistency of any measure, we can make consistent measures, but those paradoxical sets from B-T, or Vitali sets, or sets from free ultrafilters etc. will not be measurable for any \"sensible\" measure. Maybe wanting to measure all sets is too much to ask for. \u2013\u00a0Henno Brandsma Jul 20 '17 at 14:02\n\nDo you expect all functions $f\\colon\\Bbb R^3\\to\\Bbb R^3$ to be linear? Or at least polynomial? Or at least analytic? Or at least smooth? Or at least continuously differentiable? Or at least continuous? Or at least Baire measurable?\n\nWell, no. We know that amongst the functions, the continuous ones make very few of them. We know that amongst the continuous functions those which are differentiable make a negligible set, let alone polynomials or linear transformations.\n\nWe know that most of the objects we are interested in are themselves the pathological ones, and those things we call \"pathologies\" are in fact the common law of the mathematical land.\n\nSo why do we expect that all the sets of reals, or the plane, or the Euclidean space should be Lebesgue measurable? We shouldn't. Because it does not sit with the rest of the mathematical results that we have so far. Only with our wishful intuition, which itself gets rebuilt over time in order to accommodate these sort of facts. (To paraphrase von Neumann, you don't understand this, you get used to it.)\n\nChoice is certainly not the culprit. Rather it is the mixture of Infinity and Power Set which allow us to prove the existence of all manners of odd sets. Sure, it is consistent that the axiom of choice fails and the Banach\u2013Tarski theorem fails too. So to some extent, you could argue this is choice's fault. But in all these models we can partition the real numbers into more sets than numbers. So we can also partition $\\Bbb R^3$ into more sets than points. And if that is not a paradoxical decomposition, I don't know what is.\n\nThe Banach-Tarski paradox shows that (assuming AC) there can be no finitely additive full (i.e. defined for all subsets) measure (so weaker than Lebesgue measure, which is countably additive) on $\\mathbb{R}^n$ for $n \\ge 3$ that is preserved by translation and rotations. The \"paradoxical sets\" cannot be measurable for any such finitely additive measure that agrees with Lebesgue measure where possible (so that spheres have their usual volume\/measure).\n\nIn fact Banach himself had shown earlier that there is a finitely additive measure on $\\mathbb{R}^2$ (that agrees with Lebesgue measure when both are defined) defined on all subsets of the plane, and which is preserved by translations and rotations. (And also on $\\mathbb{R}$ for translations) This shows that the Banach-Tarski paradox is impossible in the plane or the line.\n\nSo the problem really is that you cannot measure everything at the same time (only nice sets like the Lebesgue measurable ones), in a nice invariant way. Vitali showed (using AC) that we cannot have a countably additive translation invariant full measure, and even CH shows this without AC (as Ulam showed). The existence of a full countably additive measure on the reals that extends Lebesgue measure implies the existence of a so-called real-valued measurable cardinal $\\le \\mathfrak{c}$ and cannot be shown from ZFC alone.\n\n\u2022 I do not think the first sentence says what it is supposed to say. \u2013\u00a0bertram Jul 20 '17 at 14:12\n\u2022 Thanks for editing. I still don't think it says what it is supposed to say: somewhere should be the words \"defined for all subsets\". (Sorry to be nitpicky; the current formulation seems likely to confuse beginners.) \u2013\u00a0bertram Jul 20 '17 at 14:18\n\u2022 @bertram You're right; I do mention it later. \u2013\u00a0Henno Brandsma Jul 20 '17 at 14:20\n\u2022 Isn't the counting measure on $\\Bbb{R}^3$ full, finitely additive and invariant by translations & rotations? \u2013\u00a0mattecapu Feb 21 '18 at 19:23\n\u2022 @GabrielRomon wikipedia mentions it, I think I read about it in the Stan Wagon book on the Banach-Tarski paradox. According to his own answer it's indeed in his book. \u2013\u00a0Henno Brandsma Jul 19 '18 at 16:46","date":"2020-01-23 20:22:11","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.8038203716278076, \"perplexity\": 360.94509423281727}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2020-05\/segments\/1579250613416.54\/warc\/CC-MAIN-20200123191130-20200123220130-00221.warc.gz\"}"}
null
null
#ifndef CookieManager_h #define CookieManager_h #include "CookieMap.h" #include "ParsedCookie.h" #include "Timer.h" #include <BlackBerryPlatformGuardedPointer.h> #include <wtf/HashMap.h> #include <wtf/text/WTFString.h> namespace WebCore { class CookieDatabaseBackingStore; class KURL; enum BackingStoreRemovalPolicy { RemoveFromBackingStore, BackingStoreCookieEntry, DoNotRemoveFromBackingStore }; enum CookieStorageAcceptPolicy { CookieStorageAcceptPolicyAlways, CookieStorageAcceptPolicyNever, CookieStorageAcceptPolicyOnlyFromMainDocumentDomain }; /* * The CookieManager class is a singleton class that handles and selectively persists * incoming cookies. This class contains a tree of domains for quicker * cookie domain lookup. The top of the tree represents a null value for a null domain. * The null domain contains references to top level domains and each node below * represents a sub-section of a domain, delimited by "." * * If a cookie has a domain "a.b.com", it will be stored in the node named "a" in this tree. * in the branch ""->"com"->"b"->"a" * * Cookie specs follow the RFC 6265 spec sheet. * http://tools.ietf.org/html/rfc6265 */ class CookieManager: public BlackBerry::Platform::GuardedPointerBase { public: bool canLocalAccessAllCookies() const { return m_shouldDumpAllCookies; } void setCanLocalAccessAllCookies(bool enabled) { m_shouldDumpAllCookies = enabled; } void setCookies(const KURL&, const String& value, CookieFilter = WithHttpOnlyCookies); void setCookies(const KURL&, const Vector<String>& cookies, CookieFilter); void removeAllCookies(BackingStoreRemovalPolicy); void removeCookieWithName(const KURL&, const String& cookieName); unsigned short cookiesCount() const { return m_count; } void setCookieJar(const char*); const String& cookieJar() const { return m_cookieJarFileName; } // Count update method void removedCookie() { ASSERT(m_count > 0); --m_count; } void addedCookie() { ++m_count; } static unsigned maxCookieLength() { return s_maxCookieLength; } void setCookiePolicy(CookieStorageAcceptPolicy policy) { m_policy = policy; } CookieStorageAcceptPolicy cookiePolicy() const { return m_policy; } void setPrivateMode(bool); String generateHtmlFragmentForCookies(); String getCookie(const KURL& requestURL, CookieFilter) const; // Returns all cookies that are associated with the specified URL as raw cookies. void getRawCookies(Vector<RefPtr<ParsedCookie> >& stackOfCookies, const KURL& requestURL, CookieFilter = WithHttpOnlyCookies) const; private: friend CookieManager& cookieManager(); friend class CookieDatabaseBackingStore; CookieManager(); virtual ~CookieManager(); void checkAndTreatCookie(PassRefPtr<ParsedCookie> prpCandidateCookie, BackingStoreRemovalPolicy, CookieFilter = WithHttpOnlyCookies); void addCookieToMap(CookieMap* targetMap, PassRefPtr<ParsedCookie> prpCandidateCookie, BackingStoreRemovalPolicy postToBackingStore, CookieFilter = WithHttpOnlyCookies); CookieMap* findOrCreateCookieMap(CookieMap* protocolMap, const PassRefPtr<ParsedCookie> candidateCookie); void initiateCookieLimitCleanUp(); void cookieLimitCleanUp(Timer<CookieManager>*); HashMap<String, CookieMap*> m_managerMap; unsigned short m_count; bool m_privateMode; bool m_shouldDumpAllCookies; bool m_syncedWithDatabase; String m_cookieJarFileName; // FIXME: This method should be removed. void getBackingStoreCookies(); // Cookie size limit of 4kB as advised per RFC2109 static const unsigned s_maxCookieLength = 4096; CookieStorageAcceptPolicy m_policy; CookieDatabaseBackingStore* m_cookieBackingStore; Timer<CookieManager> m_limitTimer; DISABLE_COPY(CookieManager) }; // Get the global instance. CookieManager& cookieManager(); } // namespace WebCore #endif // CookieManager_h
{ "redpajama_set_name": "RedPajamaGithub" }
733
{"url":"http:\/\/www.gradesaver.com\/textbooks\/math\/algebra\/college-algebra-6th-edition\/chapter-p-prerequisites-fundamental-concepts-of-algebra-exercise-set-p-4-page-61\/35","text":"College Algebra (6th Edition)\n\n$25-49x^2$ Note that standard form would list the variables first in decreasing order of exponent, so another way to write this answer is $-49x^2+25$.\n$$(5-7x)(5+7x)$$ $$=(5\\times 5)+(5\\times 7x)+(-7x\\times 5)+(-7x\\times 7x)$$ $$=25+35x-35x-49x^2$$ $$=25-49x^2$$ Note that standard form would list the variables first in decreasing order of exponent, so another way to write this answer is: $$-49x^2+25$$","date":"2018-01-21 01:11:08","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.9126607179641724, \"perplexity\": 277.32415215989835}, \"config\": {\"markdown_headings\": false, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.3, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2018-05\/segments\/1516084889798.67\/warc\/CC-MAIN-20180121001412-20180121021412-00491.warc.gz\"}"}
null
null
\section{Introduction} S0 galaxies are enigmatic objects whose formation and evolution is still not well understood. Originally, these galaxies were postulated to exist as a transition class between the elliptical and spiral sequence \citep{hubble1936}. Both elliptical and S0 galaxies lack spiral arms or major dust features. However, early work on the ellipticity distributions of galaxies showed that S0 galaxies were disk-dominated systems with ellipticity distributions that differed from ellipticals, being more similar to spiral galaxies in their intrinsic shapes \citep[{\it e.g.},][]{rood67,sandage1970}. The early work on the morphology-density relation by \citet{dressler1980b} emphasized that S0s and ellipticals both occur with higher frequency in higher density environments, while the pioneering studies of \citet{bo1984} and \citet{dg92} began to provide hints about how the early-type population of elliptical and S0 galaxies might evolve out to redshifts around 0.5 and earlier. However, it was not until {\em HST} allowed comprehensive high-resolution imaging of distant clusters of galaxies that \citet{dressler97}, for example, and others began to show directly that the S0 fraction was changing at high redshift. This early work, along with more recent studies \citep[e.g.,][]{postman2005,desai2007} found smaller S0 galaxy fractions in clusters of galaxies at higher redshifts, $z>0.3-0.4$. The implication is that the S0 galaxy population forms with different time-scales and later than the elliptical population. \citet{fasano2000}, \citet{smith2005}, \citet{postman2005}, \citet{poggianti2006}, \citet{desai2007}, and, most recently, \citet{wilman2008} all find that the majority of evolution occurs since $z\sim0.4$, i.e., in the past 4 Gyrs, and above those redshifts there is little or no evolution in the early-type galaxy fraction in clusters of galaxies out to $z\sim1$ \citep[see][for a different point of view]{smith2005}. Since S0 and elliptical galaxies have different ellipticity distributions and bulge-to-disk distributions, two simple (and related) predictions that can be drawn from the observed changes in S0 fraction with redshift is that both the mean bulge-to-disk ratio of early-type cluster galaxies and the ellipticity distribution should have changed over relatively recent epochs (since $z\sim 0.4$). The evidence for evolution in the S0 population of clusters rests primarily on morphological classifications of galaxies. The separation of the early-type galaxy population into S0 and elliptical galaxies has long been recognized as being a challenging task (see, for example, \citealt{andreon98} for a discussion of the systematic errors in classification and how misclassification mimics evolution.) S0 galaxies are defined as multicomponent disk galaxies, while ellipticals are defined as single component systems. However, a number of quantitative studies found that a substantial fraction of ellipticals have ``disky'' isophotes \citep[see][for a summary]{kormendy1989} in contrast with this definition. The analysis of \citet{rix1990} exemplifies the challenge of establishing the relative contributions of elliptical and S0 galaxies. They showed, for a $z\sim0$ galaxy, that detecting a disk component in a spheroidal galaxy is increasingly difficult as the disk becomes more face-on in projection. \citet{rix1990} found that a disk containing 20\% of the total light of a galaxy is impossible to detect over half of the range of $\cos(i)$ where $i$ is the inclination angle. Specifically, they note ``since the cos $i$ axis can be interpreted as a probability axis, this implies that 50\% of all disks with $L_D/L_B < 0.25$ cannot be detected by photometric means.'' These, however, results for a single galaxy. For an ensemble of galaxies, the bulge-to-disk ratio distribution can be constrained by the intrinsic ellipticity distribution, with the average observed ellipticity being directly related to the intrinsic ellipticity \citep{binneym1998}. Therefore, examining the distribution of galaxy ellipticities provides a direct measure of the evolution in the distribution of the bulge-to-disk ratios of that galaxy population. \citet{jf94} investigated the ellipticity distribution of elliptical and S0 galaxies in the Coma cluster, and suggested that elliptical and S0 galaxies were not distinct classes but were part of a continuum of objects of varying bulge-to-disk ratios. This result was given additional support by a recent study by \citet{krajnovic2008} who found that 69\% of elliptical galaxies have multiple kinematic components, generally disk-like components, while 92\% of S0 galaxies have disk-like components. These results give emphasis to the view that elliptical and S0 galaxies form a continuous distribution of disk fraction as opposed to two distinct classes. In particular, \citet{jf94} constructed a model of the ellipticity distribution of elliptical and S0 galaxies using a continuum of bulge and disk components viewed from a variety of angles. \citet{jf94} found a deficit of round S0 galaxies, in contrast with what was expected from their model, suggesting that some face-on S0 galaxies had been classified as ellipticals. \citet{blakeslee2005} and \citet{mei2005a} also found a lack of round S0 galaxies in three $z\sim 1$ clusters of galaxies when compared to what was expected for a disk population viewed at a variety of angles. These three studies illustrate a potential bias in the visual classification of galaxies, namely that nearly face-on S0 galaxies galaxies may be incorrectly classified as ellipticals. A number of studies suggest that quantitative measurements do not suffer the same orientation bias as visual classifications \citep{blakeslee2005,vanderwel2008b}, but robust, bias-free galaxy classification, either visual or quantitative, still remains an elusive goal. The importance of the work showing an apparent evolution in the S0 fraction in clusters and the knowledge of potential classification biases led \citet{dressler97} and \citet{postman2005} to investigate the ellipticity distributions of the S0 and elliptical galaxies in their samples. In general, the authors found that the ellipticity distributions of S0 and elliptical galaxies show no evolution over the broad redshift ranges in their samples \citep[][compared clusters from $z\sim0.25$ to $z\sim1.3$]{postman2005}. Also, the ellipticity distributions of elliptical and S0 galaxies differ from each other, providing evidence for the existence of two distinct classes of galaxies. However, these previous studies do not use a consistent measure of the ellipticity as compared with the $z\sim0$ efforts such as \citet{jf94} or \citet{andreon1996}, making a comparison between these $z>0.2$ samples observed with {\em HST} and $z\sim 0$ samples observed from the ground difficult. Traditionally, ellipticities for galaxies at $z\sim0$ were measured by visual estimates \citep{dressler1980b} or by fitting models to the elliptical isophotes \citep{jf94,andreon1996}. At higher redshifts, $z>0.2$, the ellipticities in \citet{smail1997} or \citet{postman2005} are determined by the second-order flux-weighted moments of a detection isophote. Both the data and the techniques have matured so that we can now evaluate the ellipticity distribution, as a function of redshift, quantitatively, and even more importantly, in a consistent way with minimal systematic error. We show that some approaches used previously that could not correct for the point-spread function (PSF) are probably subject to significant systematic error. Essentially, the ``blurring'' effect of the PSF will lead to galaxies being measured as rounder than they actually are. We will use a single consistent and robust approach for measuring the ellipticities at all redshifts. The ellipticities will be measured by fitting models convolved with the PSF to galaxy surface brightness profiles. This will eliminate some of the previously-reported uncertainties found when comparing ground-based imaging data taken under different seeing conditions \citep[see][for some discussion]{andreon1996}. In addition, this approach essentially eliminates the systematic error associated with the PSF ``blurring''. Our ellipticity measurements will provide an assessment of the evolution in the distribution of the overall bulge-to-disk ratio of early-type cluster galaxies from the present day to redshifts $z\sim 1$. We will discuss how we compiled our samples of early-type cluster galaxies with morphological classifications in \S \ref{sample}, and then how we measured their total magnitudes, colors, and ellipticities in \S \ref{data}. One of the advantages of our approach of using an automated measurement technique is that we can simulate the measurement process. We discuss this in \S \ref{ellmeas} and in Appendix A1. From our measurements, we find no evolution in the distribution of ellipticities of cluster early-type galaxies, which we show in \S \ref{elldist}. In \S \ref{disc}, we discuss the implications of this result and contrast with previous measurements of the evolution in the overall distribution of the bulge-to-disk ratio of cluster early-type galaxy population. We follow this with a summary and some discussion of the broader implications in \S \ref{conclusion}. Throughout this paper, we assume $\Omega_m = 0.27$, $\Omega_{\Lambda} = 0.73$ and $H_o = 71\ {\rm km\ s^{-1}\ Mpc^{-1}}$. All $B$ magnitudes we list use the Vega zeropoint ($B_{Vega} = B_{AB} + 0.11$.) Other magnitudes where given are AB mags. \section{Sample Selection} \label{sample} To carry out our study of the ellipticities of early-type galaxies from $z\sim1$ to the current epoch, we have assembled a sample of morphologically-selected, cluster early-type galaxies ranging in redshifts from $z \sim 0$ to $1.27$. The clusters used are tabulated below, as is the source of the morphologies for the galaxies samples (\S \ref{morph}). The early-type galaxies are chosen to lie within the projected $R_{200}$, which we use to define cluster membership. The measurement for each galaxy of its color, magnitude, and ellipticity, is described in \S \ref{data}. \subsection{Cluster Sample Selection} \begin{deluxetable*}{lrrrr} \tablecolumns{5} \tablecaption{$z<0.05$ Cluster Summary} \tablehead{\colhead{Cluster} & \colhead{z}\tablenotemark{a} & \colhead{$\sigma$\tablenotemark{a}} & \colhead{$R_{200}$\tablenotemark{b}} & \colhead{\# \ Early-type\tablenotemark{c}} \\ \colhead{} & \colhead{} & \colhead{(km s$^{-1}$)} & \colhead{(Mpc)} & \colhead{} \\} \startdata ACO 119 & 0.0440 & 744 & 1.13 & 41 \\ ACO 168 & 0.0452 & 524 & 0.80 & 54 \\ ACO 194 & 0.0178 & 435 & 0.67 & 9 \\ ACO 957 & 0.0440 & 691 & 1.05 & 32 \\ ACO 1139 & 0.0383 & 436\tablenotemark{d} & 0.67 & 23 \\ ACO 1142 & 0.0353 & 417 & 0.64 & 17 \\ ACO 1656 & 0.023 & 1008 & 1.55 & 203 \\ ACO 1983 & 0.0441 & 433 & 0.66 & 18 \\ ACO 2040 & 0.0456 & 602 & 0.92 & 50 \\ ACO 2063 & 0.0337 & 521 & 0.80 & 50 \\ ACO 2151 & 0.0371 & 786 & 1.20 & 58 \\ \enddata \tablenotetext{a}{The cluster redshift and $\sigma$ from \citet{struble99} unless otherwise noted. } \tablenotetext{b}{$R_{200}$ is derived from $\sigma$.} \tablenotetext{c}{The number of galaxies with E, E/S0, S0/E, S0, or S/S0 classifications.} \tablenotetext{d}{From \citet{poggianti2006}} \label{lowz_num} \end{deluxetable*} Our $z<0.05$ sample is selected from Abell clusters in the Sloan Digital Sky Survey Fifth Data Release \citep[SDSS DR5]{dr5}. We summarize this sample in Table \ref{lowz_num}, where we list the Abell number \citep{aco89} and the redshift of the cluster from \citet{struble99}. The last column lists the number of redshift-selected members with early-type classification, which lie within the projected $R_{200}$ and are on the $g-r$ red sequence in the SDSS DR5 imaging. To determine $R_{200}$, we will use the formula give in \citet{carlberg97}, or \[ R_{200} = \frac{\sqrt{3}}{10} \frac{\sigma_1}{H(z)} \] where $\sigma_1$ is the one-dimensional velocity dispersion and $H(z)$ is the Hubble constant at the redshift of observation. \citet{desai2007} uses the relation from \citet{finn2005}, which is functionally the same, so effectively our selection radii are similar to \citet{desai2007}. We selected $2 R_{200}/\pi $, instead of $R_{200}$, as a galaxy at $R_{200}$ from the cluster center will be, on average, projected to appear at the distance $2 R_{200}/\pi$ \citep[see][for example]{limber1960}. For the high redshift clusters, we required {\em Hubble Space Telescope} ({\em HST}) imaging with the Advanced Camera for Surveys (ACS) or the Wide Field Planetary Camera 2 (WFPC2) in multiple filters. We also required that the morphological classifications were done in a way consistent with the original \citet{dressler1980a} and \citet{dressler1980b} work. For the three clusters where $2 R_{200}/\pi $ was larger than the field of view over which we had imaging data \citep[generally the clusters in the sample of ][]{dressler97}, we simply used all available galaxies. We mark those clusters in Table \ref{summary} with the superscript b. Below we will detail the sources for the morphological classifications and how we measured the total magnitudes, colors, and ellipticities. We tabulate the $0.3 < z < 1.3$ clusters for which we have early-type galaxy samples in Table \ref{summary}. In that table, we list the dispersions, inferred radii, and the final sample sizes. For {CL~J1226+33}\ we have compiled a new catalog of members which we will discuss in Appendix \ref{ctw}. For {RX~J0849+4452}, we compute a new dispersion. We use both redshifts from previous work \citep{stanford2001,mei2005b} and unpublished ones we have recently collected (which we plan to publish in a future paper.) There are a total of 18 galaxies in {RX~J0849+4452}\ with redshifts within $R_{200}$. The biweight center of the distribution is $z=1.2600 \pm 0.0017$ and the dispersion is 798 $\pm$ 208 km s$^{-1}$. The errors for both the redshift and the dispersion are estimated by bootstrapping the redshift distribution. For the clusters {RX~J0152-13}, {MS~1054-03}, {MS~2053-04}, and {CL~1358+62}, we used the redshift catalogs from \citet{holden2007}. The faint magnitude limit we adopted corresponds to the completeness limits for our high redshift samples \citep{holden2007}. For the remaining clusters, we included all galaxies that met our magnitude, color, morphology and radial requirements, rejecting only those galaxies with redshifts outside of the clusters. This will mean that some cluster samples will be contaminated, i.e., some red-sequence early-type galaxies will not be members. The level of contamination is discussed below. Our $z>0.3$ sample consists of 487\ early-type galaxies while our $z<0.05$ sample has 210\ galaxies. Many of the cluster red-sequence selections we use are tabulated in other studies. For those clusters studied by the ACS Instrument Definition Team, these red-sequence relations are summarized in \citet{mei2008}. For the remaining clusters, we derive the early-type red-sequence from the data. Whenever possible, we use existing redshift catalogs to determine the red-sequence of spectroscopic determined members. We then accept all galaxies that lie within the 2$\sigma$ of that sequence, rejecting those galaxies that are known not to be members. We know that there will be some contamination by field galaxies in our catalogs. To measure the level of contamination, we used our redshift catalogs for {MS~1054-03}\ and {RX~J0152-13}\ along with the catalogs of EDisCS from \citet{halliday2004}. {RX~J0152-13}\ has a known group in the foreground with colors very similar to that of the cluster \citep[see][for a discussion]{holden2005b}. Nonetheless, when we consider all early-type galaxies that lie on the red-sequence for {MS~1054-03}\ and {RX~J0152-13}, regardless of redshift, we find a 3 $\pm$ 1\% contamination rate of nonmembers. When we examine the less extremely rich sample of the EDisCS, we find a contamination fraction of 10 $\pm$\ 3\%, which is likely more representative of the typical clusters in our sample. The small size of this contamination means we need not compute a statistical background correction for the cluster red-sequence. \begin{deluxetable*}{lrrrrrrr} \tablecolumns{7} \tablecaption{Summary of $0.3 < z < 1.3$ Cluster Data} \tablehead{\colhead{Cluster} & \colhead{z} & \colhead{R.A.} & \colhead{Dec.} & \colhead{Obs. Filters} & \colhead{$\sigma$} & \colhead{$R_{200}$} & \colhead{\# Early-type \tablenotemark{a}} \\ \colhead{} & \colhead{} & \colhead{} & \colhead{} & \colhead{} & \colhead{(km s$^{-1}$)} & \colhead{(Mpc)} & \colhead{} \\ } \startdata {CL~1358+62} & 0.328\tablenotemark{c}& 13 59 50.6 & +62 59 05 &$V_{606}\ I_{814}$ & 1027$^{+51}_{-45}$\tablenotemark{c} & 1.4 & 67 \\ {CL~0024+16} & 0.395 & 00 26 35.7 & +17 09 46 & $r_{625}\ i_{775}\ z_{850}$ & 650$^{+50}_{-50}$ & 0.83\tablenotemark{b} & 26 \\ {CL~0016+16} & 0.541 & 00 18 33.5 & +16 26 14 &$i_{775}\ z_{850}$ & 1234$^{+128}_{-128}$ \tablenotemark{d} & 1.46\tablenotemark{b} & 42 \\ {ECL~J1232-12} & 0.541\tablenotemark{e} & 12 32 30.3 & -12 50 36 & $V$ $I$, $I_{814}$ & $1080^{+119}_{-99}$\tablenotemark{e} & 1.28 & 21 \\ {CL~0054-27} & 0.56 & 00 56 56.9 & -27 40 30 &$V_{606}\ I_{814}$ & 1180\tablenotemark{f} & 1.38\tablenotemark{b} & 19 \\ {MS~2053-04} & 0.587 & 20 56 21.3 & -04 37 51 &$V_{606}\ I_{814}$ & 865$^{+71}_{-71}$ \tablenotemark{g} & 1.00 & 31 \\ {ECL~J1054-11} & 0.697\tablenotemark{e} & 10 54 24.4 & -11 46 19 & $V$ $I$, $I_{814}$ & $589^{+78}_{-70}$ \tablenotemark{e} & 0.64 & 5 \\ {ECL~J1040-11} & 0.704\tablenotemark{e} & 10 40 40.3 & -11 56 04 & $V$ $I$, $I_{814}$ & $418^{+55}_{-45}$ \tablenotemark{e} & 0.45 & 2 \\ {ECL~J1054-12} & 0.750\tablenotemark{e} & 10 54 43.5 & -12 45 52 & $V$ $I$, $I_{814}$ & $504^{+113}_{-65}$ \tablenotemark{e} & 0.53 & 13 \\ {ECL~J1216-12} & 0.794\tablenotemark{e} & 12 16 45.3 & -12 01 18 & $V$ $I$, $I_{814}$ & $1080^{+119}_{-89}$ \tablenotemark{e} & 1.04 & 31 \\ {MS~1054-03} & 0.831\tablenotemark{h} & 10 57 00.0 & -03 37 36 &$V_{606}\ i_{775}\ z_{850}$ & 1156$^{+82}_{-82}$\tablenotemark{h} & 1.16 & 59 \\ {RX~J0152-13} & 0.834\tablenotemark{i} & 01 52 43.8 & -13 57 19 &$r_{625}\ i_{775}\ z_{850}$ & 919$^{+168}_{-168}$\tablenotemark{j} & 0.92 & 36 \\ {CL~J1226+33} & 0.890 & 12 26 58.2 & +33 32 49 &$V_{606}\ I_{814}$ & 1143$^{+162}_{-162}$ & 1.11 & 46 \\ {CL~1604+4304} & 0.897\tablenotemark{k} & 16 04 24.0 & +43 04 38 &$V_{606}\ I_{814}$ & 962$^{+141}_{-141}$\tablenotemark{k} & 0.93 & 26 \\ {CL~1604+4321} & 0.924\tablenotemark{k} & 16 04 33.6 & +43 21 04 &$V_{606}\ I_{814}$ & 640$^{+71}_{-71}$\tablenotemark{k} & 0.61 & 15 \\ {RX~J0910+5422} & 1.106\tablenotemark{l} & 09 10 44.9 & 54 22 08.9 & $i_{775}\ z_{850}$ & 675$^{+190}_{-190}$\tablenotemark{l} & 0.58 & 12 \\ {RX~J1252-2927} & 1.237\tablenotemark{m} & 12 52 48 & -29 27 00 & $i_{775}\ z_{850}$ & 747$^{+74}_{-84}$\tablenotemark{m} & 0.60 & 16 \\ {RX~J0849+4452} & 1.260 & 08 48 58.66 & 44 51 57.0 & $i_{775}\ z_{850}$ & 798$^{+208}_{-208}$ & 0.63 & 8 \\ \enddata \tablenotetext{a}{The number of galaxies classified as early-types with $-19.3 > M_B - 1.208 z > -21$.} \tablenotetext{b}{Imaging area smaller than $2 R_{200}/\pi$} \tablenotetext{c}{\citet{fisher1998}} \tablenotetext{d}{\citet{carlberg96}} \tablenotetext{e}{\citet{halliday2004}} \tablenotetext{f}{\citet{dressler1999}} \tablenotetext{g}{\citet{tran2003}} \tablenotetext{h}{\citet{tran2007}} \tablenotetext{i}{\citet{blakeslee2005}} \tablenotetext{j}{\citet{demarco2005a}} \tablenotetext{k}{\citet{gal2005}} \tablenotetext{l}{\citet{mei2005a}} \tablenotetext{m}{\citet{demarco2007}} \label{summary} \end{deluxetable*} \subsection{Morphologies} \label{morph} Galaxy morphologies were obtained from the literature for all the galaxies in our sample. We use the morphologies from \citet{dressler1980b} for the $z<0.05$ cluster members. We removed all late-type galaxies from that low redshift sample, i.e., all those classified as spiral, irregular or unknown classifications. We considered galaxies classified as S0/a as S0, and galaxies classified as Sa/0 as spirals. We list in Table \ref{lowz_num} the number of early-type galaxies -- E through S0/a -- in the last column. The numbers are smaller than the number available in \citet{dressler1980b} because not all of the galaxies in each cluster are imaged in the SDSS DR5. For our higher redshift clusters, we used the classifications of \citet{dressler97} as tabulated in \citet{smail1997}, \citet{postman2005}, and \citet{desai2007}. Each cluster was imaged with either ACS or WFPC2 with morphological classifications done in a manner consistent with the previous work of \citet{dressler1980b}. The clusters {MS~1054-03}, {RX~J0152-13}, {CL~J1226+33}, {CL~1604+4304}, {CL~1604+4321}, {RX~J0910+5422}, {RX~J1252-2927}, and {RX~J0849+4452}\ all come from \citet{postman2005}. The MORPHS survey clusters {CL~0016+16}, {CL~0054-27}, {CL~0024+16}\ are part of \citet{dressler97} sample. Five clusters from the EDisCS survey -- {ECL~J1040-11}, {ECL~J1054-11}, {ECL~J1054-12}, {ECL~J1216-12}, and {ECL~J1232-12} -- have morphologies from \citet{desai2007}. Two additional, {CL~1358+62}\ and {MS~2053-04}, have morphologies in \citet{fabricant2000} and \citet{tran2003}, respectively. \section{Data and Measurements} \label{data} \begin{figure*}[htbp] \begin{center} \includegraphics[width=6.5in]{f1.eps} \end{center} \caption[f1.eps]{Ellipticity measured from the simulations, which used real galaxy images, as a function of the ellipticity in the original input image. The error bars show the scatter around the recovered ellipticity values for each galaxy. Each galaxy image is rescaled in size appropriately for the redshift of each cluster. Each galaxy is realized at a variety of signal-to-noise values covering the range over which the galaxies in the high redshift sample are observed, and were then placed in the cluster imaging data. We plot a straight line with a slope of one, the expected relation if we recover the input ellipticities. The scatter is typically $\sigma_e \sim 0.01 - 0.03$. The scatter increase at lower signal-to-noise, and matches the statistical errors from the fitting process. The median offset is $-0.01$ with a range of $0.00$ to $-0.03$, showing that our method accurately recovers the ellipticity of these low-redshift galaxies when they are observed at high redshift. No systematic trends are seen as a function of ellipticity or redshift.} \label{cl_e} \end{figure*} Our sample of early-type galaxies is based on a range in luminosity, corrected for the observed passive evolution to z $\sim$ 1. The derivation of the total magnitudes and colors used for our sample selection is discussed below. Taking that luminosity-selected sample, we then discuss the derivation of their ellipticities. These constitute the key observable for this work, and the implications of those ellipticity measurements are discussed in the remainder of the paper. Our final selection will consist of morphologically-selected early-type galaxies on the red-sequence within a well-defined magnitude range ($-19.3 > M_B > -21$ at $z= 0$) lying within the cluster core that is defined by $R_{200}$. These magnitude limits correspond to $M^*_B +1 > M_B > M^*_B - 0.75$ and to galaxies with stellar masses roughly between $10^{10.6}\ M_{\sun} < M < 10^{11.2}\ M_{\sun}$, assuming a ``diet'' Salpeter initial mass function (IMF) \citep[see][for a discussion of the IMF and the procedure we use to estimate the stellar masses of galaxies]{bell2003}. \subsection{Total Magnitudes and Colors} \label{measure} Our samples were selected based on the rest-frame $B$ magnitude. To estimate these magnitudes, we used the total magnitude in the passband closest to the rest-frame $B$. We also needed a color to correct the apparent magnitude in the observed passband to a rest-frame $B$ magnitude; how this was done is outlined below. The S{\'e}rsic model fits that we used to measure the ellipticities also were used to determine the total magnitudes and the color apertures. The total magnitude is the normalization of the S{\'e}rsic model fit. For the color aperture, we used the circularized half-light radius, $r_{hlr} = a_{hlr} \sqrt q$, where $q$ is the ratio of the minor to major axis, or $1-\epsilon$, and $a_{hlr}$ is the half-light radius along the major axis of the best-fitting elliptical model as determined by GALFIT. These are the same apertures used in \citet{mei2008} (see that paper for more detail). We adjust the magnitudes of the galaxies by $1.208 z$ as measured for early-type galaxies using the fundamental plane \citep{vandokkum2006}. This compensates for the mean passive evolution of the old stellar population. Our magnitude range covers $M^{*} - 0.7$ to $M^{*} +1$ using the $M^{*}$ from \citet{norberg2002} after converting the $b_J$ used by \citet{norberg2002} to the $B$ of the Johnson-Morgan system \citep{buser1978} that we use in this paper. We trim our sample at $M_B < -19.3$, as our high redshift samples become incomplete fainter than that magnitude. The brighter magnitude limit is set to be $M_B < -21$ to exclude the most luminous galaxies (whose formation and evolution may differ, as is explained later in \S \ref{ellm}). Thus our adopted magnitude range is $-19.3 > M_B - 1.208 z > -21$. Using our simulations of real galaxies that we discuss in more detail in Appendix \ref{simreal}, we estimate the typical error and offset for these total magnitude measurements. We find that total magnitudes as measured with ACS have an error of $\sigma = 0.10$ mag while magnitudes measured with WFPC2 have $\sigma = 0.15$ mag. There is a small offset at most redshifts, such that we measure a magnitude brighter than the actual magnitude of the simulated galaxy. For the clusters at $0.3 < z < 0.6$, this is only 0.02 mag, while it increases to 0.06 mag at $0.6 < z < 1$ and 0.10 mag at $z>1$. This offset is the same for galaxies regardless of size, morphological type or the value of $n$ from the S{\'e}rsic model fit. We do not apply this offset to the measured magnitudes. To ensure a reliable measure of the color, we applied the CLEAN algorithm \citep{hogbom74} to the original images in all passbands. Using CLEAN mitigates the effects of the different-sized PSF in different passbands, see \citet{sirianni2005} for examples involving ACS. The final ``CLEANed'' images were used for measuring the galaxy colors within the $r_{hlr}$ given above. \subsection{Redshifted Magnitudes} We transformed the observed magnitudes into redshifted magnitudes using the same process as \citet{vandokkum96}, \citet{blakeslee2005}, \citet{holden2006} and \citet{holden2007}. We calculated the magnitudes of templates in the rest-frame filters. We then redshifted the templates, and computed the magnitudes in the observed filters. For the templates, we used exponentially decaying star-formation rate models from \citet[BC03]{bc03}; the same models were used in \citet{holden2007}. These models had exponential time-scales of 0.1- 5 Gyr, covering a range of ages from 0.5 Gyr to 12 Gyr and three metal abundances, 2.5 solar, 1.0 solar and 0.4 solar. For the rest-frame filters, we used the $B$ and $V$ curves from \citet{buser1978}, specifically the B3 curve for the $B_z$ as tabulated by BC03. We use the same templates and procedure for all of the clusters in our sample. \subsection{Ellipticities} \label{ellmeas} We measured the ellipticities for our galaxies using the results from GALFIT \citep{penggalfit2002}. GALFIT fits an elliptical model to the surface brightness profile. Effectively, the ellipticity measurements we use are ellipticities at the half-light radius. The model is convolved with a PSF before it is compared with the data. The advantages of the approach we have used is that the GALFIT fit procedure minimizes the effect of the smoothing from the PSF. PSF ``blurring'' will make galaxies appear rounder than they actually are, unless the galaxies being fitted have sizes much greater than the PSF. In Appendix \ref{ellrob}, we discuss in more detail the robustness of the ellipticity measurements. This procedure is performed for galaxies at all redshifts, but requires an estimate of the PSF. For the clusters of galaxies at $z<0.05$, our imaging data came SDSS DR5. We use the software tools provided by the SDSS to extract the PSF appropriate for each galaxy. For the higher redshift galaxies, the pipeline processing system we use for ACS (Apsis -- ACS pipeline science investigation software) provided us with suitable PSF \citep{blakeslee_pipe2003,blakeslee2005}. We used empirical PSF models constructed from multiple ACS observations of 47 Tuc. For the WFPC2 data, the PSF still has a strong positional dependence and is significantly under sampled. For these data, we estimated the PSF using the TinyTim software package \citep{krist95} for each galaxy we fit. We also used the option in GALFIT to convolve the model of the galaxy with an over-sampled PSF. Before comparing the PSF convolved model with the data, GALFIT rebinned the model to the WFPC pixel scale and smoothed the model with the charge diffusion kernel. \subsubsection{Simulations of Ellipticity Measurements} We constructed a set of simulations using real galaxy images and placed those images in the data of the high redshift clusters in our sample. This is discussed in detail in Appendix \ref{simreal}. To summarize, we made multiple measurements of each simulated individual galaxy to assess both the impact of noise and any systematic effects, and each galaxy was simulated over a range in magnitudes. We found that the scatter in the ellipticity measurements of the images of real galaxies was $\sigma_e \sim 0.01 - 0.03$ at magnitudes typical of those in our samples, and only increased (to $\sigma_e \sim 0.05-0.06$) at or below the magnitude limit of our samples. These estimates of the uncertainty are in good agreement with the errors estimated by the model fitting process used to measure the ellipticity. We found no large systematic trends in the ellipticity measurements. This can be see in Figure \ref{cl_e} where we show the recovered ellipticity as a function of the input ellipticity for three redshift bins. There was only a very small overall shift of $\delta_e = 0.01$, or 3\% for the typical galaxy, such that the typical $z>0.3$ galaxy is measured to be slightly rounder than it would appear in the $z<0.05$ sample. We found the shift was the same, regardless of the redshift of the galaxy. No systematic changes were seen as a function of ellipticity. For the rest of the paper, we ignore the small systematic shift of $\delta_e = 0.01$ (noted above and in Figure 1), and simply quote the observed values. We also tested the robustness of the ellipticity measurements by using incorrect PSFs. We found that this error could result in a systematic offset of $\delta_e = \pm 0.01$ to $\delta_e = \pm 0.03$ depending on how bad the mismatch between the PSFs were. The small size of our statistical errors means that we are sensitive to systematic errors of this order, and we will discuss the implications of this in later sections. \section{Ellipticity Distributions} \label{elldist} \subsection{Ellipticity Distributions for the $z<0.05$ Sample} \label{ellm} \begin{figure}[htbp] \begin{center} \includegraphics[width=3.4in]{f2.eps} \end{center} \caption[f2.eps]{Ellipticity versus absolute $B$ magnitude or stellar mass for the $z<0.05$ clusters, as described in the text in \S \ref{data}. The dashed lines show magnitude limits we will use for this paper, $-19.3 > M_B > -21$. Below $M_B = -19.3$ our higher redshift cluster samples become incomplete, while above brighter than $M_B \sim -21$, the ellipticity distribution of the early-type galaxy population changes, becoming rounder, possibly the result of the somewhat different evolutionary history of the most massive galaxies. The galaxies within our selection limits are filled circles, while all of the remaining data are shown as open circles. The median ellipticity of the galaxies in our sample is shown by a solid line. The mass-selected sample and the luminosity-selected samples yield a very similar selection with similar median ellipticity, suggesting that mass-dependent effects are likely to be small. For the rest of the paper, we will use the $B$ magnitude limits in the left panel to select galaxies at higher redshifts.} \label{mass_e} \end{figure} In this section, we define our selection of $z<0.05$ galaxies, and discuss how we will characterize the ellipticity distributions in order to compare them with the $z>0.3$ cluster galaxy sample. In Figure \ref{mass_e}, we plot the ellipticity as a function of $M_B$, and also by stellar mass, for all galaxies in the $z<0.05$ sample that are within ${2} R_{200}/{\pi} $, and classified as an early-type galaxy. We show the median ellipticity of the whole population with a solid line. The stellar masses are derived using the prescription from \citet{bell2003}, which uses the rest-frame colors to estimate the mass-to-light ratio of the stellar population, assuming a ``diet'' Salpeter IMF. The ``diet'' Salpeter IMF is a Salpeter IMF with truncation at very low masses, resulting in a mass-to-light ratio of the stellar population 0.15 dex smaller than a Salpeter IMF. These stellar mass estimates agree well with the mass estimates from the fundamental plane \citep[see][]{holden2007}. At the highest masses or brightest magnitudes, the population becomes rounder, a result seen in other work \citep[see][for example]{franx1991,vincent2005}, likely a result of a different morphological mix among the most luminous galaxies which may have a somewhat different formation and evolution history. We will exclude these most luminous galaxies, $M_B < -21$, from our sample. We illustrate our sample range $-19.3 > M_B > -21$ with dashed lines in Figure \ref{mass_e}. At low redshifts, we know that elliptical and S0 galaxies have different ellipticity distributions. In Figure \ref{type_e}, we show that we reproduce those different distributions with our $z<0.05$ cluster galaxy sample. The elliptical population, shown in red in Figure \ref{type_e}, is much rounder than the S0 population, shown in blue. The whole of the population is shown in green. Because S0 galaxies dominate the population, the green line appears closer to the S0 distribution than the elliptical distribution. The median ellipticities are different, with the median ellipticity of S0 galaxies $\epsilon_{med} = 0.38 \pm 0.02$ while the median ellipticity of elliptical galaxies is $\epsilon_{med} = 0.18 \pm 0.01$. In Figure \ref{type_e}, there is a hint of a deficit of round S0 galaxies, a result found by \citet{jf94}. We fit to the distribution of S0 ellipticities with the disk galaxy model used in \citet{jf94}. This disk galaxy distribution is that of an oblate spheroid with the minor to major axis ratios drawn from a Gaussian distribution with mean $\bar{\epsilon}$ and a dispersion of $\sigma_{\epsilon}$. We find that the values for the Gaussian that best describes the data are similar to that of \citet{jf94}. Our values of $\bar{\epsilon} = 0.73 \pm 0.10$ and $\sigma_{\epsilon} = 0.10 \pm 0.02$ are consistent with $\bar{\epsilon} = 0.65$ and $\sigma_{\epsilon} = 0.10$ from \citet{jf94} -- a difference $\sim 1 \sigma$. At small ellipticity values, the ellipticity distribution of visually classified S0 galaxies fall consistently below the expectation of the model, which indicates a possible lack of round S0 galaxies. \begin{figure}[htbp] \begin{center} \includegraphics[width=3.4in]{f3.eps} \end{center} \caption[f3.eps]{Ellipticity distributions for magnitude-selected samples by galaxy type for the $z<0.05$ clusters. We show the elliptical and S0 population separately (red - ellipticals, blue - S0 galaxies, green - all early-type galaxies). The two sets of galaxies show different ellipticity distributions in our data, as expected from the results of previous work. The elliptical galaxy population shows a peaked distribution, with a median ellipticity of $\epsilon_{med} = 0.18 \pm 0.01$. In contrast, the S0 galaxies have a broader ellipticity distribution, with $\epsilon_{med} = 0.38 \pm 0.02$, consistent with a more disk dominated population. We show, with a black line, the best-fitting disk population drawn from a Gaussian distribution which has a mean thickness of $\bar{b} = 0.27 \pm 0.10$ giving a mean ellipticity of $\bar{\epsilon} = 0.73 \pm 0.10$, with a standard deviation of $\sigma_{\epsilon} = 0.10 \pm 0.02$. If the S0 fraction decreases with redshift, the overall ellipticity distribution of the cluster population should also evolve as there will be fewer galaxies with large ellipticities..} \label{type_e} \end{figure} Coma (A1656) is a dominant contributor to the early-type sample at $z<0.05$, with about 37\% of the total. We investigated the impact of the removal of Coma from the sample. As can be seen in Table \ref{coma} doing so makes surprisingly little difference to the ellipticity measures of the early-types or of the E and S0s separately. The ellipticity is consistent within the uncertainties. The S0 fraction of the $z<0.05$ sample is $68\pm 3$\% for the whole sample and $72\pm4$\% without Coma. \begin{deluxetable*}{lrrr} \tablecolumns{4} \tablecaption{Median Ellipticities of $z<0.05$ Sample} \tablehead{\colhead{Sample} & \colhead{All Early-types} & \colhead{S0's} & \colhead{Ellipticals} \\ \colhead{} & \colhead{} & \colhead{} & \colhead{} \\} \startdata All $z<0.05$ clusters & 0.29 $\pm$ 0.02 & 0.38 $\pm$ 0.02 & 0.18 $\pm$ 0.01 \\ Without Coma & 0.29 $\pm$ 0.02 & 0.34 $\pm$ 0.03 & 0.21 $\pm$ 0.02 \\ \enddata \label{coma} \end{deluxetable*} Both \citet{jf94} and \citet{andreon1996} tabulate their ellipticities. The median ellipticities in the Coma sample of \citet{jf94} are $\epsilon_{med} = 0.34 \pm 0.02$ for the S0 galaxies and $\epsilon_{med} = 0.16 \pm 0.02$ for ellipticals. Both medians are slightly rounder than our measured low redshift values, though the differences are small. The lower values are possibly due to the use of the PSF in our analysis. \citet{jf94} did not remove the smoothing of the PSF, and so will be offset to slightly rounder values as a result. \citet{andreon1996} derive ellipticies for the S0 galaxies and ellipticals. These values have been used as a low-redshift comparison set by other higher redshift studies \citep{smail1997,fasano2000}, it is useful to understand the difference between these measurements and ours. These ellipticities are measured at a fixed $\mu_R$ isophote. Thus measurement of the ellipticity from \citet{andreon1996} is not directly comparable to ours and is not the optimal approach for our study. \subsection{$z>0.3$ Ellipticity Distributions} \label{hizelldist} \begin{figure*}[htbp] \begin{center} \includegraphics[width=6.5in]{f4.eps} \end{center} \caption[f4.eps]{Ellipticity versus absolute $B$ magnitude for all the clusters in our sample. The magnitude range, shown by the dashed lines, is the same throughout, as we derived in Figure \ref{mass_e}. Each galaxy is selected to be within $2 R_{200} / \pi $ and to have $-19.3 > M_B + 1.208 z > -21$, after removing the effects of passive evolution. We assume early-type galaxies become brighter by $1.208 z$ mag \citep{vandokkum2006}. In each panel, the solid dots are those in the magnitude range of our selection, while the open circles show the remaining galaxies in our sample. Each panel covers a different range in redshifts, the leftmost, $z<0.05$, followed by $0.3 < z < 0.6$, $0.6 < z< 1.0$, and $z>1.0$. The horizontal line is the estimate of the median ellipticity for the sample within the magnitude limits. It is striking to note that the median ellipticity distribution does not change with redshift. Only at the highest redshifts do we see a hint of fewer highly elliptical galaxies. } \label{hiz_mass_e} \end{figure*} We plot in Figure \ref{hiz_mass_e} the distribution of ellipticities as a function of absolute $B$ magnitude for four redshift bins. As before, we select only those galaxies in a fixed magnitude range. We adjust the magnitudes, however, by $1.208 z$ mag to reflect the amount of passive galaxy evolution that is measured from the fundamental plane \citep{vandokkum2006}. We combine each cluster's sample into three redshift bins, $0.3 < z < 0.6$, $0.6 < z < 1.0$ and $z>1$. We show, with a solid line, the median ellipticity for the selected sample in each bin. \begin{figure}[htbp] \begin{center} \includegraphics[width=3.5in]{f5.eps} \end{center} \caption[f5.eps]{Median ellipticity versus redshift for the clusters in our sample. The open circles are the median ellipticities for the early-type galaxies in each cluster, after applying our magnitude and radius selection. The median ellipticity, $\epsilon_{med} = 0.29 \pm 0.02$, for all of the galaxies in $z<0.05$ cluster sample is shown by the blue square and line. The other squares are the medians for all of the cluster galaxies in the redshift ranges $0.3 < z < 0.6$ (green), $0.6 < z < 1.0$ (orange), and $z>1$ (red) samples, respectively. The median ellipticity for the whole of the $z>0.3$ sample is $\epsilon_{med} = 0.30 \pm 0.01$. The median ellipticity for cluster galaxies in the range of $0.3 < z < 0.6$ is $0.31 \pm 0.02$, while the median ellipticity for cluster galaxies in the range of $0.6 < z < 1.0$ is $0.30 \pm 0.02$. At $z>1$, the median ellipticity is $\epsilon_{med} = 0.29 \pm 0.03$. All values are all in excellent agreement with the $0.29 \pm 0.02$ we find for the $z<0.05$ sample. We find no individual clusters that have drastically different ellipticity distributions. The lack of any trend in the ellipticity, and minimal cluster-to-cluster variance, is a striking result. The median ellipticity at $z>0.3$ is statistically identical to that at $z<0.05$, being higher by only 0.01 $\pm$ 0.02.} \label{avgell} \end{figure} We find no evolution in the median ellipticity with redshift. In Figure \ref{avgell}, we plot the median ellipticity for each cluster. In this plot we show the median ellipticity for each cluster as open circles. For our $z<0.05$ sample, we show just the median value (the blue square), $\epsilon_{med} = 0.29 \pm 0.02$. The median values for the individual $z>0.3$ clusters show larger scatter, but in general are quite consistent with the low redshift value, with the whole $z>0.3$ sample having $\epsilon_{med} = 0.30 \pm 0.01$. The green, orange, and red points are the median ellipticities (shown also in Figure \ref{hiz_mass_e} as the horizontal lines) at $0.3 < z < 0.6$ and at $0.6 < z < 1.0$ and $z>1$, $\epsilon_{med} = 0.31 \pm 0.02$, $\epsilon_{med} = 0.30 \pm 0.02$, $\epsilon_{med} = 0.29 \pm 0.03$, respectively. The errors we quote, here and later in the paper, are the errors on the median, or $\sqrt(\pi/2)$ the error on the mean. We confirmed these error estimates with bootstrap resampling. We compared the scatter in the high redshift sample by computing the $\chi^2$ around the low redshift median value. We find a $\chi^2_{\nu} = 1.27$ for $\nu=17$ degrees of freedom, confirming both the good visual agreement between the high redshift data and that the scatter is not higher than expected from random errors. As we discuss in Appendix \ref{simreal}, we expect the largest systematic errors on the median ellipticity values to be $\sim 0.02$, which are not large enough to shift the high redshift data to significantly smaller ellipticity values. The lack of any change in ellipticity with redshift is striking. Formally, {\it the median ellipticity of our sample of 487\ early-type galaxies at $z > 0.3$ is statistically identical to that of the 210\ early-type galaxies at $z < 0.05$, being higher by only 0.01 $\pm$ 0.02 or 3 $\pm$ 6\%.} To add a more detailed assessment of the changes and to provide a more quantitative basis for the results seen above, we plot the ellipticity distributions of the samples in Figure \ref{sumz_edist}, both differentially and in cumulative form. In each figure, the blue line shows the $z<0.05$ comparison sample, with the normalization rescaled to match the higher redshift samples. At no redshift do we find a statistically significant change in the ellipticity distribution. We use a number of tests to quantify this, including a Kolmogorov-Smirnov, Wilcoxon-Mann-Whitney rank sum test and a Kuiper test. Taking the results from these tests we find that {\it the distribution of ellipticities at $z>0.3$ agrees with the shape of the $z<0.05$ distribution at the 1-2\% level ( i.e., the probability that they are drawn from the same distribution is 98-99\%).} This is a remarkable demonstration of the consistency of the ellipticity distributions over a time span of more than half the age of the universe. There is a hint, in our $z>1$ sample, of a lack of high ellipticity galaxies, though it is not significant in any of our tests. This is, in large part, because of the small sample size. There are only 48 galaxies in the $z>1$ cluster sample. In \S \ref{ellm}, we showed that the median ellipticity for the $z<0.05$ sample was essentially unchanged when Coma (A1656) was removed (see Table \ref{coma}). As expected from that test, there is essentially no change in these results on the ellipticity trends whether Coma is included or removed from the $z<0.05$ sample. \begin{figure*}[htbp] \begin{center} \includegraphics[width=6.5in]{f6.eps} \end{center} \caption[f6.eps]{Cumulative (top) and differential (bottom) ellipticity distributions for our four redshift bins. In each plot, we show the distribution of the ellipticities of all early-type galaxies in our magnitude and radius selection for all of the cluster galaxies in a given redshift bin. The distributions are represented by the shaded histograms, outlined in blue for $z<0.05$, green for $0.3 < z < 0.6$, orange for $0.6 < z < 1$, and red for $z>1$. For comparison with the $z>0.3$ cluster samples, we plot our sample of $z<0.05$ early-type galaxies in blue, with the low-redshift line ``hidden'' when the two lines (frequently) overlap. The $z<0.05$ sample is normalized to have the same number of galaxies as each of the $z>0.3$ cluster samples. The small deficit of highly elliptical galaxies at $z>1$ is not statistically significant because of the small sample size. Again, it is striking that there is no evolution in the shape of the distribution from $z<0.05$ to $z>1$. {\it The distribution of ellipticities at $z>0.3$ agrees with the shape of the $z<0.05$ distribution at the 1-2\% level (i.e., the probability that they are drawn from the same distribution is 98-99\%).}} \label{sumz_edist} \end{figure*} \section{Discussion} \label{disc} We find that neither the median ellipticity nor the shape of the high redshift ellipticity distribution of early-type cluster galaxies evolves with redshift, implying no change in the overall distribution of the bulge-to-disk ratio of early-type galaxies with redshift. As we show in Figure \ref{type_e}, the S0 population at low redshift ($z<0.05$) has a different ellipticity distribution than the elliptical population, with S0 galaxies having a higher median ellipticity. If the S0 fraction of the early-type galaxy population decreases, then the median ellipticity of the early-type population should decrease. The lack of evolution we observe in the median ellipticity and in the shape of the ellipticity distribution implies little or no evolution in the S0 fraction. This differs from the expectation from previous work, such as that of \citet{dressler97}, which finds a decrease in the S0 fraction with redshift. \subsection{Morphological Evolution in the $z>0.3$ Cluster Sample} \label{morphevol} One possible reason why we may not find any evolution in the ellipticity distribution of the cluster early-type population could be because of the nature of our sample. The fraction of galaxies morphologically selected as S0 galaxies may not change in our sample as has been found by other authors. However, when we look at the S0 fraction of our sample with redshift, using the visual classifications for our sample from the literature, we find a similar trend to what has been reported in other papers, i.e., a lower fraction of S0 galaxies at redshifts $z>0.4$. In Figure \ref{s0frac}, we plot the fraction of morphologically identified S0 galaxies with redshift (from the studies discussed in \S \ref{morph}). Our sample has properties consistent with previous work \citep{dressler97,fasano2000,postman2005,desai2007} as would be expected since our sample largely overlaps with previous studies and uses visual classifications from those studies. We find 42 $\pm$ 2\% of the early-type galaxy population are S0 galaxies at $z>0.4$. For comparison, the fraction of S0 galaxies within $2 R_{200}/\pi$ for the \citet{postman2005} ``$z\sim1$ composite'' sample is 35 $\pm$ 3\%. This shows that our red-sequence selection is consistent, being less than 2$\sigma$ different (the Postman {\em et~al.\,}\ 2005 value is derived by summing the individual listings in that paper's Table 4 under the item labeled ``$z\sim1$ composite''). Our $z<0.05$ sample of early-type cluster galaxies, selected in the same manner as our $z>0.3$ sample, has a S0 fraction of $68 \pm 3$\%. This fraction is consistent with other analyses. Examining the whole sample of early-type galaxies within $2 R_{200}/\pi$, we find a S0 fraction of $67 \pm 3$\% for all of the early-type galaxies within for the 10 clusters we use from \citet{dressler1980b}, in good agreement with that found by \citet{dressler97}. Therefore, our red-sequence selection produces a comparable sample of early-type cluster galaxies to those from previous efforts. We find no statistically significant evidence for evolution within the $z>0.4$ cluster sample, which is also consistent with most of the previous work \citep[e.g.,][]{fasano2000,postman2005,desai2007}. Using the visual classifications, our sample also shows that evolution in the S0 fraction occurs between $z\sim 0$ and $z\sim 0.4$ as the authors above have noted. Note that the fractions we are discussing here are the fraction of S0 galaxies in the early-type galaxy population \citep[see][for a discussion of the size of the systematic error in separating the elliptical and S0 populations.]{postman2005} The result from our measurements of the ellipticity distributions in our clusters is that there is essentially no evolution in the ellipticity distributions from $z\sim1$ to $z\sim 0$, and thus that there is no change in the overall distribution of the bulge-to-disk ratio of early-type galaxies. If we assume no evolution in the bulge-to-disk ratio distributions of the elliptical and S0 population separately as others have done, we can conclude that the E/S0 ratio does not evolve over this interval. This contrasts with the clear and significant evolution in the S0 fraction seen from many studies \citep[e.g.,][]{dressler97,fasano2000,postman2005,desai2007} based on visual classifications. While one explanation is that there is a problem with the visual classifications, this raises an interesting issue. In \citet{postman2005} and \citet{desai2007}, what evolves at $z>0.4$ is the fraction of S0 galaxies and the fraction of spiral and irregular galaxies. In contrast, the fraction of elliptical galaxies does not evolve. If the misclassification of round S0 galaxies as ellipticals alone causes the fraction of S0 galaxies to decrease, it is puzzling that there is no corresponding increase in the fraction of elliptical galaxies in \citet{postman2005} and \citet{desai2007}. Rather, in previous work, the spiral fraction increases, and there is little expectation that face-on S0 galaxies would be misclassified as spirals. The source of this difference remains to be resolved. Our study does not provide an opportunity for a resolution of this issue, but we wanted to highlight it for further work by others. \begin{figure}[htbp] \begin{center} \includegraphics[width=3.4in]{f7.eps} \end{center} \caption[f7.eps]{Ratio of morphologically identified S0 galaxies from the studies discussed in \S \ref{morph} to the total number of elliptical and S0 galaxies. The fraction of S0 cluster galaxies at $z>0.4$ is lower than that seen at $z<0.05$, as seen in previous work. We compute the average fraction of S0 galaxies in the early-type population for all of the $z>0.3$ clusters and plot that value, $42 \pm 2$\% as a solid black line. For contrast, we show the $z<0.05$ value, $68 \pm 3$\% , as a solid blue line. We plot, as squares, the average values of the S0 fraction of early-type galaxies in three redshift bins, $0.3 < z < 0.6$ (green), $0.6 < z < 1.0$ (orange) and $z >1$ (red). Our sample shows the same trend in S0 fraction found by other work. However, the very different fraction of galaxies classified as S0's at $z>0.4$ is in seeming contradiction with the lack of evolution in the ellipticity distribution.} \label{s0frac} \end{figure} \subsection{Ellipticity by Galaxy Type} Our simulations show that the estimates we use for ellipticities are robust, and do not show a large systematic change with redshift (see Figure \ref{cl_e}.) Some of the observed change in the fraction of S0 galaxies in Figure \ref{s0frac} may come about from a misclassification of round galaxies as ellipticals, as others \citep{jf94} have suggested and as we have discussed earlier. It would be useful to examine a sample of S0s for which the elliptical contamination was, likely, very small. We examined the fraction of galaxies with ellipticities above the median of the $z<0.05$ S0 population, $\epsilon_{med} = 0.38$. Measuring the fraction of galaxies with $\epsilon_{med} > 0.38$ should give us an estimate of the S0 population that we expect to be modestly contaminated by elliptical galaxies. In our $z<0.05$ sample, we find that $5 \pm 3$\% of galaxies with $\epsilon > 0.38$ are ellipticals. We plot the fraction of galaxies with $\epsilon_{med} > 0.38$ in Figure \ref{sharp} as a function of redshift. This once again, shows no change with redshift, implying a S0 fraction that does not evolve under the assumption that the ellipticity distribution of ellipticals and S0 galaxies do not separately evolve. \begin{figure}[htbp] \begin{center} \includegraphics[width=3.5in]{f8.eps} \end{center} \caption[f8.eps]{Fraction of cluster early-type galaxies with ellipticities greater than the median ellipticity of the $z<0.05$ S0 galaxies. The open circles are the fractions of galaxies with $\epsilon_{med} > 0.38$, in each cluster. The squares are the fractions for the $z< 0.05$ (blue), $0.3 < z< 0.6$ (green), $0.6 < z < 1.0$ (orange), and $z>1$ (red) samples respectively. At low redshift, this fraction has only a small contamination from elliptical galaxies, such that the fraction of galaxies with $\epsilon_{med} > 0.38$ is the half fraction of S0 galaxies with a 5\% contamination from elliptical galaxies. If the observed lack of evolution in the median ellipticity of the $z>0.3$ population is a result of evolution in the ellipticities of elliptical galaxies masking the decline in the S0 population, we should still see a change in the population of galaxies with $\epsilon_{med} > 0.38$. Galaxies with $\epsilon_{med} > 0.38$ represent the most inclined of the disk-dominated early-type galaxies at low redshift. The lack of evolution in this fraction suggests little evolution in the fraction of disk-dominated early-type galaxies as a whole.} \label{sharp} \end{figure} If the S0 fraction decreases with redshift while the median ellipticity of the early-type population stays the same, we expect that the ellipticity distribution for the S0 galaxies should increase. In Figure \ref{avge_type}, we plot the median ellipticity of galaxies that are classified visually as S0 galaxies. We show that the median ellipticity of the S0 population is higher in the higher redshift clusters. In the $z > 0.3$ sample, we find that the median ellipticity of the S0 galaxy population is $\epsilon_{med} = 0.47 \pm 0.02$ as compared with $\epsilon_{med} = 0.38 \pm 0.02$ in our $z < 0.05$ low redshift sample\footnote{These median values are the medians of the all S0 galaxies that meet our selection criteria. These are not the median of the data points we plot in Figure \ref{avge_type}. The error we quote is the error on the median, or $\sqrt(\pi/2)$ the error on the mean. We confirm these errors with bootstrapping which yields good agreement.}. The difference between the $z > 0.3$ and the $z < 0.05$ S0 samples medians is significant at the $>3\sigma$ when using a Student's t-test. Restricting the redshift range to $z>0.4$, the redshift where other authors have reported that the S0 fraction significant evolves, we find $\epsilon_{med} = 0.48 \pm 0.02$, which is also a $>3\sigma$ difference. The significance remains $>3\sigma$ regardless of whether Coma is included in the $z<0.05$ sample or not. \begin{figure}[htbp] \begin{center} \includegraphics[width=3.4in]{f9.eps} \end{center} \caption[f9.eps]{Median ellipticity versus redshift for cluster S0 galaxies. The open circles are the median ellipticities for the galaxies in each cluster. The blue squares are the median for all of the galaxies in the $z<0.05$ cluster sample. The other squares are the medians for the $0.3 < z< 0.6$ (green), $0.6 < z < 1.0$ (orange), and $z>1$ (red) samples, respectively. We also show the median value for the $z<0.05$ S0 sample as a blue line. We show, with a black line, the median ellipticities of all the S0 galaxies in our $z>0.3$ sample. The median ellipticity of the S0 population increases at $z>0.3$, with $\epsilon_{med} = 0.47 \pm 0.02$. The median ellipticity of the $z<0.05$ S0 galaxy is $\epsilon_{med} = 0.38 \pm 0.02$. Such a change in the ellipticity of galaxies classified as S0s can explain how the fraction of galaxies classified as S0's decreases while, at the same time, the median ellipticity of the cluster galaxy population as a whole stays the same.} \label{avge_type} \end{figure} In Figure \ref{hiz_mass_etype} (similar to Figure \ref{hiz_mass_e}, but with just the complete sample with E and S0 identified), we plot the ellipticities as a function of absolute magnitude in four redshift bins. It appears from this figure that there is a deficit of rounder S0 galaxies (blue points) at higher redshifts (excluding the $z>1$ bin which is less complete and has poor statistics), implying that the S0 galaxies at $z > 0.3$ are drawn from a different distribution than those at $z < 0.05$. The progression of higher ellipticities for the S0 population thus appears to come about from a change in the shape of the ellipticity distribution of S0 galaxies at higher redshift as compared with those at lower redshifts. We discuss this in \S \ref{evols0}. \begin{figure*}[htbp] \begin{center} \includegraphics[width=6.5in]{f10.eps} \end{center} \caption[f10.eps]{The distribution of ellipticity versus $M_B$ for cluster elliptical (red) and S0 (blue) galaxies in four redshift bins. The solid points are our sample within our magnitude limits of $-19.3 > M_B + 1.208 z > -21$. This plot is similar to Fig.\ \ref{hiz_mass_e}, except that we color code the S0 and elliptical galaxies separately. We show the median values of the populations as lines, red for the ellipticals and blue for the S0 galaxies. We find no statistically significant evolution in the elliptical population. There is a statistically significant ($>3\sigma$) change in the distribution of ellipticities for S0 galaxies when comparing the $z<0.05$ S0 population with $\epsilon_{med} = 0.38 \pm 0.02$ and the $0.3<z<0.6$ ($\epsilon_{med} = 0.46 \pm 0.02$) or $0.6<z<1$ sample ($\epsilon_{med} = 0.49 \pm 0.02$). The uncertainty in the highest redshift sample is too large for any useful comparisons to be made. The change in the ellipticity of the elliptical galaxies with redshift is not statistically significant. From this figure we conclude that the increase in the median ellipticity seen in Fig.\ \ref{avge_type} could arise from a lack of round S0 galaxies at redshifts higher than $z>0.3$. } \label{hiz_mass_etype} \end{figure*} In Figure \ref{hizell_type_dist}, we quantify what we see in Figure \ref{hiz_mass_etype}. We plot the distributions of the ellipticities for the $z > 0.3$ elliptical and S0 galaxies separately. We find that the shape of the $z>0.3$ S0 distribution differs from the $z<0.05$ distribution, in contrast with the elliptical distributions which show little change between the two samples. For example, if we examine the number of S0 galaxies with $\epsilon < 0.3$, we find that there are 56 in the $z>0.3$ sample, whereas we expect 95 from the scaled low redshift sample of S0 galaxies. We compared the shapes of the two S0 ellipticity distributions using a number of statistical tests. The probability of such a change in the ellipticity distribution of S0 galaxies is $>3\sigma$ when using a Kolmogorov-Smirnov, a Wilcoxon-Mann-Whitney rank sum test, and a Kuiper test. These are the same tests that showed no evolution in the ellipticity distribution in \S \ref{hizelldist}. These tests reinforce the result, from the analysis of the trends in Figure \ref{avge_type}, that the cluster S0 galaxies have a different ellipticity distribution at $z > 0.3$ than at $z < 0.05$. These trends, both in the median and in the shape of the distribution, are present regardless of how we select the higher redshift sample, whether $z>0.3$, $z>0.4$ or $0.4 < z < 1$. In all cases, the distributions differ from the $z<0.05$ sample at $>3\sigma$. \begin{figure*}[htbp] \begin{center} \includegraphics[width=6.5in]{f11.eps} \end{center} \caption[f11.eps]{Ellipticity distributions for cluster elliptical (left) and S0 (right) galaxies. The $z<0.05$ sample is shown in blue, while the $z>0.3$ sample is shown in red, with the median ellipticity for each shown as a appropriately colored vertical line. We find that the $z>0.3$ elliptical population is statistically the same as the $z<0.05$ population. In contrast, there is a statistically significant difference ($>3\sigma$) in the ellipticities of the S0 population. This appears to be a deficit of round S0 galaxies. We find 56 S0 galaxies with $\epsilon < 0.3$ in our $z>0.3$ sample, whereas we expect 95 S0 galaxies, after rescaling the $z<0.05$ to match the total number of expected S0 galaxies. This reinforces Fig.\ \ref{avge_type}, showing that the typical ellipticity for S0 galaxies at $z>0.3$ is higher than at $z<0.05$ and it appears that there is a deficit of round S0 galaxies which is causing this difference in the ellipticity distributions. } \label{hizell_type_dist} \end{figure*} Our work is not the only one that finds a different median ellipticity for S0 galaxies at higher redshift in cluster samples. \citet{moran2007} give the morphological classifications and ellipticities of a sample of S0 galaxies at $z\sim 0.45$. The authors measured the ellipticities of the cluster galaxies using the same approach and software that we use (and thus their ellipticities are PSF-corrected.) For their cluster S0 galaxies, \citet{moran2007} find $\epsilon_{med} = 0.48 \pm 0.04$, in excellent agreement with our value of $\epsilon_{med} = 0.48 \pm 0.02$. Previous work found little or no evolution in the ellipticities of S0 and elliptical galaxies. However, most of the previous work relied on measuring the ellipticities of galaxies using flux-weighted moments of galaxies, without taking into account the ``blurring'' effects of the PSF or the lower resolution of observations at higher redshifts. We show, in Appendix \ref{ellrob}, that the ellipticity measurements of galaxies based on simple flux-weighted moments are biased quite significantly towards rounder values for the ACS and WFPC2 data that has been used without correcting for the effects of smoothing by the PSF. \subsection{Constraints on the Evolution of the Bulge-to-Disk Ratio} \label{btod} The observed lack of any evolution in the ellipticity distribution for early-type galaxies has interesting implications for the distribution of the bulge-to-disk ratios of the early-type population from $z \sim 0$ to $z \sim 1$. The average observed ellipticity is directly related to the average intrinsic ellipticity \citep{binneym1998}. If the average bulge-to-disk of a population of galaxies changes, the average intrinsic ellipticity must change too, and vice versa. Our measurement of an unchanging ellipticity distribution implies that the average bulge-to-disk remains constant. We performed simple simulations to derive the average ellipticities using models of galaxies with a variety of bulge-to-disk ratios projected over all possible viewing angles with a fixed scale length for the bulges and disk. We find a roughly linear relation between the average bulge-to-total ratio and the average ellipticity of the population. For example, for these simple models, a change in the average bulge-to-total ratio from 0.1 to 0.3, or from 0.3 to 0.6, would be observed as a shift of $\delta \bar{\epsilon} = 0.08$ in the average ellipticity. Such a shift would be a $4\sigma$ change for our samples (see Figure \ref{avgell}.) While one could potentially develop a model whereby the underlying scale lengths relatively evolve with redshift, this seems rather contrived. ``Occam's Razor'' would lead one to prefer a model where a constant ellipticity distribution implies a constant distribution of bulge-to-disk ratios over the redshift range from $z\sim1$ to $z\sim0$. \subsection{Implications for Evolution in the Fraction of Disk-Dominated Early-type Galaxies} \label{evols0} We performed simulations to see if the observed S0 fraction of 42\%, for the sample of clusters with $z>0.4$, is consistent with the lack of evolution we see in the ellipticity distribution. We constructed 10,000 mock catalogs for the clusters in the $z>0.4$ sample. For each cluster, we assumed that the fraction of S0 galaxies was 42\%. We randomly drew the ellipticities for the S0s from the observed distribution of S0s at $z<0.05$, and drew the ellipticities for the Es from the observed low redshift distribution for Es (see Figure \ref{type_e}.) We added the uncertainties and systematics applicable at high redshift as detailed in \S \ref{measure} and Appendix \ref{simreal} The resulting ellipticity distributions had median ellipticities lower than the observed value (0.29) for all 10,000 of the mock catalogs, with a typical value of $\epsilon_{med}=0.25$. This rules out at $>4\sigma$ the assumption that the underlying ellipticities and S0 fraction are both constant with redshift. Our others tests which we use to compare the $z<0.05$ sample and the $z>0.3$ sample give similar results (the Kolmogorov-Smirnov statistic, a Wilcoxon-Mann-Whitney rank sum statistic and a Kuiper statistic). None of the mock catalogs show the same good agreement between the $z>0.3$ sample and $z<0.05$ sample in the ellipticity distribution as we observe. We repeated these simulations for a variety of S0 fractions. We find that the S0 fraction value that best matches the $z>0.4$ ellipticity distribution is 66\% with a $1\sigma$, or 68\% confidence limits, of $\pm$6.5\%. Another way to consider this is a $1 \sigma$ change in the median ellipticity at $z>0.3$, a change of $\delta \epsilon=0.02$, would imply a change in the S0 fraction of 6.5\%. We can rule out, at the 95\% confidence limit, S0 fractions below 53\%, and we can rule out the observed fraction of visually classified S0 galaxies of 42 $\pm$ 2\% at the $>99.9\%$ confidence limit or at the 4$\sigma$ level. To reconcile the evolution seen in the S0 fraction in the visually-classified samples with the lack of evolution in the ellipticity distribution requires that either the S0 and elliptical populations evolve in ellipticity in such a way that the combined samples shows no evolution, or that some fraction of the S0 population has been misclassified as other morphological types \citep[cf.,][]{jf94,blakeslee2005}. \subsubsection{Possible Spiral Contamination?} One possibility is that the higher ellipticity, or more edge-on, S0 population is contaminated with misclassified red spirals. This would cause the S0 fraction to be overestimated, while, at the same time change the shape of the ellipticity distribution. The spiral fraction among galaxies in the mass range of the cluster sample in our work is $\sim10-15$\% \citep{holden2007} while the fraction of dusty, red objects is $\sim10$\% \citep{saintonge2008}. Since the misclassification would be predominately for edge-on systems, these fractions are likely upper limits for the fraction of spirals misclassified as S0 galaxies. Is it possible that such a small fraction of ``spiral'' galaxies could contaminate the population visually classified as S0 galaxies and change the ellipticity distribution at higher redshift? We examined the ellipticities of the galaxies classified as spirals in both the $z<0.05$ and $z>0.3$ sample to see if there is a deficit of edge-on spirals. We found the opposite, that there is a shift in the high redshift spiral population to larger ellipticities, $\epsilon_{med} = 0.38 \pm 0.04$ at $z<0.05$ \citep[as expected, see][]{ryden2006} to $\epsilon_{med} = 0.45\pm 0.03$ at $z>0.3$, but it is not statistically significant. From this we conclude that a red spiral population is not a major source of contamination, especially at large ellipticities. Given the quantitative nature of the current study we feel that it provides a key datum for consideration of the evolutionary history of early-type galaxies over the last 8 Gyr. The result that the ellipticity distribution is essentially unchanged from $z\sim 0$ to $z\sim 1$, combined with the result that the fraction of highly elongated disk-dominated systems does not evolve (see Figure \ref{sharp}), provides strong evidence that the overall bulge-to-disk ratio distribution of the population does not evolve. \section{Summary and Implications} \label{conclusion} We have compiled a sample of 10 $z>0.05$ clusters of galaxies and a comparable sample of 17 $z>0.3$ clusters of galaxies with {\em HST} imaging. For each cluster, we selected a subsample of galaxies that lie on the red sequence and have been classified as an early-type galaxy (elliptical or S0 galaxy). To derive a robust sample at all redshifts, we selected galaxies to fall within a magnitude range of $-19.3 > M_B+ 1.208 z > -21$ and required the galaxies to lie within $2 R_{200}/\pi $ (to ensure that the de-projected sample lies within $R_{200}$) of the cluster center. We change the rest-frame $B$ magnitudes by $1.208 z$ to match the mass-to-light evolution of cluster early-type galaxies as measured by the fundamental plane \citep{vandokkum2006}. The magnitude limits correspond to $M^*_B +1 > M_B > M^*_B - 0.75$ or galaxies with stellar masses roughly between $10^{10.6}\ M_{\sun} < M < 10^{11.2}\ M_{\sun}$, assuming a ``diet'' Salpeter IMF. We performed extensive simulations of the ellipticity measurements to test their robustness and to minimize systematics with redshift. We found that it is crucial to use model fits (e.g., GALFIT) where the effect of the PSF can be modeled and removed. From our extensive simulations we find that we can robustly measure the ellipticity of cluster early-type galaxies (by using PSF-corrected model fits) out to $z\sim 1.3$ at magnitudes that allow the galaxies to also be morphologically classified. The systematic error we find in our simulations is only $\delta_{\epsilon} = -0.01$, or a 3\% change for the median galaxy. We do not apply this small correction to our data. We find that not including the effect of the PSF can cause systematic shifts of $\delta_{\epsilon} = -0.10$, or a 30\% change for the median galaxy. Using our two samples of cluster early-type galaxies, we measure the evolution in the ellipticity of $z>0.3$ cluster early-type galaxies compared with a substantial sample at $z<0.05$. \begin{enumerate} \item We find no evolution in the median ellipticity of $z>0.3$ cluster early-type (elliptical and S0) galaxies relative to the low redshift sample. The median ellipticity at $z<0.05$ is $\epsilon_{med} = 0.29 \pm 0.02$, and is $\epsilon_{med} = 0.30 \pm 0.01$ at $z>0.3$. {\it The median ellipticity of our sample of 487 early-type galaxies at $z > 0.3$ is statistically the same as that of the 210 early-type galaxies at $z < 0.05$, being higher by only 0.01 $\pm$ 0.02 or 3 $\pm$ 6\%.} \item The shape of the ellipticity distribution of $z>0.3$ galaxies also does not evolve. {\it The distribution of ellipticities at $z>0.3$ agrees with the shape of the $z<0.05$ distribution at the 1-2\% level (i.e., the probability that they are drawn from the same distribution is 98-99\%).} \item Using visual classifications from previous reference studies, we find that our sample shows a similar decrease in the fraction of early-type galaxies classified as disk-dominated systems (S0s) at $z>0.4$. As other studies have found, t he S0 fraction is 68$\pm$3\% at $z<0.05$ and decreases to 42$\pm$2\% at $z>0.4$. \item For the S0 fraction to decrease with increasing redshift, while the median ellipticity of the overall cluster early-type population stays the same, the median S0 ellipticity needs to be larger at higher redshift. There is a trend in our data for $z>0.3$ in this sense. The median S0 galaxy at $z<0.05$ is $\epsilon_{med} = 0.38 \pm 0.02$ while at $z > 0.3$, we find a $\sim 3\sigma$ different $\epsilon_{med} =0.47 \pm 0.02$ for galaxies classified as S0s. Whether this change is large enough to account for the change seen in the morphological sample remains to be determined. We explored if the change in the ellipticity distribution of S0 galaxies could come from a deficit of round S0 galaxies or from the addition of misclassified spiral galaxies. However, we found that neither of these simple scenarios can explain our results. \end{enumerate} Our results on the unchanging ellipticity distributions lead us to conclude that there has been little or no evolution in the overall distribution of bulge-to-disk ratio of early-type galaxies over the redshift range $0 < z < 1$ for morphologically-selected samples of early-type red-sequence galaxies with $M^*_B + 1 > M_B > M^*_B - 0.75$ in the dense cores of clusters inside $R_{200}$. In particular, our results allow us to rule out a S0 fraction of $<$47-51\% at $z>0.3$ at the 3$\sigma$ level assuming no evolution in the ellipticity distributions of elliptical and S0 galaxies. {\it If we assume, as in all previous studies, that the intrinsic ellipticity distribution of both elliptical and S0 galaxies remains constant, then we conclude from the lack of evolution in the observed early-type ellipticity distribution that the relative fractions of ellipticals and S0s do not evolve over the last $\sim8$Gyr, or from $z\sim1$ to $z=0$, for a red-sequence selected sample of early-type galaxies in the cores of clusters of galaxies.} These results do highlight an inconsistency within the wide range of studies that have occurred on the evolution of early-type galaxies over the last decade. Over this redshift range, and particularly since $z\sim0.4$, the fraction of morphologically-identified S0 galaxies from visual classifications has been found to be significantly lower than the $z\sim0$ value \citep[see, e.g., ][]{dressler97,fasano2000,postman2005,desai2007}. Reconciling the trends seen in the elliptical, S0 and spiral fractions, as discussed in \S \ref{morphevol} remains to be understood. The early-type galaxy population, both in the field and in clusters, does not evolve purely passively. The volume-averaged number density of red galaxies, which are mostly early-type galaxies \citep{bell2004b}, grows by a factor $\sim2$ between $z\sim 1$ and the present \citep{bell2004,brown2007,faber2007}. For the cluster population such evolution is harder to quantify, but mergers \citep{vandokkum1999,tran2005} and filaments around massive clusters at $z\sim 0.8$ \citep[e.g.,][]{kodama2005,patel2008} suggest that interactions and infalling galaxies enhance and modify over time the galaxy population in the cluster core. Besides evolution in the population of early-type galaxies, individual early-type galaxies also change over time. As pointed out by, e.g., \citet{jorgensen2005}, the evolution of the line strengths is not compatible with purely passive evolution. Moreover, early-type galaxies at $z\sim1$ were recently demonstrated to be significantly smaller than today by a factor of two \citet{vanderwel2008c}. Hence, the resulting picture is complicated: early-type galaxies, both as individual objects and as a population, undergo substantial changes between $z\sim 1$ and the present. On the other hand, many basic properties of the early-type population have remained unchanged over the past $\sim8$Gyrs, providing useful means for characterizing and quantifying the observed evolution. At any redshift $z\sim1$ early-type galaxies occupy a tight color-magnitude relation \citep[e.g.,][]{blakeslee2005} and fundamental plane \citep[e.g.,][]{wuyts2004}, which suggests smooth and regular evolution. Moreover, neither in the field nor in clusters has the early-type {\it fraction} changed significantly in mass-selected samples \citep{holden2007,vanderwel2007}. Together with these characteristics, the results presented in this paper fit into a picture in which the field and cluster early-type galaxy populations grow and change, but only while leaving many basic characteristics the same. In particular, we have demonstrated from the constancy of the ellipticities of early-type galaxies over the last $\sim8$Gyr that the bulge-to-disk ratio distribution of the cluster population remains constant. This suggests that processes that change the bulge-to-disk ratio of individual early-type galaxies and the bulge-to-disk ratios of newly formed or accreted early-type galaxies are balanced such that the overall bulge-to-disk ratio distribution remains the same. It remains an open question why this is the case, but it is clear that much can be learned about the formation process of early-type galaxies by studying their properties in even more detail and extending their observation to higher redshifts. \vspace{.3cm} The authors would like to thank S. Adam Stanford for useful comments. We would like to thank the anonymous referee for suggestions that improved this paper. Finally, we would like to thank Stefano Andreon for pointing out previously published related papers, and Dave Wilman for showing us his work ahead of publication. ACS was developed under NASA contract NAS5-32865, this research was supported by NASA grant NAG5-7697. We are grateful to K.~Anderson, J.~McCann, S.~Busching, A.~Framarini, S.~Barkhouser, and T.~Allen for their invaluable contributions to the ACS project at JHU. This research has made use of the NASA/IPAC Extragalactic Database (NED) which is operated by the Jet Propulsion Laboratory, California Institute of Technology, under contract with the National Aeronautics and Space Administration. The analysis pipeline used to reduce the DEIMOS data was developed at UC Berkeley with support from NSF grant AST-0071048.
{ "redpajama_set_name": "RedPajamaArXiv" }
789
var myId = document.location.search.split('=')[1]; var dog; var id_of_med_to_update; var id_of_app_to_update; var id_of_vac_to_update; var id_of_die_to_update; //xhr.open('GET','http://dog-tracker-api.herokuapp.com/dogs/' + myId, true); function editAppointment(appointment) { console.log(appointment); id_of_app_to_update = appointment.id; $('#appointment_date').val(appointment.appointment_date); $('#location').val(appointment.location); $('#vet_name').val(appointment.vet_name); $('.modal-edit-appointment').modal({show: true}); } function hideEditAppointment() { $('.modal-edit-appointment').modal('hide'); } function editMedication(medication) { console.log(medication); id_of_med_to_update = medication.id; $('#med_name').val(medication.name); $('#dose').val(medication.dose); $('#med_comment').val(medication.comment); $('.modal-edit-medication').modal({show: true}); } function hideEditMedication() { $('.modal-edit-medication').modal('hide'); } function editVaccination(vaccination) { console.log(vaccination); id_of_vac_to_update = vaccination.id; $('#vacc_name').val(vaccination.name); $('#last').val(vaccination.last); $('#next').val(vaccination.next); $('.modal-edit-vaccination').modal({show: true}); } function hideEditVaccination() { $('.modal-edit-vaccination').modal('hide'); } function editDietaryRestriction(dietary_restrictions) { console.log(dietary_restrictions); id_of_die_to_update = dietary_restrictions.id; $('#food_name').val(dietary_restrictions.food_name); $('#comment').val(dietary_restrictions.comment); $('.modal-edit-dietary-restrictions').modal({show: true}); } function hideEditDietaryRestriction() { $('.modal-edit-dietary-restrictions').modal('hide'); } $.get('http://dog-tracker-api.herokuapp.com/dogs/' + myId, function(data){ dog = data; $("#name")[0].innerHTML = dog.name; $("#breed")[0].innerHTML = dog.breed; $("#weight")[0].innerHTML = dog.weight; $("#age")[0].innerHTML = dog.age; $("#sex")[0].innerHTML = dog.sex; if (dog.is_spayed_or_neutered) { $("#fixed")[0].innerHTML = 'Yes'; } else { $("#fixed")[0].innerHTML = 'No'; } //$("#appnt")[0]; var appointments = $("#apptBody")[0]; for (var i = 0; i < dog.appointments.length; i++ ) { var containerDiv = document.createElement("div"); containerDiv.className = "items-container"; appointments.appendChild(containerDiv); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel1 = document.createElement("label"); newLabel1.innerHTML = "Date: "; var newSpan1 = document.createElement("span"); newSpan1.innerHTML = new Date(dog.appointments[i].appointment_date).toDateString(); newDiv.appendChild(newLabel1); newDiv.appendChild(newSpan1); containerDiv.onclick =(function() { var temp_appointment = dog.appointments[i]; return function() { editAppointment(temp_appointment); } })(); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel2 = document.createElement("label"); newLabel2.innerHTML = "Location: "; var newSpan2 = document.createElement("span"); newSpan2.innerHTML = dog.appointments[i].location; newDiv.appendChild(newLabel2); newDiv.appendChild(newSpan2); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel3 = document.createElement("label"); newLabel3.innerHTML = "Vet Name: "; var newSpan3 = document.createElement("span"); newSpan3.innerHTML = dog.appointments[i].vet_name; newDiv.appendChild(newLabel3); newDiv.appendChild(newSpan3); } var vaccinations = $("#vaccBody")[0]; for (var v = 0; v < dog.vaccinations.length; v++ ) { var containerDiv = document.createElement("div"); containerDiv.className = "items-container"; vaccinations.appendChild(containerDiv); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel1 = document.createElement("label"); newLabel1.innerHTML = "Name: "; var newSpan1 = document.createElement("span"); newSpan1.innerHTML = dog.vaccinations[v].name; newDiv.appendChild(newLabel1); newDiv.appendChild(newSpan1); containerDiv.onclick =(function() { var temp_vaccination = dog.vaccinations[v]; return function() { editVaccination(temp_vaccination); } })(); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel1 = document.createElement("label"); newLabel1.innerHTML = "Last: "; var newSpan1 = document.createElement("span"); newSpan1.innerHTML = new Date(dog.vaccinations[v].last).toDateString(); newDiv.appendChild(newLabel1); newDiv.appendChild(newSpan1); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel1 = document.createElement("label"); newLabel1.innerHTML = "Next: "; var newSpan1 = document.createElement("span"); newSpan1.innerHTML = new Date(dog.vaccinations[v].next).toDateString(); newDiv.appendChild(newLabel1); newDiv.appendChild(newSpan1); } var dietary_restrictions = $("#dietBody")[0]; for (var d = 0; d < dog.dietary_restrictions.length; d++ ) { var containerDiv = document.createElement("div"); containerDiv.className = "items-container"; dietary_restrictions.appendChild(containerDiv); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel1 = document.createElement("label"); newLabel1.innerHTML = "Food name: "; var newSpan1 = document.createElement("span"); newSpan1.innerHTML = dog.dietary_restrictions[d].food_name; newDiv.appendChild(newLabel1); newDiv.appendChild(newSpan1); containerDiv.onclick =(function() { var temp_dietary_restrictions = dog.dietary_restrictions[d]; return function() { editDietaryRestriction(temp_dietary_restrictions); } })(); var newDiv = document.createElement("div"); containerDiv.appendChild(newDiv); var newLabel1 = document.createElement("label"); newLabel1.innerHTML = "Comment: "; var newSpan1 = document.createElement("span"); newSpan1.innerHTML = dog.dietary_restrictions[d].comment; newDiv.appendChild(newLabel1); newDiv.appendChild(newSpan1); } var medications = $("#medBody")[0]; for (var i = 0; i < dog.medications.length; i++ ) { var containerDivB = document.createElement("div"); containerDivB.className = "items-container"; medications.appendChild(containerDivB); var newDivB = document.createElement("div"); containerDivB.appendChild(newDivB); var newLabelB1 = document.createElement("label"); newLabelB1.innerHTML = "Name: "; var newSpanB1 = document.createElement("span"); newSpanB1.innerHTML = dog.medications[i].name; newDivB.appendChild(newLabelB1); newDivB.appendChild(newSpanB1); containerDivB.onclick =(function() { var temp_medication = dog.medications[i]; return function() { editMedication(temp_medication); } })(); var newDivB = document.createElement("div"); containerDivB.appendChild(newDivB); var newLabelB2 = document.createElement("label"); newLabelB2.innerHTML = "Dose: "; var newSpanB2 = document.createElement("span"); newSpanB2.innerHTML = dog.medications[i].dose; newDivB.appendChild(newLabelB2); newDivB.appendChild(newSpanB2); var newDivB = document.createElement("div"); containerDivB.appendChild(newDivB); var newLabelB3 = document.createElement("label"); newLabelB3.innerHTML = "Comment: "; var newSpanB3 = document.createElement("span"); newSpanB3.innerHTML = dog.medications[i].comment; newDivB.appendChild(newLabelB3); newDivB.appendChild(newSpanB3); } }); function addAppmnt() { document.location.href = 'addAppointment.html?id=' + myId + '&name=' + dog.name + '&breed=' + dog.breed + '&sex=' + dog.sex + '&weight=' + dog.weight + '&age=' + dog.age + '&is_fixed='+ dog.is_spayed_or_neutered; } function addMeds() { document.location.href = 'addMedication.html?id=' + myId + '&name=' + dog.name + '&breed=' + dog.breed + '&sex=' + dog.sex + '&weight=' + dog.weight + '&age=' + dog.age + '&is_fixed='+ dog.is_spayed_or_neutered; } function addVacs() { document.location.href = 'dogVaccs.html?id=' + myId + '&name=' + dog.name + '&breed=' + dog.breed + '&sex=' + dog.sex + '&weight=' + dog.weight + '&age=' + dog.age + '&is_fixed='+ dog.is_spayed_or_neutered; } function addDiet() { document.location.href = 'dogDiet.html?id=' + myId + '&name=' + dog.name + '&breed=' + dog.breed + '&sex=' + dog.sex + '&weight=' + dog.weight + '&age=' + dog.age + '&is_fixed=' + dog.is_spayed_or_neutered; } function back(){ document.location.href = "dog-table.html"; } function home(){ document.location.href = "home.html"; } $('#activateAppt').click(function(){ $("#apptBody").slideToggle(); }); $('#activateMed').click(function(){ $("#medBody").slideToggle(); }); $('#activateVaccs').click(function(){ $("#vaccBody").slideToggle(); }); $('#activateDiet').click(function(){ $("#dietBody").slideToggle(); }); function updateAppointment() { var app = {}; app.appointment = { date: $('#appointment_date')[0].value, location: $('#location')[0].value, vet_name: $('#vet_name')[0].value }; $.ajax({ type: "PUT", url: 'http://dog-tracker-api.herokuapp.com/appointments/' + id_of_app_to_update, contentType: "application/json", data: JSON.stringify(app), success: function() { hideEditAppointment(); window.location.reload(); } }); } function updateMedication() { var med = {}; med.medication = { name: $('#med_name')[0].value, dose: $('#dose')[0].value, comment: $('#med_comment')[0].value }; $.ajax({ type: "PUT", url: 'http://dog-tracker-api.herokuapp.com/medications/' + id_of_med_to_update, contentType: "application/json", data: JSON.stringify(med), success: function() { hideEditMedication(); window.location.reload(); } }); } function updateVaccination() { var vac = {}; vac.vaccination = { name: $('#vacc_name')[0].value, last: $('#last')[0].value, next: $('#next')[0].value }; $.ajax({ type: "PUT", url: 'http://dog-tracker-api.herokuapp.com/vaccinations/' + id_of_vac_to_update, contentType: "application/json", data: JSON.stringify(vac), success:function() { hideEditVaccination(); window.location.reload(); } }); } function updateDietaryRestriction() { var die = {}; die.dietary_restriction = { food_name: $('#food_name')[0].value, comment: $('#comment')[0].value }; $.ajax({ type: "PUT", url: 'http://dog-tracker-api.herokuapp.com/dietary_restrictions/' + id_of_die_to_update, contentType: "application/json", data: JSON.stringify(die), success: function() { hideEditDietaryRestriction(); window.location.reload(); } }); }
{ "redpajama_set_name": "RedPajamaGithub" }
6,489
Begin Reading Table of Contents About the Author Copyright Page Thank you for buying this Tom Doherty Associates ebook. To receive special offers, bonus content, and info on new releases and other great reads, sign up for our newsletters. Or visit us online at us.macmillan.com/newslettersignup For email updates on the author, click here. The author and publisher have provided this e-book to you without Digital Rights Management software (DRM) applied so that you can enjoy reading it on your personal devices. This e-book is for your personal use only. You may not print or post this e-book, or make this e-book publicly available in any way. You may not copy, reproduce, or upload this e-book, other than to read it on one of your personal devices. Copyright infringement is against the law. If you believe the copy of this e-book you are reading infringes on the author's copyright, please notify the publisher at: us.macmillanusa.com/piracy. As always, to my husband and boys for being the light in every day of my life and showing me that real heroes exist, and that they're funny to boot. To my friends who keep me sane. My readers who take these trips of fantasy with me and who never fail to make me smile. And a special thank-you to Claire, Linda, and Robert for giving me the chance to do something I've been wanting to do for a long time and for not clipping my wings when I finally took the leap over the edge. Most of all, for my big brother, who never once rolled his eyes at my stories when I was a girl, and for all the crayons you gave me so that I could draw my characters and leave you in peace. I miss you every day of my life and wish you could have seen the series you loved so much reach even higher than that pirate kite you saved for me from the mean, angry tree that tried to eat it. You were and shall always be my greatest hero. The monster slayer who battled the closet demons of my mind and kept me sage through the darkest nights and storms that seemed to go on without stalling. I don't know where I'd be had you not been my brother. I love you, Buddy. This book is for you. Acknowledgments To my grandfathers, who introduced me to the world of demons and angry spirits, and who taught me to see beyond the veil and showed me how to protect myself and to fight for others. And for all those spiritual warriors in my life who continue the fight and who've aided me so many times when I needed you. Thank you, Tish, Bill, Leanna, and Marianne. Most of all, my Grandmother Moon, who taught me to read signs, pay attention to nature, and to see the unseen. There is magick all around us. We just have to stop and open our eyes. PROLOGUE In the Year of Our Lord 1715, July 31 Off the Shores of Cape Canaveral, Florida "Well, we learned a vital lesson here today, me mateys. You canna keelhaul a demon no matter how hard you try for it. The rotten crafty beastie bastard won't be having none of it." Half the crew turned to stare agape at Captain Paden Jack. The other half rolled their eyes and cursed him, then questioned his saintly mother's impeccable reputation, as well as the legitimacy of his parentage and all his intelligence. If they weren't about to die, he'd take a mite more offense to their sordid insults. But right here, right now, as he looked past them and saw the great, heinous monster what was rising up from the darkest swirling depths off their port bow, insubordination seemed like a wee bit of a petty concern. Never in all his years at sea had Paden beheld anything like its twisted, inhuman form, and he'd seen quite a lot. Its leathery skin literally boiled and caused the water 'round it to bubble with the same noxious fumes—a fetid sulphuric stench that exploded the moment it contacted the fire left from all the attempts they'd made to lay the beast low. Nothing had worked. Not a single trick. His quartermaster staggered back. "The sea is the devil and that wicked bitch takes pity on none." Aye, Paden couldn't agree more. They were done for. To the watery locker they be headed, with every last man-jack here. At least those who weren't headed straight for hell. Strange how he felt no fear, what with his assured damnation looming. And he should. You'd think what given the sins of his past and all the things he'd done in this life, they'd be haunting him now. Yet all Paden felt was an untoward kind of peace with it all. This was the way of it. He'd known this day would come for him—sooner, rather than later—the heartbeat he'd accepted his destiny by taking up his mother's sword and embracing the blood that flowed within him. It always did for ones such as he. His only regret was that he'd be taking his crew with him for the journey down. And that he'd be breaking his promise to marry Letty on his return. But the greatest burn of all was that his poor baby sister would be left alone in this world, with none more to look after her. That his great, horrific burdens would now fall to her tiny shoulders. Damn shame, that. Cammy deserved better than what the fates had dealt the lass. They'd be coming after her now to pick up the mantle their ancestors had cursed them with. But there was no use lamenting for it. God and all His saints had turned a deaf ear to his pleas and prayers long ago. His quartermaster, Edmond, passed a sorry stare to him before crossing himself. "What be your orders, Captain Jack?" "Abandon ship, Mr. Symmes. Save as many as you can." It wasn't until after Symmes had relayed those orders that he realized Paden had no intention of joining them in their escape. Safety wasn't his calling this day. Instead of trying to find room on a dinghy with the others, Paden was rolling barrels of gunpowder closer to the port bow, where the beast still tried its best to devour them whole. "Captain? What are you about, man?" Paden handed his quartermaster his cutlass and flintlocks. "This fine ship be me ladylove—me one true mistress and owner of me hell-bound soul. It's me duty and honor to escort her to her final destination. And be damned if I'm letting that bastard there have her without taking a piece of him with us. Get yourselves safe. Think naught of me anymore, Mr. Symmes. God be with you as I know He's never been with me." His gaze sad, Ed hesitated. But a moment was all he had, as the demon slammed against the ship, knocking her sideways and causing her to list. "It's been me privilege, Captain." He held his arm out to Paden. "Mine as well." He shook Ed's hand. "Now off with you, quick." Ed ran as the ship tipped dangerously, spilling more men over her side. Retrieving the linstock from the deck where one of their powder monkeys had abandoned it as he fled for the dinghies, Paden waited until the last of the boats had dropped. He pulled a striker and flint from his pocket and lit the cord so that he could ignite the powder. The demon started after his fleeing crew. "Hey now!" he shouted at the beast. "Where do you think you be headed, you filthy, odiferous bung!" He waved the linstock over his head to get the demon's attention back on him as he struck the side of the ship with the end of it, making as much racket as he could. It worked. Snarling, the demon turned and, with a hell-born cry, made straight for Paden. His heart pounding in anticipation of what was to come, he waited for their inevitable confrontation. This time, the beast dared to climb aboard. That's it, ye filthy bastard. Come get some of me. Leave me crew in peace. With no real form, the gelatinous mess slithered across the deck and rose up before him with dark, soulless eyes. Refusing to show his fear, as it would only make the beast stronger, or to back down before it, Paden stood his ground with every bit of grit he possessed. "Aye, you want me, don't you? You know what I am, and I know ye for the evil in your heart." Possessed of great bulbous eyes, it slobbered and drooled and reached with one taloned hand. Just as it would have slashed him open, Patrick Michel Alister Jack lowered his linstock to the keg of gunpowder that lay between them and set the barrel ablaze. The last sound he heard was deafening, and it ended with a bright flash and one massive explosion of pain. In the Year of Our Lord 1716 Jamaica "Way I hear tell it, that one's so bad, he whups his own arse thrice a week." Eyes wide, Cameron Amelia Maire Jack burst out laughing at the unexpected, dry comment she overheard above the raucous tavern voices and music. Until she caught sight of the man it was directed toward. That sobered her quick enough. Holy mother of God... There was no way to miss that giant mass of human male as he swept into the crowded room like the living embodiment of some ancient hero. Nay, not a hero. A pagan god. At least six and a half feet tall, he towered over everyone else there, and had a shoulder width so great he was forced to turn to the side to come through the doorway, and stoop down lest he decapitate himself with the thick, low-hanging beam. A feat he accomplished with a masculine grace and swagger that said he'd done it enough that it was habit from years of experience. Which made her wonder how many times as a boy he must have whacked his head afore he learned to instinctively duck like that. With a quick swipe of his massive hand, he removed his black tricorne hat and tucked it beneath his muscled arm, exposing a thick mane of unbound, wavy sable hair that gleamed in the dull candlelight. He held a set of rugged features that appeared chiseled from stone—in perfect masculine proportions. Never in her life had she beheld his equal in form, strength, or grace, but it wasn't just the unexpected sight of him. He possessed that raw, commanding presence that was unrivaled by king or commander. An air of noble refinement that was offset by an aura of bloodthirsty intolerance, cool indifference, and utter ennui. He was lethal, no doubts there. Beguiling. More than that, he was an enigmatic study of warring contradictions that quickened her heart a lot more than she wanted to admit to anyone, especially herself. In a festering den of inhospitable inequity and evil, this man reigned as its supreme emperor. And while his two companions were dressed in brightly colored brocades—like the other vain occupants of the room—this one, in stark contradiction, wore a somber black wool coat, breeches with plain brass buttons, and an unremarkable dark brown waistcoat. Even his cotton shirt and neckerchief were as black as his hair and boots. Like a Quaker... and yet his demeanor and weaponry said he didn't partake of their religion or peaceful ways. The only color on his body was the bloodred hilt of a barbarian-styled cutlass. And a flashing ruby signet ring on his pinky that caught the light. But for his fierce stance, deadly demeanor, and the firm hand that stayed planted on the hilt of that sword, he could easily pass for a respectable man. Nobleman even. Until one met that cold, dark, intelligent gaze that saw everything around him to the most microscopic detail. She could literally feel him tallying the strengths of everyone in the tavern and sizing them up for their every weakness of character and physical flaw.... As well as their caskets. He was exactly the kind of unnerving male that caused her and Lettice to draw straws on his entrance back home in the Black Swan to see which of them would be stuck for the night waiting on his table. And Cameron always cheated to make sure she wasn't the one left with it. Something that would bother her conscience a lot more but for the fact that it was Lettice's father who owned the Swan, and while Nathaniel Harrison would guard his daughter's reputation and well-being, he wasn't nearly as circumspect when it came to hers. Especially when placed against his need for profit. He'd sell all but his daughter for that. Even his own mother, and probably his wife to boot. Not wanting to think about that, Cameron scowled at the men flanking the newcomer. His companions were much more the typical pirate or privateer fare one would expect to find in such a sordid place. The one to his right had a mane of long brown hair he wore tied back in an impeccable queue, along with a well-trimmed beard, and eyes so light and merry a blue they glowed in the dim light. Each of that man's fingers held an ornate ring—no doubt plunder from some unwary ship he'd raided—if not some unfortunate corpse. Still, he seemed amicable enough. While many Caribbean pirates had a tendency to pierce their earlobes, this one had chosen to place a small gold hoop in his left eyebrow, just off its arch. His elaborate burgundy and black coat was widely cut at the waist—in the latest fashion craze. And where the beguiling and dangerous captain had chosen a plain black neckerchief to wear, this pirate's cravat was stark white silk, and trimmed in layers of decadent lace. The man on the left was dressed in a peacock blue silk coat that covered an insanely ornate gold waistcoat. One so fine a silk that it shimmered in the light like water. He wore a small white wig that concealed his hair color, but judging from his skin tone, dark eyebrows, and the careless whiskers that dusted his well-sculpted cheeks and jawline, she assumed his hair was as dark as his captain's. Yet where the captain had a set of coal black eyes, his were a deep shade of hazel blue. While his mood and countenance weren't as dark and sinister as his captain's, he was nowhere near as jovial as their companion, either. She'd guess him as the quartermaster. Or a hangman. The three of them swept past her without so much as a glance in her general direction, letting her know they saw her as no threat whatsoever—which was fine by her. Last thing she wanted was to be crossed up with such terrifying and deadly men. They made their way to the back of the tavern to an empty table. The large, burly guard who'd been keeping it reserved for them inclined his head, then went to fetch their drinks. Something he returned with so quickly that it no doubt set a speed record for the inn. From her years of working in such an establishment, she knew it said much about his fear of angering the three newcomers, and even more about their temperaments and personalities. These men did not like to be kept waiting, nor did they want to be interrupted once settled. For the first time, Cameron's courage faltered as she watched the men begin a private and intense whispered conversation. What are you doing, Cam? This was what she'd come for—to speak to Captain Devyl Bane and enlist his aid. Maybe it's not him. She knew better. He was just as he'd been described. Darker than sin and more dangerous than dancing with the devil's favored handmaiden. There was no one else it could be. The witch-woman had told her to look for a captain who'd take her breath and leave no doubt in her mind that he was the bane of the devil himself. That definitely described the man in the center of the other two. No one could be deadlier or more sinister. "Greetings, governor. You be wanting some company, like?" Cameron winced as an attractive prostitute plunked herself down on her lap. Because Cameron was dressed as a man and passing herself off as one so that she could travel unmolested and with ease, the prostitute had no idea she was wasting her time there. Grinding her teeth, Cameron caught the woman's hand before it drifted to a part of her body that would scandalize them both. Cameron shook her head sharply. "What? You mute?" She reached to touch Cameron's face and smiled wide. "That's all right, love. Don't be needing no words for what I do best, no ways. Fact is you be getting more your money's worth if'n we don't be speaking no how." Cameron caught the woman's wrist again and reminded herself to toughen her voice and lower it an octave. "Not interested, me sweet. You're not me type." She cast her gaze meaningfully toward the three men. The prostitute laughed. "Ah... can't says I blame you there. They each be so fine you can't help but crave a bite of those backsides and pray for lockjaw." With another winsome smile, she sighed. "Best of luck to you, mate. Way I hear tell it, though, you don't got a chance with none of them." And with that, she left Cameron's lap to pursue another, more probable client. Taking a deep breath, Cameron debated the sanity of seeing this mission through. It was obvious that the three men had no desire to be approached by a stranger. In fact, they appeared to be arguing. Heatedly. This is all kinds of insanity.... But Cameron Jack was not a coward. Maybe a little? She shushed the voice of reason in her head that told her to run for the door before they gutted her. Jacks aren't craven. Now get in there, me girl. Scared and breathless, she forced herself to her feet and crossed the room, trying to exude a confidence she definitely didn't feel. Her legs trembled as sweat beaded on her forehead and upper lip. For a moment, she feared she'd faint. You can do this. Don't you dare back out now. Patrick needs you. You're all he has in this world.... The moment she neared them, they fell silent and all three pairs of eyes pierced her with a malevolent glare she was sure had turned lesser beings into stone. Or, at the very least, caused them to soil their breeches. Captain Bane took a drink of his ale before he spoke in a voice so deep, it rolled out like thunder over a dark, stormy cove. "May I help you?" She took a nervous step forward. The brown-haired man pulled his sword and angled it at her neck. "That be close enough, lad. Declare yourself." She cleared her throat and met the captain's gaze levelly. "I was told that you're Captain Bane?" Without confirming it, the one she was sure was he brushed his thumb over his bottom lip. "Why do you seek the good captain?" "I was told that he... or you, rather, were part of the salvage for the Plate Fleet that went down?" His mate stood and, with his sword, forced her to step back. "We know nothing of what you speak." Too late, she realized that they probably mistook her for one of the king's pirate hunters who'd been tasked with going after the raiders of the sunken ships and their cargos. "It's not what you're thinking. Me brother was on one of the ships." Bane reached out to touch the man's hand and force the point of his companion's sword toward the floor. "And?" "I was told he went down with his ship." She choked on her tears that threatened to overwhelm her. Ever since she'd heard about her brother's fate, she'd been unable to cope. Unable to breathe. Not after all the two of them had been through together. "Please. I have to know the truth." The wigged man spoke with a degree of sympathy in his voice. "Only one ship made it out." "Aye," she whispered. "The Griffon. He wasn't on that one. His ship was the San Miguel. He was the captain of it... Patrick Jack." Bane's gaze softened. "Sorry. The captain didn't make it out." As they began to ignore her, it angered her to be dismissed so casually, and Cameron stepped forward again. "If what you say is true, then can you explain this to me." She tossed the bit of salvage that had been delivered to her door with a note from her brother. It skidded across the table to land beneath the candle in front of Bane. He and his companions froze for a full minute as she held her breath, waiting. It was a worthless trinket that made no sense whatsoever. A strange bit of a charm designed in the shape of an ornate cup, with a pair of wings rising over the rim and a stake with ribbons that fell from the bottom of it. And marked with a fleur-de-lis in the center of its bowl. While it was pretty enough, she had no idea why her brother would have sent such to her. Why he would even bother. Never mind anyone else. It would be all kinds of cruel were it a hoax. The captain scowled at the necklace charm, but made no move to touch it. "Is this supposed to mean something to me?" She shrugged. "No idea." Slowly, she approached the table and held out the note that had been wrapped and sealed around the item. "This was what he used to hold it and send it to me." Bane took the crumpled parchment from her hand and read it. The letter was simple and heartbreaking. One she'd committed to memory. Cam, Forgive me for leaving you as I have. Know that me loyalty is with you. Always. Listen not to anyone. Keep your weather eye to the horizon and this to your bosom. Tell no one that you have it. Not even Lettice. Trust none at your back. Ever yours, P.J. With a gruff countenance, Bane returned it to her. Again without touching her or the necklace charm. "And so what's the first thing you do with this?" he mocked. He was right. She'd done exactly what her brother had instructed her not to do—she'd handed it over to someone she didn't know. "True, but I have to find me brother, sir." She turned the letter around and pointed to the top of it. "Note the date. It's months after they went down, and he supposedly drowned by all accounts. Yet if he drowned, how did he send it to me?" A peculiar light flickered in Bane's dark eyes. One that made them appear almost red in the candlelight. Surely an optical illusion of some kind. "Who told you to come here?" "A witch-woman named Menyara. She said that you'd be able to help me find me brother." He let out a fetid curse under his breath. It was so foul and guttural that it caused the man on his left to snap to his feet and step away from him, as if fearing an imminent attack of some sort from his captain. "Who's Menyara?" the man asked. A tic started in Bane's jaw. "Don't ask questions you don't want answered, Will. And pray to your God that you never meet that bitch." With a dark, deadly grimace, he finally took her trinket into his hand to examine it more closely. His expression unreadable, Bane met her gaze. "Did she see this?" "Nay. Only the letter." "Why did you show it to me, then?" "I... I'm not sure." He flipped the trinket through his fingers several times while Will slowly returned to his seat. "What are you thinking, Captain?" the one in the wig asked. "All kinds of folly." He paused to meet the man's curious gaze. "I commend her to you, Mr. Meers. Take her to the ship." "Beg pardon?" He scowled fiercely. "What she be this?" The captain screwed his face up at him. "Are you dafter than a doornail, son? Our little Cameron Jack here be a lass as sure as I be your devil's bastard seed." Both of his companions gaped at him, then her. And she returned their slack-jawed stares without blinking or flinching. "How did you know that?" No one could ever tell she was female whenever she disguised herself as a lad. It was a ploy she'd been using ever since her parents had orphaned them when she was a small girl. A ruse Patrick had insisted on to keep her safe from harm, and under his nose so that he could watch after her. Bane scoffed as he reached for his ale. "Never try to fool the devil, love. I can see right through you. Besides, no man has an ass that fine. If he did, he'd serve to be changing my religion on certain things." He took a deep drink, then inclined his head to his companion. "See her to the ship, Bart." Bart hesitated. "Are you sure about that?" "Aye, and settle her in private quarters for now. Make sure the others know to leave her in peace or face my full wrath." Bart saluted him. "Aye, sir." "And Mr. Meers?" He paused to look back with an arched brow. "I expect on my arrival to the ship to find the lass as virginal after parting your company as she is on leaving mine right now." Bart let out an irritated growl. "I hate you, Bane. You live only to suck all the joy out of me death, don't you?" He snorted. "Pray that joy is the only thing I ever strive to divest from you, my friend. The day I seek greater entertainment than that is the day you should live in absolute terror of." "Duly noted, and me testicles have adequately shriveled back into me body so as to pose positively no threat whatsoever to the fair maiden in boy's clothing." "Good man." "Eunuch, you mean." "And well you should remain, lest I make that condition a permanent one." "Aye, aye, Captain." Terrified by the thought of being alone with them and their crew, but too desperate to let her fear interfere with her need to find her brother, Cameron reached for her letter and medallion, praying with everything she had that this wasn't a mistake. Please God, protect me. Swallowing in nervous apprehension, she nodded, tucked away her possessions, then followed the captain's mate. Devyl sat back to watch them leave. He cut his gaze toward his quartermaster. "What?" he snapped at Will. "As I value me own testicles... not saying a single word, Captain. Just sitting here, nursing me rum." He held it up pointedly before he took a swig. Devyl snorted at him. "Hope you find more courage than that for the task we have ahead of us." "No fear there. Have more than me fair share. But you forget that I've seen you in a fight. And I'm neither fool nor drunk enough to think I can take you. Besides, you cheat and bite." Those words pulled a rare laugh from Devyl. It was one of the reasons why he'd chosen Will as his quartermaster. Unlike the rest of his crew, Will was unflappable and bolder than he should be. He maintained his composure, good nature, and calm rationale under even the most harrowing of events. And he did so with a biting sense of sarcasm and gallows humor. More than that, Will was as courageous as stated. Courage mitigated only by a sound ability to reason and measure the merits of confrontation. Aye, William Death was one of the best men Devyl had ever fought with. It would be an honor to die by his side instead of the way Devyl had been gutted before.... "Permission to speak freely, Captain?" Crossing his arms over his chest, he leaned back to pin a sinister glare on Will. "If you've the backbone for it. Go on...." "Just wondering what mind you have to be bringing a human on board our bewitched ship." "Did you get a look at what her brother sent her?" "The meaningless bauble?" Devyl scoffed. "And you're the one who claims to be the faithful religious man between us." "Meaning?" "That bauble, as you claim it, Mr. Death—" "Deeth," Will corrected under his breath. It was ever his pet peeve that they didn't pronounce his name with a long e as opposed to the way it was spelled. Though why his ancestor had chosen to be so antagonistic with either the spelling or pronunciation was anyone's guess. "Death," Devyl repeated incorrectly, as he was ever a cantankerous bastard, "is from the sword of St. Michael." "Which one?" He reached to flip at the silver medallion that hung off a leather cord Will had wound about his left wrist. "That winged bastard creature you believe protects and watches over you." "I don't understand." "Neither do I. But until I do, I thought it prudent to put her under our guard lest something foul decide to make her its next supper." "And if that something foul proves to be a member of our crew?" Devyl allowed his eyes to flash to their natural red state. "They would have a bad day, indeed.... My mood, however, would be vastly improved by their act of blatant stupidity that would result in my natural retaliatory act of extreme and unholy violence." And speaking of... The hairs on the back of his neck rose as he felt the hand of unsavory evil prowling toward the tavern. Scowling, Will glanced about. "Do you feel that?" "Aye. It's come ashore as I said it would." And headed for the largest gathering of victims... just as Devyl had also predicted. Meanwhile, the humans in the tavern went on, oblivious to the malignant force that was headed for them. Devyl rose, intending to keep them in their ignorance. But he only made it halfway to the door before it opened and three plat-eyes came in, wearing the skin of regular sailors. Will pulled up short behind him. "Sailors from the downed fleet?" he whispered in Devyl's ear. Devyl gave a subtle nod as he debated how best to deal with the unholy bastards who'd come to feast on the innocent and take their souls back to feed their mistress. Part of being a bound Hellchaser was to let no one know that neither he nor Will had come to battle these demons. Unfortunately, the plat-eyes didn't have a Code they were tied to. They passed an evil grin to one another, then went on a vicious attack that resulted in the three humans closest to them being ripped to shreds. Utter chaos exploded as the humans sought cover and escape. Devyl cursed as he was forced against the wall by the tidal wave of terrified humans who were hysterical over being trapped inside by inhuman predators. With their preternatural abilities, the plat-eyes had sealed the door so that no one could flee them. They thought to feast tonight. Groaning and shoving at a drunken male who was trying to reach a window, Will made it back to his side. "What do we do, sir? I can't get near them for the crowd." Devyl pulled his coat off with a flourish, then handed it to his quartermaster. "Have I ever said how much I detest the sound of screaming humanity?" "Really? Rumor has it, it was once your most cherished melody." Hitting the release for his sling bow, Devyl passed an annoyed grimace to him. "Nay, the sweetest music to my ears has always been the death gurgle of an enemy slain at my feet as he gasps his last breath." Completely calm, he loaded the small bolt and released it straight into the skull of the nearest plat-eye. The beast fell back and exploded into a black cloud. Stunned, the other two turned to gape at Devyl. Then they must have realized who and what they faced. Their eyes widened in unison before they shifted into wolf form and ran for the door. But Devyl's power was greater than theirs and he held them inside. Will grinned. "That got their attention, Captain." As soon as the plat-eyes realized they couldn't escape, they shifted into their true hideous demonic bodies. Then they each split into three more beasts to attack. Will cursed. "Vulnerable spot?" "Between the eyes. Decapitation." Devyl caught the first one to reach him and twisted his head off. "But it won't kill them." "Pardon?" Will visibly paled. He took out two more before he turned to face the man. "Creatures of vengeance and lapdogs. These are shadow manifestations." He caught a fourth one with his knife and drove it straight through its skull. "To kill them for good, we have to find the bodies they assumed when they entered this realm and destroy them." Will growled before he drew his sword and dispatched the one that came at his back. "I hate me job, Captain." Devyl finished off the last, then quickly spread a compound of yew, salt, and ground jasper over the doorframe. That would keep more plat-eyes from coming inside to prey here again. Will retrieved Devyl's coat and rushed to join him as the crowd began to realize the danger had passed. Now, they wanted answers neither of them was at liberty to give. And before the crowd could compose themselves further, Devyl and Will made a fast exit. Outside the tavern, the moon had turned an eerie bloodred, and clouds hung thick in the sky, making it even darker. Handing the coat to Devyl, Will grimaced. "So those are not the beasts we seek either?" Devyl shook his head as he shrugged his coat on. "They're merely servants." Will winced. "In our last few months together, I have seen unbelievable things that appear to have been spat out of hell itself. And I can't help but wonder just what exactly does the Carian Gate hold back from this world, if we haven't seen it yet?" Fastening his cuff, Devyl met his worried stare with a knowing smirk. "The most corrupt, horrifying evil that ever gurgled up from the farting arse of the cosmos." "Lucifer?" He snorted and clapped Will on the back. "We should be so lucky. Nay, Mr. Death... what's coming up from the sea makes Lucifer look like a petulant, harmless child." Will crossed himself. "What exactly is it, then?" Devyl sobered at the memory as a wave of bitterness and fury washed over him and burned him to the core of his blackened and withered soul. "In short, Mr. Death... my ex-wife." Cameron had to struggle to keep up with Bart's long, forceful strides that she was beginning to suspect he did apurpose just to wind her. "So how long have you served on Captain Bane's crew?" He cursed her under his breath. Again. Honestly, she was beginning to develop a mental disorder over it. And an extreme case of paranoia. "How many of these questions do you plan to assault me with, lass?" "I know not. But I should like to have an answer to at least one of them... eventually. And before I die of frustration from it." He ground his teeth so furiously that she could actually hear them gnashing together. "Would it perchance stop this aggravating deluge?" "Might quell it some." Clasping his hands behind his back, Bart slowed as they finally approached the docks and gave her a sideways glare. While not as breathtaking as the captain, he was exceptionally handsome with those piercing eyes. "All of us are new to the ill-tempered captain's company. He assembled our crew a few months ago." "What happened to his old crew?" The moonlight cast spooky shadows over his sharp features, turning them sinister and cold. "There are many questions that are best left unasked, my lady. And that particular one definitely tops the list." Perhaps, but it wasn't in her nature to let things rest. "Did pirates kill them?" He gave her a sardonic smile. "They say he ate them." Cameron jumped as a thickly accented French voice came out of the shadows next to her. With an undignified squeak, she rushed to the other side of Bart, who laughed at her actions. "Leave off the lass, Roach. Captain's orders." "Lass?" "Roach?" she asked in perfect synchronization with his question as the man stepped into the light so that she could see that he was a few years older than Bart. And quite a bit shorter. Nowhere near as fashionable in his dress, he had a simple linen cap and a shirt with the sleeves rolled up to his elbows, held there by a bit of leather cord. And while he had a neckerchief, the collar of his shirt had been left unbuttoned and open so that the cloth was wound about his neck and not his shirt. His brown gloves were as worn as the dark red waistcoat he left unbuttoned. But the most curious thing was the whip he had around his tan-colored breeches in place of a belt. Nor did he carry a sword. Rather, he had a baldric that secured a small double-headed hand-axe to his left hip. And now that he was closer, she realized he had flesh-colored vambraces.... Nay, not vambraces. They were cleverly disguised dagger sheaths, which was why his shirt was tied up at the sleeves. That allowed him access to the hilts that were on the inside of his forearm and tucked into the crook of his elbow. Very, very peculiar. Bart rubbed at his brow. "Milady Cameron Jack, meet our resident cockroach, so named for the shadows he calls home and the way he scutters about them and sneaks up on everyone. Some claim so that he can cut their throats for profit and theft." The Frenchman made a rude sound of disgust. "Ignore the mannerless, motherless snipe. Armand de la Roche at your service, madame." He clicked his heels together and gave her a proper court bow that was completely at odds with his shabby, careless clothing. "Enchanté." "Merci, monsieur. Ravi de vous rencontrer." Covering his heart, he acted as if he savored every syllable. "You speak beautifully and yet I detect a hint of an Irish lilt in your voice." "Me mother was French and me father Irish. They brought us to Virginia when I was a small child." "Us?" "Her brother." There was a note of ice in Bart's tone that Cameron didn't quite understand. "Now, Roach, if you don't mind..." He stepped in front of them to cut off their path. "Pardon, Monsieur Meers... mais you do not want to be doing that." "Why ever not?" "There is a bit of a calamity onboard. It would appear as if le soul has gone a-missing... again." "Ah, dear God." Bart appeared sick to his stomach. "Oui! Exactement!" Cameron scowled at them. "Soul?" Bart let out a long-suffering sigh. "Not even sure how to begin to explain this... one of our crew—" "Absalon le lune—" Bart grimaced at Armand. "He's not crazy. Per se." "Ja, he is!" Armand's use of German amused her. "Anyway," Bart said between clenched teeth, ignoring him. "Sallie is under the stupidity that his soul was somehow sucked out of him and trapped inside an old rum bottle by a malicious witch." Cameron gaped incredulously at the utter travesty of that belief. "What? Why?" Bart gestured helplessly. "We've learned not to ask these questions, as they lead us into a realm of madness from which there's no escape. And let's face it, reason and logic abandoned this crew long ago. Therefore, we don't judge each other over the insanity, for there's not a member here who isn't a bit... touched in the head and peculiar in the ways." "That is also true," Armand agreed. "But more so than any other, Absalon is... how do you say? A moonbug?" She arched a brow. "Moonbug?" "Lunatic," Bart said with a grimace. "Roach screws up about half of everything he attempts to say. English is not his native tongue. Stupidity is." Roach made a sound of supreme irritation. And an extremely vulgar gesture that left Cameron wide-eyed and gaping—and she'd grown up an orphan, working in one of the most dangerous taverns in Williamsburg, frequented by scoundrels, pirates, and known rabble-rousers. In fact, she prided herself on being jaded and worldly for her age. Yet these men made her feel rather naïve and prudish. Suddenly, she heard a loud whooping sound that was followed by cackles of raucous laughter. "Ach, now! Ye faithless, motherless dogs! Give me back me soul! What's wrong with the sorry lot of you! What kind of cretin bastards be stealing a man's soul now, I ask you?" Bart groaned out loud and slapped himself across the forehead. "I can't believe I died painfully in order to deal with this shite. I think I'd have rather stayed in hell. At least there, I only had Lucifer and his demons to contend with, and not the Devyl's bane and his idiots. No offense, but our Devyl scares me a whole whopping more than Old Scratch. Bastard's deadlier too, and more cantankerous. Never do you know what's going to set him off. Or how he'll react to anything." Laughing, Roach clapped him on the back. "There, there, mon ami, ca c'est bon! 'Tis better than hell, anyway." The look on Bart's face contradicted that as he rushed forward to deal with the thunderous voices. Cameron stayed back, unsure of what exactly she was getting herself into on this quest to find her brother and return him home for Lettice, and her own personal sanity and safety. Time was running out, quickly, for the lot of them. Paden had left them all in a bad situation, and he had no idea of it. Nathaniel had taken ill a few weeks back—as had Lettice, yet Lettice's illness had turned out to be an unexpected pregnancy only she and Cameron knew about. The girl was to have Paden's baby, and if he didn't return in the next few months to make an honest woman of her, there would be hell to pay for the whole lot of them. No doubt, Nathaniel would take his anger over his daughter's unwed pregnancy out on Cameron's head if he couldn't locate her brother. There was no telling what the surly man might do to her in retaliation. Nor did she wish to find out. Nathaniel barely tolerated her presence in his inn and tavern as it was. Only his fear of Paden kept him in check. If he learned Paden was dead and that her brother had left Lettice in a bad way... Nathaniel would pull his protection of her, and Cameron would be penniless, homeless, without friend or family. Alone in a world that didn't look favorably upon anyone without means, references, or prospects. Those thoughts scattering, Cameron slowed as she neared the ship and saw the extent of the crew's utter madness. Men, and women who were dressed as men—so much for her being original—were chasing each other around the deck of the ship as they tossed an old amber bottle among themselves to keep it from the hands of a middle-aged seaman who stood an inch or two shorter than Cameron. With a scruffy dark beard that was liberally laced with gray, he appeared affable enough. Why they sought to torture him, she had no idea. Bart let out a fiercely loud whistle. "What manner of blatant stupidity be this? Are ye all daft? Or just wanting your enemies to sneak up and cut your throats while you're all distracted and screaming about like a bunch of weak-kneed trollops?" Strangely amused and equally terrified of this group, Cameron stayed on the dock and watched as Bart slowly subdued them and collected the poor sailor's "soul" from a large Maasai warrior before returning it to the distressed man. "Zumari!" Bart chided the warrior. "I can't believe you of all the ones on board would partake of such cruelty." "I'd have never, had he not started in on me first!" Zumari's voice was as deep and lyrical as Bane's. But his mood was much lighter, in spite of the fact that she held no doubt he was every bit as lethal in a fight. Cameron was just about to head onboard the ship to join them when she became aware of a small group of soldiers nearing her. Grim-faced and heavily armed, they stalked past her with a determined stride that didn't bode well for whatever target they had in mind. It froze her instantly. A good thing, too, since that target turned out to be Bane's crew. Stepping to the side so as not to be in the middle of whatever mal intent they had, she caught the feral grimace on Bart's and Zumari's faces the moment they saw them that said they were both a bit put out at the way fate had decided to treat them this night. With his legs braced wide apart and his arms crossed over his chest, Bart met them at the top of the gangway and refused to allow them access to the deck of the ship. "What can I do for you, gentlemen?" The icy tone of his voice undermined the cordial words. As did the number of crewmen who came to stand behind him as reinforcements. The soldiers didn't flinch, especially not their leader, a dark-haired bloke who bore a jagged scar over his left eye that said he was lucky to still have it. Unlike the others, he wasn't dressed in uniform. Rather, he wore the clothes of a well-dressed port official, or another privateer captain. "It was brought to our attention that you came into port earlier this day without colors or jack. We're here to inspect your papers and whatever cargo you might be carrying." Bart curled his lip. "On whose authority?" Their leader didn't flinch or back down. "Are you refusing to show your papers?" "I don't bow to a common pirate hunter, if that's what you be asking, Barnet. You can take your men now and begone from this ship. There are no pirates among us. You're wasting your time and ours with this useless endeavor." "If you know me, then you know I won't be leaving here until I see that paperwork." A slow, insidious smile spread over Bart's face as Zumari stepped closer to back him. "Wouldn't be taking that wager, were I you. But I'll be taking odds on your leaving with disappointment in your heart, any day. Thrice on it today." Just as the notorious pirate hunter Jonathan Barnet began to bluster in argument, a deep, resonant voice came out of the shadows. "There a problem? And the correct answer is nay, Devyl, there is not." The color faded from Barnet's face as he turned slowly to see Devyl Bane and William Death parting from the fog on the docks. They walked past Cameron without acknowledging her in the least—which was fine by her since she didn't want to be under anyone's scrutiny while they were embroiled in this bit of heated controversy. Best to keep a low profile—that was the first lesson she'd learned as a girl after the death of her parents. And how Captain Bane's voice traveled so effortlessly without his raising it, she had no idea. Yet it held that chilling, commanding tone and hung in the air like the voice of some ancient war god. "Captain Bane," Barnet greeted with the smallest hint of a quiver in his own throat. "This be your ship?" "Don't make a habit of trespassing on other men's vessels." The way he said that conveyed an insinuation that he wasn't talking strictly about boats. "Now get your mud-laden boots off her boards, as your mere presence here offends me to the core of my being, before I seek to teach you the manners your mother should have." He didn't pause to even look at Captain Barnet. Rather, he kept walking straight past the entire group as if they were of no consequence or concern whatsoever. Barnet took a step forward, but Bart and Zumari blocked his path to prevent him from following after their captain. "You have a new crew...," Barnet said. Bane didn't so much as glance back at the infamous pirate hunter. Instead he made his way straight to his cabin. William, on the other hand, paused at Bart's side and turned to smile at Captain Barnet and his men. He fussed at the cuff of his jacket in the manner of a jolly fop. "Greetings, Johnny. Catch any scary pirates lately?" Color returned to the pirate hunter's cheeks to darken them with a sudden rage. "Looking for Captain Cross. Heard he'd made his way into our waters. Him and Jean St. Noir." William tsked. "Does this look like the Fickle Bitch or the Soucouyant? Barnet..." he chided. "I'm highly offended. Our lady ship's offended." He tsked at the group with Captain Barnet. "Best you go on before Bane hears of this and takes a sword to you for the insult to our lady's honor. This be a first-rate man-o'-war here, not some half-rigged sloop or frigate. He won't like that slight... not at all." Grimacing, Barnet swept his gaze across the silent crew who stood around to back their quartermaster. "There's something not right about the lot of you." William winked at him. "There's something not right about the lot of the world, mate. We just embrace our natural differences with gusto." And with that, Captain Barnet and his soldiers finally departed the gangway. William followed them down to the dock as if to ensure they left the area and didn't double back in an attempt to sneak aboard some other way. Cameron didn't move until after Captain Barnet and his men had vanished into the night. "Did they scare you, ma petite?" Cameron let out a startled shriek at the voice that manifested right beside her ear. Jumping away from it, she turned to see a peculiar man standing so close that she could feel his breath on her flesh. His skin was a rich caramel color, stretched tight over a body that rippled with defined muscles the likes of which she'd seldom seen on any male—Captain Bane notwithstanding. And that wasn't the only peculiarity he possessed. His black hair was cut short and worn spiked atop his head in a strange, unique style. And those eyes... Merciful heaven! They were unlike any shade she'd ever beheld in her life, especially with the rest of his coloring. A cool, steely blue, they had a deep grayish cast, and yet... The color truly defied explanation. More like a silvery storm on a dark, sinister sea. In a weird way, it reminded her of how the parson and his scriptures described the color of the pale horse that Death rode in the Apocalypse. Stranger still, the sleeves of his black linen shirt were rolled up to his elbows, displaying that both his forearms were covered with scrolling black tattoos that appeared more akin to a second skin color than actual ink. He quirked one finely arched eyebrow at her continued silence. "Devil got your tongue?" She shivered at the sound of his voice. "That is an incredible accent you have there. Wherever are you from?" His smile turned warm and charming. "A place I know you've never heard of. Wyñeria. The accent's a form of Igñeri... Island Carib." He was right about that—she'd never heard of his homeland before. But over the years, she'd learned of many different towns and small islands in the Caribbean. "Which island?" "Let's just say it's between Trinidad and Tobago, and keep it at that." "Leave off our new crew member, Kalder. Captain's orders," William said as he joined them. His tone wistful, he spoke to Mr. Death in a lyrical language Cameron had never heard before, then he headed for the ship. She scowled as she realized Kalder was barefoot, with no stockings. As with his arms, his legs from the knees down held peculiar scrolling tattoo marks. "What did he say?" she asked William. "Not fit for repeating to a lady, me love. Afraid you'll find the majority of our crew isn't the most refined of creatures. Kalder Dupree is one you'll be wanting to give a bit of a berth to." "Why? He seemed cordial enough." If not a bit unnerving with his silent movements and piercing stare. He winced. "If you keep going on what things seem to be, child, rather than what they really are, you're in for a long haul with this group." A sudden whistle rent the air. Before she could ask about it, William took her arm and ran with her for the gangway. He all but dragged her onboard while the crew scrambled as if they were making sail in the dark. William didn't slow until they reached the mainmast, where Kalder stood next to an even more peculiar-looking man. This one was tall and lean, with a bare chest decorated by animal bones, beads, and feathers strung together to form the kind of adornment she'd only seen worn by certain Powhatan tribal elders who came to trade with merchants in Virginia or meet with town officials. Yet that and the feathers strung to his staff and beaded armbands seemed at odds with his long, dark blond dreadlocks that were favored by some of the islanders she'd met on this latest quest. And he'd painted his face like no one she'd ever seen. Not shaman or warrior. Meanwhile, he wore the breeches and boots of a fine European nobleman and the sword of a Saracen nomad. Truly the man had a style unique unto himself. "What is it?" William asked them as he let go of her arm and moved to stand beside the strange man. "There's an ill breeze blowing off the port bow." The man glanced to Kalder. "Reeks of what we're charged with policing." Kalder rolled his eyes. "I think the fetid bitch just wants to make sure none of us sleep tonight." He snorted at Kalder's rude words. "I'm not the one you need to fear, brother." He jerked his chin at something behind Cameron. "Sancha appears to have been ass-up in Nelson's Folly a bit early tonight." Cameron turned to see an exceptionally tall and gracefully lanky woman headed for them. Her long, curly black wig was askew as she weaved across the deck, making her way for the steering wheel. Without a word, the woman clapped a hand to Kalder's shoulder as she attempted to step around them, fell against him, then righted herself. With a kiss to his cheek, she pushed herself away and fell against Bart, who then helped her stand upright. How the woman could make her drunken dance appear so beautiful, Cameron had no idea. Yet Sancha was elegant while tipsy. But when the men actually allowed the woman to take her place at the helm, Cameron gaped at them. "What the hell, man?" The curse was out before she could stop it. "You're planning to let her steer the ship while drunk?" The strangely mismatched man laughed. "Of course. We only fear her when she's sober. Then Sancha's a nasty tart with a wicked twist of the whip... and a tongue that lets even more blood, ever quicker." That only confused her more. "Then why did you say you feared her?" "Everyone fears her, love. I merely commented on the fact that, second to the captain, she's the scariest thing on this ship, and that she's imbibed quite a bit tonight... even for her." He winked at Cameron. "Name's Rosenkranz, or Rosie, and what be the name of such a sweet tender morsel as you?" As she opened her mouth to answer, a cry sounded for Kalder to duck. Yet before he could oblige the call, a bucket of water ended up being slung against him. She expected him to explode into anger. He didn't. Rather, he groaned as his entire body changed instantly... his skin became slick and silvery like a fish's iridescent scales. Gills opened at his neck, while his teeth elongated to fangs. What she'd mistaken for tattoos became fins that protruded from his arms and legs. Choking, he sputtered and coughed, then turned to glare at the sailor who'd doused him. "Careful! You lousy bilger! Watch where you be tossing that or I'll be making you drink it through your nose!" "Sorry, Kal, it slipped from me hands. Won't happen again." "See that it don't. Or else I'll be plaguing and poxing a piece of your anatomy you're going to miss using." "Here, Mr. Dupree." Cameron bit back a scream as Captain Bane literally appeared out of nowhere to stand beside Kalder with a towel for him. He handed it off, then began to help shout orders as they cast off for the open seas. Too stunned to speak, she watched as Kalder's skin and coloring returned to normal, though "normal" was beginning to take on a whole new meaning with this particular group. Kalder cast an amused grimace toward her. "You handled that well, for an air-breather. Surely, you have questions about it... and me?" Aye, she did—of course she did. But the more she looked at this crew... She didn't know where to begin as her head spun from the madness of it all. The riggers moved along the masts and lines with inhuman skill. It was terrifying to watch the way they scaled the spiny wood and thick ropes to drop sails, without fear or hesitation. The way all of them rushed about, displaying talents that hadn't been born of this world or of a typical woman. Surely, they were demons all. This is a crew of the damned. And she'd walked right onboard. Voluntarily. With both feet. What have I done? She'd given no real thought to joining them. Not really. Rather, she'd placed her trust in total strangers she knew nothing about. And that wasn't like her. Ever. Cameron Maire Jack trusted no one. Never in her life had she done such as this. Was she really that desperate? Of course I am. Without Paden, she had nothing in this world. She had no one. Even before her parents had died, she'd worshiped her older brother. He'd been everything to her. Her best friend and protector. Her confidant and playmate. While her parents' deaths had been hard to bear, news of his had devastated her to a level she'd never known existed. The pain had been unimaginable. Indescribable. Sent her reeling into a despair she had yet to recover from. Since the day she'd learned what death meant when she was a girl at age five and her favorite pup had perished after tangling with a fox, she'd known that her parents would precede her to the grave. That was to be expected, as it was the way of things. The natural order that children outlived their parents and carried on their lineage. But Paden... Five years her elder, he was to always be here. Always. No matter what, he wasn't to leave her alone in this miserable world. He'd sworn that to her. That he would be forever by her side to keep her safe. He wouldn't fail her or his word. Not for anything. Not for anyone. It would always be the two of them. Thick and thin, and all that lay in between. Not even the devil and all his demons would keep her brother from her. That had been his vow every night of her life when he'd tucked her into bed.... Have no fear. Keep your cheer. It'll always be You and me. Thick and thin To the end. Neither heaven nor hell Will keep me from me Cammy-belle. How could Paden have broken her heart so? Did he not know that it wasn't his life he'd lost at sea? It was hers. But worse than that, he'd taken her faith and hopes with him to the grave. Her heart. Her belief in God Himself. Truly, she was now a hollowed-out shell with nothing inside except a profound, unending pain, and a sense of loss so deep she feared she'd never feel anything else ever again. "I think we've sent her into shock." Cameron turned at the high-pitched feminine voice to find... Well, she wasn't quite sure what this newcomer was. Only an inch taller, she was dressed in a high-fashion robe à l'anglais, yet it was made of sackcloth. Her skin didn't appear human, but rather was made of straw.... She smiled at Cameron. "You have that look, dearest." Cameron blinked in confusion. "What look is that?" The woman sighed in that odd voice of hers as she cast her gaze toward Bart. "It's the look, isn't it?" "Aye. But you can't fault her for it, really." "Suppose." She let out another heartfelt sigh. "Still, I'd like to meet someone and not have it anymore." "Have what?" Cameron asked with a frown. "The look that says I'm a freak," she whispered in an ominous tone. "Name's Valynda. And yes, I'm not human... though I was at one time. 'Til a love spell went awry and this became the consequences of it." Cameron paled. "What?" She held her hands up in helpless despair. "Wasn't my spell, mind you. Rather, the idiot who wanted to make me love him. He bought a lwa from a witch, and this is what it did to me because he knew naught what he was doing. Sucked my soul straight into the doll and there was nothing to be done for it." "Nothing?" Cameron asked, aghast at what she was hearing. Was this even real? Was any of this possible? Surely she was dreaming.... No one could be turned into a living rag doll. Could they? By accident? Truly it was a horrifying thought. William shook his head. "Superstitious preacher burned her body. Left her in a bit of a pickle, indeed." Valynda nodded. "But for Lady Belle, I'd have been trapped in between forever." In between what? Cameron wasn't sure she wanted to know that answer, so she asked the other question that plagued her. "Belle?" "Our doctor," Bart said, jerking his chin toward one of the riggers. "Belle Morte's one you don't want to run afoul of. She's a powerful maven who can give the strongest hell beasties a run for their money." Cameron scowled at the sight of a beautiful dark-skinned woman who seemed harmless enough—until she pulled out a large machete to slash expertly at the ties of a sail before flipping down to land on the deck with the skill of a master assassin. In one fluid, graceful movement, she sheathed her weapon then shimmied up another rope. Aye, the deadliest objects were often the most beautiful. "An Obia?" "Nay, love. Something much, much darker. We don't speak of it, lest we offend her and she curse us for it." Cameron crossed herself. What have you gotten me into, brother? She'd come here seeking help and salvation for the two of them. Yet there was no salvation on this ship. Never had she seen a more damned lot in all her life. If ever there was a crew bound to Lucifer's lowest pit, this had to be it. And she was sailing in the midst of them all, straight for hell's domain. Stark cold terror seized her as a rotten feeling crept through her very soul. "Question, Mr. Death?" "Aye, lass?" "Am I the only human on board this ship?" To her deepest chagrin, he hesitated. And when he finally answered, it wasn't what she wanted to hear and gave her no comfort whatsoever. "Define the word 'human.'" "Am I the only human on board this ship?" Devyl didn't so much as blink at Cameron's question as she came to rest right in front of him where he was issuing orders to the riggers on deck. If anything, the good captain appeared bored by her while they left the port behind and broke into open sea. "Suppose it depends on the definition one uses for 'human.'" She gave him an irritated, droll stare as he repeated his quartermaster's words in a bland mumble. "I am unamused by your hedging, Captain." He arched a sardonic black brow with a look that caused a chill to run down her spine. "Who says I'm hedging?" It was a titanic effort not to roll her eyes at a man—or perhaps infernal beast would be more accurate—who she was quite certain might very well suck out her immortal soul and feast upon it. "Can you at least tell me why I was brought on board this ship, then?" "For your protection." Why did she have such a hard time believing that? Probably because she couldn't imagine a more dangerous group in existence than the one rushing around her. "From?" Forget the crew, she was beginning to doubt if there could be anything more lethal or terrifying than the creatures who called this ship home. He let out a long, slow breath as if seeking some sort of patience. "We are not your enemies, Miss Jack. Of that much you can rest assured. While we might be an unsavory, untoward, and uncivilized group, we are not without our honor." "Meaning?" "Meaning we reserve our venom for those who've earned it." And those words failed to comfort her. "You'll have to forgive me if your benediction causes me alarm." "No need to apologize. You've every right to fear us. As I said, we are an unsavory lot." He turned those dark, soulless eyes toward her, and this time, she saw for a fact that they did indeed turn red as blood. They glowed in the darkness with an unholy light. "And an acquired taste." Yelping at his sinister tone, she jumped back on the deck and crossed herself as true, unmitigated horror engulfed her. This was not what she'd meant to sign on with when she'd promised herself and Lettice that she'd find her brother no matter what and bring him home. She had already been gone longer on this quest than she'd ever anticipated. Longer than Nathaniel Harrison would forgive her for. Nor had she meant to find the devil's ship and his crew to sail with. No doubt to hell itself they were bound! Dear heaven, I've consigned myself to Perdition.... Everything had seemed so simple when she'd opened her brother's letter and first set out to locate him. She was to come to Port Royal and ask a few questions. Find out why Paden hadn't come home after the shipwreck that he'd obviously survived. Take him to task for being so cryptic in his missive, then return home to her life with her wayward brother in tow, and let Lettice beat him sideways for his thoughtlessness and the worry he'd given them. This was never supposed to be part of it. And the horrifying captain in front of her was definitely not part of the bargain. Bane froze as he witnessed the absolute stark terror inside Cameron. She literally quivered by his side to such an extent he was amazed she didn't wet the planks beneath her feet. There had been a time once when he'd lived to instill that amount of fear and intimidation in others. When the sight of petrified men had been mother's milk to his cold, dead heart. Compassion and tenderness had been virtually unknown to his warring people. And yet... In the flash of one single heartbeat, his mind took him back to the days when he hadn't been the leader of his race. To the time before he'd first taken a life in battle and had been nothing more than the beloved older brother of his younger sister. No longer on this ship, he was again in the green meadows where he'd run as a boy. And as was his wont, he was off to join his friends to hunt for game and play for a rare afternoon of freedom—something he'd worked and suffered hard for. And as was typical of his sister, Elyzabel was hot on his heels, annoying the very piss from him. Five years his junior, she was a tiny wisp of a thing, yet she thought herself his equal in size and abilities. "What are you about, Du? Why are you carrying Ta's spear? Does he know you have it?" "Aye, he knows. Why are you bothering me now with your inane prattle? Off with you! Isn't there someone else you can annoy for once besides me? We have a sister, you know. Surely, she's more suited to your tastes than I." But she'd never preferred Edyth's company over his. And not that he blamed her that. Edyth was a futtocking handful on her best day. "Are you off to hunt? Can I come? Please, please!" "Nay!" Turning on his heels, he'd growled at Elyzabel. Then froze as he saw the tangles in her brown hair and the dirt on her freckled cheeks. More than that, he noted that, beneath the dirt, a bruise had started to form that deepened the shade of her amber eyes, and there was a tear in her dress. Though scarce more than tick-size, she was ever ready to stand toe to toe with him, never flinching in her temerity whenever he'd said or done anything that displeased her. She would even dare to shove at him when no man save their father would so much as meet his gaze in anger. Shout in his face whenever she was mad at him. She even stood up to their father during his most drunken rages. Her guts and fire had always amused and amazed him, even when he'd wanted to put her through a wall for not listening to him, or refusing to hide when it was the more prudent thing to do. In all his life, he'd never loved anyone as much as he'd loved his little sister. Not even Vine. But while he might have verbally fought with his sister whenever she pushed the boundaries of his patience and all common sense, by the very gods, no one else was allowed to do such and no one was ever to lay hands to her. No one. Not even their father. And he had the scars to prove it. "What's all this about?" he asked, indicating her cheek. Elyzabel glanced away. "'Tis naught. Can I come with you?" "Elf..." he'd chided, cupping her chin and gentling his tone with her. "Tell me what happened to you, lass." She let out a long sigh before she finally screwed her face up and confessed it. "'Twas the beast!" "Derphin?" "Nay. The other hairy one I hate most of all." "Ilex?" "Aye! He said a girl wasn't fit to climb a tree and that I should get back to me mum's breast before I got hurt. So I climbed the tree to show him what a girl could do, and then he shoved me down and we fought about it." Those words had ignited his fuse. "He hit you?" She nodded. That had been the first time Devyl had met the part of himself that had made him famous on the battlefield. That cold, unreasoning beast that wouldn't stop until he had his enemy lying in pieces at his feet, either dead or begging for a mercy he'd never shown anyone save his precious Elyzabel. Only Elf had ever stayed his furious hand. Only her tears had ever moved him to mercy or compassion. Until today. Something about Cameron reminded him of his precious sister, and this tiny chit touched the last shred of a humanity he'd thought had gone to the grave with his Elf. Sink me.... Cameron swallowed hard as she met Bane's fierce, bloody gaze. For the first time, she saw the slightest softening of his demonic countenance. The merest glimpse of a soul beneath the evil. His grimace lightened as he held one large hand out toward her. "There's no need in that, lass." Refusing to give in to her terror, she forced herself to her feet and fell back on the strength Paden had taught her to stand on after the death of their parents. Let no one see your weakness, Cam. Ever. We are Jacks, by God. And Jacks don't buckle or fold. In it for a half-pence. In it for a pound. For that matter, she was in this whole matter way over her head. No way out now. Hell, or high water. Or damnation itself. Whatever it took. She had no choice, except to see it through. "I still don't understand why it is you brought me here, Captain." "Truth? Neither do I. Other than I fear something quite unholy has taken control of your brother. My experience with such things is that when they happen and the poor bastard who's held in thrall reaches out to an innocent such as yourself... the consequences are always dire to said innocent, especially when it involves something as important as the trinket in your pocket." "It's not a worthless bauble, then?" The wind whipped at his wavy black hair while his eyes faded back to their ebony color. He glanced across the stormy sea surrounding them. "Quite the contrary, Miss Jack. Wars have been waged for that bit of gold you keep, and countless throats cut. Tell no one else you carry it. Ever." He glowered at her. "How your brother managed to get that to you is what puzzles me most." "It came in the post." He gaped at her as he found that the most incredulous bit of all. As if it defied all reason. She held her hand up in solemn testimony. "I swear it. I thought it nothing more than a letter that must have been sent before he left on his voyage. I kept it nigh on a fortnight before I could bring myself to open it to read it, and then when I did..." "Did anything strange happen to you around the time you received it?" "Other than meeting all of you and the lady Menyara?" His dark grimace said that he didn't appreciate her humor. She softened her own expression to let him know she was teasing. "Nay, Captain. Nothing untoward." In fact, she'd not had so much as a nightmare since receiving it, which was strange given that she'd had a number of them before it came. "Very peculiar, indeed." Cameron narrowed her gaze on him as he continued to watch the dark waters around them, as if seeking something only he could detect. "What is it that you're not telling me?" The red returned to his eyes an instant before he dropped his coat from his shoulders in one fast, graceful shrug and unsheathed his cutlass. "Kalder! Off to port! Sancha, bring a spring upon her cable! They're coming up our stern!" He took Cameron's arm and gently nudged her toward William while Kalder jumped over the side, into the sea below. "Seal her to my quarters for the fight." "Aye, aye, Captain." William grabbed her fast and hauled her away. But not before she saw what was rising up from the bowels of the stygian waves to engage them. Holy mother and all her saints...! Cameron couldn't breathe at the sight of what had to be Lucifer's own prized pet shark he'd crossbred with an octopus. Scaly, huge, and tentacled like nothing she'd ever seen or heard of, it came after them while the crew took aim and fired cannons at it. The deck beneath her feet vibrated from the recoil of it all. Her ears rang from the sharp percussion. William shoved her into Bane's quarters and slammed the door tight. Gaping and terrified, Cameron stumbled toward the windows to watch the creature that was after them. One who appeared to have brought even more sinister friends with it. Her heart pounding in her chest, her ears filled with the sound of rushing blood and more cannon fire, along with shouts and gusting wind. The smell of gunpowder and sea nauseated her. Never, never had she seen or heard such. This was the stuff of nightmares and horror. From where she stood, she could see Kalder fighting against the beast that dwarfed him as they tangled in the water. The merman stabbed it with a long spear while Captain Bane sent balls of fire from his fists into its scaly hide. The creature screamed and arched its back, reaching for them both with its thorny tentacles. Until the beast met her gaze through the lead glass as if it sensed her watching it. Time hung still for a long minute until it let out a piercing cry unlike anything she'd ever heard. It was so shrill, it shattered the glass between them, raining pieces of it over her. Closing her eyes, she raised her arms to protect her face until the shrapnel settled. The ship rocked from the fierce waves the creature caused. Nauseated by the rolling sensation, she staggered back against Captain Bane's desk. Winds from the sea whipped against her, tearing pieces of her hair free from her queue. With a deep growl, the creature dove for her, heading straight toward the cabin. She gripped the desk so tightly that the wood bruised the palms of her hands. In that moment of sheer, utter terror and unbelievable horror that reminded her she was without weapon or protection, Cameron reached for the medallion in her pocket and remembered the prayer her mother had taught her as a girl. The one that Paden had always recited with her whenever she was scared... "Thou shalt not be afraid for the terror by night, nor for the arrow that flieth by day. Nor for the pestilence that walketh in darkness, nor for the destruction that wasteth at noonday. No evil shall befall thee, and neither shall any plague come nigh thy dwelling. For He shall give his angels charge over thee, to keep thee in all thy ways. They shall bear thee up in their hands, lest thou dash thy foot against a stone. Thou shalt tread upon the lion and adder, the young lion and the dragon shalt thou trample under feet. Because He hath set his love upon me, therefore will I deliver him. I will set Him on high, because He hath known my name. He shall call upon me, and I will answer Him. I will be with Him in trouble. I will deliver Him, and honor Him. With long life will I satisfy him, and shew him my salvation." No sooner had she finished those words than her pocket and hand began to heat up—the pocket where she held the stashed talisman Paden had sent her for her protection should she need it. * * * Devyl staggered back as he saw the shimmering veil fall over the ship and every member of his crew. It even covered Kalder in the water. A gossamer light rained down like a spring shower. Only, instead of leaving them wet, it cast their skin in an ethereal glow, like that of coal that held fire inside its darkness. William and Bart stared at each other with slack jaws. Then they turned toward him for an explanation he couldn't even begin to give them. "Captain?" Belle asked as she shimmied from the rigging and moved to stand beside him. He had no answer for her, either. Not for this. And definitely not for whatever caused the beast and its compatriots in the water to splinter into a fine gleaming mist that settled over the waves only to vanish in the blink of an eye. What the hell? If that wasn't shocking enough, a huge wave lifted Kalder from the sea and set him down on the deck near the prow, as if to make sure he was safe, along with the rest of them. His own jaw agape, Devyl handed his sword off to Belle before he made his way toward the only source for this he could imagine. Cameron Jack. He found her in his cabin, on her knees, clutching at the medallion her brother had sent her. Her eyes had lost all color. Her lips were as pale as her body as she whispered a barely audible prayer. Even her hair had turned a bitter white. The stark red, bleeding cuts caused by the shattered windows provided the only color anywhere on her body. Yet the strangest part? Glass hovered in the air around her, forming the illusion of glittering wings jutting out from her back. William drew up short behind him and cursed. "What manner of creature is she?" When Bart stepped around them with a raised sword to attack her, Devyl stopped and disarmed him. "She's not our enemy, Mr. Meers." He returned the sword. "What is she?" He repeated William's question. "Something that would piss down the leg of those what don't think much of us if they knew she was among our crew. And it explains much about what happened to her brother and why the Plate Fleet be sunk as it was." William scowled. "You've lost me, Captain." Devyl carefully closed the distance between them before he took the medallion from Cameron's hand. The moment he had it pried loose from her fierce grip, her hair returned to its natural chestnut shade and her eyes to their blue-green color. The glass fell to the floor, where it struck and let out a small, tinkling sound reminiscent of jester bells. Cameron blinked twice as if waking from a deep slumber. With a fierce grimace, she glanced among them. "Is the fighting over?" Bitterly amused, Devyl released a tired breath as he rubbed his thumb against the searing medallion. The ancient power and the soul of the warrior it contained thrummed from the metal, similar to a heartbeat. No wonder Menyara had sent her to them. Damn that interfering bitch for it. "Aye." He glanced to his men over his shoulder. "It appears we needs amend our earlier answer to the lass, Mr. Death." "Deeth... and what answer be that, Captain?" "There are no humans aboard this ship, at all." Cameron gaped at him. "P-p-pardon?" He held the medallion up in front of her face so that she could see the remnants of the faint glow it contained from having been activated by the evil that had come up against them. "Do you remember anything from the last few minutes?" Her scowl deepened as she cast her gaze around as if seeking an answer before she shook her head. Handing the medallion back to her, he closed her fingers over it. "You are born of a Seraph's bloodline, lass. And this trinket of your brother's is the proof of it. I'd been hoping I was wrong with my earlier assessment. Sadly, I wasn't." He stepped back as he contemplated what it all meant. "The good news is, since you had no idea of your family's origins... unless you have a sibling your parents failed to speak of, your brother's still alive somewhere—you were right with your assertions. They didn't kill him, after all." Cameron gasped as hope finally filled her. "You're sure about that?" Bane nodded before he dipped his chin toward her fisted hand. "As we've all just seen, the medallion reacts to your blood when you're under demonic threat. Had Captain Jack died, you'd have been approached by those he serves about replacing him in this fight. Since no one's come for you, he's alive without a doubt. And that medallion is from his own sword, which I'm sure he inherited from one of your parents." Cameron's breath caught as she opened her hand to study the emblem more closely. Never had she seen it in her parents' possession. "Me mother had a sword that belonged to her father before he died, but we were never allowed near the locked chest where she kept it. She always said that it would pass to Paden on her death." She bit her lip as she remembered something she hadn't thought about in years. "After her death, he never let me see it, either. I never thought anything about that, until now. Like her, he guarded it with the strictest care." "Because of the power it contains, a vile beacon it be. One that draws evil to it like a flame summons moths. Unless it's kept shielded and enclosed, it would be a threat to any nearby innocent unaware of what it actually is." Devyl crossed his arms over his chest. "Your brother must have sent the Seraph medallion to you to keep his enemies from using his sword or destroying the soul of your ancestor. And to keep you safe in his absence." "What is this Seraph you keep mentioning?" William asked. Before Devyl could speak, a pale, shimmering woman appeared in the center of the cabin. Gasping, Cameron shrank away from her. The men, however, didn't blink. They acted as if her ghostly presence among them was normal and expected. More beautiful than a fairy queen, she stood eye to eye with Devyl and had hair unlike anything Cameron had ever seen before. Pale golden-brown, it was laced with strands of ice white—not gray or any facsimile of gray. It was a silvery, gleaming white... like fey-locks that fell in unadorned waves to her waist. Her black-and-white-striped silk gown was plain, yet richly cut and elegant. A white lace kerchief encircled her neck, and as with her hair, it had shimmery silver threads laced through it—the same lace decorated the edges of her sleeves and hem. Yet the most peculiar bit was that she stood barefoot even while she held the bearing of some grand empress. Obviously she didn't fear splinters from the ship boards. And her eyes... Almond-shaped, they were a deep amber brown. She turned to face Cameron and offered her a kind smile. "No need to fear me, child. I mean you no harm." Devyl stepped forward. "Cameron Jack, may I present you to our lady ship, Marcelina?" Cameron bowed to the noblewoman. "It's a pleasure to meet you, my lady." Marcelina smiled. "I'm not a lady, child. You misunderstood Du's words, as was no doubt his intention." She passed a chiding grimace toward Captain Bane. Confused by that, Cameron waited for an explanation. William laughed while Bart bit back a smile. Devyl gave each of the men a chilling glare before he explained the lady's comment. "Mara is this ship we sail upon, Miss Jack. Our warden—in all senses of that word—for this grand misadventure." "Pardon?" "Perhaps this will help?" Marcelina posed herself like the ship's figurehead. Before Cameron's eyes, she turned into the wooden piece from head to toe. "Holy mother of God!" Cameron crossed herself. Marcelina returned to flesh. "No need to panic, child. As Du said, I'm the guardian for all who reside here. So long as you fall under my protection, I will do anything to keep you safe." "And ensure you have no fun whatsoever," Bart mumbled under his breath. The captain elbowed him in the stomach hard enough that he doubled over. Shaking her head, Cameron did her best to absorb all of this, but... "How is this possible? How can she be the boat?" The smile returned to Marcelina's face. "I come from an ancient race. We are the wood and the wood is us." "They were the gods and guardians of the forest," Devyl said. "Ever lurking among humanity and causing problems for them and us." "I don't follow." Marcelina glared at Devyl. "We are the protectors—" "My ass cheeks." "Du, please! Watch your language!" "Watch your lies! Are you really going to stand there and preach that as if I wasn't there?" Marcelina grimaced at him. "And what of yours? How many fell to your race and army? Need I remind you how we met?" "Need I remind you how we parted? Blood soaks us both!" "And you're an unreasoning beast!" "Better than being an unreasoning—" "Don't you dare!" Marcelina shrieked, cutting him off before he could insult her. A fierce tic started in Devyl's jaw as his eyes glowed a deep, dark red in the dim light. Her breathing ragged, Marcelina turned toward Cameron. "Anyway, my race predates the existence of mankind by centuries." Cameron frowned as she tried to understand what they were telling her. "Then why have we never seen you? How is it that I've never heard of your people?" Marcelina turned another hostile grimace toward the captain. "War thinned our numbers to virtual extinction. While there were millions of us centuries ago, there are but a handful now." She gestured at the captain. "Du and I had our destinies bound together long before the world you would recognize came into being. So when he accepted this task, I was forced to it, as well." "Payback's a bitch," he mumbled under his breath. Cameron didn't understand his hostility, but at least she was beginning to figure out his peculiar relationship with his crew and boat, and why they spoke of things the way they did. As William had warned her, things here were not as they seemed, in any sense of the word. She inclined her head respectfully to Marcelina. "So you're the captain's wife, then?" Captain Bane snorted rudely. "Hardly. I'd have slit my own throat first." "As would I," Marcelina said in the same scoffing tone. "Neither of us had a real say in our fates or misbegotten whatever this travesty burden we share is." She swept a less than flattering grimace over his body. "I can't imagine a more horrid fate than what you speak." Captain Bane laughed bitterly. "I can... being husbanded to you." William cleared his throat as the captain and Marcelina began to escalate their verbal conflict. "Ancient ones? You have children present and it upsets us when our parents fight." "Speak for yourself, Will," Bart said with a smirk. "I find it highly entertaining. Especially when they begin to launch things about, and throw fire at one another." Without so much as glancing in his direction, the captain let fly a dagger at Bart that seemed to have appeared from thin air. William caught it and tsked. "Best be careful with that sudden flailing, Captain. Could put out someone's eye with this." "Was rather hoping to put out someone's life with it." "Och now, that's just mean." "Do they always fight like this?" Cameron whispered to Bart. He screwed his face up in thought. "Actually, this is rather tame for them. Thinking it must be because you're new to our company that they're tamping it down a bit." "Anyway," Marcelina said again, returning her attention to Cameron. "My race—Deruvian—was all but destroyed by the very ones we're after. Our goal is to keep the same fate from befalling mankind." Marcelina moved to stand near William. "And to answer your question, Mr. Death"—she spoke his name correctly—"Seraphs were chosen from an elite group of fighters who once battled beside my race for the survival of this world. After the war ended, the Cimmerian forces refused to stop preying on the innocent. And they proved more resourceful and resilient than the gates made by our side that held them back from your realm. Even worse, they found ways to beat back the Seraphim until there were only thirty-seven of them left out of their once great army. As a last resort, and to keep the balance intact, the Sarim council made a dark bargain and used forbidden magick to make those last thirty and seven souls immortal—with the help of my people, they bound them to medallions like the one in your hand." Devyl let out a heavy sigh. "It was a desperate but necessary act, as those last thirty-seven possessed unique skills and powers that take years to master and learn... provided an apt pupil could be located for the instruction. But rather than start from the beginning, the medallion allows the soul of the Seraph to temporarily take over the body of their descendent to battle their enemies." Marcelina nodded. "Aye, and it must be a member of their direct bloodline to fully access their powers. Otherwise, the Seraph becomes tainted and an easy tool for evil." "So each soul must be carefully watched over and guarded to ensure no other finds it, corrupts, and bonds with it," Devyl said. "Along with the sword the soul controls." The captain picked up Cameron's hand that held her medallion. "The bad news is that now that you've tapped the power of your bloodline, you've sent out a signal to those who seek to destroy all of the remaining Seraphim. They won't stop until you're dead and they have your medallion." Cameron winced at the last thing she wanted to hear. But that left her with another question. "Are you a Seraph, too?" Stepping away from her, Devyl scoffed bitterly. "Nay, lass. I was the very thing they gave their lives fighting against." "I don't understand." The red returned to his eyes as his expression became sinister. "Never mistake that I'm anything more than a damned soul, gal. I'm here only for vengeance and blood. I leave redemption and kindness for better folks than I, as I've no use whatsoever for any of it. To hell with anything save blood and violence." And with those chilling words hanging in the air, he left them. When William started after Bane, Marcelina stopped him. "Let Du go, Mr. Death. He's in no mood for comfort and won't welcome anything more than bloodshed in his current state of mind. Trust me, you don't want to be on the receiving end of it." "As you say, mum." He inclined his head to her, then left in the opposite direction the captain had gone. Bart hesitated. "Should I show Miss Jack to her quarters?" "I'll see her settled. Take the helm from Sancha and make sure Kalder takes the watch." "Aye, aye, mum." And with that, he departed. Marcelina offered Cameron a kind, benevolent smile. "The men were right. For a woman with no experience in such matters, you are taking all this rather well. Should I be worried?" Cameron slid the medallion into her pocket. "Sadly, hard knocks are rather the norm for me life. Though, to be honest, these have left me reeling quite a bit. I think I'm rather drunk from the punches here of late." She laughed. "I can imagine." Cameron rubbed the sudden chill from her arms as she tried to come to grips with all the new information she'd been run over with. Honestly, it had her staggering as she tried her best to get some bearings with everything she'd heard and seen. "May I ask you something?" "Of course." "Why do you call the captain Du?" "'Tis his real name. Dón-Dueli. Du or Duel for short." Dón-Dueli... that name sent another shiver down her spine. It denoted a sense of evil even darker than the name Devyl Bane, and reminded her of the tales her father had once spun of his Irish homeland. Of the sinister fey and the dark bean sidhe who stalked the night and preyed upon the weak. "I've never heard of a name like that before." "Like me, he comes from an ancient race. Only, where my people sought tranquil peace, his sought war and domination." "Is he a demon?" "Nay, child. That would be an easy excuse for him and his kind, when there is no reason for the brutality he embraced in his mortal lifetime. He reveled in the misery of those around him, and drank it in like mother's milk." "Then why is he helping you and the others now?" "I assure you, it's not by any real choice or out of any sense of noble obligation. He was forced to this task against his will to right a wrong he once committed." "Against?" "A girl like you. Sweet. Innocent. Until she met him and made the mistake of commending her heart to his most callous hands." There was no missing the bitter undertones in her voice. Or the hatred. "You?" "Nay, child. My younger sister." * * * "Did you sink that damnable ship?" The lusca paused as he noted the anger in his lady's voice. More grateful than ever that she had yet to breach the barriers that kept her locked from the world of man—and from reaching him—he swallowed hard. "Nay, my lady. They carry a Seraph with them now. When I tried to break the hull, it activated a shield of some sort around them all and the ship, and almost killed me." Vine shrieked in frustrated rage as she slammed her hand against the portal that kept her shielded from the world she was desperate to enter. And from the creature she wanted to disembowel. The shield cracked more. But not enough. Only a mere fraction, teasing her like the merciless bastard who had trapped her here while the world of man loomed just beyond her reach. Damn you, Dón-Dueli! And damn Marcelina for her interference. Sister or not, she wanted Mara's heart in her fist every bit as much as she wanted his. Wanted to feel both of their organs beating against her fingers while their blood coated her flesh, until her need for vengeance was quenched. And the world of man bowed to her feet and licked them clean. Gathering her layered skirts, Vine turned to glare at the pathetic bastard her servants had managed to drag through the portal for her amusement a few months ago. Weak and bleeding, he was barely recognizable as human now. While his strength had been formidable in the beginning, he was starting to fade beneath the barrage of their endless feedings from him. Still, he refused to give them the location of the key they needed to open this damnable doorway so that she could walk the human realm again. But the Seraph would break eventually. They always did. No matter who or what had shat them out into this universe. And that begged a very important question. "A Seraph sails with them, you said?" she asked the lusca. "Aye, dearest lady. There was no doubt about it. I saw the transition myself." That could not be a coincidence. She toyed with a crimson seam along the edge of her veined skirt. "Did you perchance catch a scent of its bloodline?" "Nay, Lady Vine. I couldn't get close enough for that." Growling, she flung her hand out and used her powers to drag the lusca closer to the barrier. Its tentacles left a slimy smear across the earthen floor that smelled even worse than the sea monster itself. Or perhaps it was the piss the creature let loose in fear of her intentions for it and its realization that, though Duel's magick kept Vine locked in, it didn't completely protect those near the barrier from her wrath or powers. Not that it mattered. It was good for them to fear her. Fear kept the lesser creatures in line. And they should be afraid. For, sooner or later, she would be free again and once she was... She would rain down her wrath on all those who'd participated in locking her in here. And then she'd finish what she'd begun. A new world order, where she reigned as queen and blood flowed freely to feed her and her blode sisters. "Gather whatever it takes to sink that ship, and bring me the heart of the bitch it's carved from. Do you understand? Or it'll be your soul I drink next!" She used her powers to knock the creature away. Furious and determined, she returned to the man hunched on the floor. His breathing was shallow and ragged. Pain filled. They'd made good use of the Seraph bastard and still he wouldn't give them what they asked. His resolve and strength reminded her much of another man she'd known once. He, too, had resisted and fought against her. In the beginning, at least. To this day, she'd never met his equal. Not in face, form, or strength. Only he had ever had the ability to fully resist her. Only he had ever had the ability to defeat her. It was why she'd been forced to cut out his black heart and feed it to him before he turned on her completely. Damn you, Dón-Dueli of the Dumnonii! But she wouldn't think of her ex-husband. She'd deal with that devil later. Right now... Right now, she had a Seraph to torture and a gate to crack. She was done with these games. Her patience was through. "Nah! None of that, now. You'll be bunking with us." Cameron paused as Valynda and Belle practically kidnapped her from her assigned cabin and dragged her off to their quarters, which they shared with Sancha and an affable Trini named Janice Smith. Valynda twirled Cameron toward a low-lying bunk that was covered with a dark blue quilt. The peculiar design of the bed was more like a crib, so that it would keep her from being tossed about in a storm. "You can sleep between me and Janny." With a wealth of long, wavy black hair flowing over her shoulders, Janice looked up from the Tarot cards she had spread out across her bed to smile at Cameron. "Welcome aboard, Miss Jack. Nice to have another woman in the mix. There be too few of us here as it is. We need to stick together in this testosterone stew where we've been tossed." Cameron opened her mouth to thank her for the welcome, then scowled as she saw the Death card in her spread. "Is that not a bad omen?" Janice wrinkled her nose, which somehow made her even more beautiful. "Bah! Nay! Only to those who don't know the cards. Only means a change is coming. Death to one thing is the birth of another. The cards to fear are not so obvious in their meaning, and it takes more than one bad card to make a bad fate." "That's good to know, and applies to more than just a reading, eh?" Janice winked at her. "Truth to that, me girl." She held her hand out to her. "Be nice meeting you, Miss Jack." She shook her hand. "And you, Miss Smith. What brings such an elegant lady to this rowdy bunch of miscreants?" "Janny be our necromancer," Sancha said as she offered Cameron a mug of rum. "Like Lady Belle, she has powers that are frightening beyond belief. The kind they burn the witches for." As Cameron took the mug, she noted the burn mark on Sancha's wrist that was identical to the ones they all bore—a strange Celtic cross ribbon, with a circle in the center that held a skull and crossbones. Inclining her head to the mark, Cameron scowled at it. "Might I inquire about the source of that?" Sancha pulled her sleeve back to expose more of the mark. "Sure you want to know?" They all seemed to hold their breath in expectation of her answer. But Cameron wanted to understand this new place she seemed fated to call home. "Aye." Sancha pulled the dark wig from her head, showing that her hair beneath was snow white. The color most wore wigs or heavily powdered their hair to achieve. Cameron had never seen a human being with hair that pale before. Especially not a young person, nor one whose skin and eyes were so dark. Sancha couldn't be more than three-and-twenty, or five-and-twenty at most. She tossed the wig down on her own bunk before she drained her mug and spoke again. "That be the Deadman's Cross we bear." "Pardon?" "We are the dead, Miss Jack. And the damned. Every jack and molly here." She fell against her bunk and let her insanely long legs fly up. "It's why all who sail on this ship are known as Deadmen. The Deadman's Cross be the mark of our bondage to a beast they say is the son of the devil himself." "The captain?" It would make sense, given his name. Sancha laughed. "Nay, love. The real and true Lucifer, who sits on a fiery throne in hell and rains down his wrath on those poor souls he's taken in." Cameron glanced at each woman in the room. Belle, Valynda, Janice, and Sancha. "I'm not sure I follow." Belle answered in her own lyrical accent. "You know about me Valynda there, and how she died her death. Sancha and I lived less than auspicious lives. Unlike poor Valynda, we earned our damnation with both fists, brawling every step of the way to our deaths. As did the rest of the men on this ship. Hell-bound from crib to grave we all were." "But each of us committed at least one decent act that brought us to the attention of a..." Sancha screwed her face up as she reached for more rum. "How would you describe the beast?" she asked Belle. "The devil is the beast," Belle said blankly. "And the beast is the devil." Cameron cocked her head at the casual way Belle spoke, trying to make sense of it all. "Captain Bane or the other?" Belle let out a low, evil laugh. "The other." She reached for Sancha's rum to drink it. "This one gives our fair dark captain a run for his money when it comes to his evil aura and badassery." "Thorn be this beastie's name, though." Valynda picked up the tale. "As Sancha noted, they say he's the son of Satan himself. For true. As in Lucifer's very spawn. And it's a story I believe. He has the air of it. And the power to pull souls from hell itself—which would make sense if he is the son of Old Scratch. 'Tis how some of us have come to be here. The Deadman mark is what allows us to stay on this side of things and not be sucked back to whatever dark realm he pulled us from. It's a binding spell that holds us on this side of the barrier." Sancha lifted her cup. "And to keep other creatures from returning us to whatever dimension we came out of until either Thorn wills it or we earn back our freedom." "Aye, and he has the power to remove the Deadman's mark at will should we do something wrong and fall from his favor." Belle took a swig from the bottle. "It's the bargain Thorn made with the lot of us. We serve his needs. Police his demons back to their respective cages. And should we survive our trials and battle, we'll earn our salvation and be returned to the land of the living as full mortal beings." Cameron suppressed the chill that ran down her spine at the very thought of what they described. "If you fail?" A shadow darkened Sancha's gaze. "We're cast back to the demons that were torturing us when he saved us." "That hardly seems fair." Belle scoffed at Cameron's puerility. "Fair's got nothing to do with our sorry lot. Never did. Never will." Sancha nodded. "Truth be to that." They clanked mugs. Cameron paused to consider everything they'd told her. Which made her wonder one particular thing... "So how many demons does it take to redeem yourselves, anyway?" "Depends on the severity of the deed what got us damned and our remorse for it. Each has his or her own path to follow." Sancha pulled back her sleeve to show her emblem to Cameron. "The mark lightens as we get closer to earning our freedom. When it's gone completely, so are we." "How do you mean?" Sancha reached for her drink. "We're set free and given a chance to screw up anew." "Even Valynda?" Valynda nodded. "That's what Thorn promised me. A brand-new body as a woman, once more. I pray he's not lying. I would love to be human again." She closed her eyes and smiled. "To have a real human body!" "And Janice?" Cameron asked. "Did you earn your freedom already?" Unlike the others, she didn't bear the Deadman's mark on her wrist. Janice shook her head as she gathered together her cards. "I be a little different from them, me lovey." She pulled her shirt up to show a double bow mark on her hip. "I was not damned, per se. Me mistress be a Greek goddess, and me soul be held by her for all eternity, under an entirely different set of rules and conditions." What the blue devil? Cameron gaped at the last thing she'd expected to hear. Even among these preposterous tales. While her father, who had been enamored of the Classics, had taught her and Paden much about ancient Greeks and Romans and their beliefs, she'd never believed any of it to be real. "Come again?" "I gave up me soul for vengeance over a wrong what was done to me and mine. Technically, I shouldn't be here with the Deadmen, as it's not really allowed for a Dark-Huntress to mingle with them." "Which tells you how dangerous our mission is that Acheron would allow her to live and work among our crew," Valynda whispered. "Even the Dark-Hunters have a vested interest in our success." "The Dark-Hunters?" "Be the term for what I am, Miss Jack. Acheron be me boss man." Janice covered her mark. "Deadmen pursue demons who've escaped their prisons or who be preying on humanity and return them to their place of origin. Dark-Hunters are a band of warriors what hunt demons known as Daimons." "There's a difference, then?" "Oh, aye to that. Our demons be born of an ancient race, cursed by the Greek god Apollo." "Cursed why?" "'Tis said their queen was once a beloved of Apollo's and that she lost his favor, after her miscarriage of Apollo's child, to a beautiful Greek princess who bore him a son. So jealous was she that the queen ordered her soldiers out to slaughter Apollo's mistress and son, in the most brutal of ways. She wanted them ripped apart as if an animal had done it." Cameron cringed at the horror. No wonder the god had cursed them. She'd have wanted revenge herself had someone dared take the life of her child. But only on the ones who'd done it. She certainly wouldn't have gone after other innocents over it. As her mother had so often said, two wrongs never made a right. Especially in a tragedy of this magnitude. Janice placed her cards aside. "To thwart his curse, some of them Apollites done learned to steal souls so that they could feed from them to elongate their own lives. But the problem is, when they do that, they destroy the soul forever. Our goal is to kill those Daimons and free the stolen souls so that they can restore themselves and go on to their eternal rest. If we fail, those souls vanish forever." Cameron crossed herself at what Janice described. "Was it Apollo who made the Dark-Hunters, too?" Belle shook her head. "It was Apollo's sister, Artemis, who used her own blood to create the first Dark-Hunter to hunt the Daimons and kill them. That original Dark-Hunter, Acheron, is now their leader, and he's the one what trains them whenever Artemis makes a new Hunter." "That's why Janny has fangs and we don't... different Hunters, different abilities." Sancha winked at Janice. Cameron let out a nervous laugh, hoping that was a jest. Surely the woman didn't really have fangs. Did she? "W-w-what?" "'Tis true." Janice opened her mouth to show off her unique dental features. Holy mother of God! Cameron shot off her bed to move closer to Belle, who laughed at her overreaction. "There now, girl! No fear of our Janny. She only bites male posteriors." Janice grinned. "Truth be to that. And that I do with great relish. In particular, wouldn't mind me a piece of a few of the ones what be sailing on this very ship, or me boss, Acheron. Oh, that one..." She sucked her breath in sharply between her teeth—or fangs, rather. "He's got the finest backside what's ever graced a man. If ever there be a one you want to sink teeth to..." "And pray for lockjaw?" Cameron added, remembering what the prostitute had said to her earlier. "Hear, hear," Sancha laughed. "Wouldn't mind a romp in the sheets with Acheron meself. Can you imagine the skills he must have after all these centuries?" "Or Bane?" Belle said with a laugh. "I'd lay money he's not one to be shy or timid. Rather, he'd no doubt set fire to the bed, what with his passions." Janice grinned wider. "Or our dear William or Kalder." "Or Bart." Sancha purred. "Hell, sign me up for a piece of that Wild Kat or Zumari! Would love to offer up a salutation to their flagpoles and change their religions." She winked. "Aye!" Belle and Janice agreed in unison. Sancha took a deep quaff of rum and sighed. "One day, me ladies, we've got to find some way around the captain's ban on crew fraternizations. Even if it means all of us seducing our good captain at once to change his mind on that particular law that chafes me all the way to me nether quarters." Valynda laughed. "Stop it now, you're scandalizing our Miss Cameron. Look at the poor thing! She's as red as a British officer's jacket." "I've heard worse." She cleared her throat, even though her cheeks were scalding hot. "Work in a bawdy tavern at home." Cameron returned to sit on her bed before she spoke to Janice. "So how is it that you've come to live among the crew if you're not supposed to be here?" Janice let out a tired sigh as she propped up her pillow and leaned back against it. "Evil Apollite bastards thought it funny to set me out to sea to die. I'd have burst into flames had Bane not seen me boat and known me for what I was. Caught me right before dawn, he did, and barely saved me hide." That made no sense whatsoever to Cameron. "How do you mean?" "Apollites are the race Apollo first created, then cursed," Belle explained. "Just like the Dark-Hunters can't kill humans, they can't kill Apollites until they begin taking souls, as they're considered innocent until they take a human life. The Hunters, like we Deadmen, have a strict code they must follow that dictates what they can and can't do and who they're allowed to hunt and when." Janice nodded. "So there I was, adrift at sea in a tiny dinghy, helpless as a newborn babe. No oar and no way of getting back to shore on me own, since I know not how to swim. Cursing every line of Acheron's Dark-Hunter manual he forces us to read and live by. Thought I be a goner for sure... even after I was seeing this fine ship pulling up alongside me. Couldn't imagine how to explain me predicament to a normal crew of folks. Lucky I was it turned out to be this group of miscreants what knew who and what I was. They rushed me under cover just a mere heartbeat before I'd have burst into flames." Cameron arched a brow at her dire tone. "Burst into flames? That a metaphor?" "Oh..." Janice flashed a grin. "Nay, lovey. That be an important detail, indeed. Never open a port window and be letting daylight in whenever I be down here, as it be quite lethal to me health." "Really?" "Aye!" they said in unison. Valynda poured more rum for Cameron. "All Apollites, Daimons, and Dark-Hunters are forbidden by Apollo to be in his domain. A single ray of sunshine will instantly cause their skin to blister and burn. Full exposure incinerates them. Part of their curse from the evil sun god who hates the sorry lot of them." "How awful!" Cameron shuddered in sympathy as she tried to imagine having to live her life without daylight. For eternity, no less. She could imagine no worse existence. "'Deed!" Janice sighed. "Honestly, I feel bad for the buggers. The Apollites, not the Daimons, mind you. Can you think of being cursed to die at age twenty-seven for an act your ancestors done committed that you had nothing to do with? Tragic, really." Belle snorted. "Feel bad if you want, but few in life are innocent past their walking knickers. Most are out only for themselves, Janny. Hence your unfortunate past what caused you to be in our company." Sighing, Janice nodded glumly. Before Cameron could ask her to elaborate, Valynda moved to sit beside her. "So what about you, Miss Jack? Have you a beau or a belle at home?" She scowled at the exceptionally bold and scandalous way these women talked. While she was used to some bawdy ways from the patrons of the Black Swan, this group put even the rowdiest men there to shame. "Neither, I'm afraid. Paden and I had been making plans for him to purchase the Black Swan once he returned from this latest voyage. The current owner has been looking for a buyer and they had an unofficial agreement for it. We'd planned for me—and the girl he was to marry on his return—to run it for him while he sailed. Because of that, I wanted no entanglements from any man to distract me or turn me head from business." "Wise woman." Belle leaned back on her bed. "Men are ever a distraction." "Aye to that," Sancha agreed. "But they're oft the best kind of distraction. At least for a few minutes." She wagged her eyebrows, which caused Belle and Janice to laugh and Valynda to groan and shake her head. While Cameron understood the insinuation, she chose not to comment, as it was apparent that she was the only one in the cabin without direct experience in this matter. Something the others quickly picked up on. Sancha tsked at her. "I take it from your silence that you've never sampled the dangling fruit of the bull, Miss Jack." More heat crept over her face. "I have not. Though I've heard quite a lot about it in my time." "Working in a tavern with the reputation of the Black Swan, I imagine you have," Belle said with a laugh. "Probably seen a few, too." Janice snickered. "More than I care to think about." Cameron cleared her throat as more embarrassment filled her. "Some are not as circumspect as they should be." "Yet you've never been curious?" Valynda arched a straw brow. "Not with what's walked through the door of me tavern. They were all welcome to keep their fruits and nuts planted firmly in their breeches." They all burst into laughter. Still, Cameron couldn't refrain from allowing her thoughts to wander toward a couple of the men sailing aboard this ship that the others had mentioned earlier. Unlike the patrons of the Black Swan, the crew here were a different breed. A much finer, more handsome group she'd never seen confined in one place. The ladies were right about that. The Deadmen definitely stood out as if hand-selected for their exceptional forms. Which made her curious about something else.... "Are all of you really dead?" "Aye," Belle said, sobering. "Every last one of us. The only living creatures here are you and the ship, herself. To our knowledge, Lady Marcelina never perished. She alone retains her lifeblood." "Even Kalder?" Sancha nodded. "He was gutted. There's a vicious scar on his belly what shows where his enemies slit him good." "But it be the scar on his soul that continues to bleed." Belle scoffed at Janice's words. "'Tis the scars on all our souls that continue to bleed, sister." She turned her dark gaze to Cameron. "Even our fair Miss Jack. I feel her pain. It reaches out to me and twists like a dagger in me heart. She has her own secrets that she keeps, and it's not just her brother what haunts her." Cameron's jaw dropped that the woman would guess something that she'd have sworn she was keeping quite private. "How do you know that?" An esoteric smile curved her lips. "No one hides from me, love. I see everything. Even the fact that you haven't been completely honest with the captain." "What?" "Are you going to deny it?" Cameron wasn't sure what to say. "I'm not hiding anything." But even as she spoke, she knew it was a lie. Worse? So did Belle. * * * Devyl listened to the creaking of the boards and to the whispers of things he wished he couldn't hear. To the voices of the aether that never left him alone. Ironic really, since he'd sold his soul long ago for the ability and powers to tap into the very things that now irritated him. Or perhaps it was justice that he was tortured by them. "You dared to call for me?" He looked up from the book he was reading to the shadowed corner where his old enemy peered at him. "You dare take that tone?" Thorn scoffed as he stepped into the light. Though he wasn't quite as tall as Devyl, he was still a well-muscled bastard who would intimidate most. But then, Devyl wasn't most, and the two of them had never been particularly friendly. Indeed, they'd once battled hard against each other. Their armies had waged a bloody, devastating war on opposite ends of an intestine-laden field. It was so odd to peer into those frigid green eyes without a battle helm framing them. To sit peacefully in the presence of a being he'd once sworn to see dead at his feet. Much had changed. Instead of ancient ringed armor, Thorn was dressed in a fashionable brocade coat and buckled shoes. Hell, he even wore a powdered wig over his brown hair. How fucking off. But then, Devyl was a long way from his warrior's cloaked armor, too. His braids were gone, as was his thick black beard and philosopher's paint. Nor did he brandish his twisted runic staff. Nay, they were not the same barbaric enemies they'd been. Neither were they friends. Certainly not family. Probably the best term for them was bitter strangers. Thorn crossed the cabin to stand before him. In a move that was as audacious as it was foolhardy, he knocked Devyl's feet from the chair where they rested and took a seat on it. Leaning back, he folded his arms over his chest and cocked one arrogant brow as if daring Devyl to take him to task for his brave stupidity. "You are a cheeky bastard." Thorn smirked at him. "And you're a bullish one. Now can we dispense with the insults and you tell me why you rang my bell?" Closing his book, Devyl scratched at the whiskers on his cheek. "We have a bit of a problem." "Demons proving too much for you?" He cast the bastard a menacing glare for that dig when Thorn knew better. Not even the mighty Thorn and all his army had been able to take Devyl down. Had it not been for Vine's treachery, they'd all be paying homage to him under his eternal reign as evil overlord. Damn shame the bitch had gotten greedy and he'd gotten stupid. "Hardly. Nay, there's a bit of a fluff you need to know about." Thorn arched his brow even higher. "What fluff is this?" "I've stashed it belowdecks with the Dark-Huntress I dredged from the sea." "Pardon? What Dark-Huntress?" Devyl tsked at him. "You've fallen way behind, Leucious. How unlike you to not know everything I've been up to." "Well, as cute and adorable as you are, Duel, I do have other, much more appealing asses to stay on top of. Now, would you like to catch me up? Or should we continue this game?" He let out an annoyed "heh" before he spoke again. "Appears your friend Menyara has sent a Seraph to my door." Thorn actually choked. Pity it wasn't fatal for him. Devyl handed his mug to him to help clear his throat of the gall that had gagged him. He took it and drank deeply, then spat the contents out and cursed Devyl for everything he'd never been worth. "Blood? You're drinking futtocking blood and you handed it to me without warning? Seriously? When you know what blood does to me?" Devyl didn't react to the fact that such a beverage could turn both of them into mindless killing animals who would commit any atrocity to taste more of it. "Since when do you discriminate? Besides, it's demon blood. Not human. Pity, that. But I knew you'd get your tits in a wad if I chose a more fulfilling libation." "You evil excuse for a sentient being. I can't believe"—Thorn stressed the word—"I let Savitar talk me into bringing you back." Devyl snorted. "As you said on my resurrection, to destroy evil of this magnitude you don't send out choirboys, unless you want to feed your enemies lunch." Thorn sighed irritably as he wiped his hand over his mouth. "Is there anything in this place to drink that didn't once filter through internal organs?" "When did you become such a prissy quim?" "Careful, Duel, lest I don my armor and we take up where we once left off." "That would be fine by me. We never did settle that last fight, as I recall. You turned tail and ran." The expression on Thorn's face could have frozen fire in August on the equator. "I advanced in a new direction." Yeah, right. Scoffing at the bullshit answer, Devyl cast his gaze to the corner where he kept his alcohol. "Cabinet behind you. Serve yourself." Thorn got up to peruse the meager potent potables Devyl kept on hand for his visiting crew, who would be even more horrified by his preferred beverage than Thorn. "Not by my choice. I'd have gladly sent you to your precious Annwn that day, had it been up to me." "You'd have tried. 'Twould have been your heart I'd have delivered to your father for my reward, rather. Quite the price he places on you." Thorn went ramrod still. "Fear not, Leucious," Devyl said, using Thorn's real name. "I have no intention of telling anyone who your true father is. Or the truth of your birth. A bastard I might be, but I'm not a scabbing piece of shit. Your family trauma be no business of mine. Have my own to deal with." Relaxing, Thorn chose a hearty wine to pour. "Appreciate your discretion." Devyl snorted. "Don't. As you know, I settle my issues on a battlefield, as the gods intended. I've no use or respect for sneaky treachery, or those who participate in it." "That's the one thing I've always respected about you, Duel. Even when we were enemies. Always knew where we stood." He returned to sit. "So tell me of this Seraph." "It's not her, per se. Rather, it's her brother, who seems to be in Vine's custody. Somehow he managed to smuggle out his medallion to his sister, who in turn was sent here by way of Menyara." "How did he manage to get his medallion separated from his sword?" "That be the question, don't it? But then, he's of Michael's bloodline." Thorn released a low whistle. "Powerful blood, that." "Indeed. I never knew he had issue. Other than rumors, of course. Did you?" "I don't delve into those places or ask those questions. I'm no more welcomed among my brethren than you'd be. For that matter, I'm trusted even less, given what fathered me... and how." "Never mind the why of it." "Exactly." Thorn nursed his wine as he considered the matter. "If Vine has a Seraph in her custody—" "A powerful one..." "She could open the gate." "Could open more than that. Michael's blood is a most potent tonic. And if she has custody of his sword to boot..." Thorn winced. "You're sure the sister holds the medallion?" "Saw it myself. And it activated under threat. There's no missing that spectacular light show. Lit up the sky for leagues. Surprised you missed it." Devyl set his book aside. "Is Michael still among the Sarim?" "No idea. As I said, they don't exactly talk to me. We're Hellchasers. The Hell-Hunters are a different breed entirely, and they don't trust me or like us as a rule. The Necrodemians have always been prissy assholes when it comes to our demonic ranks." Because they expected treachery from Thorn. Born of two powerful, cunning demons who'd betrayed them all and a weak human mother's greed, Thorn was likely to turn on them—at least that was what they assumed. It didn't matter that for thousands upon thousands of years Thorn had served the same side as they. They still refused to trust him completely. Devyl couldn't blame them for that. It was a rare dog indeed that didn't return to its vomit. Only the strongest of the strong could resist the urge. Of course, he'd never met any creature stronger than Thorn, and while he'd never admit it aloud, it was what he respected about the beast. Thorn possessed a rare integrity that he knew would never be tempted by the darkness that Devyl willingly gave in to. But then he didn't have the tethers to the light that Thorn did. There was nothing for him to hold on to. Nothing he craved or wanted past Vine's head on his wall. At this point he didn't even care if he returned to his infernal pit of eternal torture or not. He'd endured it for so long that it no longer held any deterrent to him whatsoever. Indeed, a part of him had even learned to derive a bit of masochistic pleasure from the pain of it all. Sick though it was. Thorn pinned him with a probing stare. "You're taking this awfully well. Should I ask why?" "Unlike you, I don't fear the gate opening. 'Deed, I hope it does." "Since yours is the first ass Vine will be after, might I ask why you're so eager for it?" "As you said, mine is the first ass she'll seek. This time, when I go to my grave, I won't be headed there alone. I plan to take her and all her sisters along with me." "Including Marcelina?" "If she gets in my way." "What happened between the two of you, anyway? Why does she hate you so much?" Devyl fell silent at the question that took him back to a time and place he hated. Back to a boy who'd died a harsh, painful death long before Vine had carved out his heart, fed it to him, and ended his mortal life. "She blames me for corrupting her sister." "Did you?" "What difference does it make? The past is done with. Blame is nothing more than a waste at this point. Besides, we're all guilty of something." Thorn knew that look in Duel's eyes. A pain so profound and deep that you dared not speak of it because no amount of time could dull the way it lacerated your soul and left it bleeding and raw. It was a turmoil he lived with himself. Guilt. Anguish. And a self-hatred that overrode all other feelings to the point you wondered at times how you managed to remain sane. Or maybe you didn't. Maybe you were insane. That would at least explain the horror that was life. The travesty of it all. Denial was the easiest way to cope. You ignored it as much as you could and prayed it stayed in the dark recesses where you locked it away tight and prayed it never got out again. Yet no matter how great the seal—how carefully you guarded that door—sooner or later some stupid bastard always had to open it and force you to look inside. Face the very thing you didn't want to see. Today, he was that stupid bastard. It was almost enough to make him feel sorry for Duel. Perhaps there was some semblance of a soul left in this vicious blighter after all. Then again, given some of their nastier battles, he wondered if there'd ever been a soul in Dón-Dueli of the Dumnonii. They hadn't called him the Dark One or Black Soul because of his hair color. A knock sounded on the door. "Enter." Thorn was ever impressed with the way Duel could command his voice to such a threatening intensity without actually raising it to a shout. As a warlord himself, he'd never quite perfected that shit-in-your-breeches growl to the same extent. William drew up short as he saw Thorn in the cabin. "Beg pardon for the interruption, but we've got a bit of a situation and wanted your input, Captain." Devyl let out a weary sigh. "Who has Sallie's soul now?" "Not that. There's a ship approaching fast off the starboard aft. She just hoisted her colors." He arched a questioning brow. William swallowed hard before he answered. "Red jack." A pirate flag. Take no prisoners. Show no mercy. Death to all. No prey. No pay. A slow smile spread across Devyl's lips. "Slow her down, Mr. Death. Swing her about and, by all means, let the bitches catch up." Devyl stood on deck with his telescope, eyeing the approaching ship, while Thorn moved in to rest just behind him. Something the demon knew made the hairs on Devyl's neck rise—along with his hackles. He'd never been one to stomach a friend at his back. Never mind a former enemy who'd once lifted his sword in battle against him. Though allies they might be today, it still didn't erase the years they'd fought viciously to destroy each other. Nor did it lend itself to the formation of any kind of trusting bond between them. It never would. Devyl used his powers to check the Sea Witch's defenses. Cannons had been rolled into position and stood ready to rain down iron hell on the approaching group. To keep his crew from spooking, he lifted his telescope to survey the sloop that was gaining on them, even though he didn't really need it to inspect them. With or without it, he'd have been able to catch the name of the ship that was painted next to the green mermaid figurehead. Soucouyant. "Avast!" he ordered Will. There was no need to blast this particular crew of pirates from the waters. At least not quite yet. Confused, William arched a disbelieving brow, but passed the order along without hesitation. Though it was obvious the man didn't quite agree with it. Devyl's hesitation proved to be prudent when one of the Soucouyant's crew members waved a white flag of truce over his head at the same time they lowered Captain Cross's red jack and replaced it with a plain white flag for parlay. Not quite trusting them, as Rafael Santiago and his pirates weren't exactly known for their honest ways, Devyl kept his men in position, then tapped his powers again to determine the Soucouyant's threat level. He didn't pick up any treachery. They had yet to roll their cannons into place. And no one seemed to be scurrying about in subterfuge. But then, one never knew for sure, and he wasn't about to risk his ship or crew for any reason. Especially since he knew Santiago had other means of attack no one, other than he, Thorn, or Belle would see coming. Attacks his crew wouldn't be able to defend against with traditional weaponry. Glancing at Thorn over his shoulder, he caught the older demon's eye. "What do you think?" "That Santiago knows you too well to try it." Thorn was right about that. Firing on the Sea Witch never ended well for anyone. "Hoist the truce back, Mr. Death! Stay your positions." And if the pirates tried anything, he'd be feasting on more than demon blood tonight. The thought brought a rare smile to his lips. Please try something. He would relish a good fight. True to his nature, the Soucouyant's captain, Rafael Santiago, came forward to stand on top of the rail until they'd pulled up close enough that he could swing from his deck to Devyl's. The moment Rafael's black boots touched their boards, Bart and Zumari flanked him. He laughed at their threatening bluster and clapped them each in turn on the back as they brought him closer to Devyl. Even in height to Zumari, Rafael was broad shouldered and well muscled. His dark skin was covered with scrolling tattoos on both arms, his neck, and even his shaved head. Devyl was one of the few who knew the true origins of Captain Cross, or Rafael Christoph Santiago, as he'd been named at birth. The son of Masika, a freed Ethiopian slave, and a "merchant" father, Cristóbal Cruz Gabriel Santiago, Rafe had learned the buccaneer trade aboard Captain Cris Cruz's pirate ship at the loving hand of his beloved father. And much to his mother's horror, it was a proud family tradition Rafe carried on, in spite of land law and common sense. Fearless, and bold in the manner of any second-generation pirate, Rafe ignored his escorts and approached Devyl. "I knew the red jack would work to slow you down." He winked. "You're way too predictable, mate." Snorting, Devyl crossed his arms over his chest. "Hell of a gamble you made." "That's what life's all about, my friend. No risk. No reward." Devyl shook his head at the ever-jovial marauder, who had more bullocks than brains. "So what brought you on this suicidal quest?" "Heard you were in these waters. Been looking for you for days now. You're a hard crew to find." He flashed another grin at Devyl and William. "Anyway, took something a sennight ago... Am thinking you need to see it, Devyl. It's got your Belle written all over it. We could definitely use her expertise on this bit of cargo. And yours." Even more curious, he passed a questioning brow to Thorn. "Want to join us for this inspection?" "Why not? I'm here. Better than nursing curiosity." Now it was Rafe's turn to appear perplexed. "Rafael Santiago, may I present Thorn?" Devyl stepped back so that Thorn could offer his hand to the pirate legend. "Friend?" Rafe asked. "More like brethren." The snide smirk on Thorn's face made Devyl want to knock the expression into oblivion. Especially since the bastard was currently in possession of his soul and held full control over him—two things that rankled every last bit of Devyl's core. Brethren, my ass. More like pox or plague on his private anatomy. Rafe shook Thorn's hand and stepped back. "No surname? Or is Thorn it?" "Thorn is all anyone needs to know about me." "As in thorn up all our collective nether regions," Devyl muttered. Rafe laughed. "Understood." He gestured toward his ship. "Gentlemen, after you." Devyl snorted at the invitation that could still be a trap. "I'll pull the rear." Rafael gave him an exaggerated innocent stare. "What? Don't you trust me?" "After you took a shot at me outside that tavern last time? Nay. But don't take it personally. I never trusted my own mother, either." Rafe feigned indignation. "'Twas a drunken misfire at someone else. How many times do I have to tell you that?" "Until I believe you, which will be never." Thorn shook his head and sighed before he swung himself over to Rafe's ship. He sent the line back for Rafe, who followed suit. Refusing to have his hands that far away from his weapons, Devyl ignored the line when Rafe slung it to him and, with a running start and Herculean feat, jumped from his ship to Rafe's. Something that caused an echoing gasp and ripple of stunned awe to rush through Rafe's pirate crew. And Devyl's. Especially as he rose slowly from his crouch like the predator he was and swept a weather eye around the entire group to make sure that if any treachery existed in their hearts, they rethought it fast. He was, after all, a motherless bastard who wouldn't hesitate to lay an attacker low. Rafe snorted with an amused smirk on his handsome face. "Always one for the grand entrance, eh, mate?" "Benefits of a heartless reputation, and quick sword arm." Thorn laughed at Devyl's surly tone as he crossed the deck to stand by his side. Though he'd never admit it out loud, he actually held a lot of respect and affinity for the giant beast of a warrior. "Heartless for you is a step up, my brother." And yet there had been a time in his past when Thorn would have slit his own mother's throat to have commanded a general as cold-blooded and ruthless as Devyl Bane. Even a warrior with half this demon's incomparable skill set in battle. It was a good thing the boy hadn't been born until long after Thorn had turned against his father and abandoned his cause for a far more nobler and kinder goal. As united warlords, they would have brought this world to its bloody knees and ruled every part of terra firma. In retrospect, a terrifying thought. So thank God Bane had been born centuries later and none of Thorn's original generals had been this fierce or capable. Or willing to slit a throat to win a battle or hold their lands. Devyl glanced about the top deck as a strange sensation went down his spine. And this time it wasn't from Thorn's presence here. Nay, there was another powerful entity here. One trying not to let him sense it and yet unable to remain hidden from him. "So what's this about, Santiago?" Rafe motioned for them to follow him below. Wary and highly suspicious, Devyl cast another jaundiced gaze around the ship and its crew before he climbed down, with Thorn right behind him. Irritating bastard that he was. It only took a moment for Devyl's eyes to adjust to the darkness. But the scent down here was unmistakable. Unique and revolting to any beast who was familiar with it. Like dried musk, mixed with something soured. It sent a chill down his spine. He instinctively moved his hand to his sword and prepared to confront something that should be dead and buried. Or better yet, burned beyond all recognition and scattered to the four winds so as never to rise again. Rafe lit a lantern. "At first, we thought it a jumbie." "It is a jumbie." Only this one didn't live in a silk-cotton tree. It was a Blackthorn. One of the deadliest of its breed. "Dón-Dueli..." The creature's voice was low and husky, and filled with malevolence. "Free me, my lord, and I will serve you again." He felt his eyes begin to turn. Something verified by the crew, who scrambled madly for the ladders to escape being belowdecks with him. Only Rafe held his ground. "Should I ask about that?" He jutted his chin toward Devyl's eyes. "Not really." Devyl paused to glance around. "Did you find anyone around it?" He inclined his head toward the demon in the cage. A demon that swayed like a tree in a breeze only it could see or feel. "Nay. We discovered her on a ghost ship. No one was on board and no traces of the crew remained. Not even a bone fragment. We assumed they'd abandoned ship to escape her." They'd most likely been eaten before they had a chance to flee. Devyl winced at the poor, unsuspecting bastards' fates. "She seemed friendly enough at first. Told us sickness had claimed the others. Then she went for my throat... with fangs bared." Of course she did. Devyl folded his arms over his chest. "How did you capture her?" Rafe pointed to the talisman he wore on a black cord around his neck. "My mother's protection. When she came for me, my mother's spell knocked her out. Thank God for that. We bound her here, and haven't gone near the cage since, except to toss food and water at her." Too bad that wasn't what the creature needed to sustain her ill-begotten form. Devyl cast his gaze to Rafael. "How is your mother?" He'd only seen her once, when Rafael had been transporting her to his home so that she could meet the pirate's intended. And yet, she'd been a woman of extreme kindness and grace. One of the purest, gentlest souls he'd ever known. Sadness darkened his eyes. "She took ill last winter and passed." Damn shame, that. The world could use more people with the integrity and decency of Santiago's mother. "My deepest condolences." "Thank you." "Aye," Thorn said earnestly. "Sorry for your loss." Rafe rubbed at his necklace. "At least I was with her at the end. And my father, as well. And it was peaceful. There are worse things in life, and I like to think she was watching over me and my crew when we came upon this creature." No doubt. Something exceptionally powerful had to have been protecting them. It was a rare, rare beast who encountered a hostile Deruvian and survived. Especially when they didn't know what they were facing and the creature had gone Winter on them—a term Devyl's race had coined for anyone who embraced the dark ways of Marcelina's people. Judging by this one, she'd been Winter for quite some time, too. And having been married and bonded to one, Devyl had more experience with one in Winter than most. His stomach pitching with disgust and anger, he neared the cage where she watched him from a pair of hate-filled whisky-colored eyes. She lay in chains. Her black hair gnarled and greasy. Malnourished from her captivity, she held a grayish tint to her skin, and her veins appeared black beneath it. Thorny. Yet even with that, her lips were a vibrant, unnatural shade of red. "Blackthorn... where's your partner?" Sinister laughter answered his question. "Where is yours?" Hissing, he rushed toward the bars, wanting to rip out her heart and eat it raw until he was whole again himself. Like her, it'd been too long since he'd fed on what sustained him, and he was starving for what he really needed. Still, she offered him a cold smile. "Anger you, did I, Majesty?" "Don't play this game with me. I could use a good bonfire." He raked her with a meaningful glare as he imagined her being consumed by the flames. That form of a death sentence for her race was what had led to the burning of witches in mankind's history. Not knowing about the Deruvians, Christians had taken up the punishment Devyl's people had once reserved solely for hers and used it against innocent humans. Even the test to see if witches floated in water came from the fact that Deruvian bones were made of wood, and it was how earlier human tribes had once identified her species when they didn't have access to his people to help them determine Deruvian threat. Foolish humans. They had no idea what they were dealing with. No idea that the only way to kill a Deruvian was to burn them completely and then scatter the charred ashes over water so that they couldn't take root and regenerate. Otherwise, the bastards returned even angrier and more vicious and vengeful as enemies. Not human sorcerers. Rather, preternatural creatures with powers far beyond mortal comprehension. And if they regenerated a third time, they came back petrified as a supreme power unlike anything imaginable. That was the last thing anyone wanted to fight or encounter. An unholy hell-beast that only those well trained could stand against or kill. Her eyes glowing softly in the dim light, she laughed again. Until her gaze went past his shoulder to focus on the other "Thorn" in the room. That sobered her quick. "Well, well. Bedding with your enemies these days, I see. How fast the mighty do fall." Fuck this. He had no tolerance for her or her insults. Stepping back with a sneer, Devyl turned to Rafael. "Take her topside and set her ass on fire. Scatter her charred and besalted ashes over the waves, far out to sea." With those words, he headed for the ladder. "Druid! Wait!" Devyl froze as she let out the one tidbit of his past he never spoke about. To anyone. And it sucked every bit of oxygen from the room. Only Thorn and Marcelina knew about the days he'd donned the black robes of a pagan leader and counselor. Only they knew the cost of that particular stupidity. He took a deep breath to control his rage, then continued on for the exit. "Wait!" she screamed again. "I can help you!" "Can and will are two entirely different things," he shot over his shoulder. "I will help you! Duel, I swear it. Please!" He paused to look back at her. "I should believe you... why?" "Because the Carian Gate is cracking even as we speak. More of us are being unleashed. I know you want to find it and reseal it before she is released." Hardly. The bitch had no real, true idea how badly he wanted Vine's neck within his grasp. However... "I don't need you for that." "But you need me to find the Seraph she holds, if you're to free him. You'll never find him without me. Not alive or before she turns him." He steeled himself to show no emotions whatsoever. To give nothing away. It was the only way when dealing with a species so treacherous and cold. "What Seraph?" "Surely the great Dón-Dueli knows about the Seraph Vine captured." She cackled with laughter. "Is that not what brings the great Forneus here, too?" At the mention of Thorn's one true demonic summoning name, Rafael crossed himself and stepped back. He paled considerably from his sudden fear of who and what Thorn really was. Thorn went completely stiff, while Devyl held his breath at something not even he had the bullocks to do. The use of his Leucious birthname was ballsy enough and as far as he dared take insulting the demon. After all, in life, there were some actions just not worth the gamble. Jumping from a cliff that overlooked a raging sea and sharp rocks. Eating glass. Throwing yourself into a raging inferno inside a volcano. Touching the Dark-Hunter Acheron on the back of his neck. Trespassing on the Chthonian Savitar's island without his permission. Telling the demon Simi no when she didn't want to hear it. And using Thorn's summoning name. "Your lack of discretion is foolish," Devyl warned her. "Were I you, I'd stop before I lose more ground and my head." "Is what she says true?" Rafe asked Thorn. "Are you the demon Forneus?" Thorn passed an irritated grimace toward the pirate. "No one can help who they're born as. But we all have a choice as to who we become, and especially in who we are. The demon Forneus died an excruciatingly long time ago, as Captain Bane can attest. I'm not the same beast who led his army of demons over the lands of man to conquer this world for his father. I'm here to make sure creatures like her mistress pay for their crimes and harm no innocent." Rafe arched a quizzical brow at Devyl. He met Thorn's cold green gaze before he answered with the truth. "Thorn isn't Forneus." At least not anymore. Though to be honest, Devyl would have liked to have met that warlord. They could have been friends. Better still, they could have been allies. But the curse of this world was that it was ever changing. Friends today. Enemies tomorrow. And, as was presently true, even enemies could become friendly. Life was ever peculiar that way, as it kept everyone on their toes. You never knew where it was going to land you, or how quickly. Sinner to saint. Hero to villain. A person's role could reverse itself in the blink of an eye. All it took was one good deed for redemption. Or one misplaced lie by another that others were too quick to grab on to and hold close to their hearts, even though they knew it for the fabrication it was. In that one single heartbeat, your whole life was ruined. For no other reason than people didn't want to do their own thinking or learn their own facts. Rather, all too many were willing to follow along like mindless sheep to the slaughter. Or the lynching. He'd never understand the human mind. Especially the hypocrisy of it all. Just as he'd never understand why Thorn had given him this chance to earn back his soul when they both knew he didn't deserve it. Thorn wasn't the one Rafe should be cringing from. He was. In his day, he'd made a mockery of the vile, evil creature Rafe had caged before them. And with that knowledge firing deep in his gullet, Devyl turned on Mona and bared his fangs at the Blackthorn bitchtress. He let his eyes glow their true bloody color so that she could see he was through with her games. "Tell what you know, Mona! Where is she?" "So you do care, don't you now? Och, Du." She tsked at him with her blackened teeth. "The truth comes out. Dark lord you might be, but me lady always held your nubby heart, such as it is. You should have been there when we fell, my lord. Vine herself lamented your death over it. She said that, had she not killed you, we wouldn't have been taken. None to blame for it but herself, she said." He scowled at her nonsense. "Stop the riddles!" He blasted the cage with his powers. The force of it knocked her from her feet and sent her straight to the ground, where she slammed against the side of the ship. From the floor, she wiped one pale, black-veined hand across her bleeding nose and laughed. "Poor Du!" When he went to blast her again, Thorn caught his arm. "Don't bother." Growling deep in his throat, he curled his lip at Thorn's compassion. "What are we to do with her? We can't leave her here. Sooner or later, she'll feast on them all, and well you know it. You banish her to return to her prison and she'll only escape and be back to bother us all the more and wreak who knows what harm on the humans. She's naught but a disease to plague and eat away at anything that she sets her roots to." An insidious smile curved Thorn's lips. "I'll plant her in a place from which there's no escape." Bitter amusement swept through Devyl as he realized that Thorn intended to take her into his home realm of Azmodea. He was right. It would be the one place from which she could never again escape. But what a hellish nightmare that would be, especially if Thorn planted her in his garden.... Devyl smirked. "You are an evil bastard." "Indeed." As Thorn headed to her cage, she shrank away from him. "I'll take you to the gate, Du! Please, lord! Mercy! Mercy!" Devyl met Thorn's gaze and let out a tired breath, as he actually felt sorry for the bitch and the fate that would await her in that hole. This was a bad idea. Every instinct he possessed told him he was a fool to even consider it. She was lying about helping them. He knew it without fail or doubt. And yet... What if she wasn't? It would be a lot easier to have a map to the gate than to play the guessing game they'd been doing by following the trail of the plat-eyes and other creatures released from it. Save them time. More than that, it would save human lives, and that was what Thorn wanted him to do. They might actually make it to the Seraph before Vine killed him and absorbed his blood and its power. Or, as the Blackthorn had pointed out, Vine converted him into a tool they could use against them—which was the last thing any of them needed. "Well?" Devyl asked him, even though it wasn't in his nature to confer with anyone. Thorn released an equally agitated breath. "I leave it up to you. Feel free to gut or burn her later, I suppose." Rafe let out a low whistle. "And they call me heartless?" "Aye, well, you might want to stand back as I release her, or she might make that a literal statement instead of a figurative one." Devyl headed for the cage. He hesitated as he swept his gaze over her fragile appearance. She looked so harmless and weak, and yet she was one of the deadliest of creatures. Like a rabbit possessed of a cobra's venom and razor-sharp teeth. She brushed at her dark, matted hair. Licking her lips, she reminded him of a street beggar. "I need sustenance, Majesty." "We have pig blood on the ship." Curling her lips to expose her fangs, she groaned in protest. "There's no living person there for you to feast on. We're all Deadmen." She screwed her face up into a perfect expression of absolute horror. "What?" "'Tis true. There's not a living creature among us." He didn't make mention of Cameron, since the last thing the girl needed was to be singled out by this beast. She groaned even louder. "Then leave me here." "Never." Mona would only escape her cage and destroy Rafael and all his crew. "You go with me or Thorn. Your choice." Glancing to Thorn, she shook her head. "I'll take me chances with you, Du." "Why do I feel so insulted?" Thorn asked. "You? I think I'm the one most slighted by her choice." Devyl was definitely the one most offended by her stench. Holding his breath, he opened the cage and tried not to think about the fact that she seemed to be rotting. From the inside out. Gah, the bowels of hell had reeked less. Mona smiled up at him as she followed Thorn toward the ladder. While this wasn't the most ideal situation, at least she was getting off this ship and away from the crew that had captured her. Sooner or later, Du would have to make port and then she could feed. But first... First she would find the Seraph medallion Vine had sent her after. Then she would tear the heart from the fetid beast and deliver them both to her mistress for reward. Along with the souls of every member of Devyl Bane's damned crew. And then they would all have their just rewards, and the world would finally be their playground. "You know this is a trap and that creature is a liar?" Devyl passed a smirk to Thorn. "Of course I do." Shaking his head, Thorn snorted. "Still letting the bitches catch up?" "Best way to keep an eye on your enemy is to have them under your thumb. Learned that from you." "And here I thought you weren't paying attention." There was a light of respect in Thorn's eyes as he watched Rafe's men escorting Mona up the ladder. "You sure you're ready to take her?" Rafe hesitated before they completely released her. "I'd much rather she be among my crew than yours." His Deadmen—and, more to the point, Mara—could handle the beast and put her down if needs be. Santiago's sailors were nothing more than a walking banquet for the hag. They were all lucky that, given Rafe's mother's extreme powers and knowledge about such things, the pirate captain had known and wasn't taken aback by the fact that Devyl wasn't quite human. That Rafe had recognized the fact that Mona was highly dangerous when they'd found her, and his mother's spell had protected them all. Anyone else would have been killed instantly and their crew sacrificed. In fact, Santiago was among the tiny few who knew Bane and his men were not of this world, but belonged to another species entirely. Rafe clapped him on the arm. "No offense, my friend. But I feel better with her in your custody myself." Devyl snorted at his misplaced humor. "Before we go, I should warn you that Barnet has moved into our waters and is hard pressing for information as to your whereabouts. He's determined to collect the bounty on your hide." "Wonderful," Rafael said drily. "Appreciate the heads-up. I'll be sure to warn St. Noir and Bonny about it when next I see them, as well." Devyl almost smiled at the mention of the female pirate. Anne Bonny was a unique piece of work. "Give Rackham my best." A strange look came over Rafael's face. "You know Anne isn't with Jack anymore, right?" That news stunned him. Jack Rackham, Anne Bonny, and Mary Reade were so tight that he'd assumed the three had magically melded into a single life form. "Since when?" Rafael let out a nervous laugh. "Since she conceived Jean-Luc St. Noir's child and Rackham found out about it. The three of them have been at each other's throats ever since." Wow. That was indeed impressive news. Devyl shook his head. Pirate drama. They could get into more shyte than anyone he'd ever known. "What of Reade?" "She and Anne have both taken up with St. Noir's crew for the time being. While Mary was fond of Rackham, her loyalty will always be to Bonny." "Well then, give them all three my congratulations." Rafael appeared bemused. "All three?" "Aye. Jean-Luc and Anne for the baby. Jack for escaping the hell known as matrimony and fatherhood." Rafe laughed. "Ah." Then he sobered as the demon was hauled past him and taken topside. The look in Mona's eyes promised Devyl a merry time to be sure. Little did she know, such challenges only fired his resolve. And they never boded well for his enemies. Thorn had the scars to prove it. Looking forward to the challenge, Devyl said his good-byes to Rafael, then returned to his own ship with Thorn in tow. By the time he was on deck again, William and Bart already had Mona in custody. "What do you want us to do with this?" William gestured at their newest "guest." Devyl pondered his options. In truth, he still wanted to set fire to her and scatter her ashes. The glimmer in Thorn's eyes said he concurred. But for now... "Put her under Belle's guard and have Miss Jack moved to my quarters." William's jaw went slack as Bart's eyebrows shot northward. "Pardon?" William's voice cracked on the question. "Have you lost your hearing, man? Those be your orders. See about them and be quick on your way." "Aye, aye, Captain." They hurried away while a slow smile curled Mona's lips. Devyl was tempted to blast her. Yet somehow he managed restraint. Though it was one of the rare times in his life that he'd ever done so. Thorn slid a knowing smirk toward him. "I take it Miss Jack is the Seraph's sister?" "Aye. She is." Thorn paused as if considering that for some reason. Though why it warranted such stern attention, Devyl had no idea. Cameron Jack was the last woman he was interested in. His heart had been claimed long ago by a callous lady who still held it with an iron-taloned fist. "And you offer her your direct protection?" He pinned a murderous glare to Thorn at the insinuation in his snide tone. The boots on his feet were older than the girl. "She's an innocent child." Thorn had to keep his own jaw from dropping at the defensiveness that lay beneath those deeply growled words. Dón-Dueli... the Dark One... the World-King who'd slaughtered any and everything that got in his way, was protecting someone? Anyone. No fucking way. It was unprecedented. Thorn couldn't get his mind to wrap around this inconceivable concept. For the first time in his insanely long life, Thorn's treatment at the hands of the higher Sarim council made sense. Aye... now, I get it. Because this... this made no sense whatsoever. It was so far out of character for the vicious beast he knew Devyl to be. There was a better chance of Lucifer becoming a virginal choir girl than Devyl Bane sheltering someone without it benefitting him. Yet those thoughts vaporized as soon as he saw the woman nearing them on deck. At first glance, Thorn thought her a very slender teen boy or young man like Devyl's rigger Katashi—Wild Kat as the crew had dubbed him. Until Thorn noted the delicate arch of her brows and the line of her cheeks. Though her thick chestnut brown hair was pulled back into a queue and she wore the coat and breeches of a man, it was still obvious that those hips and that posture and walk belonged solely to a woman. One with a nice, well-rounded ass. And her hazel blue-green eyes were absolutely mesmerizing. But none of that should induce a cruel, heartless bastard like Duel to protect her. Nay. Her features were too average and pretty. Her guile lacking all sophistication. She was nothing like Duel's ex-wife. Possessed of vibrant titian hair, and goddess curves, Vine was exquisitely formed. Breathtakingly beautiful. The kind of woman who left all women lurking in her shadow in a jealous rage, and men gaping and speechless, fully erect and incapable of any coherent thought other than how to entice her into a bed as fast as possible. He'd never had any trouble figuring out how Duel had lost his heart or his soul, never mind his life, to that bitch. Any man who favored female companionship would have gladly done whatever Vine asked and abandoned all conscience and reason for her. But this one... The only part of her that was remarkable was just how woefully average she appeared. "That's Michael's bloodline?" Thorn whispered to Duel. "You're sure?" "Aye." Incredible. Normally, those born to Michael's blood were hard to miss. They were blond, as a rule, tall, and exceptionally handsome. This one... Well, she did have one thing in common with the ancient being. Her eyes stewed with venom as she planted herself firmly in front of them. "I'm not sleeping in your cabin, Captain. Have you any idea how inappropriate that is?" "Aye, and I couldn't care less. There's not a soul here who would dare defy me or speak ill of my intentions. You will sleep where I say, Miss Jack." She laughed incredulously. "You would be wrong." She sobered to glare up at him with an audacity that was as stupid as it was commendable. "Most wrong." Devyl actually felt a smile tugging at the edges of his lips as she started in the opposite direction of his cabin. "Miss Jack?" She paused to look back at him with an arched, defiant brow. "My cabin, or we leave you adrift in the sea... without an oar... or boat. I believe the term is 'walking the plank.'" "I beg your pardon?" "Beg all you want, but it changes naught. You heard me, lass, and I meant it. Those be the terms of your stay here. Now hie thyself off to where you're supposed to be headed." "You can't be serious." Devyl arched a brow at the cheeky lass. "I can and am." With a foolish stride, she returned to stand in front of him. "You will regret this, Captain Bane." Doubtful. The only thing he regretted was the stunned look on Thorn's face that made him want to slap the bugger. Thorn finally managed to shut his gaping mouth. "Can I see her medallion?" She paled at Thorn's question. "You told him about it?" she whispered to Devyl. "Aye," he whispered back. "And the low tone is useless, as his hearing is without equal." A deep red stain crept over her cheeks. Thorn laughed. "No fears, child. I'm the last one who would harm you for the token. I only want to see it for myself to make sure Devyl doesn't have a head injury that's causing him to imagine things." Devyl felt another impulse to give him one, but didn't move as she reluctantly pulled it out and handed it to the repugnant oaf who made his current living death even more unbearable than his time spent in hell. The moment Thorn saw the medallion, his eyes shot to the same hue of red as Devyl's natural state. He turned the medallion over in his hand. It glowed a deep, vibrant green in protest of Thorn's demonic grasp. It even hummed as if screaming in agony. Devyl definitely knew that feeling, as he felt the same compunction himself. "You're right. No doubting the origins of this." Devyl crossed his arms over his chest. "Told you. I'm not the one with a head injury." Thorn locked gazes with him, and if he didn't know better, Devyl might think there was actual panic there. "We have to get to her brother. Sooner rather than later. Otherwise, there's no telling what Vine will do to him." "Well aware of that fact." Thorn clenched the medallion in his hand. "Mind if I keep this for a bit?" Cameron was aghast at his question. "Of course I mind. Me brother entrusted it to me care." "I know, but I really need it for a little while so that I can use this to hopefully find him." She glanced to Devyl. "Can I trust him?" "You probably can." "What does that mean?" "That I would never trust him. For anything. Not even to clean spit from my boots. But you shouldn't have any problems, as he doesn't virulently hate you." Jerking her head back, she scowled up at him. "I thought he was your friend?" Thorn let out a hysterical laugh. "Devyl has no friends. He doesn't believe in them." She gaped. "Truly?" Devyl snorted at the innocent question and stepped back toward Death's location. "William? Tell our innocent guest here what friendship gets you in this life." Will didn't hesitate or pause over his standard motto. "A conviction and a noose." Devyl lifted a smug, taunting brow at Cameron, who gaped at them both, especially given how flat and dry William's tone had been. "You can't really believe that?" she asked them. "Believe it?" William challenged as he drew near her. "Know it as truth." He pulled his cravat down to show her the obvious imprint of where he'd been hung. There was no mistaking or denying the mark of where the rope had torn through his flesh and left him with a bitter, awful scar. Gasping, she reached for it, then caught herself, as she must have realized how inappropriate it would be to touch him so intimately. "I-I-I-I'm sorry." "So was I when the executioner dropped the floor from beneath me feet, then waited an eternity before he yanked me legs to finish the job. Bloody plague-ridden bastard." William straightened his collar. "Sorry I ever made the mistake of calling anyone me friend. Sorriest of all that I put such a rotten piece of dung at me back." He cut a seething glare toward Thorn. "Swore to meself when Thorn brought me back that it was the one mistake I'd not make again. Put no one and nothing to your shadow unless you're prepared for a blade to be sliding between your shoulders when you least expect it." The captain moved to stand shoulder to shoulder with Will. "And that's why we get along so well. Mutual understanding." William smirked. "And mutual mistrust." "Exactly." "That just makes me sad for the both of you." She stepped forward to hug William and then the captain. Devyl froze at the sensation of her arms around his waist. Of her body pressed so intimately against his. For a full minute, he couldn't breathe as a wave of fire erupted through his veins and awoke a peculiar feeling inside him he would have never believed possible. No one had touched him like this since the day he'd buried his Elf. Not a sexual embrace, or one intended to lead to such. This was an innocent hug meant to give comfort. One offered out of kindness and true compassion for another. It was true caring and innocence. And it awakened something. He couldn't even name this feeling because it'd been far too long since he'd last felt even an inkling of... Words failed him utterly. What the hell, man? She gently rubbed her hand against his arm, offering him a compassionate smile before she turned to face Thorn. "I'm trusting you, Mr. Thorn. Please return me brother's trinket to me as soon as you can." As she walked away, Devyl realized he was gaping now, too. Snapping his mouth shut, he cleared his throat. Then saw red as it dawned on him that she was heading back to her quarters, where he'd stashed the Deruvian bitchington. "Fetch the lass, Will!" He shoved at his quartermaster. "See her to my quarters!" "Aye, Captain." He ran to obey. Turning, he caught the look on Thorn's face. "Don't start with me, demon. In the mood I'm in, I'm likely to stock up on my favored beverage supply, and your blood would be a most special and welcomed vintage." Thorn held his hands up in surrender. "All I'm thinking is that it's her Seraph's blood you're reacting to. Nothing more." "How so?" "That unnatural attraction you feel inside you has nothing to do with any real feelings you have. You know it as well as I do. When you're born in darkness, you seek the light. We crave it. It's how they destroy us in the end. We're so helpless against its lure that we dive into it even when we know we're headed for our ultimate doom." He scoffed at the older demon's wisdom. "What do you know of it?" Sadness darkened Thorn's green eyes. "More than you can fathom. And I loved mine in a way I wouldn't have believed possible. She alone tamed the angry fury inside my heart. She's the only reason I'm human now." Those words shocked Devyl most of all. "You're confiding in me?" "Nay, brother. I'm warning you. The moment she learned what I really was... saw the truth? My lady never believed another word from my lips. How could she, given what I've done and who my parents are? She never once thought me capable of any kind of love. To this day, I can't blame her for that. Some days, I'm just as sure as she is that I'm incapable of it, too." He glanced away. "That's our curse. To seek the light and to always be banished back to the darkness that birthed us. We are the damned and hopeless. Maybe that's all bastards like us deserve." And with that, Thorn vanished. Devyl stood there, ruminating on what Thorn had said. While he recognized the truth the demon spoke, there was one vast difference. Cameron had seen the beast in him. She knew what he really was. Still she'd hugged him. Hugged. Him. It defied all reason. "Captain!" Blinking to clear his thoughts, he walked toward the prow, where Sallie was rushing back and forth between the muscled mountain that was their striker, Simon Dewing, and Katashi, who barely cleared five feet in height. Wiry and lean, Kat had black hair and deep hazel-brown eyes. Because of his proclivity for pranks and harassing any sailor not doing their part, half of Bane's crew was convinced the Japanese sailor was part namahage. A fear Kat played into by the way he dressed and wore his hair in feathered knots around his head. But Devyl suspected a lot of it came from the fact that Kat had been the youngest of five boys. Something that tended to make him rambunctious and forever into things he should leave alone. Like a hungry rat ferreting. Hence his nickname. It was both a play on the fact that Kat was mouselike, and therefore they called him by a rodent's mortal enemy. And he was curious to a level that Devyl didn't doubt for an instant Kat would sacrifice nine lives to uncover one truth. Likewise, Simon, as a former priest of Exú—like the African spirit he served—was an innate trickster capable of being a fierce protector or a vengeful enemy. Almost even in height to Devyl, Simon wore his hair in a short black Greek style that softened the sharp, angular lines of his handsome features. And while Devyl's eyes became red under stress or threat, Simon's dark brown eyes would turn a vibrant gold serpentine whenever he communed with his spirits. "What mischief are you about?" He eyed them as he saw how distraught Sallie was. "They've stolen me soul again, Captain. Make them hand it back!" "Si... Kat... where is it?" he growled at them. "Captain," Simon chided. "It's ridiculous for you to humor him so. The man needs to learn his soul's not in a bottle." Devyl felt his eyes turning at their cruelty toward their older mate. "And what harm is it to you if he chooses to carry his soul in a bottle or not? Were you once frightened as a small child by a bottled soul?" Kat laughed. Simon's nostrils flared, but he knew better than to show his anger to Devyl. "I can't believe a grown man is so ridiculous. You should shatter it now, Captain, and show him how foolish he's being." "And you should both be ashamed of yourselves for tormenting the poor lad over his soul in this manner. Now hand it over and let him have his peace." Kat pulled it out of his pocket with a grimace. "It does seem a bit off, Captain. He nurses it like a child with a poppet. I've even seen him talking to it." "Again, I ask, what's the harm to you if he does? Would you rather he be talking to you or nursing you?" He gave a pointed stare to each of them. "And I'd like to think the two of you, of all the members of this crew, would be the least likely to torment another over any matter." Simon grimaced. "That's just a low blow, Captain." "And so's stealing a man's soul." "We were just having a bit of fun." Kat moved to stand closer to Simon. "Fun at the expense of another's suffering isn't fun, Mr. Mori. That bitch is known as cruelty, and her mantle is lasting anguish. It's the inalienable right of all sentient creatures to sleep in peace. To live lives of dignity and free of torment. To pursue whatever courses they, themselves, choose of their own volition. And no one should ever be beholden to another. Not for their necessities, and damn sure not for their liberty nor for their lives. And never for their immortal souls. Now hand the man his soul that you took before I aid in sending yours back to hell!" Those last words came out as a deep growl that caused them to scamper away the instant they handed it over. Devyl returned the bottle to its owner. When he started to leave, Sallie stopped him. "Thank you for understanding about me soul, Captain." Devyl inclined his head to the physically older male. However, he had been born long before the man in front of him, or even Sallie's great-grandparents. "No worries, Mr. Lucas. Though might I suggest in the future that you find a smaller bottle or safer place to be keeping such a precious commodity?" Absalon grimaced. "I tried a smaller bottle once. Damn thing's too big to fit in one. Caused all manner of ruckus over it. Sad to say, this is the smallest I could manage and keep him happy." Devyl bit back a smile. "'Tis a mighty large rum bottle." "He likes the rum the best. Gives it a nip, every now and again. For good health, you know?" "Take a nip myself, for the same reasons." "Well, me thanks again, Captain." Cradling the bottle like an infant in his arms, he wandered off to tend to his duties. Devyl took a moment to visually check where his men were and listen to the sea and the aether that stirred around him. A million voices screamed out in it, letting him know that Vine was awake and on the move again. So close that he could almost smell the scent of her skin, and yet he couldn't reach her. He needed that gate's location. How ironic that he couldn't find it, given that he was the one who'd sold his soul to lock her there. But then, that had been part of it. She'd been imprisoned after his death, so that he hadn't had the pleasure of seeing her downfall and imprisonment that he'd caused. Damn her for it. Yet how he'd have loved to have seen her expression the moment she learned his powers had been so great that he'd been able to reach out from the grave to extract his revenge on her and trap her in her hellhole so that she couldn't enjoy her success over him. It was the one thing she'd never imagined. Marcelina either. No one had held any idea of just how incredibly powerful he'd been as a mortal being. He'd always been a creature of secrets. One who never let anyone know anything about him. Not even his own wife. And this was far from over. I will find you, you bitch. You're not safe, even in your prison. One way or another, he would get to her and seal that gate and make sure that she stayed locked in her hole for all eternity. Even if it meant returning to hell himself. Or he'd have spare lumber for his ship and new blood for his cup. Aye, he'd win either way. And mount Vine's head upon his mantel. "Why did you never tell me about your sister?" Devyl froze at the barely whispered words. Words that drove a bitter wave of agony through his heart. Ignoring Mara's question, he kept working. Until she manifested in front of him and pulled the rope he was knotting from his hands. "Answer me, Du." "There's nothing to say." Sadness darkened her pale eyes to a vibrant shade of blue. "She was the reason you attacked my village that day, wasn't she?" He felt his own eyes turning red as he met her gaze. "I don't talk about Elf... with anyone." Marcelina flinched as he brushed rudely past her, no doubt to join his crew outside, away from her. Closing her eyes, she saw the day they'd met so clearly in her mind. Dón-Dueli had sat in his saddle as tall as a mountain. A giant, muscled mass of rage who'd ridden into her forest like an avenging spirit from the very bowels of hell itself, dressed in his black leather armor, with a full black beard and long, braided hair. Even his horse had seemed more like a demon than a flesh-and-bone animal. Painted to appear as a skeleton, the beast had been given fairy hair to make it seem even more fierce and supernatural. Like his rider. A creature of supreme and unholy malice and wrath. Never had she witnessed that level of carnage or fury from any man or creature. Dón-Dueli had come alone and burned her sisters and brothers to the ground in their nemeton as he sought information about a rival clan they protected. Or so she'd thought. Not once had she had an inkling of what had truly driven him to viciously slaughter three dozen of her people that day. The savage brutality of his crazed fury had chilled her to her very bones. No one had been able to slow him down or defeat him. Anyone who tried fell fast and hard to his ruthless battle skills. Combining their powers, the Sylphs and Deruvians had tried their best to fight him off and drive him from their forest, while he demanded the heads of the ones who'd gone after... "Elf!" He'd shouted that name to the heavens. A fierce, anguished cry that had sent animals scrambling through the brush and birds into flight. "Give me the ones who attacked my Elf! I want them, and I will kill every fucking one of you until I get to the culprits and pull their intestines out through their arses! So help me, Dagda! I will not leave before I taste their blood and feast on their desecrated corpses!" She'd stupidly thought that the possessive way he used "Elf" had meant he was there over a pet or his servant. It was an unheard-of name for a human. Calling out that name as a battle cry, he'd cut them down or used his sorcerer's fire to scorch them to ashes. But given what she'd heard him tell Thorn earlier... It all made sense. He'd been there that day to avenge his younger sister. Something Mara could definitely relate to. Pain choked her as she remembered Dón-Dueli grabbing her while she'd sought to distract him from her own sisters who'd fled to safety. With hell-born fury in his eyes, he'd forced her at sword point to her knees. Shaking in terror, she'd waited for the killing blow she was sure would come. A blow he'd hesitated to take. At the time, she'd assumed it was because he wanted information and she was the only one of her people who'd been stupid enough to transform into a human body that he'd seen. The only one dumb enough to fall into his hands, because she was intentionally distracting him to save the others. But as their gazes locked, and his eyes flared to their unholy red, she'd seen his desire to strike her down. Seen the anguish and torment that burned so deep inside his soul. And in that instant of his hesitation, she'd reached up and cradled his sword hand in hers. Then, she'd whispered the sacred, binding words. It'd been a desperate gamble to join them in an unholy alliance. One she'd spent ten thousand lifetimes regretting, as Dón-Dueli recognized the fact that she'd bound their life forces together. Her intent had been to take him with her to the grave. Then, as now, he'd proven an uncooperative beast. But how could she have known that he'd have knowledge of her people and their ways? That he'd instantly realize her spell and what its consequences were? He'd cursed her for everything she was worth. "Undo your sorcery, Deruvian!" "I cannot. Once spoken, it's everlasting. We are one. Kill me now and you die with me." She'd expected that to end it. That he'd be so insane as to slay them both in his anger. Instead, Dón-Dueli had captured her and forced her to watch as he continued the slaughtering for days on end. By the time his wrath had cooled and his rampage ended—only after he'd done unspeakable things to the ones who'd harmed his Elf—she'd lost count of the lives he'd ruthlessly taken. Lost count of the days. Ceased to see him as a human, or even a basic sentient life form. He'd become an unfeeling animal to her. The very epitome of the Aesir her people had hated so vehemently, and a prime example as to why they'd warred against them, trying for generations to eradicate his kind from existence. And still the Dumnonii branch of the Aesir had bred and spread like a plague upon the earth. Sowing destruction and war everywhere they went. Pillaging. Looting. Raping. Barbarians all. Though to be fair, while Du had seldom spared anyone his sword, she'd never known him to rape a woman. Not that he needed to. Even the conquered women had fought and clawed for a place in his bed. It'd sickened her, especially when his men would pit poor women against each other to fight it out and then offer up the victor to their leader as a trophy. She'd hated absolutely everything about Du and his people. Had cursed every day she'd been forced to endure his detestable company. Hated herself for the spell that had united them even more tightly than marriage. For his part, he'd ignored her and only summoned her to a human body whenever he wanted to feed on her blood for his own spells. Until the day Vine had come to her. Broken and bleeding, her sister had been near death from a separate group of barbarians who'd attacked her husband's nemeton. Terrified of losing her last family member, Marcelina had done her best to keep Vine hidden from the Aesir and, in particular, Du. To make sure none of Du's men saw her or that Du discovered her presence, lest they harm Vine, either because of her beauty or because she was Deruvian. Mara still didn't know how Du had finally met Vine. One day, Mara had been summoned away to protect a family she was bound to, and on her return, she'd found the two of them in bed. That image of him rutting with her sister was forever seared into her memory. He'd only stopped when he realized she was watching them in horror. Instead of being embarrassed, he'd given her an insolent smile. "Care to join us?" Blushing, and chiding him for his jibe at her, Vine had grabbed a fur to cover herself. "It's not what you think, Mara!" Without any remorse or modesty, Du had rolled over onto his back and propped himself on his elbows to watch them. His obscene display had caused Mara untold discomfort as she sought to glance anywhere else in the room. Though, to be honest, he'd held one of the best physiques she'd ever seen on any male. Rippling with muscles, his tawny skin could beckon even the most chaste. And he was exceptionally well endowed. Something she'd really tried her best to ignore. But it hadn't been easy. Worse? Du had known it. He'd always known how women coveted his body, and that devilish smirk on his face confirmed it as he cut a glance toward her sister. "Actually, it's exactly what she's thinking, love. I was buried to me hilt inside you when she arrived to disturb us. Damn shame she couldn't have tarried a bit longer." Vine had blushed an even a darker shade of red than Marcelina. "Why are you being so cruel as to taunt her?" Refusing to answer, he'd let out a deep sigh, then gotten up to wash himself off without dressing or covering any part of his anatomy. He was a shameless barbarian, after all. But it was only then that she'd seen the horrendous scars on his back and across his buttocks. Deep and ridged, they'd made her jaw go slack as she tried to imagine the horrendous beatings he must have endured to be marred so grievously. Vine pulled her dress over her head, then rushed to Marcelina's side. "He's not so awful, sister." As if! She knew better than what Vine proclaimed. "You weren't there. You didn't see—" Vine had cut her words off by placing her fingers over Marcelina's lips before she led her into a dark corner. "You are the one who told me that no one is beyond redemption or unworthy of forgiveness." Mara had choked on those words being thrown in her face. While she believed that where others were concerned... "He's a different beast!" Most assuredly! Those whispered words had caused him to glance at her with a sneer that had chilled her all the way to her soul. Snatching at his black robe that had been cast to the floor with careless abandon, he'd thrown it over his head, and left them to speak in private. But not before he'd given her a look so cold and malevolent that it had rattled her all the way to the marrow of her bones. "What were you thinking?" She'd scowled at Vine. "That an enemy leashed is better than one who wanders, unwatched." "Meaning?" "We have no one to protect us. You are bound to him. Forever. Since you can't leave and I have nowhere else to go, I was trying to woo said beast and tame him." Marcelina had gaped in horror at the very thought. "Are you mad? There are some beasts beyond taming. And I'd plant him firmly at the top of said list." "You don't know him." "Neither do you." Vine shrugged and stepped back. "Maybe, but he's the best chance we have at survival. You know it as well as I do." She'd rolled her eyes at Vine's naiveté. How could her sister be so stupid? So blind? And against all her protestations and rationale, Vine had pursued Dón-Dueli until he'd convinced them both that he was harmless and in love with her sister. Like Vine herself, Marcelina had bought into those lies. Though he'd never been overly affectionate toward Vine, he hadn't been cruel to her. Which for him was a miracle, as he was a bastard animal to everyone else. Everyone. Even fiercely trained, massive warriors had scuttled away like terrified rodents at his approach. But to her and Vine, at least, he'd practiced restraint. So long as Marcelina had lived in his home, he'd treated her with deference and had gutted anyone who showed her anything less than their best behavior. His protection over Vine had been even more extreme. To the point that some of his savagery still haunted her. Honestly, Mara didn't know what had finally happened to tear his marriage apart. Or why her sister had chosen to kill him. Vine had never explained herself. While Vine had been high-strung and at times overemotional, she hadn't normally been that extreme, reckless, or cruel. Of course, Du tended to bring out the very worst in all beings. And since their return to the mortal realm, Du had been even more distant and hollow than while married to her sister. Colder. Meaner. Until Cameron. In all the centuries Marcelina had known him, she'd never seen him so... Kind. And for the first time, it made her wonder what he'd been like with his sister. Could he have been someone's beloved older brother, who watched after and cared for her? If that were true, then maybe, just maybe, he wasn't the tyrannical animal she'd always thought.... Was he? * * * "I don't want to be here!" Devyl let out a tired sigh at the strident tone that left his ears figuratively bleeding. "Neither do I, Miss Jack. Believe me. But until we recover your brother and secure him, I can't allow you near the..." He paused as if biting back an obscenity. "... creature we just took custody of." "Is she one of the evil beasts who captured him?" The intensity of her tone caused him to look up from his book to see she'd stopped pacing in front of his desk to glare at him. He had to force himself not to smile at the cheeky way she postured with clenched fists as if ready to take on the world. He'd always admired courage in anyone, but especially one so tiny. "Supposing the answer was aye, what do you plan to do?" Bleed on the bitch would be the most apropos answer, as she was hardly prepared to deal with a creature of such powers and venom. "Depends on if the answer is aye or nay." He laughed in spite of himself. And the sound of it shocked him thoroughly, as it was a real, unexpected laugh. Not the feigned kind he normally practiced whenever it was socially expected of him. What the hell? Sobering to his usual gruff demeanor, he cleared his throat. "No need in you being ruffled, lass. Calm yourself and rest. Tomorrow's a bitter day." "Meaning?" He turned the page in his book, and tried not to think about the Sight he'd been born with that too often fed him coming details he'd rather not know. "'Tis nothing. We are a ship without marque, sailing through pirate waters and bearing the red jack as our only color. Trouble is forever finding us, even when we try to avoid it." Cameron hesitated at his words. A letter of marque was what some captains carried that authorized them to prey on ships and cargos from enemy nations. Essentially legal pirating. Most pirate crews carried such letters, many of them forged. Along with flags from multiple nations, just in case. The fact he didn't bother with a forgery or fake colors said he was a man of honor.... Or completely insane. "May I ask you something, Captain?" He let out a sigh that said he was put upon by her question. "If you must, Miss Jack." "How is it you came to be captain here?" He whispered something that sounded like a curse beneath his breath before he answered. "Lady Marcelina made it so." "Why?" "No doubt so that she, much like your incessant inquisition, could forever torment me." That caused one corner of her mouth to quirk up as she struggled not to smile. "I torment you?" He glanced up. "Conversation in general annoys me." "You sound like me brother. He used to threaten to sew me lips shut if I didn't shush around him." Grunting at that, he returned to reading. "So where do you intend to sleep, Captain Bane?" With a deep growl, he slammed his book shut and set it on his desk. "Apparently, in my bed, as you seem to have no interest in using it for yourself. Am thinking one of us should get some use out of it in these wee hours. Aren't you the least bit tired?" For some reason she couldn't even begin to fathom, an image of him in said bunk went through her mind. Followed by a thought so scandalous that it caused her entire face to heat up. He stood slowly. "Careful where your thoughts lead you, lass." As he headed for the door, she stopped him. "Can you hear my thoughts?" "I can read your expressions, and they lay bare everything in your mind." Heavens, he was astute and frightening. And still she dropped her gaze to his lips. She'd never kissed a man before. Had never wanted to. Until now. She didn't even know why. Bane was completely unacceptable to her. He was a beast and a terror. A man who liked to intimidate and frighten others. And yet... "What made you marry a Deruvian if you hate them so?" Devyl winced at a question that shredded what little blackened soul he had left. He didn't intend to answer. He never answered such questions, as they offended him and were no one's business. But his lips didn't listen. Like everything and everyone else in the universe, they betrayed him. "Vine was kind to me." Cameron scowled deeply at such a shocking, unexpected answer. "Kind?" "Aye, Miss Jack. When you've never been fed anything save insults, degradation, and horror, a little kindness goes a long way." And with that he left her to seek fresh air and a clear head. That was what he intended. Unfortunately, the past was a treacherous bitch who forever sought to bring him to his knees. Tonight that whore was after him with a vengeance, churning up images he'd rather see buried for eternity. Except for one. It was the only comfort he'd ever known. And it'd come to him on the night he'd murdered his parents. Or maybe "murdered" was a bit strong, given that it was self-preservation. After all, his bastard father had been trying to kill him first. And for what crime? Having the nerve to protect his sisters. Even now, he could feel the heat of the fire on his face as his sisters had cried in the shadows. While their mother's shrieks as she begged for mercy echoed against stone walls, they'd come running to his room, where he'd been trying to ignore his mother's pain. Not because he didn't care, but because the one time he'd tried to stand up for his mother as a boy, she'd punished him for it far worse than his father had. "He's my husband, boy! And your father! You don't ever raise a hand to your parents!" So while he hated to see his mother beaten, he'd learned to leave his parents alone to deal with it. Until that night. He hadn't known what the fight between his mother and father was about—it could have been anything from his father's dinner hadn't been salted properly to his mother had put her shoes in the wrong place. At least not until Edyth and Elf had burst into his room to hide. Bemused by their peculiar act, he'd scowled at them. Though none of them liked the sounds of their parents fighting, they were well accustomed to the routine familiarity of it. Like him, his sisters normally stayed in their beds and pretended to sleep through the cacophony. Yet this night, everything was different. The fact that Edyth had come into his room was strange in and of itself. Barely a year older than him, she had never thought much of her younger brother. Other than to use him as a target for her acerbic tongue and ridicule. He couldn't remember a time in his life when they'd gotten along. So for her to seek him out was a rare event indeed. Elf, on the other hand, had run to his bed and thrown herself against him to weep such horrendous wails that he'd feared for her health. "Calm yourself, Elf! Breathe and..." His voice had trailed off the instant he'd seen the marks on her young body. The heartbeat he'd seen what their father had done to her. Horror had filled him as he met Edyth's tormented gaze over her rumpled hair. "I tried to stop him, Duel." Her sobs had matched Elf's. "I never thought he'd do it to her, too." Too? That one word had hung in the air like some ghastly fiend that taunted him without mercy. Clutching Elf against him, he'd sat there stunned and cold as his fury turned into something he couldn't even begin to describe. A rage so deep and dark and foul that it'd left him with a heightened sense of calm that terrified him. "How long?" Shame darkened her gaze. "Since I was Elf's age." Edyth had sunk down in the shadows as if trying to blend in with them. "I-I-I tried to keep him from her, then I went to get Mum." "And?" "She held me in her room until he finished. Then he came for me and... they started fighting." Closing his eyes, Devyl had cursed himself for being such a stupid fool as to not realize the source of Edyth's bitchtress nature. To have never known what went on between them at night. How could he have been so incredibly blind to his sister's pain and suffering? So stupid? But no more. With a kiss to Elf's head, he'd stood with her in his arms and carried her to Edyth. "Stay here. Both of you." Edyth had clutched Elf against her trembling body—like a mother with a toddler. "You can't go out there! Ta will kill you, Duel!" "I came into this world fighting and covered in someone else's blood, Ed. I got no problem leaving it the same way. And if I must go out like that, then I plan to take the bastard with me to Caer Vandwy and hand his heart to Y Diawl meself. One way or another, I swear to the gods that he'll touch you no more!" Still cold. Still furious, he'd walked out of his room to find his father in the Great Hall. His mother sobbed off to the side while his father sat in his chair as if all were right with the world. At least until their gazes met and locked. His father had snorted derisively, then poured himself more wine. "What do you want, boy?" With a calmness he still couldn't fathom, Duel had walked to the wall, pulled down an axe, and smiled. "Your head... both of them." The stupid bloody bastard had had the nerve to laugh. And then he'd sicced his hounds upon Duel with a kill command. They'd charged him, but, too angry to care, he hadn't moved. Rather, he'd glared at the ferocious beasts and dared them to attack. "You want me? Bite me and I'll send your heads to Annwn, where you can guard for him!" Those growled words had caused the hounds to back away in confusion, then whimper and flee. Unlike his father, who lacked the hounds' good sense. Instead, Axe of the Dumnonii had risen slowly to his feet and unsheathed his long sword. "Well, well, the worthless tosser's finally found his spine." The fierce dark warrior had come at Devyl then, with the intent to lay him in his grave. But too many years of frustrated abuse, hatred, and vengeance burned inside Devyl. Within a few strokes, he'd taken the bastard's head as he'd promised he'd do. Instead of being grateful that he'd finally liberated her from his father's cruel fist, his mother had rushed him with her dirk, screaming that she'd avenge his father. A dirk she'd sunk deep into his shoulder, then yanked out and aimed at his throat. Devyl hadn't meant to kill her. He'd struggled with her in an attempt to wrestle the knife from her hand. But when she'd used her own powers against him, they'd ignited his. Too young to have full control yet, he was unable to stop the innate self-preservation that was deeply rooted in his blood. It lashed out without compassion or restriction and consumed his mother in one single fiery emotional blast. Horrified by the sight of her scattered remains lying in his father's blood, Devyl had finally lost the fury inside him. And with its passing, he began to shake. To cry. To feel. And he'd hated every moment of it. Bitter and gutting, his grief had risen inside like an unholy serpent that was feasting on his innards. Shredding and eating away every last bit of innocence he'd ever possessed. Not that he'd had all that much. His father's brutality and mother's weakness had seen to that. It devoured all his worth and happiness. Any sense he'd ever had of being decent or good. It left him shattered and bitter. Worthless and used up. With a sense of being hollow and lost. Too stunned to move, he'd still been there hours later when the servants had come in for work, only to discover the carnage that surrounded him. Since his father had been the leader of their tribe, Devyl had fully expected to be hanged for what he'd done. He'd expected no mercy whatsoever from anyone as his father's men had rushed in to check on his parents' remains. Still coated in the blood of his father, Devyl had refused to answer any question. Refused to speak at all. How could he explain it? He didn't want to tell anyone their family secrets. Didn't want to expose what had been done to his Elf or to Edyth. He refused to see his sisters shamed or harmed in any way. Their parents had wounded them enough. By the gods, their brother wouldn't harm them, too. It was his duty to protect them. Let their people damn him alone. It was a secret he would take to his grave. And as the watchmen sought to drag him from the room and into their custody for the murders, Edyth had come forward to shove them away. "There were wandering bandits who broke in during the night! Duel fought them off by himself! You can't take him for it. He's our hero! But for him and his bravery, we'd be dead now, too. He saved our lives!" Elf had backed her story. It was the only time in the whole of his life that anyone had sought to protect him and keep him safe. The only time anyone had ever stood to defend him. While he'd loved his little sister before that, he'd become even more devoted to her. And to Edyth. He would have done anything for her after that day. When she'd died of a rare fever a year later, it'd damn near destroyed him. How cruel that they had finally become close, only to have something as pathetic as a worthless cold take her life and rob him of a very special friendship. So he'd clung to his Elf after Edyth's passing even more and with a passion that had oft left her so frustrated at him that she'd spent endless hours playfully teasing him for it. You're stifling me, brother! Can I not have a moment to myself? I swear it wouldn't surprise me to find you sitting atop me one day as I do my morning business in the privy, like some great mother hen! Indeed, you're so close that I eat the food and you burp for me. Words she'd spoken with humor and never with malice. Unlike him, his Elf had never held any ill will or anger toward anyone. God, how he missed her. Don't think about it.... Because thinking about her even now, after all these centuries, still tore him apart. "Captain?" He looked over his shoulder to see Belle headed his way. "Aye, milady Morte, what can I do for you?" "Be ye aware of what it is you've taken aboard the ship, sir?" "Indeed. Why? Is she giving you trouble?" "You could say that." He arched a brow at her evasiveness. "I did say that. What sayest you?" "Well... she got a bit lippy with us." Ah, dear gods. He arched a brow as she paused in her recitation of what all "lippy" entailed. "And?" he prompted when she failed to elaborate. "Well," she repeated, "be it all right with you if Mr. Death pins her to the wall?" Devyl hesitated as several scenarios for those words went through his mind. William having his way with the beast in a corner. Or Will literally daggering the hag. Not sure which of the two would be worse for the lot of them, Devyl headed for the women's quarters, where he quickly found his quartermaster one heartbeat away from killing the bitchington. Grabbing the sword from Will's hand, he arched a brow. "Really?" William grimaced at him. "Begging your pardon, Captain. I should have asked. May I kill the worthless trollop?" "Sorry, Mr. Death. I want that particular amusement myself." Gagged by a piece of linen, Mona shrieked and struggled against the ropes William had double-knotted around her hands. Especially when Devyl turned on her, sword held at the ready. Aye, this time, he was going to gut her. Gate be damned. And no one would stop him. Just as Devyl would have killed the Deruvian, Mara appeared in the room and used her powers to dissolve his sword. His temper flaring, he glared at her. "Don't need a sword to destroy your sister." As he started to choke Mona, a massive, invisible wave knocked him away, into a wall. "Don't push me, Du. I'm not the scared little child you found that day in the Fforest Fawr. I've come a long way, and so have my powers." Growling, he faced Mara with his full demonic visage. One that caused Belle, Janice, Sancha, Valynda, and even William to pull back in fear. Even the bitchling slithered toward the shadows to hide from his wrath. "And who gave you those powers?" he growled. "Do not push me!" she repeated. He closed the distance between them so that barely an inch separated them. "Ditto." Her breathing ragged, she lifted her chin while her eyes blazed defiance and hatred. An unseen wind flared her pale hair around her slender form while she hovered above the boards of the ship that had been crafted from her body. "You're still just an animal, aren't you?" Those words cut him to the quick, but he refused to let her or anyone else know it. Insults and abuse were mother's milk to his blackened soul. They were all he'd ever known, and so what if she gave them to him? "Savage and rabid from my first breath to my last." "Then you need to leave and let me deal with this. Calmly. Without you." It took everything he had not to retaliate. She had no idea how lucky she was that he wasn't the beast she accused him of being. He curled his lip to sneer at her. "Deruvians forever, aren't you? It's why we hated the Vanir so. You were always so high and mighty in your arrogance. Thinking yourselves above the rest of us." If only she knew the real truth. "You dare lecture me on morality? On humanity? Seriously?" He let out a bitter, scoffing laugh. "Nay, lady." He sneered the word, turning it into an insult. "I would never deign to tarnish your people. None of you ever committed a single atrocity against anyone. Did you, now?" "What's that supposed to mean?" "Think about it." With those words, he stormed from the cabin to leave them to it. Let Marcelina have it. He was done seeing condemnation in her eyes. Damn her for it. Even after everything her sister had done to him... after the atrocities her Vanir people had committed against his, she still refused to acknowledge it. They were perfection, while the Aesir were feral barbarians. That's all she'd ever seen any of them as. Her blind loyalty to her people over all others galled him to the core of his being. But it hadn't begun that way. Her precious Vanir were the ones who'd started the war between them. And for what? Futtocking selfishness of the worst kind. Marcelina could deny it all she wanted. He knew the absolute truth of it all. This battle between their cultures and generations of hatred had started when his great-grandfather had made the mistake of asking the Vanir Deruvian princess Gullveig and her court to help their people after a plague Gullveig had deliberately sent to them had swept through their lands, laying waste to everyone. Man and beast. Sadly, they hadn't known the Vanir were behind the plague then. Naïve to a fault, his great-grandfather had been unable to conceive of such treachery. All he'd known was that Gullveig was a goddess of healing and her skills in that regard legendary. So Woden had swallowed all pride and appealed to her to save the life of his son Tyrin and their people. As a goddess of healing, it should have been easy for her to do so. And that was all that had mattered to the Aesir king. Not his pride. Not his crown. His love of his son and people had led Woden to make a bitter, foolish bargain. But that was the way of the Aesir. They were a communal race who believed in the good of all. One life was inconsequential when compared to the benefit of the whole. They were born a cog in a larger machine, and it was hard-wired into them to serve the good of their race. To put others before themselves in everything. Not so with the Vanir. To them, the one was always greater than the whole. Petty and vain. Better to sacrifice their entire species than see one hair on their individual head harmed. The rights of one individual were forever superior to the rights of the whole. They were selfish, through and through. And so Gullveig had agreed, but only if she married the king and was given the whole of their gold. Since his people didn't value gold over life, Woden agreed. After all, what good was gold to the dead? It was only a metal to be bartered for supplies. Too weak to smelt for weapons, it wasn't even used by his people for decoration. The Aesir had never placed any real value on it. In fact, they'd used iron for coin because it was the more valuable metal to their people. Far more important than gold. So they had turned all their gold over to the greedy goddess without hesitation. The moment Gullveig had it and was wed, she'd used her magick to poison the great king and all his heirs from his first wife. Her people had quickly moved into their lands and begun taking everything for themselves. But Gullveig hadn't known about Woden's daughter, who'd married a fey husband long before the arrival of the Vanir goddess. A daughter who had gone to Alfheim to live there among her husband's people. Determined to avenge her Aesirian family and save what remained of her people, Devyl's grandmother had returned to her father's home. There, Kara had stabbed the goddess and set fire to Gullveig in the hall of the murdered king. Not once, but thrice she'd laid the goddess down in flames. Each time, the Deruvian whore had returned to life. That had been the Aesir's first exposure to the regenerative powers of the Vanir Deruvians. Worse? Gullveig had come back stronger after every death, and on her third incarnation from the flames, she'd emerged as the goddess Heiðr—more powerful and more evil than any creature the Aesir had ever encountered before. A ten-year bloodbath had ensued as the Vanir gods had demanded vengeance against the Aesirians for the attacks on Gullveig. They'd wanted the life of Devyl's grandparents. And all hell had broken loose as a result. Yes, his people had gone more and more feral during that war. The Deruvians had forced them to it in order to survive against them and their unholy magick. The sad truth of survival was that it seldom brought out the best in anyone. Rather, it forced people to take actions that went against every moral they held and left them bankrupt and bitter. Wondering if they'd ever be whole again. Over a thousand years later, and Devyl was still as broken now as he'd been then by his own wars he'd led against the Deruvians for additional crimes. And for what? Not a damn thing, in the end. I should have stayed in hell. At least there he knew his place and had found a sick kind of comfort with his misery. Or at least he'd come to terms with it. He didn't belong in this callous world where no one could be trusted. He never had. There was nothing here for him save pain and utter misery. Everything he'd ever loved had been brutally stripped from him. Friends. Family. Devyl had no quarter of any kind. Suddenly, and as if to prove those very words, he felt a sharp, stinging pain to his side. Gasping, Devyl doubled over from the vicious ache. "Captain!" He tried to blink past the staggering agony, but even without Will and Bart, who continued to call out to him, he knew what had happened. Marcelina was wounded. Damn her for her blindness in dealing with the other Deruvian wench! With a fierce grimace, he bit back his groan and headed for the cabin where he'd left her. He ignored the men who tried to explain the events he had full knowledge of. Marcelina had reached out to Mona and the Blackthorn bitch had taken advantage of it. As was Mona's Deruvian nature. They were treacherous to the end. Why was Mara in such denial when she had to know that even better than he? His vision blurring, he found Mara on the floor with Belle standing guard over a jubilant Mona. Growling deep in his throat, he issued orders as fast as he could. "We've a hull breach! Death? Meers? Gather the men and find it! Sancha, head us toward land before we sink entirely. Get every man on the pumps!" They ran to obey him. Mona gave him a twisted smirk. "You won't make it." "You best pray we do. Otherwise your heart is the last thing I'll be feasting on." His breathing ragged, he turned to Janice. "Guard her, and if she so much as belches in your general direction, set her ass on fire and burn her to ashes." With those words spoken, he picked Mara up to carry her from the cabin toward her own chambers. But that was much easier said than done given the amount of pain he was in. Which told him how severely the ship was wounded. "How much water are we taking on?" he gasped as he struggled to carry her. Marcelina groaned as she clung to him—an action that betrayed the depths of her injuries. Otherwise she'd die afore she touched the likes of him. "I'm trying to close the gap." Tears glistened in her eyes. "Thank you, Du." "For what?" "Not rubbing my nose in this." He answered with a grimace as he kicked open the door to her room and carried her to her frilly bed that looked more like a cloud than a place of rest. With a gentleness he resented, he set her down and staggered back, intending to leave. Unfortunately, he only made it to the opposite side of the small room before his own misery drove him to his knees. Damn... it'd been a long time since anything hurt him this much. Glowering, he grimaced at her. "What hit us?" "Not sure. I told William to keep Kalder from the sea, lest it kill him. Whatever it is, it's a foul beast that has ripped me asunder." With a bitter half laugh, he met her gaze. "Well then, 'tis high time I met him and thanked him personally for this stomachache." Mara gaped as she watched Du push himself up. "You can't be serious?" Yet against all odds, he managed to stand. "He wants a fight... I'll give him one." And with that, he was gone. Mara shrieked in frustration as she called him back, knowing it was futile. Duel listened to no one. Ever. "You stubborn, stubborn fool!" What was it in him that he could never back down from a confrontation of any kind? She'd never seen anything like it. Coughing and choking, she rolled from her bed and tried to go after him. What good would it do if he got himself killed? Again. He'd take her with him to the grave. Then what would become of their crew? Of the world they were sworn to protect? Then again, what did she expect from someone who'd been born of such a violent race? All he knew was bloodshed and killing. Mayhem. Chaos. Yet she couldn't quite forget the gentleness of his touch as he'd carried her to her bed. Even while he'd been in pain, and though it must have galled him to come to her rescue after he'd warned her of Mona's treachery, his touch had been as gentle as a fairy's kiss. Just as he'd been kind to Cameron even though he'd known her origins. As much as he hated the Seraphim. As much as he hated Menyara. And why shouldn't he hate them all? He'd sold his soul to the dark forces to keep the Romans out of their lands. Had tapped forbidden power and the blackest magick to make himself king and ensure that no one could ever defeat him. He'd fought against Thorn and the Sarim for years. Had laid waste to every army they'd dared send against him. Gutted any man who'd tried to take his crown or questioned his authority in any manner. After years of living in hell with the oafish brute, Mara had been delighted when she'd learned that Menyara had combined her forces with Thorn's and planned to move against Du in an all-out attempt to overthrow him and end his bloody reign and life. She had been sure they'd finally defeat him and free her from their godforsaken bond. But that hadn't happened. Instead, Du's army, at his command, had torn them asunder. He'd scattered their forces and set them ablaze with a zeal that still caused the bile to rise in her throat whenever she thought about it, or the way he'd returned home afterward. Triumphant. Jubilant. Giddy. He'd laughed as he recounted the carnage in gory detail. Worse? He'd mocked her for the fact that she didn't share in his merriment over such raw brutality. "What's the matter, Mara? No stomach for it?" he'd asked while he drank warm, mulled red wine from the stained skull of the largest soldier he'd killed in battle. That had left her retching for days. Nay. She'd never had any stomach for the lot of it. And even less for blood and gore. Unlike him. But that being said, never once had he ever acted ignobly toward an innocent. Never slaughtered a child or raped a woman. Nor had he allowed his men to do such. If they killed a woman, they were punished harshly for it. Indeed, for all his evil ways, he wasn't one for deceit of any kind. Duel came at his enemies in the open. Well announced. And usually with a great deal of fanfare. It was virtually his only endearing quality. But now that she thought about it, he had a number of... well "good" was a stretch. Better traits? He could be extremely tolerant of others. Where many would be put off by the flamboyant and oft-eccentric ways of his crew, Duel was practically indulgent of them all, no matter how peculiar their quirks. He never said a word about Sancha's extreme language or drinking. Or Belle's pungent spells that required some rather noxious ingredients. He guarded Sallie's soul bottle as a sacred object and made sure no one harassed Kat and Simon for their unconventional relationship. Indeed, he'd even performed a marriage ceremony for them without lifting so much as an eyebrow over it. She was the only one he was openly rude to. And much of that was her own fault. She did bait him unnecessarily and without cessation. Much like a nagging spouse... Feeling a foreign twinge of guilt, she forced herself to stand, and followed after him. On the upper deck, she found Duel locked in battle with a giant squidlike monster that was rising from the water, breathing fire and trying its best to engulf them all. He and Zumari, along with William, Bart, Belle, and the rest, were throwing their own fire and tar grenades at the beast. Shooting cannons. Nothing deterred it. With fangs as large as a man, it snapped at them, and reached with its barbed tentacles, trying to flay them where they stood. Several of their crew were lying on deck, wounded, while others tended them. She used her own powers to keep the ship upright even though she could feel the lower deck taking on water. The sensation made her sluggish and sick. Tipsy. But if she gave in to the weakness, it could kill them all. That she could never allow. If Duel could find it within him to fight in the same condition, then it was the least she could do to carry on for them all, as well. But it was so hard. The rocking wasn't helping. It left her weak and disoriented. Her stomach pitched as a wave of nausea threatened to undignify her before them all. "Dammit, Mara!" Duel snarled as soon as he caught sight of her on deck. "Get below!" She shook her head. "You fight. I fight." The curse he let out rang high over the roar of battle. Impressive indeed. But not nearly as much as the sudden explosion that sent wood, water, and pieces of the beast flying over the lot of them. "What the hell!" Devyl ducked as the sea itself rained down on him. Along with a lot of blood and intestines. He turned to see another ship fast approaching on their starboard side. His gunners struggled to turn their cannons into position for it and reload. As they made ready to fire, he realized that the ship wasn't aiming at them. It'd struck its mark. Devyl grimaced as soon as he saw who it was. "Halt! 'Tis friendly." Sort of, anyway. Though a friend should be a little more circumspect than to be firing at them like this. William groaned out loud as he recognized the ship. "Santiago?" "Aye. Bugger's no doubt thinking to lend us a hand." Devyl grimaced at the slimy chunks of entrails that clung to him. "Would rather he lend me a towel, to be honest." William laughed. "Indeed." Then he sobered as he glanced around at the number of their crew who'd been wounded or "killed." It was a sight Devyl could have done without, as it took him back to a past he'd never been particularly proud of. Aye, he'd led his army through untold bloody conquests. Driven by reasons that seemed paltry now, he'd been ruthless as he tore his enemies asunder. But at least this army wouldn't stay dead. In fact, their "dead" were already rising up from where they'd fallen. Griping and moaning in colorful alacrity as they returned to physical form and pulled themselves together. Literally, in some cases. It was the one benefit they had in serving Thorn. The only way the Deadmen could die again was for something to obliterate their bodies or souls. So long as their flesh remained intact, as well as their souls, they would reanimate. Fire, axes, and acid, however, could still ruin their days. Even a vat of piranha could prove a rather grisly end for them. Hmmm... that gave him a thought for their guest. He turned toward Bart. "Did we lose anyone, Mr. Meers?" "Don't think so, Captain." He cast an eye toward one of their crew who was slowly healing from death. "Least not permanently." Devyl continued to wipe at his face and neck. "Good. Send over some of our best rum to Santiago, with my compliments." "Aye, aye, Captain." With a determined stride, he headed for William. "Death? Get to our Miss Jack and keep an eye on her. Make sure she stays put and safe. Continue heading us toward land to patch our lady. Keep a weather eye for more attackers." Bart drew up short at those words. "You think there are more?" "I know it." And with that, he continued on to return belowdecks so that he could make sure Belle hadn't been injured in the fighting. If she had... He'd be bathing these guts off his flesh over a Blackthorn bonfire. As soon as he entered the small cabin room and Mona saw the expression on his face, she shrank back in terror. And well she should, for he was through playing her games. Worse, he was in too much pain for them. Bile rose into his throat as he seized her wrist and yanked her forward. "Do you know what my people did with zraif?" He used the ancient name they'd given the Blackthorns. She paled considerably. "Nay." An insidious smile curled his lips. "'Tis said sulphur runs through you. Powerful magick is in the root of your hearts and bones. Bones we'd grind into blood potions to protect us during war and for healing any wounds we might incur. Potions we used to commune with our darker gods when we summoned them for wisdom and insight. Or make blood offerings to Mórrígan and Aeron before battle. But the most prized parts?" She gulped audibly. "W-w-what?" "Your hearts we'd devour for spells and eyes we'd eat for visions." "You're a monster!" He laughed at her. "You've no idea. Now, you will tell me where that gate resides or I will begin carving off pieces of your anatomy and adding decoration for Rosie's chest plate." Her blood turned black in her veins as his words struck their mark. It ran down her pale skin, forming a road map over her body, marbling over the alabaster. "I told you I would give it to you." "And then we were attacked." "I-I had nothing to do with that." Devyl scoffed. "I don't believe you." She tried to pull away, but he held her fast. Cringing, she put her arm up, over her face. "Why would I betray you?" "Because you're an idiot." "Duel! Let her go!" He ignored Mara as she came into the room with them. "Answer me, Mona, or else I will begin carving you into all manner of objects for my use." "Duel!" He glared at Mara over his shoulder. "I'm not a dog to heel at your command!" "Yet I am your commander, am I not?" His eyes glowed an instant before he let out a curse so foul even Thorn would have blushed had he heard it. Reluctantly, he released Mona and stepped back, but not before he passed a sullen grimace to Mara that would have made a petulant toddler proud. Disregarding his distemper, she stepped forward to deal with their betrayer. She put herself between Mona and Devyl, and it took everything he had not to cut off both their heads. If not for the fact it would only make them stronger, he would have given in to the impulse. With a calmness he couldn't fathom, Mara took a deep breath. "Vine sent you here, didn't she?" "I don't know what you're talking about." "Very well." Mara reached out then and shoved her hand straight into Mona's chest. Devyl's jaw dropped as she wrested the bitch's heart from her bosom and yanked it out, then used her powers to incinerate Mona before she could hit the floor. Her expression one of total serenity, she turned to face him and held the bloody heart toward him. "Use it to heal us as fast as possible. I'm sure others are on their way to attack us." Dumbfounded by an act that was completely incongruous to her nature, he stared at her as if seeing her for the first time. "I can't believe you just did that." Still her features betrayed nothing. "In all the centuries we've been together, you've never bothered to learn the most basic thing about me. Never had a single conversation with me where you asked about my thoughts on any matter. And you know nothing of my people. When Vine killed you, she knew I would die, too. Did that thought never occur to you?" Nay, it had not. "In my darker hours, I've wondered which of us was the real target of her wrath. And why she did what she did. I've always assumed it was you, Du, because it was more comforting to do so. Yet what if it wasn't? Either way, she is our enemy now. Both of ours. Mona has proven that without a doubt. You would have left Mona alive, not knowing that Vine was able to use her as a living conduit to us. A doorway better kept closed. And now I am weak. My powers are fading. I can't heal myself. Therefore, I need you to do it for me." He caught her as she passed out. Cradling her against his chest, he took care not to crush Mona's heart or harm Mara. As gently as he could, he carried her to her cabin and placed her on her bed. Then he set about preparing the potion that would restore her strength and heal her injuries. All the while trying to come to terms with a side of her he'd never suspected existed. Honestly? He liked it. Black looked good on her. It was why he'd do anything to heal her. Even use the darkest kind of magick he'd learned from his father. The kind his Druidic forefathers had specialized in. Unlike the rest of their breed, the Dumnonii branch of the Aesir hadn't been just counselors, teachers, and priests, they'd been warriors, too. Protectors imbued with a fierce sense of noblesse oblige to safeguard the fledgling humans from their brethren who'd sought to harm them. Descended from the gods themselves, the Dumnonii had been the ones who'd established the Druidic orders and taught them the ways of magick and given them their wisdom and ability to commune with the gods. They had brought order to the world of man. It was why their home realm had been termed Asgard and not Asaheim. Why the world of man was known as Myddangeard or Mydgard and not Mydanheim. This wasn't just the home realm of mankind or Asgard the home of the Aesir. These two realms were where they'd brought order and discipline to the chaos of it all. They were wards set up to protect humanity. When the primal gods and their creations had been at each other's throats and were tearing the universe apart, this was where his ancestors had drawn the battle lines and put the boundaries that protected humans from their armies that would have destroyed them. From their monstrous creations that would have preyed on the humans without mercy. Out of all the nine known and established realms, only these two worlds bore the protective "gard" suffixes that designated them as places of human refuge. Places where order and discipline reigned supreme over animalistic, primal urges. The rest were the home realms of horrific preternatural predators who made feasts and war on humanity. Realms where the gods and others lived and ran rampant with unchecked powers. Home dimensions that existed behind carefully crafted veils that shielded them from human knowledge and sight. Alfheim. Myrkheim. Jotunheim. Niflheim. Muspelheim. Helheim. Even Mara's precious Vanaheim, where her Vasir had descended from. They were all the realms of some of the most vicious creatures ever spawned by the universe. Creatures who cared nothing for humanity, who only thought of themselves and what they wanted. Creatures who saw humans as prey or tools to be used and then discarded. Creatures such as Vine. Creatures like me. Devyl winced at a truth he wanted to deny and couldn't. He hated that part of his mother's blood that beat inside him. He always had. But no matter how much he tried to fight it, he couldn't deny that it was there. That selfish part that was forever tainted by a union that should never have been. It was what had made his father so weak and hate-filled in his latter years. Had Axe been an honorable Aesir, dedicated to their cause, he wouldn't have been the monster Devyl had been forced to kill that night in their hall. I am a beast. Like father, like son. Like mother, like son. He would never be able to escape it. But at least he could stop Vine from destroying the world. That was one promise he would keep, no matter what. And sooner or later, he'd have to be put down again. Mara had been right about that. It was why he didn't expect to survive this quest. Didn't expect Thorn to free him. Not for one heartbeat. He had no delusions there whatsoever. His kind didn't belong in this world. They were the worst sort of predators. Mara knew it as well as he did. He was barely leashed on his best day. His ancestral fury simmered just below the surface, ever a pot on a steady roiling boil that just waited to overflow the edges of its confines. All it took was one blink, and a disaster would ensue that didn't care whose hand it scalded. No conscience. No constraint. Nothing mattered except that he destroy whatever was nearest him, consequences be damned. Aye, that be he. And his explosion was coming. He could feel it deep within. His Sight was ever unerring. His mother's one gift to her son, besides the back of her hand. Dera had been an exceptionally gifted sorceress in that regard. 'Twas what had led his father to her. Why Axe had wanted to bind their bloodlines together and had sought the treaty with her tribe. Too bad she'd failed to see what a scabbing bastard his father was. Or her own fate at the hands of the worthless son she'd birthed for him. Don't think about it. The past was a course that had been cast and set. Cruelty laid in by the gods to torture those who survived it. He needed all his resources and attention on the future. That was still in motion and changeable. While he'd been unable to save his Elf and his people, he had a chance to help those on this ship. To help the Seraph and his sister. His own soul was blackened and unworthy of redemption, but theirs were not. They were good and decent beings who'd lost their way. With a little prodding, they could go on and find the right path again. That was what Thorn had seen in them. Hope. Redemption. Core goodness. And as a commander, Devyl understood that strategy. To win, certain sacrifices had to be made for the good of all. He was the pawn that would be leveraged so that they could live on. An acceptable loss for all involved. Perhaps even a relief to them. And as he cast the healing spell for Mara, he realized that she shouldn't be part of any of this. She should never have been. His selfish wrath had snared her and brought her into a war that was never hers to fight. "I'm sorry, Mara," he whispered for the first time, as the guilt of his actions against her choked him. If only he could find some way to unbind their destinies and free her, too. She deserved to have a life of her own. One that didn't involve his surly, unreasonable ass. She would have made someone a fine mother. An incredible mate to stand by the side of her husband. Any man would have been lucky to call her his. He alone had robbed her of that. Disgusted by his own actions, he brushed his thumb over her gentle brow. She was so incredibly beautiful. But then, she'd always been that way to him. And while in the past he'd often seen her as an annoying vexation, as an enemy to be hated, today, he saw her for what she really was.... His innocent victim. And he hated himself all the more. "I will make this up to you." Words spoken so easily. As all vows were. The trick was in the fulfillment of them. The devil in the details. But then, he wasn't called Devyl Bane without a reason. He picked her delicate hand up and rubbed her limp fingers against his lips. Closing his eyes, he tried his best to access his Sight and see the future. Like everything else in his life, it failed him utterly. It shouldn't surprise him. He'd never been able to depend on anything when he needed it. His own horse had once thrown him in battle. His sword had broken at the worst possible time. My own wife cut my throat. Sighing, he placed a kiss to Mara's palm and tucked her hand beneath her covers. His side still ached, but the pain had lessened, letting him know that the spell had begun to work. What a futtocking bad day this had been. But then he'd known going in it wasn't going to be a boring one. Dawn would be breaking soon. He had a fledgling Seraph on board, along with a Dark-Huntress who couldn't be in daylight. One massive hole in the side of his ship. A crew of human pirates trailing them who were being pursued by an infamous pirate hunter who wanted a piece of them all. A motley band of dead lunatics at his command and the bitch of all time out to send him back to hell. "It's good to be the living dead," he said with a bitter laugh. But then he'd never been one to shirk from a challenge of any kind. He was a surly bugger that way. And honestly? He was looking forward to the fight. Staring up at the heavens, he smirked. "Bring it, bitches. With both fists. You want a piece of me? I'm ready for you." Because they'd never gotten the best of him. Even after they'd killed him, he'd still found a way to strike back from the grave. One thing about the Devyl, he came with the heat of hell behind him and packing an army of demons in his wake. And if you knocked on his door for a fight, then you better be prepared for what you were asking. It was a new day and the Devyl was here to get his due. Mara awoke to the warmth of bright sunshine on her face and the welcomed scent of fresh salt water. Seagulls screeched from outside, along with the sounds of raucous laughter and jovial music. For a moment, she forgot where she was and thought herself a girl again. It felt and smelled just like the seaside town where she'd been born. Where she'd frolicked with her sisters in the nemeton. But that happiness inside her heart didn't last, because she knew this wasn't ancient Cornwall. And those weren't her people out there. Then again... Perhaps they were. At least they were the closest thing she had to a family now. The thought lightened her spirit a bit, but it didn't return the joy to her heart. Not really. Because it wasn't the same. She hadn't felt that raw, unmitigated happiness of homecoming in so long that she could barely remember the taste of it. The sensation of that long-forgotten friend. All she recalled was loneliness. Isolation. Desolation. An unending sense of despair, and unquenchable longing for family that she'd once known. Du had robbed her of so much. Not just her safety and normality, he'd taken away all semblance of belonging to a community. His people had been so incredibly violent and callous. Animals who wore itchy wool and lived in spartan hovels. Warriors more at home on a battlefield than at a feast. Their belief had been that you were judged more on how you died than on how you lived. And warriors who died in the midst of bloody battle were rewarded far greater than those who'd lived long, honorable lives and died peacefully in their sleep, surrounded by family. And that had never been the belief of her race. She shuddered at her memories of having been forced into Duel's world of violence and mayhem. They had never gotten along. Yet for reasons unknown, he'd hesitated to kill her that day he'd come to her adult nemeton. She still didn't know why. Any more than she understood why her sister had killed him. Nothing made sense in this world. But at least she appeared to be healed now. Grateful that Duel had kept his word, she pushed herself up and went to see where they were. As she reached the upper deck, Mara expected them to still be at sea. Instead, they were docked on an island, and she'd slept through most of the day. The sun hung low in the sky, casting shadows across the palms and greenery, while fishermen, merchants, sailors, and those inclined to less than legal means of support scurried about their business on the docks. But the most curious of all had been left aboard her own ship, while the others appeared to have taken a short liberty ashore. Mara scowled at the two inseparable humans who were working on swabbing the deck. Though to be honest, they were far more engrossed in swapping insults than completing their assigned task. Jake Devereaux and Blake Landrey. Rugged and tough, they were opposite in every way. One tall, the other short. One plump, the other emaciated. One fair and the other darker than sin. Yet they were best mates and forever fighting over every little thing. She'd never seen anything quite like them. "Would you stop with the shifting the bucket while I be mopping, Jake? What's wrong with you, man?" "Me? Ye be the idiot what's moving it!" Hinder Desai, who'd also been left behind to referee the two—lucky him for that punishment—let out an exasperated sigh as he raked his hand across his face and met Mara's gaze. "Can I be killing them, mum? You think the captain would notice it?" She laughed at his dire tone. "Probably. Where are we, Mr. Desai?" He wiped at the sweat on his forehead, then pushed back his black hair before he answered. "Tortuga. We pulled in about two hours ago to make repairs. How are you feeling, mum?" "Much better. Thank you." "Good. Do you need me to fetch anyone for you?" She considered it. "Are most of the crew on board or on shore?" "Shore, mum." As she figured, then. "Thank you, Mr. Desai." "Pleasure, mum." She wandered away as she considered his disclosure. It wasn't like Du to clear the ship completely. What could he have been thinking? Lost in thought, she collided with Kalder, who came out of nowhere to catch her against his lean, hard body. She gasped in startled alarm. "You all right?" he asked quickly as he righted her. "Aye. Sorry. I didn't see you there." "It's all good. Captain told me to stay behind and keep an eye on you. Not get in your way. Least I accomplished half my mission." She laughed. "Where is he?" "Chasing demons." Her chest tightened. "Was he fit for it?" "Didn't think it my place to question him, as I didn't want my throat handed to me." She bit back a curse. "Where did he go?" "That way." He pointed toward the gangway. She gave him a droll, irritated glare at the obvious answer, since that was the only way to leave the ship and it gave her no clue as to which way Duel had traveled once he'd reached shore. "Really?" He shrugged teasingly. "You know if the captain dies, Mr. Dupree, I go with him to the grave." "That would really be a bad day for those of us standing on the ship. Especially if we're out to sea when it happens." Screwing up his face, he scratched at his neck. "Except for me, of course. Wouldn't matter, as I breathe water. But I'd sure feel bad for the rest." "Aye. 'Twould be bad for them, indeed." "Shall we go find them, then?" She wrinkled her nose. "Let's." Clearing his throat, he allowed her to lead the way. Mara wasn't sure where to start. Tortuga wasn't the most savory of places. Rather, it was a favored haunt of the derelicts of humanity and otherworldly beings who preyed on those sordid creatures. If ever someone sought a reason as to why a zombie apocalypse should be allowed and why humanity should root for their enemies to win, this place gave them cause for it. She pressed her hand to her nose and sought to breathe through her mouth so as not to gag on the unholy stench of it all. How anyone could stand to live here, she couldn't imagine. Yet there were many who deemed this hellhole some kind of desired paradise. Jack Rackham. Anne Bonny. Blackbeard. Jean-Luc St. Noir. Even Rafael Santiago was known to frequent these shores with giddy delight. They were all mad, if you asked her. But as they searched the taverns, Mara and Kalder found no sign of Du. Only a number of their crew embroiled in things she'd have rather remained ignorant of. Especially when she found Bart in a full-on orgy with not one, or two, but three buxom maids. While the man's dexterity and prowess impressed Kalder, it left her a bit piqued and embarrassed. And Bart seemed flustered as he scrambled for his pants. "Well, then..." Mara paused outside in the hallway of the brothel as they left Bart in the room to finish with his doxies. "I think we've run the course of the stews on the island." "Aye to that." And she was honestly grateful that they'd found no sign of Du in any of them. More grateful than she'd ever admit to out loud. But there had been no sign of Belle, William, Cameron, or Du anywhere at all. It was as if they'd vanished into thin air. She couldn't imagine where they might be. "Any idea where to look for our missing members?" "Your guess is as good as mine, mum." And her guess was worthless. Although... She felt a peculiar pull. The kind she hadn't felt in a long time. Unsure about it, she allowed it to guide her down the stairs and back to the street, through the filthy town where she saw nothing redeeming about the place. Only absolute misery lived here. Along with the pox, neglected children, women in need of stern morals, men in need of lectures and decent role models, and poultry possessing some kind of feather-molting plague that ailed them. Even the cats and dogs seemed to have questionable virtues. She wandered aimlessly, wishing she were anywhere else. Until she reached the outer edges of the soiled, brightly painted buildings. Here, there was a pristine little white church. Well kept and inviting, with long, opened hurricane shutters. Yet by its isolated and lonely condition, it was obvious no one in this godforsaken place sought refuge for their immortal souls. Better-kept chickens ran freely around the building, along with three stray cows that grazed in the yard and several mud-covered pigs. Dried-out palm trees twisted around the building like skeletal guardians. It was strangely eerie. Yet it beckoned her closer. She had no idea why. Until she entered the building and stopped dead in her tracks at the absolute last thing she'd ever expected to find. Kalder was so stunned he actually slammed into her back. Gaping, she blinked, then blinked again, unable to trust her own eyesight as she stared in total stupefaction at what was in front of her. Du sat on the rear porch with a little girl in his lap, surrounded by a herd of children, reading a collection of Aesop's Fables to them. Nay, not just reading to them, but reenacting the stories to the children while Belle made poppets for the girls and William carved soldiers for the boys. Cameron was helping some of the children dress their toys with spare rags from a box on the floor. Well, I'll be... Du looked up and caught her gaping stare. The little girl in his lap pulled her thumb from her lips and scowled at Mara before she leaned back to stare up at Duel. "Is she an angel, Uncle Dubu?" "Nay, Lizzy. She's another member of our ship. That be your aunt Mara." "Oh. She looks just like them bootiful angels Father Jeffrey talks about." He didn't comment on that. Rather, he took a deep breath and closed his book. Then he gave a light hug to the girl in his lap. "Well, children, it appears I should be going." They let out a loud sound of communal disappointment. "Don't let me disturb you," Mara hastened to assure them. "It's all right. Their dinnertime approaches." "Will you come again?" A young boy rose from beside the chair to pull at Du's arm. Du brushed tenderly at the boy's hair and smiled. "Of course, Robby. You know you're my only reason for coming here." The boy threw himself against Du with a giddy yelp and hugged him before he rushed off. Du stood with the girl in his arms and carried her to an old priest who'd come forward from a side door that had been left ajar. She reluctantly allowed the older man to take her from Du's arms while Belle and the others finished up their tasks. The priest, who must be Father Jeffrey, thanked Du for his reading and promised the girl that Du would come again, as was apparently his habit. Kalder moved to help Cameron while Mara went to retrieve the book from where Du had left it in the whitewashed chair. It was one she recognized from Du's private collection he kept in his cabin on board the ship. Now that she thought about it, he'd always been strangely studious... as far back as she could recall. There had never been a night he didn't read at least an hour before going to sleep or a morning that didn't begin with an hour of quiet study time. Even before Vine had joined them, he used to travel to monasteries to barter for books. Ofttimes they'd rebuffed him entirely for his pagan ways, or tried to convert him before allowing him to look through their collections. Several times he'd almost been killed by the Romans as he sought scrolls from them. Yet it'd never deterred him from seeking their knowledge. He'd even haunted the Cornish docks where foreign merchants would come to trade, asking if they had any manuscripts or scrolls he could purchase. It was as if knowledge and books were as much nourishment to him as food. Suddenly, his shadow fell over her. Looking up, she caught the haunted ghosts that resided deep inside his soul, and for the first time, she was curious about them. Curious about him. "What made you love the written word so?" "My grandfather. He always said that education is an ornament in prosperity and a refuge during adversity. And that a learned mind is the only wealth worth hoarding, as it is the sole treasure that can never be stolen." "Yet you were a ruthless barbarian?" "Even a scholar has to eat." She glanced back to where the children were smiling and playing. "How is it that in all the years we've been together I missed seeing this more tender side of you?" He shrugged nonchalantly. "People make their own realities. They paint the truth as they want it to be, regardless of fact. For those who want to believe, no proof is ever required. For those who refuse to believe, no proof is ever enough. And so you see me as nothing more than the monster you first met. I can never be anything else in your eyes. It's a fact I've long accepted." He was a lot wiser than she'd ever given him credit for. And yet she shouldn't be surprised. Not really. It took more than sheer strength to win the wars he'd fought. He had been cunning in the face of far greater numbers. His shrewdness had been remarked upon and admired by his enemies and allies every bit as much as his stamina and sword skills. Nay, he'd never really been the mindless animal she'd accused him of being. However, this was a role that she'd never seen him in. Doting and kind. And it was one that did the strangest things to her breathing. Made her feel a peculiar kind of weepiness she'd never known before. "How long have you been coming here?" "Since Thorn freed us and Rafe told me it existed. His mother taught here. This orphanage and church were her pet charity." He jerked his chin toward the door. "It's why it's named St. Rafael's. His father built and donated it for his mother, and she named it for her son... with the church's blessing." "And you volunteer time here?" "He gives a lot more than that." Father Jeffrey came forward with a small stack of papers for Du. "The children wanted me to make sure I handed you their thank-you letters, Captain. With what you and Captain Cross donated, we should have the girls' dormitory finished by winter." "Glad to help." He took the letters and inclined his head to Mara. "Father Jeffrey, may I present Lady Marcelina?" "My lady, it's an honor." "The honor's mine, Father." With a quick bow, he cleared his throat. "Now, if you'll excuse me, I'd best be seeing about that dinner. The wee ones get a mite frisky if they're not fed on time." Du smirked. "Believe me, I understand. The big ones are much the same." Laughing, the father left them. Mara scowled at Du. "Why do you always do that?" "Do what?" "Introduce me as a lady?" "Would you rather I introduce you as a trollop?" She rolled her eyes. "Nay, but you know I'm not a lady." "And you're not exactly common, either." Crossing her arms over her chest, she narrowed her gaze on him. "You're avoiding the answer, Dón-Dueli." Devyl paused to let out a long, tired breath as he considered a complicated response. "What do you want me to say, Mara? I'm a bastard beast who plucked you from your forest and your species. I know full well what you really are, and therefore I refuse to see you treated as anything less." "And what am I?" "A goddess." Mara's jaw dropped as he walked nonchalantly past her after lobbing a cannonball at her. Had that been a compliment? From the evil Dón-Dueli? Unable to believe it, she watched as he went to help Belle and Cameron gather their things to return to the ship. "Are you the captain's pretty lady?" She turned at the high-pitched voice to see a beautiful blond-haired girl behind her. "Nay, child. I'm just a friend to him." "Oh. But he seems to like you a great deal." "You think so?" "Aye." The girl smiled as she rocked back and forth on her feet. "You're very beautiful, my lady." "Thank you, child." The girl twisted her finger in her hair as she glanced over to the others. "Might I ask a favor of you?" "Of course." "I lost my poppet in the woods outside. Would you please help me find her?" "Sure." Smiling, the girl led her toward the door. * * * A peculiar chill went down Devyl's spine as he stopped to look about the room for Mara. She was nowhere to be seen. "Where's Mara?" Belle paused to glance around the church. "She was just here." His gaze went to Cameron as a streak of white appeared in her chestnut hair. Even though Thorn had yet to return her medallion, her blood was reacting to the same thing he felt in his bones. There was something here that didn't belong in this realm. A douen. Shite... "Fan out and find her. Belle, keep an eye on our Miss Jack." "Aye, Captain." While William, Kalder, and Belle began to search, he took a moment to warn the priest to secure the children within the confines of the church. If it was a douen, they were bad to go after the souls of the innocent, and children in particular. No doubt that was what had brought the demon here originally. They would normally find any child they could and lead him or her off so that they could either possess them or kill them. Wary, he made his way into the underbrush to search. He knew better than to call out for Mara, as that would strengthen the demon's power over her. Damn them. They were crafty beasts. Some of the most dangerous. They preyed on people's kindness. Preyed on their sympathy. And Mara held far too much of both, in spite of her Deruvian blood. Little wonder the douen had found her. On this island, compassion was in short supply. Hers would have stood out like a beacon to draw the demon straight to her kind heart. "Come on, you bugger." He was thirsty and in need of nourishment. It'd been a long time since he made a meal off something as powerful as a douen. It'd do his own powers good to feast on this bastard's heart. Provided it didn't kill Mara first and end him in the process. Where would it have taken her? Not like it could kill her in the open. Or maybe it could. These bastards were more brazen than most. It was what made them so dangerous. Devyl went deeper into the thicket, where the overgrowth was so dense it was hard to see much. Even daylight. Suddenly, he heard a rustle near him. Turning, he summoned philosopher's fire into his fist. And moved in for the attack. "Halt!" He barely caught the release before he unleashed the flames over the newcomers. "Dammit, Alabama! Rafe! You almost lost your heads! What are you doing here?" "Kalder said our lady had been taken. We're here to help you hunt." Alabama was one of Devyl's gunners. A large, beefy member of their crew, he'd belonged to the Choctaw nation before his death and recruitment to the Hellchasers by Thorn. Like Rosie, he wore feathers braided into his long, black hair, and a bone and beaded choker. "I take it you haven't found her?" "Nay. Can you track them?" Alabama shook his head. Devyl cursed. Out of the three of them, someone should have been able to pick up something. For them to have nothing at all... Then he felt it. "This way!" He ran through the brush as fast as he could. Birds scattered at his reckless pace. At the end of the path, the trees broke to a clearing. And not just any clearing—there appeared to be a hole in the very earth. One that dropped straight down to what seemed to be hell itself. Devyl barely caught himself before he fell into it. "What the devil is that?" Alabama breathed. "Eye of Mama D'Leau." Rafe crossed himself as the hole began to quickly fill with bubbling water. Alabama scowled. "Who and what?" "She's a goddess," Devyl explained. "She protects these lands and people. And in particular the sea. You cross her and she's capable of all manner of evil." He glanced to Rafe. "Can you get her to help us?" "I can try." Rafe rubbed his hand gently against his necklace that his mother had made for him. "Mama! I implore your kindness and offer you my faithful heart and loyalty. My mother taught me to respect you and Papa Bois, and all your creatures of the land and sea. Now an evil jumbie—a douen—has taken a friend. Will you please help me and my friends find her? I implore you, my lady, in all grateful humility." Biting his lip, he waited for a full minute as the water swirled more and churned angrily about, threatening to spill over the banks of the hole. Then it went perfectly still. Not even a single ripple. It was as if the whole thing had frozen over. Rafe sighed regretfully. "She'd probably respond better to Belle." That was the theory until a bright red mist blew up from the water. Shimmering and dancing, it formed the likeness of a beautiful African sea goddess. Her eyes were made of Tahitian pearls and her lips the color of vibrant coral. She smiled at Rafe. "Son of Masika, you have been faithful. Let my light guide your way." She opened her hand and breathed across her palm. The moment she did so, a small ball of bloodred light appeared. Like a beautiful firefly, it bounced and hovered. Mama D'Leau faded back into the waters and vanished into the waves. Waves that evaporated until nothing remained but the giant hole in the ground. The light quickly headed for the forest. Devyl and his companions ran after it. Unlike them, the tiny light had no trouble whatsoever locating the douen. The problem was? It wasn't alone. In fact, it had spawned well. Alabama cursed as he saw the large circle of demons that surrounded Mara. Rafe gulped audibly. And Devyl smiled at the sight. He'd be feasting well tonight. Or dying painfully. Either way, he'd be free of Thorn. Marcelina could neither move nor breathe as the stench of sulphur invaded every part of her being. It felt as if the demons around her were pulling out her life force, molecule by molecule. As if they were draining her powers with excruciating slowness to cause as much pain as they could. They laughed while they did it. Unable to protect herself, she couldn't even cry out for help. Never had she been so helpless. Worse? She still didn't know how she'd gotten into this position. One moment she'd been walking with what she thought was a small child, looking for a doll, and the next— She'd been slammed to the ground by an unseen force. Then bound in a vortex and held up for them to feast upon. How could they do this to her? She didn't understand it. She was more powerful than this. No one, other than Du, had ever bested her in anything. Yet they'd tricked her with nary an effort. She still reeled from the ease with which they'd worked their magick on her. Suddenly, she heard them screaming. Heard the sound of their agony. "Mara?" Tears welled in her eyes as she heard Du's deep, resonant voice nearby. Never had his ancient accent been so welcome to her ears. Or at all, for that matter. Even more relief flooded her as she felt his grip on the ropes that held her bound. For the first time ever, she was grateful he was here. Grateful to feel his strong grip on her hands. With a fierce grimace, he tore her bindings away and scooped her up into his arms. Sobbing in relief, she clung to him and buried her face against his neck. The scent of his skin and the hardness of his body anchored her and reassured her that she was finally safe and that no one could harm her. A beast he might be, but he would always keep her safe. That much she knew beyond doubt. If not for her own sanity, then to at least protect his own life. He was her beast, and never had she been more grateful for it. Devyl hesitated at Mara's embrace. At the warmth of her breath on his skin as she clung to him. Never once had she touched him so intimately. She sank her hand into his hair and fisted it there to hold him as if he were sacred. As if she were desperate to keep him close. "Thank you," she breathed against his ear, causing chills to rise up along his arms and back. And other things to rise he was best to not think upon. He gave her a bashful grin. "You've got to quit falling into such messes, my lady. One day I might not find you and then what would happen to us?" She laughed nervously. "Perhaps you should teach me to use a sword, then?" He arched a brow at her teasing tone and knew better than what she suggested. "A Deruvian swordmaiden?" "Why not? You're a Druid warrior." She had a point. It would be no more unlikely or out of character than his own past. "Perhaps I shall teach you, then." He set her down by Rafael and Alabama. "Would you mind escorting her back to the ship while I finish this?" She hesitated at his tone. "Finish what?" "I'm not sure you want to know my answer, given how they need to be dispatched, lest they return to prey on more hapless victims. And since their primary targets would normally be the children of Rafe's orphanage..." She placed her hand on his arm. "Do whatever you must." And with that, she headed back toward the docks with Alabama, leaving him to stand in total stupefaction after her departure. Rafe gave him a knowing grin. "You're gaping, Devyl. And, no offense, it's scaring me." Indeed. He was flat-out floored by her words. Baffled beyond rational thought, he set about destroying the demons' remains while Rafe left to join the others. Yet he couldn't quite get the strangeness of the day from his mind. What had caused Mara to change so drastically where he was concerned? To touch him when she normally couldn't look at him without sneering. Dare he even hope that... Don't think it. You know better. She hated him. Nothing had changed. It never would. Ever since Thorn had brought them back, she'd been as frigid and vicious to him as always. He was everything Mara despised. Everything she found repellent in the world. Meanwhile, she was the epitome of beauty and grace to him, even though he did his best to deny and extinguish all untoward thoughts. A light that shined so brightly he didn't dare look at her for fear of going blind from the intensity of her innocent purity. Never had he met her equal in character or kindness. If only she'd have shown some to him. Instead, they had fought worse than his parents. Any time she came into his presence, it ended in a vicious verbal altercation that left him wanting to strangle her. Left him one heartbeat away from the violence he deplored as much as she did. Nay, there was nothing between them except centuries of hostile regret and bitter words. "Duel?" He froze as he moved toward one of the decapitated demons. Awake and alert, it stared up at him with eyes that were the same color and form as his ex-wife's. He smirked at it. "Well, well... the empress of all bitches finally speaks. How are you, Vine?" She hissed at him. "As if you don't already know. But have no fear, Duel. I will get out of this hole where you cast me." He gave her a tolerant smile. "Tell me where you are, love, and I will come get you. Open the door myself and let you out." She released an evil, seductive laugh. "You'd like that, wouldn't you?" More than she'd ever know. Thoughts of their reunion were the only thing that kept him going. "You should have kept fighting when I told you to, you worthless bastard. But no... you wanted peace. Tell me, how does it taste?" He tossed another demon onto the fire. "Wouldn't know, since you deprived me of it." "You promised me the world!" "And you promised me your heart. Guess we both lied." He reached for another head to add it to the pile where he'd already placed the others. "Any final words?" "Watch your back, Duel. I won't lose again." "Neither will I. Beat to quarters, love. Be coming for you, dead running. Above board." He tossed the head in and watched the flames consume it as he tried not to let her words get to him. It was, after all, what she wanted. Mental warfare was how she played, and he knew it well. Besides, she couldn't possibly have a spy among his crew. No one would be so stupid. They were too afraid of him for that, and well they should be. One thing he'd learned from his father, an iron fist went a long way in limiting treachery. Betrayal was never served from the hand of an enemy. It was a blow that by its very nature came from the fist of a friend or loved one. Hence his current stint in this lesser perdition known to his people as Myddangeard and his sentence in the greater inferno Christians called hell. And for what? Not giving a large enough shit about himself and his own needs. Rather, he'd been damned for trying to save his people. For his crimes in attempting to drive the Roman plague from their lands and for keeping the dark fey tribes from overrunning them. Marcelina was right. He'd been a brutal, bloody warlord after the death of his sister. One who'd sold his soul to keep his clan safe from all who wanted them enslaved or eradicated. It'd seemed a fair enough trade at the time. There had been nothing and no one else for him to live for. He'd lost all hope. All sense of any kind of purpose or desire. His own existence had meant absolutely nothing to him in those bleak days. Because of the brutality of Elf's death, he'd gone to war with the world and hadn't cared about anything, other than making sure no other woman or child under his protection fell victim to a similar fate. In truth, he'd wanted death to come and spare him the agony of living. But he'd been too good at fighting to go down in battle. Too contentious and spiteful to die to a lesser swordsman. They'd taken everything else from him. He wasn't about to let them take his reputation, too. Nay, by the gods, he wouldn't fall to a lesser barbarian. If he was going to perish from this earth, it would only be to a greater bastard than he. At least that was what he'd thought back in the day.... Devyl blinked as the heat and flames of the pyre in front of him took his mind back to that one moment so long ago in Iron Age Tintagel when he'd stupidly slit his own throat and not known it. Unlike his parents', his death hadn't come so swiftly from his own stupidity. Oh no... Once set in motion, it'd taken Vine a bit longer to find the courage to end him. But she would never have done it had he not given her the motivation. "What do you mean you're negotiating peace with those mindless sheep?" Still covered in the blood of the boys he'd slain in battle, Devyl had set his dented helm on the table and reached for the goblet of mead Vine had been drinking upon his arrival. "You heard me. I'm done with this, wife. 'Tis time we let peace reign in our fields for a while. Our borders are secure. The Romans have retreated. I've been at war and in battle since before I first grew whiskers on my cheeks. No more." Draining the cup, he poured more and locked gazes with her. Damn, she was ever a great beauty. With hair as red as her fiery temper and curves that men dreamed about losing themselves in, she never failed to turn his thoughts away from anything else whenever she was near. "Besides, you promised me a son. 'Tis time we set about that family." And right then, she was the only field he wanted to plow. She'd screwed her face up at him. "But what of the Mercians? The Saxons?" "What of them?" "What if they encroach? For that matter, the Romans are likely to return. You can't trust them." Scoffing at her ridiculous concern, he passed a droll stare over her body. "Given the number of heads upon pikes on our borders, I doubt it. Am told even the Picts and Adoni Fey pissed themselves when last they saw my grisly fence." In retrospect, he should have known by the way her eyes darkened that she was plotting his demise that night. But his thoughts had been on the fact that her gown had dipped low enough to expose the top swell of her breasts. And on the fact that her hair teased the creamy crest of it. The fact that if she leaned forward just a bit more, or sneezed, she'd most likely spill out of her gown completely.... I was such a fool. His own parents had been incapable of showing him even a modicum of affection. Why had he thought for even a heartbeat that a Deruvian bitchington would be any better? He'd been nothing more than a tool for her. A weapon she'd used to strike back at her own enemies. Devyl blinked as he forced himself to return to the present and to the fire, where he cut the heart from the last of the demons for his supper, taking care to save its blood, and then threw it to the fire. That was all he'd ever been to anyone. A stupid pawn. Even Elf, really. While he liked to pretend that his sister had loved him, in his more melancholic moments he couldn't help but wonder if perhaps she was no less self-serving than everyone else he'd known. Maybe even she'd seen him as nothing more than her mindless tool to be manipulated at her whims. Just a rabid attack dog Elf had set loose on those she didn't like. In her meaner moments, it had been something Edyth had frequently taunted him with when they were children. A vicious, cold insult she'd known wounded him to the core of his worthless, black soul. And Vine. She'd taken a sick, vicious pleasure in telling him that he had no other use in the world. You're nothing, Duel. Just a cold killer incapable of feeling anything more than the sword you hold. The only warmth you know is the blood you spill. Face it, they might proclaim you a king, but at the end of the day, you're nothing more than a servant to the blood-hunger inside you. A mindless animal forever seeking a comfort you were never born to know. You trust no one. Not even yourself. Throwing his head back, Devyl let loose a cry of bitter agony and grief. A cry born of utter loneliness as he drank from the demonic blood he'd spilled. Just once in his life he wanted to know what it felt like to be cherished. To be desired. To be touched by a tender hand. Not because he was a weapon or tool. Because he was loved. You're still a futtocking idiot. And he was old enough to know better. Love was for women and children. He was a creature of vengeance and hatred. It was all he'd ever been, and all he'd ever be. Vine was right. Not even friendship came to the likes of him. I am the Devyl's Bane. There was no need to fight destiny, because sooner or later that bitch always came and took whatever she wanted. And his destiny was darkness and pain. Accept what you are and be done with it. There was no need to fight destiny. Not when he was the hand it'd chosen to be its executioner. * * * "Are you all right, child?" Cameron jumped at the soft tone of Marcelina's voice as she walked up behind her in the galley. "Sorry. Aye." She pursed her lips and scowled. "Sort of." Blinking, she met Mara's gaze. "Are you all right, mum?" Mara pulled a cup from the shelf where Cameron had taken one down just a moment before. "Like you, I'm a bit shaken by the day's occurrences. Not used to dealing with demonic children. There's something profoundly wrong with that entire concept." "Aye, indeed. Says much for what we're up against that they'd stoop so low." She handed Mara the rum. "Your sister, is it?" She nodded. "Not as innocent as I wanted to think." Mara took a drink, wishing she could stop remembering a few disturbing truths that she'd been trying her best to keep buried. Yet in spite of her best efforts, they wouldn't stay chained. Rat bastard things... "What devil lives in that grimace? And don't be saying the captain. I'm beginning to know ye better, me lady." Mara snorted at the lass, who was a bit too astute for her own good. "I'm just thinking... there's a disease among my people that comes from the misuse of our magick. One that causes our hearts to shrivel and petrify into a hard stone." With color fading from her cheeks, Cameron gasped. "You're serious?" She nodded grimly. "We call it Heart-rot or Wintering. It's where we begin to decay from the inside out. Like what you saw with Mona. We turn pale and our blood darkens. Those of us who are strongest can mask the disease longer than those who are weaker, but sooner or later, it will show itself. And when it does, it turns us into monsters who live on the pain and blood of others." "Is there a treatment for it?" Shaking her head, Mara winced at the brutality of the plaguelike illness. Though it wasn't common among her people anymore, she'd seen more than enough of the illness in her time to be afraid of contracting it, and to want nothing to do with any manner of Wintering. "Because the heart no longer beats on its own, it causes a painful hunger inside the sufferer for fresh blood, to the point they will hunt others for it. Tear them apart and devour them whole to get what they need. Even their own children aren't safe around them. No one is. 'Tis said when it gets bad enough, they'll even gnaw on bones like rabid rats, trying to get every last bit of blood they can out of the very marrow of them." "It sounds awful." "You've no idea." Anger brought a bitter taste to her mouth as she silently seethed. "Worse? It was Du's race who first cursed us with it. His own grandmother, Kara, sentenced her stepmother Heiðr for killing Du's grandfather after they were married. A dark Disir goddess, Kara gave this disease to my people for what was done to hers, and we returned the favor to them with our own version of a similar illness. First Kara was stricken with it, then her son, and finally Du himself came down with it." Cameron gasped as she realized what that meant and why Du was so very evil. "If there's no treatment, can it ever be healed?" Again, she shook her head. "It's what causes his eyes to turn red whenever he becomes angry. What makes him an unreasonable beast. It's a credit to him that he contains his madness as well as he does. Most are driven so insane by it that they have to be put down like rabid animals." "'Most' implies that some escape." Mara sighed as she poured more drink. "There are legends—silly ones, of course—that claim they can be saved by true love's kiss. Or the hand of one who can see past the beast to love them in spite of their cruelty. But that's such hokum as to be ridiculous." "You don't believe in love?" How could she? She'd never seen it in her extremely long life. And she'd seen some rather miraculous things. But never love. Never anything close to what the poets described in their ridiculous songs. "Do you, Miss Jack?" "Aye. Me brother loves his Lettice. It's why I think we'll find him. He won't leave her. Not without a bitter fight." "Then they are lucky, indeed." Cameron sipped at her rum. "So you've never been in love, then?" She shook her head. "My people didn't believe in it. Not the way humans do. And the gods know Du's definitely didn't. He'd laugh like a madman if you ever so much as hinted at it. They only believed in duty, honor, and family." "You mock that?" "'Tis not mockery you detect in my tone. Just pity. No matter how noble something is as a concept, when taken to extremes, anything can become corrupted and used as a vehicle for evil." "So you think the captain is beyond all redemption?" Mara paused at the question. A few months back, she'd have said yes unequivocally. Now... She scowled as her gaze went past Cameron's shoulder to focus on Devyl's massive form, headed for them. There was an intensity to his swagger that she hadn't seen in a long time. One he reserved for battle. Or enemies he intended to gut. He hadn't approached her with it since the day they first met, and it wrung the same reaction from her now as it'd done then. Her gut tightened as every part of her sanity screamed for her to run. Unfortunately, flight wasn't in her. So she stood her ground, even though a part of her expected to wet herself at any moment. Without a word, he took her arm in a fierce grip and hauled her from the galley to the upper deck. "What are you doing?" He practically carried her. Though he was insistent, he wasn't rough, per se. Still, it unsettled her. And it seriously rankled her. But not as much as his continued silence on the matter. "Duel! Answer me! What is this about?" "You wanted to learn to protect yourself. I'm here to teach you." What? Stunned and confused, she blinked at him as he finally let loose of her arm so that she stood in the center of the deck, near the mainmast. "Pardon?" He handed her a sword. "You're going to learn to fight." Now? Had one of the demons possessed him? She'd never seen him quite like this. And she'd been jesting earlier. Surely he'd known that. By his actions, she'd assumed he'd known it for the japing it was. Glancing around at the crew that had paused to watch them, she shook her head. "I don't need to learn to fight." It was what she had him for. "Aye, you do." He pressed the cool grip of the hilt into her hand. She refused to take it. "What are you about?" Pure unmitigated fury darkened his brow. It was so cold and fierce that it actually scared her—something she wouldn't have thought possible. "Take. The. Sword." Each clipped word cut even more sharply than that weapon would. "What is wrong with you?" His eyes flared vibrant red. "Take that sword!" he growled in that deep, demonic rumble. "Now!" "Nay, I will not." Du shoved her back. "Is that your answer then? To let your enemies have you? To bleed? To die? To do nothing while they rape and dismantle you?" "Captain?" Du shot a fire blast at William as he came forward to lend a hand to her. "Stay out of this, Mr. Death, before I make your last name a permanent condition not even Thorn can save you from." He turned back toward her. "Is it?" Her lips trembling, she hesitated at the sight of what she saw in those red eyes. There was something a lot darker than a demon soul inside him. Something a lot worse had its claws in his heart. "Duel... I'm not going to get hurt." "Don't patronize me. Not after what happened today." He grabbed her hand and forced her grip around the hilt of the sword. "Take it and learn to protect yourself!" With a ragged breath, she shook her head. "You can't teach me to fight in one day... in one session. Duel, you know this! A single lesson is absolutely worthless. Do you really think you can train me to be you in one afternoon? How long did it take you to learn your craft or train an army?" Anguish lined his brow as her sanity broke through his madness. His own breathing picked up speed. He glared at her with the worst hatred she'd ever seen on his face. It made a mockery of what he'd directed at her on the day they'd met. "I won't bury you! Do you hear me, Mara! I won't do it!" Those words baffled her. "Then graft me and I'll return." His nostrils flared and for the merest instant she'd have sworn she saw tears in his eyes before he stormed off toward his cabin. Relieved, shaking, and still quite terrified, she glanced about at the stark and pale faces of the crew, all frozen in place by their captain's strange outburst. William was the first to recover himself. "Are you all right, mum?" She nodded. "See to the ship, Mr. Death." "Aye, mum." With a deep breath to attempt to settle her raw nerves, she headed after Du. Cameron was nearest the cabin door. "Are you sure you want to go in there alone?" Not really. But it had to be done. "Aye. I don't think he'll harm me." Or so Mara hoped. Cameron arched a skeptical brow. Not that Mara blamed her for her doubt. She wasn't so sure herself. That had been quite an explosive display Duel had given them. Offering a smile she was certain didn't reach her eyes, she headed into the cabin to check on Duel. He was knocking back something she was positive he shouldn't be drinking. "Du?" He froze instantly for a few heartbeats, then drained his goblet. Her hand shaking, she reached out and touched his shoulder. "Talk to me." Snorting, he poured more blood. She caught his hand to keep him from imbibing any more, then gently took the cup and set it aside. When he started away, she fisted her hand in the billowiness of his sleeve. The size of him overwhelmed her for a moment. It was easy to forget sometimes just what a massive beast he was. But this close... He could tear her apart. Yet he didn't move. Even though his fury reached out like a tangible force, he stayed completely still in front of her. The only movement was the tic in his whiskered cheek that kept time with his rapid breathing. "Why are you so angry?" He growled like a rabid predator. "Why didn't you fight them?" "They were children." "They were demons." "I didn't realize that until it was too late." Pain flickered across his brow. It darkened his eyes back to their natural black state before they flared red again. "You're just like them. I hate you for it." Those words should hurt her. They should cut, but the agony beneath them said that his hatred was directed more at himself than at her. "Them who? Vine?" A single tear fell down his cheek. So fast and unexpectedly that her jaw dropped. He swallowed and shrugged it away on his shoulder, then stepped back and cleared his throat. "You should leave." Like hell! "Not until you explain this to me... Duel. Please." Devyl started to tear into her. It was what he'd have normally done. What he wanted to do. And yet he couldn't bring himself to hurt her. And for that, he hated himself all the more. Damn it to hell and back. And damn him, too. Why had he always been weak where she was concerned? It was what had brought them to this place and time. What had allowed her to bind them. That one moment when he'd been so furious and bloodthirsty... He'd looked down into her terrified amber eyes as she stood so bravely and defiantly against him, and lost himself to her completely. It was why he'd slept with Vine originally. While their coloring was different, their features were not. The two women could be twins but for their hair color, and oft at night, he'd closed his eyes and imagined Vine with hair of silvery white and eyes of amber. That she smelled of feathery roses and spice. But in the end, Vine had been a cold substitution he'd used, hoping to drive Mara out of his thoughts. Hoping to purge the unholy craving he had for her from his heart. In spite of it all, he was forever drawn to her. Against all sanity and reason. All common fucking sense. Like now. Wincing, he closed his eyes and swallowed hard. Why not tell her at this point? Why continue the farce that had driven him to more madness than the curse her people had placed on his? It seemed ludicrous. So he took a deep breath and finally spoke the single coveted truth that had lived inside him for countless centuries. "You remind me so much of my mother and sisters." "Pardon?" He turned to lay his fingers against the coolness of her pale cheek. The softness of her skin reminded him of a fragile flower petal. The kind Elf used to make and line their beds with. "You're a white oak. Me mother was a dera sylph." She let out a soft gasp as that unexpected news hit her. Her eyes widened as she stared up at him in utter disbelief. By her expression, he could tell that she didn't want to believe him. That she wasn't quite sure if he was being honest or trying to deceive. But this was one thing he'd never lie about. After all, it was the one thing he'd spent a lifetime denying and hiding with everything he had. A dark secret he was entrusting to her alone. "What?" "Aye. Elm. She was designated as my father's guardian when he left Alfheim to take his place as the leader of the Dumnonii. She was supposed to keep him grounded and stable. Never were they to marry." Because it was forbidden. A Druid-Aesir was never to touch his guardian Deruvian. They paid homage to them and set up nemetons for their honor and comfort. Never were they to "know" or marry them. Her breathing turned ragged as she continued to struggle with an impossible truth. Not that he blamed her. There were times when it was preposterous to him as well. "That's the secret of your power." He nodded. "Why no one could ever defeat me. I'm not just an Aesir, but Vanir and dark Adoni, too." Covering her mouth, she let out a ragged sigh as she finally appeared to accept it, even though her amber eyes were still troubled. "Did Vine ever know?" "Nay. I've never told anyone." She arched both brows at that shocking declaration. And again, he couldn't blame her. They were enemies, after all. Had been for countless centuries. "Why tell me?" He let out a bitter laugh at a question that surely had to be transparent. "Don't you know, Mara?" He took her hand in his and led it to his heart. His eyes faded to black. Mara swallowed hard at the fierce beating of his heart beneath the palm of her hand. At the tender heat in his eyes as he watched her with an expectation she couldn't even begin to fathom. She was still reeling from his news. Reeling from this new side of him that she'd never known existed. And now this? It was more than she could cope with at once. More than anyone could handle. Honestly, she'd rather battle demons out to steal her soul than deal with these strange feelings that made no sense to her. Face down the real devil than think for one second that she might have tenderness for Devyl Bane—the scourge of her people. The creature who'd torn her world apart and left her with nothing and no one. Nay, she hated him. Aye, she did. She must remember that. Hold to that. It was the truth. Was it not? Determined to stay the course, she met his gaze unflinchingly. "You know there's nothing but hatred between us, Du." A deep, heart-wrenching sadness darkened the shade of his eyes. "Aye." Letting out a tired sigh, he lifted her hand to his lips and placed a tender kiss to her knuckles before he headed back to the main deck. Mara didn't move as she heard him calling orders to the others. As the sea rocked against her planks and she felt the motion of the waves. And inside her body, she was as hollow as the ship itself. Hollow because she knew who the real beast was on board. For once, it wasn't Devyl Bane. Remember, sister... you bring me Du's heart and I will see to it that you're set free to live out your life independent of the ties that bind you to his fate. I swear it. While she wasn't sure she could trust Vine, she knew she could trust in her sister's hatred of her ex-husband. To get him in her clutches, there was nothing Vine wouldn't do. And if there was one creature in existence who could undo the spell Mara had cast that united her life to Duel's... It was Vine. That was why she'd followed the demons away from the orphanage. Vine had promised Mara through the guise of the douen that she would free her. For too long, Mara had been bound to him. Had been forced against her will to serve him as his helpmate and guardian. To give her blood and powers for his spells. This ship was a prime example. He'd sold his servitude to Thorn, then forced her to become this vessel to carry the lot of them and watch over his crew like some warden that they cursed her for. She was done with it. It was time to take back her life. Even if she had to end his to do it. It's the right thing to do and you know it in your heart. But if that was true, then why did it hurt so much? And why did doubt plague her so? Mara leaned her head against the boards as she allowed herself to merge with the wood and seek comfort there. While it wasn't the same as being in a mother's arms, it was the closest sensation she'd known since the day the winds had scattered her parents' essence to the corners of the world, and allowed them to return to the universe that had birthed them. Wanting... nay, needing to feel connected again, she touched the locket her mother had given her so long ago and allowed herself to freeze that way as buried memories tore through her. So easily, she saw herself as a girl on that day in their small nemeton where they'd made their home. Saw her mother as she placed the locket around her neck and placed a tender kiss to her brow. "What is this, Mam?" "That be your harthfret, precious." Scowling, she'd opened her locket to find the glowing and pulsating green kernel inside it. Similar to an acorn, it'd been unlike anything she'd ever seen before. The fire that held the rhythm of a heartbeat mesmerized her as it danced and glistened against her skin. With a child's enthusiasm, she'd started to bite into it, but her mother had stopped her. "Careful, Mara! That's your life source you hold." "P-pardon?" Her mother had laughed and taken the kernel back to return it to its caged nest in her locket. "On the day we're born, all Deruvians carry a harthfret in their navel that falls free when they lose their umbilical cord. 'Tis said that it was from the first Deruvian and his harthfret that mankind was born to the earth. But because mankind lost their harthfrets, they lost their immortality and higher powers. It's why they're so much weaker than we are." "But we kept ours?" "Aye. And so long as we have it, we are virtually immortal. With it, we can call on the powers of the universe and command them. It's our connection to the higher mother. To all that runs through the vast heavens and all the worlds." "Where's yours?" Her mother had smiled. "I planted mine here in the nemeton beside your father's. One day, you'll meet the man you love and the two of you will plant your hearts together to put down your own roots. But be warned that when you do so, you will be forever bound to that one place. For all time. So never do so lightly, daughter. It's the same as a binding spell. You might leave, but you'll never be whole. And if gone too long from your roots, you will wither and die. For no Deruvian can exist without their life source." "Then I shall never plant my harthfret." Laughing, her mother had tucked her hair behind her ear. "Careful of those convictions, little one. They have an awful way of coming back to haunt us." "I'll be careful, Mam." "Good, and whatever you do, never let anyone steal your harthfret." "Why?" "Because that is the essence of who and what we are. It's the source of our power. Whoever possesses it can command us to do anything they want. They become our owners and we are enslaved to them, especially if they combine it with their blood. Then there is nothing we can do so long as they live. We are forever their slaves. So guard your harthfret as you would your life, for it's much more sacred. It, my precious, is your freedom." Mara cursed herself for the day Duel had captured hers. It'd been her own arrogant stupidity that hadn't believed him capable of knowing its significance. In all these centuries, she'd never known how it was that he'd learned the carefully guarded Deruvian secret. Now she did. He was one of them. Which meant he had a harthfret, too. And if she could find it... Then he would be hers to command for all eternity. * * * "So, you didn't lie. How ever did you manage to get one of his ilk here?" Vine smiled at the dark Seraphia who stood before her. Clad in the ancient bloodred armor her species had once donned for battle, Gadreyal was a winged beauty of extreme and utter grace. Tall. Sleek. Voluptuous. It was easy to see why she was the first among those sent to tempt the army of the Kalosum to their downfall. And as a member of that same loathsome, sanctimonious army, Paden shrank away from her approach. He cringed even more as Gadreyal reached for him. "Don't touch me!" His Seraph form activated, turning his hair instantly white and causing his own wings to spring out of his back. The golden feathers extended out and slashed at them both. Laughing, Gadreyal caught one of his wings and snapped it. The sound of breaking bone was harsh even to Vine. Paden cried out and arched his back against the pain. With a fake, sympathetic tsk, Gadreyal cradled his head against her shoulder, exposing his throat. "There now, little one. Don't come at your betters. I'm not one of the halflings or mickles you've been fighting." She ran her silver talon over his Adam's apple. "And I can make all this misery go away in an instant. All you have to do is give me your vow of loyalty. Fight for us and I'll free you." Tears welled in his eyes. "Never!" "Awww." She mocked his pain with a treble note. "Poor little Seraph. All alone in this hole. No one to care for you. To rescue you. Do you really think the Sarim will come? That my brother cares what happens to you? I promise Gabriel laughs at your suffering. Michael even more so." "I will not turn." "Aye, you will," Gadreyal whispered in his ear. "And you will cut the throat of your own sister to give me that medallion before all is over, too. Trust me, little man. Far greater warriors than you have fallen to my wiles." She kissed his cheek and stepped away. Her gaze turned bright red as she closed the distance between her and Vine. "You should leave now, Deruvian. I will take it from here." "What of my reward?" Gadreyal smiled coldly. "I haven't forgotten. The moment I have his medallion and his soul, you will be freed. That is what we do." * * * Thorn felt the shift in the air around him and knew instantly what caused it. Fury spread through his veins like lava, demanding satisfaction. And blood. "Misery!" He summoned his demon companion from her hole. Honestly, he should have killed her long ago. She was a feckless bitch who could never be trusted for anything. Other than sheer treachery. Which was why he trusted her. Because he knew better, and therefore she was incapable of betraying him. His guard never laxed around her. She appeared before him with an irritated grimace. "You shouted, my rampaging overlord?" "What are your sisters up to?" Shrugging, she started to leave, but he caught her wrist and jerked her back toward him. "Don't play this game with me, Misery. Or I'll make you earn that name." Fear replaced her smug expression as she saw the face of Forneus and realized the tenuous ground she stood upon. For all her arrogance, she was his slave and at his utter mercy. Something he ran very short on, especially when it came to creatures like her. She gulped before she gave up her answer. "They have the spawn of Michael." "Tell me where he is." Shaking her head, she pulled away from him and went to cower in a corner of his study. "I don't know." Thorn reached for her, which caused the shadows that were concealing her to shrink away and leave her exposed to his gaze. Even they knew not to tempt him when he was in this mood. No one, other than his own father, dared his wrath when he was like this. Squeaking, she tried to teleport out of his study, but he used his powers to trap her here. "Don't, Misery. Just don't." She visibly shook as she sprang to her feet and moved to put a chair between them. "I swear to the Source, I have no idea. They... they know I serve... that I'm bound to you. T-t-there's only so much they'll say in my presence." He threw his arm out and drew her to him so that he could wrap a single hand around her throat. Not tightly, but enough to remind her of how much power and how little regard he had where her life was concerned. "I hate you for what they did to me. Do you understand?" She nodded eagerly. "I should never have been conceived or born. And I begrudge all of you every single breath I've ever drawn. For that alone, it's a daily struggle not to kill you." He tightened his grip to let her know how serious he was. "You will find the Seraph they hold before he's turned or I will spend the rest of eternity going to bed to the sounds of your screams for mercy. Do you understand that?" "I understand, my lord." "Good. Now go!" He cast her away from him and watched as she scrambled from his study. Fury pounded through his veins so vehemently that it caused his own wings to jut out. His skin turned the vibrant gold he resented even more. Ever since the day he'd learned who and what he really was. How his mother had come to spawn him... Damn them all to the fiery pits! "Forneus?" Great. That was just the maggot-licking bastard he needed to suffer in this mood. What? Were the gods really that bored? Reining in his temper as best he could, he turned to find the last creature he wanted to face. Second only to his father. Folding his wings down, Thorn crossed his arms over his chest. "Michael... been a while." Seven feet in height, he was a massive bastard. Whereas most of the Seraphim were pretty enough to pass as women, Michael was ruggedly handsome. No one would ever mistake him for a Seraphia. And in his Seraph form, he was snow white—armor, weapons, every part of him. Even his eyes were a stark silvery blue. So it was always shocking to Thorn how dark the tool was whenever he donned a more human appearance. Dark hair, tanned skin. The only thing that remained the same were those celestial blue eyes that glittered like spiked icicles in front of a setting sun. And they had the same effect today that they always did on him. He wanted to punch the sanctimonious bastard in the face. "What are you doing here, Mikey? Last I heard, none of you would sully yourself by crossing the boundary into this dimension." "You have something that belongs to me." "No. I have something that belongs to your bloodline and I promised her that I'd return it. So sod off." Michael let out a tired sigh. "You can't help it, can you?" "What?" "Being a complete and utter asshole." Thorn smirked. "What can I say? I take after my father." "You know, throwing him in my face is a really bad idea. You weren't there that day in battle. You've no idea what it feels like to have the person beside you—the one whose back you've protected for centuries—turn their sword on you. To look into the eyes of a friend and see an enemy. It's a special level of hell I wouldn't wish even on you. And when we look at you, we see your father and remember he was one of us once. Until he got crossed up with his own siblings." Rubbing at the bridge of his nose with his middle finger, Thorn snorted at his tirade. "Should I get my violin out? I feel this little chat of yours needs an accompanying rhapsody." Michael rolled his eyes. "And that nasty attitude doesn't help us get past our natural distaste for you. Any more than the fact that, at the end of the day, we all know you turned on your own men and brutally slaughtered them." Thorn arched a brow at that. "I didn't turn on my men. I gave them a choice before I declared war." "Tomato, tomahto." "No, arseling! Big. Futtocking. Difference. I turned on my father once I learned of his lies—same as all of you. There's no difference whatsoever there. Then, I gave every sword under my command an opportunity to either fight with me for a new cause or to be on the receiving end of my skills. Those stupid enough to choose my father were given a head start before I went after them. I never put anyone down without allowing them their chance to change, which is more than any of you ever offered me." "What about your son?" Thorn hissed as the demon inside him exploded and took over completely. For a moment, he almost went at Michael's throat—which was probably what the bastard wanted. But he roped the dragon down and forced it into submission. His breathing ragged, he glared at him. "Never speak of Cadegan again, or I will slit you from asshole to appetite." Michael held his hands up in surrender. "You've put together teams of demons. Released on parole in all corners of the world. Living side by side with unsuspecting humans. Do you really think we're all right with what you're doing?" "I'm redeeming the damned. Giving them another chance to learn from their mistakes and make something of their lives and eternity. Is that not what we're supposed to do? Is that not what all of you have preached since the beginning of time? To protect the innocent from those who prey upon them?" Michael scoffed at him. "It's the ones you've chosen as their guardians we take issue with. These aren't the souls of those who were borderline damned. You've chosen some of the blackest souls ever spat out from the farting abyss of hell itself. Have you any idea what you've released back into the world? Especially with this latest batch of... What are they calling themselves? Deadmen?" "Jackdaw flies with jackdaw." "More like the vultures circle together." "Whatever. The Cimmerian Magnus has a team to tempt saints to be sinners. I figure it's only fair we have a team to tempt the sinners back to saints. Balance. If anyone in the universe should appreciate that... should be you, Mikey." Michael stepped back with a frown. "When you put it that way, what you're doing almost makes sense." Yet after a second, he shook his head. "I can't believe we're on the same side. How is this even possible?" Thorn snorted. "Does this mean you're going to help me now? Are we friends... lovers?" "You're such a sarcastic wanker." He growled deep in his throat. "While I don't trust you, I do commend you. And I hope you don't live to regret what you're doing." Thorn didn't comment. The only things he'd ever regretted had to do with his son and the woman who'd birthed Cadegan. To this day, they were the only ones he'd ever loved. The only ones who'd ever gutted him. "Just so you know... the reason I came? Because of what's happened with the Carian Gate and with your swift actions that helped hold back what's been unleashed so far—" "Excuse me? I believe the correct words you're looking for are Thank you, Thorn, for saving our asses when we got caught with our britches down." Michael cleared his throat before he continued on without acknowledging Thorn's interruption. "We decided to stop being so adversarial toward you and yours. From now on, whenever your Hellchasers need backup, they can call on our earthbound Necrodemians. Either they, or we, will answer your miscreants." "Really? Hell froze over?" "Not yet. But one of its main gates is fractured. So long as there's no similar rebellion of your troops, we will back you in this fight." "How magnanimous of you." "I believe the words you're seeking are Thank you, Michael. We could use the help and appreciate it." "And you'll hear those words from me the day Lucifer's cock rots off from frostbite." Michael let out an annoyed sigh. "I so miss these conversations with you. Like having my head drilled and skull pried open." Wrinkling his brow, he pressed his fingers to the bridge of his nose as if their exchange was giving him the same migraine currently thumping through Thorn's head. "One last thing. The gate? It's located in the Quella." Thorn winced at the mention of the chain of notorious islands. They should have known. "Of course it is. And which fun island holds the honor? Oh wait, let me guess. It wouldn't be the one inhabited by pissed-off dragons. They'd only eat us, and there's no fun in a quick death. Or the island of demons, because that would be too routine, and half of Bane's crew would be delighted since they, including Bane himself, would consider it a buffet they could gorge on. Nor the land of the seven giants... because, again, death would be too quick and painless for them. Nay. This fun-filled adventure could only be found on Meropis. Am I warm?" "Your deductive reasoning impresses me." Thorn scoffed. "How 'bout I do you one better, then? Out of all the places they could have planted that gate, they put it squarely on that one island—bet I can actually peg the correct lost and abandoned city where it's housed... Anostos." So named because it literally meant No Return. "Again, you astound me." His voice matched Thorn's level of sarcasm. "I hate you so much, Michael." The Seraph leaned forward to playfully slap at his cheeks. "Back at you, demon." And with that, he vanished. Thorn didn't move as he considered this strange turnaround. It wasn't like the Sarim to reconsider anything they did. And especially never their attitudes on a matter. Or a person. The Sarim were forever right in all things. Everyone else was wrong. Always. But in this, they'd reversed course and come around to his line of defense. More than that, they agreed with him and were willing to aid his cause. That... that actually scared the flaming shit out of him. The world really was coming to an end. He just hoped he'd chosen the right side to be on. Maybe I ought to rethink a visit to good old Dad.... Mara stretched as she resumed a human form. They were far out to sea now. Santiago still trailed after them, but, at Du's insistence, at a safe distance. She pulled up short at the sight of food someone had left for her in her room. Nay, not someone. Only Du ever did that. She'd never been quite certain how he knew when she'd be resuming her human skin, yet he always did. Because he's Deruvian, too. He must be able to sense her moods the same way she sensed them in others of her kind. And yet, she'd never once had an inkling that he was one of them. Of course, she hadn't looked for it either. Still... She scowled as her gaze dropped to a small box he'd left next to the tray of food. It was set upon a folded note. Scoffing at whatever he had to say, she opened the box, then sat down promptly in her chair as her legs gave way from the shock of what it contained. Her missing harthfret that he'd taken so long ago. With a gasp, she reached to finger the small gem and recalled the day Du had taken it from her. "Where is it, you bastard!" she'd demanded as she rushed into his bedchambers to begin searching through his chests and belongings for it. He'd arched that black brow in the same arrogant expression that always made her want to claw out his eyes. Dressed all in black, he'd been freshly bathed and groomed for once. Not that it mattered. A clean beast was still a beast. "Don't you knock?" he'd challenged before he shut the door behind her. She'd ignored him. "What did you do with my necklace?" Smirking, he'd pulled it from the small leather pouch on his belt and handed it to her. The moment it touched her fingers, she knew the harthfret was gone. "You took it without asking?" Nonchalant, he'd shrugged at her indignant tone. "You bound my life to yours without my permission, so I can't trust you with your freedom, as it is now intrinsically tied to my own. It seems only right to me that I hold both." She'd hated him for that. And for all the centuries he'd kept it hidden from her. Now... Unable to believe he'd finally returned it, she opened the letter that he'd left so that she could see why he'd finally changed his mind after all this time. I should have given this back long ago. It was an unbelievably selfish thing to do and I won't keep you bound any longer. When we make our next port, I'll purchase a new ship for the crew. Santiago has agreed to take you to any port you wish. Not that you need it, as you are the ship, but I did ask because I know how much you hate to be alone. D. A strange weepiness possessed her as she stared at the strong, masculine script. Undeniably thoughtful, this was the kindest thing anyone had done for her. What was more, he'd had her stone reset into a new necklace. A beautiful, delicate cage that formed the outline of an ancient oak. The glow of her harthfret silhouetted the gold to make it appear as if a moon or fairy light illuminated it. It was so beautiful and carefully constructed. As if made by a loving hand. His own hand, no doubt, as he wouldn't have entrusted it to anyone else, since a careless smith could have accidentally destroyed it and killed them both in the process. Aye, metalworking was another of Du's gifts from his human life. Though the only thing he'd ever given such tender care to was the forging of his weapons or the carving and engraving of his ogham runes and casting sticks. The things his life depended upon. Cradling it in her palm, she went to find him. Which didn't take long. He was on deck, next to Sancha, while the tall, ethereally beautiful woman straightened the collar of his shirt and jacket that had gotten rumpled from some activity. "Best be careful, Captain. You almost fell overboard." Du snorted. "Water's the least of what concerns me. Besides, Kalder would have fished me out." Mara didn't miss the way Sancha's hand stayed a little longer on Duel's chest than what was necessary to fix his collar. Or the hunger in the woman's eyes as she smiled up at him and brushed her hand down his arm to smooth the jacket down more. As if sensing her presence, Du looked up and caught her gaze, which must have betrayed her irritation. At least the questioning expression on his face said he had a good idea that she was less than happy about their exchange. And apparently their close proximity, as he quickly stepped back from Sancha and gruffly cleared his throat. Adjusting his somber cuff, he came over to Mara. "Is there a problem?" Aye, but she wasn't about to give him the satisfaction of stating it out loud. He was arrogant enough already. Worse? She had a sudden, inexplicable urge to duplicate Sancha's actions with Du's standing collar, even though there was nothing amiss with it at present. "Nay. I only wanted to thank you." Her gratitude appeared to embarrass him. "Nothing to thank me for. If you'll excuse me..." He moved past her to speak with William. Mara started to call him back, but that would be cruel given her earlier words to him when he'd offered her friendship—perhaps even more—and she'd returned it with rude enmity. Now she mentally kicked herself for that stupidity. Why had she never noticed before just how handsome he was? How caring he could be whenever he chose it? Instead, she'd focused solely on his short temper. His caustic ways with those he didn't care for, and the fact that he was extremely reclusive. But then, given his mixed heritage, she couldn't blame him for the latter. His parents had saddled him with a horrible secret. One wrong move and his Aesir brethren would have cut his throat to claim the other half of his blood. The Deruvians would have been no better. Indeed, what had they done to him and his family? Killed his sister and slain him while his guard had been down. Vine had slit his throat, then cut out his heart to use for spells. Which made her curious.... She rushed back to his side. "How did you die?" Du stepped back from the rigging he was examining to scowl at her. "Pardon?" "How did Vine kill you?" "You were there. I'm told you lived half a day before your curse took your life along with mine." That wasn't entirely true and they both knew it. Somehow, Duel had managed a spell that had first elongated her life and then cast her to sleep while he'd been dead. A spell he must have done long before Vine had cut his throat and never mentioned to anyone. Not even her. She still remembered how shocked she'd been to find out about his death and learn that she maintained her own life for those precious few hours he'd provided. To this day, she had no idea how he'd done it. What magick he possessed that had trumped hers. Or why he'd cared enough to bother. "Aye, but if you're..." She glanced around to make sure no one could overhear them. When she spoke, it was in a whispered tone. "... one of us, how could you die by Vine's hand?" He leaned down to whisper back. "It was my third death. And I was reborn." "I don't understand." He let out a bitter laugh. "I placed you under a sleep spell to keep you from knowing that I came back. But I was reborn on the other side. It's why I changed my name. As you know, on the fourth reincarnation, if we've gained enough powers and mastered enough skills, we are transformed. In such rare cases, never do we keep the name our mothers gave us." Her heart sank to her feet at that revelation. Dear gods... "You're a coryn," she breathed. It was the status they all prayed to attain. The most powerful of their kind. A sorcerer of unparalleled strength and abilities. Wiser than wise and virtually invincible. "Better. I'm a corymeister." His eyes turned vibrant red. Gasping, she stepped away. "Why did you bring me back?" With those powers, he could have kept her asleep forever. His gaze dropped to her lips, and the hunger in those red depths was terrifying. "I told you, Mara. I wanted you with me." He lifted his gaze to lock onto hers. "I realize now that you're one mistake I can't afford to have at my back. It's why I expect you to be gone in the morning." "Aren't you afraid I'll seek my sister?" He laughed bitterly. "Tell her. It changes nothing, except my feelings toward you, and since you don't care about those... it affects no matter of any great import. Whether she knows or not, the end remains the same. I will see her dead and scattered." With those words spoken, he left her again. Mara ground her teeth as Belle approached her. "Trouble with the captain?" Indeed, and yet... "Nothing new." Belle jerked her chin toward him. "Except you see him now, whereas you didn't before." "Pardon?" she gasped. She smiled at Mara. "You know me, mum. I see right through you both." "Then tell me how this ends." Belle tsked at her. "That I can't do, Marcelina. Only you can. Our lives are always only up to us." She glanced at the Deadman's Cross on her wrist and ran her fingers over it. "As is our damnation." Then she cut a sideways glance toward Duel. "And sometimes our salvation. What we seek is always what we find." Mara didn't speak as Belle went over to speak to Rosie. The wind from the sea whipped across the deck, bringing a chill with it as they sped along their way over the hostile, unforgiving black waters that hid many secrets. Just like she did. Like all of the passengers who were currently sheltered under her boards. Her sister had offered her much for a bit of Duel's flesh. Nay, for his heart. Her bargain with Vine had seemed a simple one. But now... She rubbed her hand over her necklace and the warmth that came from having her harthfret again. You hate him. You know you do. Yet if that were true, why was she having to attempt to convince herself of it? * * * Devyl tried to ignore the pair of eyes he could feel on him. If only that was the part of her he wanted touching his flesh. Damn it. He had no one to blame for Mara's hatred and resentment of him but himself. Nor could he blame her for it. It was better than he deserved, all things considered. Still, he couldn't keep his rampant thoughts steady to the course. The sooner he removed her from this crew, the safer they'd all be. "Captain?" He glanced over his shoulder to see Bart eyeing him. "What can I do for you, Mr. Meers?" "Sallie's soul has gone missing again." With an irritated grimace, he turned to face Bart. "Am I captain or the nursemaid of small children?" "Apparently, you'd be both." He flashed a sarcastic smile at Devyl. Growling at the aggravation, he handed his spyglass to Bart. "Batten down, Mr. Meers. There's a storm headed in. Secure the deck and sails. It'll be a heavy squall." Bart looked up at the sky. "You sure? It's as clear as it can be." "Won't be within the hour. Trust me." "Aye, aye, Captain." As Devyl neared his cabin before he dealt with Sallie's soul, he felt Thorn's presence there. Or at least the remnants of it. Curious about the visit, he stepped inside to find a map pinned to his desk with four very specific kinds of daggers. The kind that would have angered him had a fifth one not held a note pinned to a set of islands north of San Juan. Your ex-bitch and her pack of demons can be found here. Guard your back, my brother. They will be gunning for you. The Sarim send their best to you. Claim they'll come should you call. Wouldn't bet on that, but you can always try. You know where I am. TTUYA Devyl actually laughed at the signature, which stood for "The Thorn Up Your Arse." He'd give the demon credit. Thorn was even more antagonistic than he was. He strangely liked that in a person. Liked it even more in a demon. Prying the dagger loose, he glanced over the map. Then cursed and rolled his eyes as he saw where they'd be heading. Meropis. He should have guessed that on his own. What better place to put a gate to a hell dimension? Perfect. Just futtocking perfect. A chill went up his spine. Not from the location, rather, there was a breach he felt. Cocking his head, he listened carefully. He'd just about convinced himself that he was being paranoid when all of a sudden he caught the scent of the beasts that had crept on board, under their collective Sights. Water sprites. Shit! Grabbing a dagger, he rushed to let the others know before they were sent to the bottom of the ocean, compliments of Vine. Cameron was talking to Kalder when a bit of the sea came up over the side of the ship. At first, she thought it nothing more than the usual spray. Until the water took on the form of a muscled man. Then it quickly formed armor over his aquatic skin.... Her jaw slack, she felt the blood heat up in her veins. Kalder turned, then called to the others as he dove for the creature. The moment he touched it, his body changed over to his merman features. William, Rosie, and Kat unsheathed their swords to lend a hand. But before they could, more creatures came over the side in slick tidal waves. Valynda grabbed her arm. "We need to get belowdecks. Fast!" "What are those?" "Water sprites." Cameron had never heard of such. "And how do you fight them?" "With a great deal of skill... there's a split instant when they solidify into flesh to attack. It's a blink of an eye and the only time they're vulnerable." Cameron saw what she meant when one went after Kalder. It rose up for him and just as Valynda described, it became flesh for only the merest heartbeat. Kalder quickly jabbed his sword into its chest right as it turned solid. With a fierce, ear-piercing shriek, it exploded into a gory mess and rolled across the deck. She started forward to help, until another wave manifested in front of her. It rose up like a skeletal monster and turned toward her with fangs bared. It reached out with a clawed hand. Too petrified to move, she froze as it reached for her. Just as it would have seized her, a sword went through its middle. Like the other, it exploded into a bloody mess to show her the captain who'd speared it. "You all right, Miss Jack?" "Aye, sir." "Then you'd best be getting below." He turned to fight another. Mesmerized, she watched him as he took down two more with expert skill—one right before it would have killed Kat. He was amazing. At least until one of the masts came free and slammed into him, an instant before two of the sprites sank their fangs into his flesh. Kalder and William rushed to his side to fight the sprites off. Time seemed suspended as she expected the captain to be swept over the deck by the waves of attackers. Yet a heartbeat before he would have been taken into the sea, the side of the ship rose up to cradle him and hold him fast from their grasp. It took her a moment to realize that it was Marcelina as the ship who was now fighting off the sprites and protecting the crew. But why had she waited to stop them? Belle let out a chant. One that was taken up by Janice. Then Rosie. Together, their voices caused a shield to go up over the ship to protect it and block the sprites from accessing their decks. Only then did Bart and William lift the captain from the deck and carry him between them toward his cabin. Cameron and Valynda followed, intending to help. Though to be honest, Cameron didn't know much about medicine or doctoring. A bloody nose or black eye were the worst injuries either she or Paden had ever suffered at home. "The captain can't die, right?" she asked them. Valynda screwed her face up at Cameron's question. "Technically true." "Technically?" "While we can't be killed the way a person can, we can be deported back to where we came from." "Meaning?" "Remember what we told you about Thorn? How he could revoke our pass and return us to the hells he saved us from?" "Aye." Valynda drew her brows together into a deep fret. "He's not the only one who can do that. Other creatures have that ability, too. Problem is, we don't always know which ones we're fighting against what can do it. Until it's too late for us." William sighed as he pulled the covers over Captain Bane. "And sometimes the process of being pulled back looks an awful lot like this." He jerked his chin toward Devyl. Bart nodded in silent agreement. "Is there anything we can do?" Cameron asked them. "Pray," they said in unison. Marcelina entered the cabin and quickly shooed them out. Cameron hesitated in the doorway. She wasn't sure why, but something inside her was unsettled. "Mum? Why did you wait so long to help the captain fight against the water sprites?" "I thought he had the matter well handled." She narrowed her gaze on the older woman. For reasons she couldn't quite name, she wasn't sure if she could believe a word of that. Mara arched her brow as she sensed a change in Cameron. A darkness inside her that hadn't been there before. A sudden mistrust. "You have something more to say?" "Why do you hate him so?" "For reasons you'd best be glad you can't fathom. I've seen a side of him that is inconceivable to one of your inexperience." "I'm not near as naïve as you be thinking, mum." Cameron glanced back to the bed and frowned. "None is perfect. 'Tis what me mum always said. When first she met me da, he was hiding from the law. 'Twas what brought us to America, after years of living in terror of being found, and their fear of what would become of me and Paden should the law find me da over there. They'd have hung him in England as sure as I'm standing here. So they changed their names and left all they knew to protect him so that we could start fresh." "Is there a point to this story?" "Aye," she said sharply. "He got his own brother and me mum's killed during a robbery what went bad in London. For that, she hated him. Yet she knew her brother had loved him as his friend and so she didn't turn him in when he came wounded to her to hide." Cameron paused a moment before she continued. "As me dear father used to say, we can easily forgive a child who is afraid of the dark, but the real tragedy of life is when men are afraid of the light. When we refuse to see the truth that lies before us because facing it is too hard and scary for us. Because when we acknowledge that light, then we see the monsters the dark no longer hides and we are honor bound to do something to stop them. It's easy to lock your heart with hatred. But only when it's free will you be able to move forward without pain anchoring you to a past that's holding you back." Grief filled her eyes. "Like you, mum, I've lost many what were dear to me. But were I ever lucky enough to find one who could love me, one who looked at me the way the captain stares after you whenever he thinks no one's watching him... that I'd hold on to with a white-knuckled grip." And with those words, Cameron left her alone with her Bane. How Mara wished it were as simple as the girl thought it to be. Unfortunately, Duel had a way of complicating the simplest of matters. He always had. Her heart heavy, she went to the bed to inspect his injuries. The good news was that he'd heal. But he was rather battered. And it was her fault. As Cameron had said, she'd let her indecision go on far too long and delayed helping him when she shouldn't have. He would never have withheld his protection of her. No matter their quarrel. Grimacing at the bruises and cuts, she gently pulled his shirt over his head, then used her powers to manifest a towel so that she could dry him off. Yet as she began to clean and dress his wounds, she became aware of the scars that marred his perfect physique. The roadmap of battles he'd fought for his people. And for his sisters. Every part of his body was covered with them. And in her mind, she didn't see the captain. She saw the barbarian warlord in his black armor who'd ridden at the head of his army. The bastard leader of the Dumnonii. As she touched his hand and saw his ring, those thoughts scattered. Was that... Her heart stopped. It was a harthfret! How had she missed it? In all the years they'd been together, she'd never really looked at his ring. Never once noticed what the vibrant red stone was. Biting her lip, she reached for it, then hesitated. He'll kill you. Deader than even dead itself! In fact, he'll bring you back just to kill you again. Aye, he would. But if she had control of him, he wouldn't be able to harm her. She'd own him completely. Scared and trembling, she forced herself to pry the ring loose from his finger. Yet the moment it came free, it shot a light through the room. One that blinded her. More than that, it ripped a hole through her emotions as she realized too late that it wasn't his harthfret, after all. It was his sister's. Suddenly, she was in the past. In the Great Hall of Tintagel where Dón-Dueli's family had ruled with an iron fist. "Elf!" he roared as he came through the doors in all his massive glory and sent the hounds and servants scattering for cover. Even the watchmen seemed a bit nervous and in want of shelter from even so much as his passing glance. The only one who wasn't afraid was a tiny wisp of a teen girl who sat in a wooden chair near the window, doing needlework. "Would you stop calling me that already? My name is Elyzabel." He'd snorted dismissively. "Why weren't you in the list to train?" "I told you why. I've no intention of learning swordplay. It's what I have you for, Duey." The growl he let out succeeded in causing the watchmen to withdraw from the room. They scurried away like rats fleeing a fire. She laughed. "You're scaring the guards again, brother." "Too bad I can't scare you." Sighing, she tied off her thread, then bit it in twain. "Well, you need the frustration of dealing with me. Everyone else gives you your way." With a grimace that would have caused a sane person to wet herself, he knelt by the girl's chair and handed her the cup from the floor so that she could sip at it. "Why won't you train?" She reached to toy with the braid that fell down from his temple. "I've no wish to take a life." When he opened his mouth to speak, she placed her finger to his lips to stop his argument. "That is no judgment against you, Duey. I love you more than anything in this life and I always will. But as you know no peace, I want to know no war. Ta gave you no choice in your life or your fate. He forced a sword into your hand as soon as you could walk, and saddled you with responsibility for me and Edyth and our people. Never once have you ever complained of it. I've watched you all these years as you've grown from a beautiful boy to a handsome man. I couldn't be prouder of you. And I thank you for the fact that you've given me a choice as to my future here with you and with our people. Please don't take it from me now." He lifted her hand into both of his and kissed it. "I want you safe, Elf. You've no idea what horrors I've seen. What happens to the women when their men fail to protect them. The Romans keep advancing on us. I've held them off thus far. As well as the Adoni, but should I fall—" "You will not fall," she said with a chiding smile. "No one can defeat my brother." He brushed his hand tenderly over her scarred knuckles. "What happened to my little Elf who used to climb trees and beat any boy who said she couldn't run as fast or shoot as well?" Sadness darkened her eyes before she blinked it away. "Childhood scuffles are vastly different from what you do." "You blame me for our parents." He started to stand. She held him fast by her side. "I never said that. 'Tis your guilt driving you, not me. I want to see you happy, Du. You never speak of family or peace. 'Tis as if you don't think yourself worthy of either." He let out a bitter laugh. "How can I marry and have children when every woman, save you, cringes at my approach?" "Not true. I've seen the ones what vie for a place in your bed." "And flee the moment we're done as if terrified I'll strangle them come morning." "Then let them see the side of you that you show to me." He glowered at her. "What side is this?" "Well, not that expression. Dagda's toes, Duey, you'd scare grown warriors to their graves." She used both hands to smooth out the furrows on his brow until she had him smiling. Something that betrayed a set of deep dimples in his cheeks. "There now! That's what would melt the coldest heart. No woman could ever resist a smile so sweet." "Sweet? You've gone completely daft." Standing, he tugged playfully at her braids. It was an action so out of character for Du and yet so completely normal for an older brother that it warmed her heart. "In spite of what you think, Duey, you are a kind man. A good man. And a fair one, to boot. Never let anyone tell you otherwise." He didn't speak, but the expression on his face was unlike anything Mara had ever seen. It was one of pure affection. "So what do you want?" There was a teasing note beneath those gruff words. "Pardon?" "I know you, Elf. You never compliment me unless there's something you've got your heart set upon." A blush stained her cheeks. "Who says I want anything?" He gestured toward her face. "That does. So tell me already." Clearing her throat, she reached for more thread and refused to meet his gaze. "I want to marry." His eyes flared red. As if sensing it, she glanced up and tsked at him. "Nay, you cannot disembowel him, brother. He has not laid a finger to me for fear of what you'll do to him. He's barely spoken to me." "Then how do you know he wishes to marry you?" She arched a brow. "Am I that intolerable?" "You know what I mean." Smiling, she wrinkled her nose at him. "I do, and we have spoken. He's merely a quiet man. Like you. He wishes to ask you himself, but is terrified of how you'll react. So I told him I'd approach you first to keep you from lashing out and gutting him before you've had a chance to acclimate to the idea of it." His nose twitched as if he were holding back a deluge of curses or an outburst. But after a few heartbeats, it settled down to a fierce tic in his jaw. "It's what you want?" "It is." "I suppose if you change your mind later, I can always kill him then." "Du!" "What?" he asked innocently. "I'm king here. Can do as I please." Shaking her head, she laughed. "You're incorrigible." Then she sobered and met his gaze. "Have we your permission?" "Only if he asks me himself. Then I shall give it." "Without a gutting?" "Aye." She arched one brow. Making a sound of supreme annoyance, he flung his hands out. "Fine! No denutting, either. Though that's being unfairly cruel to me, just so you know." She laughed again. "You'll survive." "And he'd best be good to you or else I'll tear him to pieces." Duel went over so that he could lean down and kiss the top of her head. "Love you, Du." He growled in response, then stepped away. "Don't you dare think for one minute that I'll allow you to move away from here. He's to move in with us. Final word on that." "Whatever you say, dearest." "Mean it, Elf. No planting of any rocks will be done. I won't have it. You keep you-know-what caged and around your neck or else I will have his nuts planted at my feet." "Aye, brother." Mara blinked as the scene faded. She wasn't sure why Elyzabel's harthfret had taken her there. Not until it flashed again and she saw the image that had driven Duel to madness. Against Du's words and threats, and at the insistence of her fiancé, his sister had planted her stone in the nemeton where Mara had been born. "Why here, my love?" Mercyn smiled at Elyzabel. "I was born in this forest. While my father's hall may be gone now, he told me that this would always be my home. That the trees here would shelter me and mine. So I wanted a piece of you placed here so that they can watch over you, too." But it was a trick. He didn't want Elyzabel as his wife. He wanted vengeance against Du for his own family, who'd been slaughtered during a raid that had been led by Du's father. The same raid that had destroyed that hall. A vengeance Mercyn had known he couldn't take until Elyzabel was separated from her harthfret and brother. That was how they'd managed to kill her—especially since she wasn't fully Deruvian, but rather half. Separated from her stone, she'd been unable to regenerate. They'd raped and slain her as a human woman. And left her floating in the lake where they knew Du went in the mornings to read. It was the cruelest thing they could have done. Mara gasped out loud as she saw his sister's brutalized, naked body as Duel had found her. Tears blinded her at their cruelty. No wonder he'd gone insane. Through his sister's harthfret, she could feel his anguished shouts as he sprang from his horse and called her name. Feel his heart shattering the moment he gathered her frail body into his arms and held her like a baby against his chest, willing her to open her eyes and live again. But they'd seen to it that she couldn't. Never in her life had Mara seen anyone so heartbroken. Heard more sorrow as he shouted his misery to the heavens and demanded the gods spare his sister and take his life in her stead. No one had answered him. That was the Duel she'd met as he'd torn her nemeton apart in an effort to find the ones who'd taken from him the only person who had ever given him kindness without cruelty or condition. The sole heart he'd held sacred above all others. The only person or family he'd had in the entire world. "Oh, Du," Mara breathed as she finally saw the truth of him. All he'd ever known was pain and loneliness. Heartbreak. Betrayal. No one had held him when he'd ached. Or grieved. No one. He'd gone through it all alone. Without friend or family. With her cursing and damning him every step of the way. That was why he'd hesitated that day in the forest. Even after everything they'd done to his sister, he'd refused to harm her. Because deep down, in spite of Mara's Deruvian magick and his desperate need for vengeance and blood to assuage his sister's death and his own guilt for not protecting Elf, he'd known that Mara was weaker than him. That she couldn't defend herself against him any more than his sister had been able to fight off her attackers. And rather than see her harmed or lay another innocent in her grave, he would have walked away and left her alone. Because, in spite of his ferocity, it wasn't in him to harm anyone who couldn't fight back against him. Du was not the savage beast she'd proclaim him. It's all my fault. All these centuries, she'd blamed him for something she'd done to herself. The truth slapped Mara hard and furiously. Duel wouldn't have gone after her sisters. He hadn't been burning the women. It'd been the men he'd attacked. They alone had been the ones he'd wanted to slaughter. Because they had been the ones who'd attacked his Elf. He'd been in so much pain. And no one had reached out to help him through it. So he'd lashed out, needing relief, and had sought it through the only means he knew. Violence and vengeance. Why didn't I see that before? Why hadn't she seen him before this? Because she'd been angry and afraid. Her heart pounding, she sat down on the bunk beside him and returned the ring to his finger. The last thing she'd ever do was separate him from this most precious piece of his sister. It was all he had left to treasure. No sooner had she settled it back in place than he took a deep breath and groaned. When he started to thrash about, she placed her hands against his chest. "Easy, Duel. You're injured. Do you remember what happened?" With a fierce grimace, he glared at her. "You smacked me in the head with the mast and knocked me to the sprites." Leave it to him to remember that part. "I also saved you from them." "You hit me first." He rubbed his hand across his stomach and winced. "Are you here to finish me off?" "Nay. I've been tending you." He scoffed rudely. "Really, why are you here?" She'd be more offended and outraged by his doubt had she not earned his suspicion. "Answer me one thing first. Had I not bound our lives together, what would you have done with me that day we met in my nemeton?" Devyl looked away, but she caught his cheek in a gentle grip that seared him all the way to his soul. How cruel it was that the only thing he'd ever craved was a tender touch from her. And it was the last thing she'd ever give the likes of him. Against his will, she turned his head until he was forced to meet her gaze. "I want the truth." "I wanted to kill you. Truth. When I first saw you, my only thought was that you'd be the perfect revenge for what they'd done. What they'd taken. To give back to them exactly what they'd done to my sister, in full brutal measure. But when I looked into your eyes and saw your fear, I knew I couldn't do that to you. For I saw no enemy that day. Only a frightened girl who was brave enough to stand when she knew she had no way to defend herself. And it infuriated me that your own had left you there alone to face me while they ran to save their own arses, like the very cowardly dogs they all were. That was the renewed fury you saw inside me. First, they'd violated and desecrated my blood, then they'd cast you out for what they thought to be the same fate. I wanted them all for that. None of them deserved your loyalty. Or your noble sacrifice." Tears welled in her eyes. "And my sister? Why did you choose her for wife?" Devyl ground his teeth at a question that burned even deeper. He didn't want to open himself up for her rejection. She'd cut him enough and he was done with it. He was too old to play these games. So he started to rise. Mara held him fast. "Truth, Dón-Dueli... please? I want to know why you married Vine." That simple, innocuous question wrung the most excruciating wave of pain from deep inside his soul. He'd had mortal sword wounds to his gut that hurt less. He had no intention of ever speaking about such anguish. To anyone. Not for any reason whatsoever. And yet the truth spilled out of his treacherous lips before he could stop it. "I wanted you and you wouldn't have me. So I let her seduce me with words I knew were false. I felt her coldness every time she touched me." "Then why marry her?" "She told me she was pregnant. I've never wanted anything more than the babe I thought she carried." Mara winced as she realized the lie. "She was never pregnant." "Something I suspected, but couldn't prove. She played her hand well and then told me that she lost the child not long after we married. Then promised me that there would be others. A home filled with them. Even at the time, I doubted her words, but you loved her and so I let her stay." She laid her hand against his cheek as she stared into the torment that haunted those dark eyes. All he'd ever wanted was for someone to love him. To have the very thing that others took for granted. And her people and family had robbed him completely. "I'm so sorry, Du. Sorry for the lies my sister told. And sorry for what my people did to yours. For what they took from you, personally." "I don't want your pity." "Good, because I don't offer you any." She toughened her voice with him, knowing he couldn't abide insincerity or patronization. He was too strong for that. Physically, mentally, and emotionally. "Then why this elaborate show?" She snorted at him as she sank her hand in his tangled hair and balled her fist in the silken dark strands. "For such an incredibly smart man, you're such an idiot." And with those words, she pulled his lips to hers. Devyl couldn't breathe as he tasted the passion she offered. Tasted a desire that he'd never known before. What fresh hell was this? But he couldn't think straight. Not while her tongue swept against his and she clutched at him with a hunger he'd never expected from her. Growling deep in his throat, he fisted his hand in her dress and pressed her body closer to his as he lost himself to a dream he didn't want to end. How many times had he fantasized about holding her in his arms and having her in his bed? He'd tortured himself with this. Lain awake for hours on end, knowing he could force the issue, and yet refusing to ever hurt her because her heart meant so much more to him than his own base needs. Indeed, he would bleed just to see her smile. A part of him hated that she had so much power over him. Hated that he couldn't stop himself from caring. He'd tried so many times to purge her from his thoughts and heart. Nothing had ever worked. The more he attempted to carve her out, the deeper she seemed to sink into his soul. A never-ending madness. Now this... He was lost. And only she could anchor him. Mara closed her eyes as she drank in the scent and taste of her irritating nemesis. And yet right now, she felt something so very different. Not an enemy, but rather a missing piece. It made no sense. She should hate him. Despise every breath he drew. And yet, for the first time ever, she didn't hate him at all. Not even a little. This wasn't a beast she held. He was a wounded man. One who'd been abandoned and betrayed by everyone he'd ever dared to let near him. And when he pulled away, she saw vulnerability in his eyes. Never before had he shown that to anyone. He'd always been so steadfast and strong. Incredibly cocksure. No weakness of any kind. He brushed his thumb against her lips. An action that sent chills down her spine. "What do you want from me, Mara?" "I don't know, Duel. Right now, I'm as confused as you are. I've spent so many centuries hating you that this concept of not... it leaves me at a loss. But I don't want to hate you anymore. If you can find it inside yourself to forgive me, I should like to try for a new label." "And that is?" She bit her lip as she considered it. If they weren't enemies, then what were they? What was left? "I'm not sure. Friends?" He snorted. "I want more than that, Mara. Much more." In truth, so did she. "I know. But I'm not sure how to give you that." He scowled at her. She smiled at his consternation. "I was scarce more than a girl when you plucked me from my nemeton. You're the only man I've ever been around, Du. Think about it." And with that she faded from the room to return to her nestling. Devyl felt his jaw go slack as he finally understood why her blood had always held so much power for his spells. So much power for him. She was virgin still. "How could I have been so stupid?" She was right. He was an idiot. Raking his hands over his face, he cursed himself for the fool he'd been. Normally, he could sense such things. Had no problem, point of fact. Marcelina had always been different. She was his weakness, through and through. Today, she'd almost been his death. I have to get rid of her. It didn't matter how much he might love her. She'd forever been his one blind spot. The one vulnerability in an otherwise impenetrable fortress. He rubbed his finger over his ring as he finally admitted the one truth that he couldn't escape. Mara didn't need his harthfret to control him. He'd been her hopeless slave since the moment he first gazed into those amber eyes. She owned him, body and soul. His only salvation was the fact that she'd been as blind to him as he was to her—that she'd never once realized he wasn't the one in control of their relationship. She was. For her, there was nothing he wouldn't do at her simplest command. That was why he'd brought her back to be their ship. He didn't want to be here without her. Even if it meant enduring her hatred and scorching condemnation. So long as she spoke to him in any manner, he'd take it. But no more. It was time that he severed their tattered past and let her go. All things came to an eventual end. It was time he cast away his heart and made sure that nothing stopped him from what was to come. He was the one who'd given Vine her powers. Who'd enabled her to become the threat she was. Thorn had charged him with protecting the world and that was his duty now. He couldn't let anything else get in the way. Not even Mara. And certainly not himself. Nay, he would give his life to this cause. That was the way of it. There was no other outcome to be had, and he knew it. Mara groaned as the tumultuous sea crashed against her sides and battered every part of her. For hours now, the storm had surged violently as if trying its best to send them to the bottom of the ocean. All of the crew had taken cover belowdecks. Meanwhile, she lay in her bunk, sick to her stomach, wishing for any reprieve from this misery. It was so bad, she couldn't even change forms for it. The last thing any Deruvian wanted was to regurgitate in their wooden form. That was a sight and sensation no one needed. Ever. And just when she didn't think she could take another minute of it, strong arms pulled her against an equally hard chest. "Drink this." "I'm too sick, Du." He brushed the hair back from her cheek. "I know, love. This will help." He lifted the cup to her lips. Convinced she'd return it within a few seconds of swallowing, she obeyed. But as she got a bit of it down, it did indeed ease her nausea. After a few minutes, her headache began to lessen, too, and it was only then that she realized Duel was in the bed with her, holding her against his warmth while he rocked her in time to the sea. He set the empty cup on her nightstand. But due to the storm, it didn't stay there. Rather, it was thrown to the floor and rolled across the boards to land in a corner. "What was in that?" "Ginger root. Peppermint. A little honey..." When he didn't continue, she arched her brow at him. "And?" The corner of his lips lifted into a teasing half smile as he smoothed her hair around her face. "Best you don't know." Laughing, she let out a small groan as another wave went through her. "How much longer till the storm passes?" "The worst of it is over. The sea should settle within a few hours." "A few hours?" she moaned. "I shan't make it." He snorted at her misery. "Sure you will. Just think about something else." "Like what?" The teasing light remained in those dark eyes and for once, she caught a glimpse of the dimples she'd never known he had until very recently. "How much you hate me." Impishly, she placed her hand over one of those beckoning deep indentations in his cheeks. "I told you, I don't hate you." "Anymore." Grimacing at his continued torment, she glared at him. "I'm too ill for this, Duel. Please don't harass me." She dropped her gaze down to the bruise on his arm from his fight earlier that day. "How are you feeling?" "Honestly? I'm in agony." "You handle it well." Much better than she did. "'Cause I'm used to it." As he started to withdraw from her bed, Mara stopped him. "Stay with me and hold me. I've no wish to be alone when I feel like this." Rolling to give him her back, she snuggled up against him and rested her head against his muscled arm. "I haven't had any comfort in so long.... I miss it terribly." Devyl winced as guilt stabbed him hard at those whispered words. He was the sole reason for that. Had he not removed her from her home, she would have been with her family and friends. Not locked in his hell where she sought to avoid all contact with him and his people. Or worse, kept in stasis because of his magick. Wanting to make it up to her, he settled down behind her and pulled her back against his chest so that he could hold her in the dim light. Before he could stop himself, or think better of it, he caressed the softness of her silken cheek. Thoughts of what could have been haunted him and tortured him. If only he could go back in time.... Closing her eyes, she let out a contented sigh. But he was far from satisfied with this small bit. Rather, his body was rock hard and aching for the one thing he knew she'd never give him. And now that he knew she'd never been touched by another... That was out of the question. He'd purposely avoided virgins. They were a complication no man needed. He preferred women who knew their own minds and bodies. Those well experienced who didn't get their hearts entangled needlessly. Yet therein was the problem. Her heart was something he'd wanted since the first day they met. And for once it wasn't to feast upon it out of vexed frustration. Squeezing his eyes shut, he tried to banish the part of him he hated most. That weak, insipid, useless piece that continued to crave frumpish things he knew he couldn't have. Home. Family. Love. Those were for better men. Never were they meant for the likes of him. And as he lay there, harder than hell, the unthinkable happened. She trailed her hand down his forearm until she laced her tiny fingers with his. Then she brought his hand up to rest between her breasts so that she could snuggle against it. "Why do you tremble so?" she breathed. Because her gentle touch humbled him. It wrought a foreign tenderness inside him that wanted to protect and hold her forever. But he would never admit that out loud. "I'm trying to respect you, my lady." Mara rolled slightly so that she could meet his gaze, which swam with emotions she'd never seen there before. The moment she did, she felt his erection against her hip and saw the vibrant red color of his eyes. "Are you angry?" "Nay. Too hungry to feel any other emotion." "Then you should eat." He gave her that handsome, adorable, crooked grin of his. "It's not food I be craving." Her heartbeat picked up speed. "Would it take my mind off the storm?" Again, he tried to pull away. But since he didn't use his powers, she knew that he didn't really want to go. "Duel?" "You have to leave, Mara. So long as you're here, I can't do what I need to." "And what's that?" "Stay focused on closing the Carian Gate." "If I go, a regular ship can't protect you or the crew the same way I can. You know that. It's why you awakened me from hibernation." "I'm a Deruvian, too. I can do it." She arched a skeptical brow. "Have you ever?" He looked away. "Nay, you have not," she chided gently. "You've spent the whole of your life hiding those powers, haven't you? And you'll find it's not as easy as you think. You learning to bend the laws of nature to make and run a ship would be the same as my trying to learn swordplay. You can't just pick up and run until you've mastered crawling. And you have yet to stand on your own with those powers." Refusing to release her grip on his hand, she pulled him back into her arms. "We have been together far longer than we lived as single beings, Dón-Dueli. By Deruvian law, we would be considered married." Devyl swallowed. What she said was true. Deruvians considered marriage to be any communal arrangement where two of them took care of each other and cohabitated. Where two unrelated by blood were dependent upon each other. As much as he wanted to deny it, he needed her with him. He always had. "And what about your sister?" "She's a widow by her own hand. You're free to marry another." Dagda's hairy toes, how he wanted to believe that. Nay, he needed to believe it, but... "Is this a trick?" She pulled her necklace over her head and placed her harthfret into his palm, then closed his fingers around it. "No trick, Du. The more I think it through, the more sense this makes. I've known no man save you. I can't imagine my life without you aggravating me." He laughed bitterly at those words. "I aggravate you?" "'Deed you do. All the time." Sinking his hands into her hair, he kissed her playfully. This was all kinds of madness. To even contemplate it... But as she said, he couldn't imagine his life without her in it. And if she would have him, then he had all the more reason to fight Vine and win. All the more reason to see this through to the end and come out of it alive. If Mara truly meant what she said, then he would see his soul redeemed. Her words gave him hope for the first time in his life. A reason for living past the closing of the gate. And he was desperate for that future. For any future that didn't leave him alone. She pulled his shirt off. Devyl froze, half expecting her to change her mind and order him from her room. Instead, she ran her hand over the scar across his ribs where he'd been stabbed centuries ago in battle, and then to the jagged remains of where Vine had cut out his heart. That gentle touch set fire to his blood, but not half as much as when she dipped her head and replaced her fingers with her lips. The chills and desire awoken by her breath on his flesh wrung a fierce groan from him. Never in his life had he experienced anything like this. Unable to stand it, he lifted her across his chest and rolled so that she rested on top of him. Mara smiled before she nipped at his whiskered chin. This was a miracle and she knew it. For the first time, she didn't see his mistakes or shortcomings when she thought of him. She saw only all the thoughtful things he'd done for her over the centuries. Such as making sure she was cared for. That she had her own small nemeton in the courtyard grounds of his hall when they'd lived in Tintagel. Small matters, really, and yet he'd taken great care of them all, to ensure that she had everything she needed. Closing her eyes, she held him close as she remembered the way he'd looked just a few months ago when he'd awakened her from her slumber. She'd been so angry to find him in the shadows of an abandoned abbey. So terrified of the foreign landscape that had seemed eerily familiar and completely alien. "What is this? Where am I?" "You swore an oath to protect the Myrce." It was, after all, what her name, Marcelina, meant. "They're being threatened and I need your help to banish their threat back before it eradicates the last of the people you guard." Stunned, she'd stared up at him in total disbelief. "I saw you dead. How are you here?" Dumbfounded, she'd glanced around the overgrown courtyard. "How am I?" "I was returned to life to fight the threat. Because I'm back, so are you. Are you with me for this?" She'd nodded without full understanding of what he was proposing. Without knowing about Thorn or his Hellchasers, or the fact that it was her sister they'd be up against. While her people weren't warriors like Duel's, they did use their magick to control the elements and to shield those who came under their protection. Their idea of battle and war was vastly different than his. And his people had no concept of love. At least that was what she'd always been told. But as she met his gaze and saw his tender expression and felt the hesitancy of his touch, she finally knew better. He did know what love was. It showed in everything he did for her. All those little things that he'd gone out of his way to ensure were done to make it easier for her, such as having food ready, or lodgings. To guarantee that she was always respected. Seeing him clearly now for the first time, she lifted her hips as he slid her nightdress up so that he could skim his hand over her thigh, to her waist. A moment of panic went through her at the shocking contact, but she forced it away. There was nothing to fear with Duel. Of all beings, he wouldn't hurt her. Not intentionally. She knew that without a doubt. He left her lips so that he could kiss his way down her body, to her exposed belly. Hissing, Mara sank her hand into his wavy mass of soft black hair and held him closer to her as his hot breath caressed her skin. Devyl took his time sampling every inch of her skin, and especially her breasts. He still couldn't believe he was here and that this wasn't a dream. That she was finally allowing him to have her. How many times had he imagined being with her like this? Dreamt of her touching him with something other than scorn or hatred? And the reality was so much better than anything he'd ever concocted in his fantasies. Licking his lips, he pulled her gown over her head, then rolled to trap her under him. "Are you feeling better?" She touched her nose playfully to his before she answered. "You were right. My mind is completely off my misery." Too bad his wasn't. The pain of wanting to be inside her was excruciating. And it took every bit of his will not to rush, but this was her first time and the last thing he wanted was to ruin it for her. Or worse, cause her pain. A smile tugged at the edges of his lips as she bashfully reached for the waistband of his breeches, then hesitated. He kissed her again. "You can touch me, Mara. I promise you, I won't mind at all." A bright red blush crept over her cheeks. Tsking at her, he took her hand into his and slowly guided her toward his cock, then showed her how to stroke him. Mara bit her lip as she watched the pleasure play across Duel's face. He was so hard and soft at the same time. Like velvet stretched over steel. That familiar tic returned to his cheek as he growled deep in his throat. It made her feel powerful to hold him like this. To know she controlled his pleasure. At least until he returned the favor and began stroking her intimately. Arching her back, she cried out at the most incredible pleasure she'd ever felt. What was he doing to her? But even more incredible was the unexpected surge it gave her powers. They sizzled through her body. "Can you feel that?" she whispered. "I feel it." Mara gasped as she realized that his eyes were no longer red or dark. They now glowed a vibrant amber... the color of a Deruvian magus's eyes. She trembled at that significance. "How much power do you wield?" "My grandfather was the king of the Adoni, and my mother a daughter of Yggdrasill." Mara's head swam at that confession. A daughter of Yggdrasill would have held unbelievable powers. No wonder he could predict the weather. Which made her wonder... "Can you control the elements?" "I can summon storms, but not banish them. And I can command lightning, but the control of the sea is beyond my abilities." That sent a shiver over her. "And from the Adoni?" He nuzzled her neck as his hand sent ribbons of pleasure through her. "Is this really the conversation you wish to hold right now?" She blushed again at his question. "I'm just trying to understand you." Devyl nibbled her collarbone. There was nothing for her to understand. Not really. He was terribly uncomplicated. Just a broken man who was bent on vengeance. Of course that was a little more complicated given the fact he doubted Mara would stand by while he took her sister's head. The one thing about Mara, she was loyal to a fault. There was nothing she wouldn't do for her sister. Worse, he held a secret that, if she ever learned it, would guarantee her enmity for all eternity. But he didn't want to think about that right now. Not when her warm, supple body was beneath his. His heart pounding, he pulled away long enough to remove his boots and stockings. Mara traced the scars on his back with her nails, sending chills over him. "Are all these from battle?" "Nay," he said gruffly. "My father was a firm believer in the lash. As was my mother." "I'm sorry, Duel." "It doesn't bother me." That was the truth. Perhaps there had been a time in his childhood when it had, yet he couldn't recall it. "Better me than either of my sisters." She rose up to gently kiss his scars. He sucked his breath in sharply. And when she wrapped her arms around him, he lost himself to her completely. Dagda help him. He wanted to die in this moment. To end eternity right here and now on this one perfect feeling of being wanted. Desired. He could almost believe that she loved him, and that was the worst of all. Because he wanted it to be real. He wanted this fantasy. Craved it with everything he wasn't worth. But it was bullshit. He had no doubt. And yet... His hand trembling, he undid his breeches and slid them from his body. Mara froze as she saw him completely bared. Not that she hadn't seen him that way before. Many times. He'd never been a particularly modest person. Point of fact, he'd seemed to delight in embarrassing her. But this was very different. "Are you all right?" She nodded. "I haven't changed my mind." "Good." A tiny smile played at the edges of his lips before he leaned her back on the bed and covered her with his warmth. She sighed at the pleasant weight of him, reveling in it and in the massive size and hardness of every inch of his flesh. His body felt incredible against hers. And when he slid himself inside, she cried out and clutched him as pain overrode her kinder thoughts where he was concerned. She sank her nails into his back. He held himself completely still while he kissed and nuzzled her. "Breathe, blodwen. I'll never hurt you. I swear. It'll pass in just a moment." Mara choked on a sob at his endearment and kindness. Blessed flower. For their people, that was reserved only for those who resided deep within your heart. And it wasn't an endearment bandied about idly. No one used it unless they meant it. To a Deruvian, it was as sacred as saying I love you. Pressing her cheek to his, she cradled him with her body. "I love you, too, Duel." He rose on his elbows to stare down at her in disbelief. "What?" "You don't have to look so stunned. Is it so hard to believe that I feel the same?" "A little bit. Aye." She snorted at him and his continued suspicion as she brushed at his long hair that fell forward to frame his face. How strange that such a simple thing could make so ferocious a beast appear boyish and vulnerable when she knew full well he was neither of those things. "Not exactly the reaction I was wanting, Captain." This time, he gave her his full dimpled smile and charmed her completely. "You've stunned me past all rational thought, my lady. Therefore, you'll have to have a bit of leniency with me while I acclimate to hell freezing over." Laughing, she kissed his lips. Until he started to thrust against her. She bit her lip against the pain, but as he'd promised her, it quickly subsided into the most incredible pleasure she'd ever felt. And to a deep intimacy that overwhelmed her. He locked gazes with her as he stroked her with his entire body. Honestly, she didn't think anything could feel better or more personal. Not until he quickened his strokes and thrust so deep inside her that it splintered her. The moment she came, her powers shot out and echoed around the room in a vibrant ricochet similar to lightning. Duel caught them with his powers and laughed as he absorbed them to keep her blasts from doing harm to the ship or the lanterns. But his own laughter died a moment later when he found his own release. And with it came a new charge to her Deruvian abilities. It was unlike anything she'd ever encountered. Colors exploded through the room, raining down over them like a spring shower. She not only felt and heard the aether. She saw it. Nay, she saw the very fabric of the universe that bound together every creature that was both living and gone. Her breathing labored, she struggled to get a handle on it and understand what was happening and why. "Duel?" "It's all right, my love." Rolling over, he pulled her across his chest to cradle her there and comfort her rising panic. "It's a by-product of what we are. There's nothing to fear. It'll pass in a moment, but you will be stronger." He was right. With every heartbeat, she could feel the charge inside her. "No wonder Vine sought you out so much." He took her hand in his and placed it against the center of his chest, over the scar where her sister had cut out his heart. "I never did this with Vine. I wouldn't allow it to happen." Those words baffled her. "What do you mean?" "We had sex. But it never charged our powers. I never gave that part of myself to her, as I knew what she'd do with it. And I'm a fool for letting you have it now, but I couldn't stop it from happening. My feelings for you run too deep. There was no way for me to pull it back before it happened. I'm afraid I have no control where you're concerned." "How do you mean?" That familiar dark shadow returned to his gaze and saddened his eyes. "I know about your bargain with Vine, Mara. I'm well aware of the fact that you're planning to hand me over to her to get yourself free." "Thank you, Miss Jack." Cameron smiled up at Kalder as she knotted the bandage on his arm. "My pleasure. You should be more careful while you climb about the rigging in a storm. You could have been killed." He snorted as he reached for his mead on the galley table. "Not really at the moment. Just would have injured me pride more than me head. Oh, wait! It did. Teach me to not pay attention in a tempest, but then to have such a beautiful lass tend me wounds, it was worth a little flesh off the bones and lost dignity, I think." Blushing at his unexpected compliment, Cameron paused her hand over the marks on his skin that appeared as tattoos. She knew now they were his fins. How strange that they lay so flat whenever his skin was dry as to be indistinguishable from his flesh. Indeed, there was no difference whatsoever. He appeared completely human. What a strange thing to have happen. "Does it hurt when your body changes?" He screwed his face up as he kept his arm completely still in her lap. "No more than you with yours. Just a mild sensation really. I barely notice it." Realizing that she was holding on to him a lot longer than she should be, she quickly released his arm and put more space between them. Even though she didn't want to. There was something about Kalder that drew her to him a lot more than it should. He was a very handsome man... for a mermaid. And that thought made her smile. "What are your people really called? I don't think 'mermaid' quite fits you." Nay, it definitely did not, as he was more masculine and handsome than most of the men on the ship. There was something innately deadly and fierce about him. Something that made the Seraph blood in her quite literally hum whenever he drew close. Kalder laughed at her words. "For the record, Miss Jack, I hate to be called a mermaid. It sticks in me fins a bit, but don't let the others know or there will never be any peace from the bloody bastards for it, as they'll assume it to be a personal challenge to make me life hell. Especially Bart." He winked at her. "We're correctly called Myrcians." "Like the medieval kingdom?" "Aye. Those were some of us originally. Till they mingled with humans and lost the ability to breathe water. They kept the name, for reasons only they know. However, they were only one group of many of our tribes. At one time, we were found all over the world, in great numbers, but war and angry gods have thinned us down to only a small handful these days." "I'm sorry." He shrugged nonchalantly. "It doesn't help that we're a belligerent bunch, by and large. Sooner fight than do anything else." He passed a teasing grin over her body. "Some of us, that is. I meself have that tendency. But I can be persuaded to other, much more pleasurable endeavors... if the company be right." This time, her cheeks heated to a volcanic level. What disturbed her most was the fact that she wasn't offended or even all that adverse to what he was suggesting. Indeed, she was nowhere near as mortified as she should be. And definitely not insulted. Rather, she was drawn to him against all sanity. "I find it hard to believe you'd be belligerent, Mr. Dupree. You seem exceptionally kind and sweet." He slapped his hand over his heart. "Ah, lass, you wound me to me core. And call me Kalder, please. 'Mr. Dupree' sounds like I ought to be in some posh coat and hat, issuing orders. Me people don't run on such formality." She shook her head at his cheerful play. While "surly" definitely described a certain large proportion of their crew, Kalder most assuredly was one of their more jovial members. "You seem rather easygoing to me." He sobered at that. "Looks are deceiving. Let's just say there's a good reason I was gutted." "Aye to that," Rosie chimed in as he walked by and handed off his rum bottle to Kalder. "You're on his good side, Miss Jack. Trust those of us who are permanently engraved on the bad end—you'd gut him, too. Especially in the morning. He's a beast of a fish, then." She didn't believe it for a minute. Kalder laughed, and took a drink. "Hey there! What's that sound?" William cocked his head. Cameron didn't hear anything other than the storm—which was concurred by the others as they responded to William's question. They heard nothing either. Not until Simon suddenly lifted his head from where he'd been resting in the corner. "I hear it now. It sounds like... takarum!" Bart cursed as he shot to his feet. Kalder and the rest did the same. "Takarum?" Cameron scowled at the unfamiliar term. Since she had no idea what it was, she was much slower to rise to a battle station. "Souls of those who've died at sea." Belle and Valynda moved to stand by Zumari. "They're here to find bodies so that they can possess them." "Or those they can take down to the locker to replace themselves so that they can go free and live again." Simon crossed himself and spit. Cameron's hair went white. Her back began to burn as if her wings were trying to break through the surface of her skin. They were right. Whatever was here wasn't human. And it was here for prey. "Where's Janny?" Belle glanced about for the Dark-Huntress who'd been playing cards with Sallie, Kat, and Roach a few minutes ago. Valynda's eyes widened. "She went to the privy." Unsheathing his cutlass, Simon cursed. "She'd be the one they'd want most. We have to get to her afore they do." Cameron was confused by that. "Why would they be after her more than anyone else?" "Janny's soulless already." Belle pulled a torch from the wall and lit it. "They wouldn't have to struggle to take her over. Nor take her to the locker. They could move right into her body and make themselves at home." She ran for the door. Cameron rushed after her with the men following closely behind them. She was just about to ask what she should be looking for when she saw a shadow move off to her right. And not the way they normally did. Rather it came toward her like a vicious predator. More than that, it appeared to have dreadlocks and a skeletal form. One that developed fangs and bony fingers. With a whispering rattle, it reached for her. Kat grabbed her and pulled her back, out of its reach. "Don't let them swarm you. That's how they claim their victims and drag them down. If they pull you from the light, you're done for!" "Stay to the light!" William warned. Rosie used a torch to scatter the takarum back into the crevices of the ship. They made a peculiar scurrying sound that was similar to that of bat wings and rushing rodents, and yet unique to the beasts. "Aye to that! They fear light and fire. It's the only thing we have to fight them with." Yet a takaru doubled back through the shadows, and grabbed another sailor who was at their rear. With a scream, he was pulled into the shadows and then vanished as if he'd never existed at all. Only a faint image of his screaming face was left behind as an impression in the dark wooden walls, and the faintest of outlines of his body. Cameron froze as she realized he really was gone. Completely. Those... those things had dragged him away quicker than she could blink. The others scrambled to light the corner, but it was too late. "Is there any way to get him back?" Belle shook her head. "It's done. Whatever you do, lass, don't let them sink their claws into you." "Janice!" Simon shouted, rushing past them. "Can you hear me?" More of the takarum crept across the boards, reaching out for them like insidious puffs of smoke that only the light could disperse. Valynda handed Cameron a torch. Cameron swung it as one of the shadows reached for her. She twisted out of its reach. Bart tried to open the door, then cursed. "We're sealed in with them." William scowled at those words. "What do you mean?" "I mean we're locked down here." He kicked at the door as hard as he could. It rattled on the hinges, but didn't give at all. "Someone's latched it from the other side." William tried the handle. "What the hell?" Zumari shoved them aside so that he could try it, but as when they'd attempted it, it didn't budge. The anger in his eyes said that he was about to have a fit to make a toddler proud. Cameron felt her cheeks growing warm as she tried to think of a way out of this mess. The room grew darker and darker as more shadows closed in on them. The torches began to dim. What new hell was this? Suddenly, she heard her brother screaming outside, in the hallway. Her jaw went slack. "Paden?" She headed for the sound. Simon caught her by the arm. Fighting against him, she tried to get free. "It's me brother!" "It's a trick." "Nay! I know his voice!" He picked her up and tossed her over his shoulder, refusing to let her go. "'Tis their cruelty, lass. Trust me. Your brother's not there. It's a lure they're using." It didn't feel that way. Nay, she even smelled his cologne. "Paddy!" she called. "Is it you?" "Cammy-belle? Where are you? Help! I need you!" "It's him!" Cameron fought with renewed vigor against Simon's hold. And she'd almost succeeded in gaining her freedom when something struck the ship so hard, it knocked it off keel, tipping it dangerously to the starboard side. They all stumbled, fell, and rolled to the starboard wall. Everyone paled as objects skittered across the boards and slammed into them. Several sailors screamed out as the takarum reached from the shadows and claimed them. Valynda and Belle combined forces to form a shield wall while Bart and William were forced to extinguish their torches or risk setting the ship on fire. "Where's the captain?" No sooner had Roach asked the question than a booming voice answered. "On deck! Now! All of ye! Move your sorry arses!" There was no missing the fury in Captain Bane's tone as he ripped open the door that was no longer locked. He and Marcelina came into the room and helped them up, and then one by one they left the room until they were outside in the rainstorm. The ship finally began to right itself so that they could stand on deck and not risk being swept overboard. "Stay out of the shadows," the captain ordered them. "Sancha, head us due north toward the Quella." "Aye, aye, Captain!" She ran to obey him. As he started below again, Cameron stopped him from his descent. "They have me brother, Captain." He paused to meet her gaze. "Nay, lass. I fear something a lot worse than the takarum has your brother. Now stay here and let me clear them." He gave her a gentle push back toward Marcelina before he vanished through the hatch. She turned toward Mara and scowled. "I don't understand." Marcelina handed Cameron the medallion she'd loaned to Thorn. "Paden's been seduced by the darkness, child. He's no longer the man you knew him to be. Rather, he's someone else entirely." Nay, Paden wouldn't have done that. She knew better. "I don't believe you." Thorn came up on deck, not far from them. "Believe it. I did everything I could. I'm sorry, Cameron." Nay... Nay! This wasn't right. Cameron could feel it deep in her soul. But she didn't know how wrong things were until a moment later when William and Belle swung about. "Cameron! Avast! Them ain't Thorn and Mara!" "They be shifters!" Belle warned. "Duck, lass!" Before Cameron could move they seized her and swept her overboard. "Duel... it's not what you're thinking." He arched a brow at Mara's whispered, guilt-ridden words. "Then you're not intending to hand me over to your sister as soon as we reach the gate?" She cringed as she realized that he did indeed have an exact handle on her original plan. Pity, that, for her, anyway. "It was the plan.... But things have changed." "I'm sure of that." Sarcasm dripped from his tone. A sarcasm Mara didn't understand given all that had transpired this day. "Meaning what?" No sooner had she asked the question than she understood exactly where his thoughts had gone. And why. Her jaw went slack. "You can't honestly think that I'd have seduced you for that! Can you?" "To make me more pliable for your wiles and an easier fool to manipulate? Aye. It's the exact kind of treachery Vine specialized in. So why not you? As her sister, it makes complete sense." "How dare you!" She raked a furious grimace over him as she felt an urge to do him bodily harm. Pushing herself up, she wrapped the sheet around her body to glare down at him. "And if you truly thought that and slept with me anyway... you're... you're despicable!" It took everything she had not to reach out and slap him for such an insult. Relief filled his eyes as he reached for her and pulled her back to the bunk. "Don't be angry at me, Mara. 'Tis glad I am that you're not that treacherous. But can you blame me for being a mite suspicious after learning you'd made such a pact with her behind me back when you know how she did me?" When he put it that way... She still wanted to punch him on her basest level. However... "Don't you dare be reasonable in this, Dón-Dueli. Not when I want to be mad at you for that insult you just dealt." He snorted at her agitated tone. "Well, far be it from me to deprive you of anything, love. If you want to beat me arse, I'll even get naked for it...." He lifted his bare leg out from beneath the covers to wiggle his toes at her. "Oh, wait, I already am." The teasing finally returned to his eyes. Yet even so, the hurt beneath those words wrung her heart and she hated that she'd caused him even an instant of pain or doubt, because she knew how much treachery had been served so coldly to him in his lifetime. It was the last thing she'd ever do to him now. As he said, it was her sister's specialty. Never hers. And she hated herself for ever having conspired with her sister to do him harm. Surely, there was a special corner of Annwn reserved for her punishment. "I won't betray you, Duel. I swear it." He cupped her cheek in his warm palm. "Then I shall put forth all my meager faith in you." But she saw the shadow of doubt that remained in his eyes and it made her ache all the more. Not because he felt it, but because she knew that she honestly deserved it. That she had earned his mistrust. I swear I will make you believe in me. She had no idea how, but she'd find some way to erase that doubt. Come the devil or the sea, she would prove it to him. Beyond any reason. Du would know that she was sincere, and that in her he had at least one person in his life that he'd never again have to fear betrayal from. Suddenly, they heard a loud clamor, on the top deck outside. "I thought everyone was below for the storm?" Duel scowled. "As did I. I told them not to risk it." Getting up, he quickly dressed and went to see what the noise was about. She dressed and followed suit, only to find the crew scrambling to retrieve Kalder from the raging sea, where he must have fallen overboard. Yet how strange. It wasn't like him to ever lose his footing for anything. Even in a storm. He only did that whenever he was trying for the attention of a maid—and usually then, only on land. A ploy Devyl and the others had oft chided him over. But surely, Kalder wouldn't have tried that in this storm.... Especially not with the women onboard. He'd respectfully kept his distance from them all, since they lived in such close proximity. And, in spite of Kat's and Simon's rather untraditional marriage, it was forbidden by Thorn for them to fraternize. A rule Devyl had just broken with Mara, but he'd deal with that later. Mara hesitated on deck as she took in the frenetic madness. Rushing past the shouting crew trying to pull Kalder from the sea, Duel didn't hesitate to dive in after him and be swallowed by the black, crashing waves that sought to drown them both. She ran to the side, wanting to yell and curse him for his reckless stupidity that never failed to frustrate her. Terrified of the way the giant surf surged and ebbed like mountains, Mara choked on a scream and watched with her heart in her throat until she finally saw Duel break the surface to bob and float above the dangerous mess. Against all odds, he quickly made his way to Kalder and somehow, in spite of the furious waves, he helped the Myrcian back to the ship. She used her powers to lengthen the wood and scoop them both out, taking extra care to cradle Duel. Coughing and wheezing, Kalder crawled up her planks to lie on deck while Belle swept her jacket off to lay it over him. Mara carefully placed Duel at her feet and checked on his condition, but he'd have none of her coddling. With an irritated grimace at her fretting over him that was softened by a peeking dimple in his cheek, he rose and squeezed her hand gently in his, then pressed past her to examine Kalder. "What happened?" Duel demanded, kneeling beside the merman. "Bastard shifters took our Miss Jack." Bart added his jacket to Kalder's shivering body so that he could use it to blot the water off his skin and hair. "We were trying to stop them from fleeing when lackwit Kalder jumped in after them in an effort to save her. Sadly, didn't work." Duel cursed. "Anyone else go over?" William shook his head. "They be the only two, Captain. Miss Jack and Shite for Brains. But we did lose a couple below earlier to the takarum." Ignoring the epithets he agreed with, Devyl met Mara's fretful gaze and bit back what he really wanted to say. Instead, he let out a long, tired sigh. Damn it all. He hated to lose any member of this crew. For anything. Things were getting bad. Worse? He was getting desperate. Devyl ground his teeth. "You know, when I become the sole voice of reason in any given affair, we're in a sad, sorry state, mates." William laughed, until he met Devyl's sinister grimace. That quelled his mirth. "What are your orders, Captain?" He glanced over his shoulder to where Belle and Janice stood, both soaked as much as Kalder. And that gave him an idea.... "We need to raise a water witch." Sancha laughed out loud. "I'm not that drunk, Captain." "Then you need to grab yourself some more rum, Miss Dolorosa, for that be the next step. We're going in for a long, deadly haul." Belle paled considerably. As did Janice and Kat. "Have you ever raised a witch of that magnitude, sir?" "Aye." But it'd been a while and hadn't gone very well. They tended to be cantankerous bitches, hence the boo-hag moniker they'd earned. With no better plan, he locked gazes with Mara and waited for her to join the others in calling him a fool. "Are you sure about this, Du?" Not even a little bit, but he couldn't let the others know how much he doubted his own intelligence in this. Or his abilities. "We can't leave Miss Jack with them. Signal to Santiago, and we can transfer the bulk of our crew to his ship. I'll need a few volunteers to—" The sound of their protests drowned him out. But none were louder than Mara, Bart, and William. "We're in this together, Devyl," Will said. "To the end. Come what may. Ain't a man-jack or molly here what's going to leave the others to burn." "Aye!" they shouted in unison. "We burn together!" "But I'd rather we try other means, first." Valynda cleared her throat as she spoke over their raucous voices. "Not that I'm afraid, mind you. Just, being made of straw, would rather we think about it first. And set fire to our enemies before we give up our ghosts so cavalierly." "Hear, hear!" Zumari agreed. "Died once. Not eager for a repeat." Sallie snorted. "Bugger that. I say we set the whole of the world on fire. Damned be he who cannot fight and get out of our way!" "Oui!" Roach clapped Sallie on his back. "Make the blackguards rue that which birthed them and the very air we breathe!" William grimaced. "You mean they breathe?" "Non! They should regret that we breathe, for we will make them weep at all the wounds we give unto them. I piss down the throats of the swine!" Laughing, William clapped him on the back. "Thieves, drunkards, lunatics, wastrels, and whores we might all be, but there ain't a coward among us." Sancha crossed her arms over her chest as she dared Devyl with her gaze to try and move her from the ship. Devyl wasn't sure what to make of this camaraderie. Honestly? It scared the shite out of him. He'd never known it before. Not even his own army had been that loyal. Rather, they'd been too scared to raise arms against him for fear they wouldn't kill him. Only anger him so that he'd disembowel them for the affront. But that being said, he was all about going after Miss Jack and her brother and seeing this made right. Whatever the cost. Even if they did have to set the world on fire as Sallie wanted. Bart handed him a towel. "The shifters pretended to be you, Captain. They told us to head toward the Quella." "Well then, let's not disappoint them. Full speed. Storm be damned, me hearties. In the meantime, let's see about conjuring us up a hag, shall we?" Mara groaned out loud, finally giving voice to the doubt he expected from her. "By all means, open the door to hell and unleash someone even more terrifying than Vine. Why not?" She rolled her eyes and shook her head, then narrowed her gaze at Devyl. "Are you sure we need to? Shouldn't we call for Necrodemians instead? Thorn said we could." Devyl snorted at the thought. 'Twas the last thing he'd ever do. "I'd sooner trust Vine. At least I know where I stand with her. Problem with good men... you never know when they're going to do something evil in an attempt to make something right. Personally, I like stability in battle." He pulled his flintlocks from his belt and handed them to Bart who, in turn, scowled at him. "Should I ask, Captain?" "You never want a water witch to lay her hands on gunpowder, Mr. Meers. Even if it be damp. Disarm yourselves, everyone. It's not worth what could happen." "He's right." Mara glanced about. "Make sure all the powder's put away before he embarks on this next round of idiocy he's set himself to." Devyl smirked at her recitation of his idea, but didn't bother to correct her words. Mostly because she wasn't wrong. It was just irritating to have her undermine him out loud before their crew. Belle paused beside Devyl to stare up at him with a knowing grimace that melted into a smile. "Feeling better now, Captain?" He bit back a groan at her silent insinuation. "Don't be getting cheeky with me, Miss Morte. Me humor's still not restored fully." Her gaze slid to Mara. "I'd wager otherwise." "You know, I ate the last crewman who annoyed me." She laughed at that. "I'm not worth the indigestion, Captain." And with that, she flounced off to clap Mara on the shoulder and kiss her cheek. Trying not to think about the fact that he was actually embarrassed, Devyl waited until all the weapons and powder were secured before he and Janice began the conjuring necessary to summon the witch up from the ocean. And not just any hag. The handmaiden of Tiamat herself. Some said she'd been banished to the bowels of the ocean as punishment by a jealous goddess who envied her for her beauty. Others claimed it was a coven of other witches who'd been commissioned to chain her there by women who were sick of her preying on them and their men at night while they slept—that she'd visit them in the form of a cat and suck away years of their life so that she could maintain her beauty and immortality. The latter being what they attributed sudden sea storms to in this region. It was the old sea hag needing souls to maintain her longevity, and the only way she could get them to her prison. None ever returned from her watery home. He turned to Mara. "Can you hold her after I summon her?" She arched a brow. "Did you mean to insult me?" "Nay, love." He winked at her with a laugh. "I'd never do such... out loud. Besides, I'm about to put my life in your hands. But I didn't want to put your life in danger. If you need reinforcement, I'd rather get it now than summon her and find out too late that she's more powerful than we thought. Last thing I want is to have to cut me own throat for allowing you to be harmed." Mara choked on a joyous sob at those words. Words that Dón-Dueli wouldn't say lightly, which made them all the more valuable. While he might be protective, he never spoke publicly about such things. To say it for others to overhear... I love you, too, my surly beast. He left her side to instruct Simon to signal to Rafael and his crew what they were about while they brought the ship around to head for the area where Strixa was known to prey on unsuspecting vessels. Kat watched Rosie, then Devyl, as the sea kept the ship rocking while the storm continued to rage. "And do we know for a fact that this be where the boo-hag haunts?" "The she-bitch takes the form of a giant black owl with glowing red eyes whenever she spies for victims. And an owl at sea tends to stand out." Simon crossed himself. "What are we summoning her for, Captain?" He hesitated on giving up the entire reason. There were some things he didn't want the others to know. So he settled on a smaller, more logical one they wouldn't argue with. "It'll behoove us to pay homage to her, as the gate lies in the midst of her perching range, and we'll be passing by it. Anyone who doesn't give her her due regrets it immensely. Not to mention, nothing goes on in this area that Strixa doesn't know about it." "Sound reasons." William called for them to set anchor and steady the ship as best they could, given the storm. Belle returned with her oils and salts to help him, and Janice cast the circle for it. "Be ready whenever you are, Captain." While Belle set about beginning the ritual with Janice, Devyl took a moment to make sure that Rafael was far enough away from them to be protected should something go amiss—which, given his luck, was highly probable. No need in putting both their crews at risk. Besides, the Deadmen would need to be fished out of the sea if things didn't go to plan. Devyl turned to the man who was the closest thing he'd ever had to a friend. "Should this go afoul, Mr. Death, I want you to save as many as you can." "No fears, Captain. Me arse'll be the first one I'll be rescuing." He scoffed at the surly tone, knowing Will better than that. William would never see to himself over the life of another. It was, after all, what had caused him to be hanged. And that had been over someone William knew had betrayed him, yet he took the noose for the man anyway. Because, aye, Will was just that loyal. Once they had the ship as stable as they could, Devyl turned to Mara. He saw the concern in her eyes and it warmed him a lot more than he wanted to own up to. "It'll be fine, my lady. I've done worse." "Indeed. That's what scares me most. For I have witnessed some of your more stellar moments of gross recklessness... and stupidity. I shudder at the thought of you repeating them." With worry haunting her eyes, she stepped back and melted into the ship so that she could better control it and form a cage around Strixa once she manifested. Devyl took the small iron pot from Belle's hand, where she'd already begun the mixture they needed to bind the powerful creature they were evoking and not invoking. A dangerous thing that, especially when dealing with gods and those most powerful. The fumes from the pot were pungent enough to make his eyes water and to catch in his throat. Sancha rubbed at her nose as he began to make sigils on the deck. "Doesn't she prey on children?" "She can. Why?" "I'm trying to think if there's an easier way to lure her. Mentally, Kalder should draw her in." Kalder gave a loud, fake laugh at her insult. "I've heard she prefers to drink the nectar of loose women, meself." "Well then, we get a double dose of it with you." Sancha grinned at him. Kalder laughed good-naturedly, taking her insults in stride. At least until a fierce, harsh, screaming wind began. Devyl grimaced at the banshee-like sound. "Relax. It's her. She's protesting our interference with her free will." "Is she going to—" Bart's voice broke off as a massive swell of water came over the starboard side and sent the ship careening. Several members almost fell overboard, but Mara caught them in a basket and held fast. Devyl cursed as more waves pummeled them and uprooted their anchors. "Hold tight!" Easier said than done. Strixa was after their blood and their lives for this. And not just to take a few years off. She wanted them entirely. As a result, a wave lifted the ship out of the water and sent it crashing down with a force that rattled their bones and sent them all to the deck. It was so fierce, it shattered the cage Mara had created to hold her. "Mara?" Devyl shouted, terrified she might have been injured. "I'm fine." But her tone was stressed. "Don't worry over me. You be careful." He pressed his cheek against the plank, wishing she was in her body. "Do not get harmed in this," he breathed before pressing his lips to her wood. "Above all, do not risk yourself." The planks warmed beneath him. "Above all, Du, do not be harmed." Devyl caressed the boards before he pushed himself to his feet. "Strixa!" He shouted for the witch as he began to evoke her, chanting in the ancient language of his people in an effort to calm her fury and save his crew. It didn't work. She came out of the sea like a phoenix on fire, trailing a stream of water in her wake. Her black wings flapped with the force of a hurricane, sending their ship plunging beneath the waves. Only Belle's shield, Janice's chant, and Mara's determination kept them from being ripped apart and sunk. The crew lashed themselves to whatever wood they could and many prayed as it seemed the ship was trying to buck them all off into the sea to be drowned. "This was a stupendously bad idea," William said as he wrapped rope around his waist and the mainmast. Devyl growled as he pulled himself up and stood to the side. "No bitching, Mr. Death. I tried to get you to leave." "Deeth! And I regret me decision, Captain. Seriously. Should have done it when you told me to." Bart caught Zumari as he went skittering past and helped him to anchor himself to the deck. "Am thinking... she's an owl. They like insects. I vote we feed her Roach and run for it." Roach let loose a long string of French obscenities. Ignoring them, Devyl used his powers to summon Deruvian fire so that he could shoot it at the ancient being to get her attention off his men and onto him, where it belonged. With a loud screech, she ducked his blast and came for him. He expected her to fight. Especially as she angled her talons at him. Instead, she flapped her wings as the sea and storm settled down into an eerie, fog-laden stillness that was far more terrifying than the storm they'd just been in. It was so quiet now, he could hear his heartbeat and the creaking of the ship boards around him. The clanking of winches against wood and the slapping of ropes against the side. A single cannon ball rolled across the deck. In one bright flash, the great black owl turned into a woman dressed in a long, flowing ebony gown and a cloak covered with iridescent owl feathers. An ornate red crown held back her black hair from a face that was perfectly sculpted and beautiful beyond description. Features that could easily belong to a goddess. Her dark skin glistened from the drizzle as those red eyes focused on him while she held her cloak back from her body with graceful fingers that were tipped by the same red metal as her crown. Only these formed filigree talons for each of her phalanges, including her thumbs. Nearing Devyl, she cocked her head in a very fowl-like manner as if she were studying him from one eye only. She reached to cup his chin with her taloned hand. The chains that connected each digit hung down, making her hand appear as a flower. "Well, well. You're a fair one, aren't you? Are you my offering?" Before he could draw in a single breath to respond, Mara manifested beside her and socked her one. "Get your hands off my husband, she-bitch!" Devyl wasn't sure who was the most stunned by her unexpected declaration. And explosion. Basically, they were all gaping. So much for Mara not being born of violence. That had been a spectacular show of Aesiran anger that he'd have never attributed to a full-blooded Vanir. Furious over Mara's actions, Strixa came around to return the blow with her own. Devyl quickly caught her arm before she could deliver it. "None of that, now. I promise you, you lay hands to my lady and you'll be meeting a side of the devil you never want to." "You think not?" She leaned in to whisper in Devyl's ear. "I know what you are, and I know who you serve. And you cannot cage me. Neither of you have those powers." He smiled at her. "Perhaps not, but there's no blood here for you to feast upon. No souls for you to claim. Yet you've shown us your true form...." She gasped as she realized what she'd inadvertently done. Bound herself to him, as her curse forbade her to ever show her real face to anyone, save her victims. And since she had no victims on this ship, she was now enslaved to him. Screeching, she tried to change forms to flee. But it didn't work. More than that, she wasn't the first of her kind that Devyl had bound in such a manner. "Mara?" She manifested his spirit scepter and handed it to him so that the wolf skull at the top of the yard-long staff faced the sky. Crowned in gold and feathers and encrusted with radiant jewels, the scepter had been the most sacred object at Tintagel. For many, many reasons, and not just because his ancestors had embedded it in their battle shields and thrones. With this totem, generations of Tintagel kings had bound, held, and commanded countless demons, spirits, and ghouls. It was said to be even more powerful than Solomon's key and seal combined. And it was deep in the jaws of the skull that the holder of the scepter placed his harthfret on the day ownership passed to him or her. Something they never spoke of until the heir of the scepter was old enough to understand the repercussions of allowing anyone else to know exactly what the staff was and how powerful a talisman they would inherit. This had been the symbol of the Dumnonii people. Every generation of his family, from the beginning, had offered their own blood sacrifice to the wand, and with it, they had become one of the most powerful families of the British Isles. Until Vine had viciously slain him. Thinking his harthfret was a piece of jewelry and not knowing he was strong enough to regenerate without it, she'd stolen his mother's necklace he'd worn and cast his scepter away, never knowing what it really was. Any more than Mara knew now as she handed it over to him. But this... This was the key to his soul and power. With that in mind, he snatched one of Strixa's black owl feathers from her cloak and placed it in the brightly colored crown that haloed the skull. "You are mine until I free you." She let loose a venomous hiss of fire, yet because he controlled her, it couldn't harm him. He held the scepter up to catch the fire and be charged by her anger. It glowed like a second sun. Baring her fangs, she raised her arms and shrank away from it as if it burned her. "Do you really think that paltry stick's magic can protect you?" "Not really, but I find it to be a most apt bludgeoning weapon should the occasion call for it." He raked a meaningful sneer down her body. "Shall we test it?" That succeeded in calming her a bit, as she wasn't sure whether or not he meant that threat. While he didn't relish the thought of doing battle with a woman, he wasn't about to lie down and let another cut his throat. He liked to think that he learned from his experiences, and that was one particular event even he was definitely not eager to repeat. She curled her lip. "What do you want of me?" "Calm seas. Cessation of the water sprites, and a few more of your feathers." "Feathers?" She drew her brows together into a perfect baffled expression. "Why?" "For me to know and you to give. Do we have an accord?" Her gaze slid from him to Santiago's ship in the distance before a slow smile spread across her face. "Don't think it. 'Tis too late for you to seek their blood for your freedom. You're bound already." That was the beauty of his people. The ability to control her kind and bind them was instinctive. It was what had allowed Mara to combine her life force to his on the day they met. Unfortunately, she'd been too young and inexperienced with her powers at the time to do it properly. He wasn't so foolish. And the water witch belonged to him now. Baring her fangs again, she showed him the sight of her true hideous form. "You will regret this." "I do most things I choose." He smiled coldly in her face. "Now give me your word or I'll bind you to something very uncomfortable for a long, long time." "You wouldn't dare!" "Care to try me?" She finally backed down as she lifted up a corner of her cloak and the weather instantly calmed. "I will see you to the bottom of this ocean before all is said and done." "And I'll make sure to take your heart along with me." He plucked the feathers his spell required and handed them off to Mara. When Strixa opened her mouth to speak again, he used his powers to transform her back into her black owl form. "How 'bout you remain like this for a bit. Safer for us all, I think." She let out a fierce shriek as she flew to land on the ship's railing so that she could glare at him with her glowing red eyes. William cleared his throat to get Devyl's attention. "Beg pardon, Captain. Can't help wondering if taunting her isn't a bit foolish? Most especially given our current situation?" "Of course it is, Mr. Death. Why else would I be about it? Where would be the fun of practicing caution and intelligence? If we're bound for hell again, let it be with full sail and flagrant disregard of all sanity, I say." William let out a nervous laugh as he turned toward the crew. "Who is with me for a mutiny, eh?" Bart clapped him on the back. "I'd say aye, but the captain scares me too much." "Aye to that," Zumari agreed. "Besides, he'd take too much pleasure in eating our entrails. Methinks he's the only captain alive—or dead—who craves a mutiny." "Would definitely explain some of his more peculiar actions," Bart muttered before he cast an exaggerated grin toward Devyl. "Don't know why I said that, Captain. Must be the witch a'witching my tongue." Devyl rolled his eyes at the sorry lot of them. "Sure of that." His tone carried the full weight of his sarcasm. "So what's with the feathers?" Kalder picked one up from the deck to hand it to Devyl. "Not sure why it was worth the risk of attracting the witch's notice for so paltry a thing." Before Devyl could answer, it was Belle who stepped forward and volunteered it. "Why, Mr. Dupree, ye might be able to swim with the fishes, but with what you have in your hand, the rest of us can fly with the birds." "Pardon?" Devyl nodded. "With those... we can cast a spell that will grant us flight. Forget relying on the winds to find your Miss Jack. We're going airborne to get to her. And this time, they won't be able to stop us from taking her back." "He doesn't love you. You have to know that his kind is incapable of comprehending what you think of as love. It's beyond their ability." Mara ignored Strixa's words as she went over the map in Du's room while waiting on him to join her there. "You know nothing about him." Still in her owl form, she pinned those creepy red eyes on Mara. "I know his kind. As do you. They only value the goal and their people. You are a pawn to get what he wants. Worse? You're his enemy." "And you are a troublemaker." Mara picked up Du's baldric from where he'd left it, draped across his chair. Hand-carved with intricate Celtic scrollwork, it was a piece of exquisite beauty. And a lot heavier than it appeared. Gracious! No wonder the man was so muscular, wearing things that weighed so much. "I won't allow you to come between us." Strixa shook her fowl head. "I'm not the one who will come between you. He doesn't need my help in that. You two have broken a cardinal rule. Think you you'll be left alone to live in peace?" That was honestly what she feared most. But she refused to show it to the creature. "I know what you're about and it's not working." Yet in spite of her denials, it was, and she suspected the witch knew it as well as she did. Returning the baldric to the chair, Mara swallowed hard. Even if Du's flying spell worked, they still had a ways to go to get to the islands that made up the Quella. Antillia shouldn't be that hard to get past... especially if they weren't in the water. It was policed by a group of fairymaids who were known to lure sailors to their deaths. They haunted the shoreline caves and rocks where they would call out for help, and when the unwary tried to lend a hand, the fey creatures would drown them. But so long as they didn't wreck the ship or find themselves forced to land near Antillia, nothing would happen. The fairymaids shouldn't come near them. Of course, if they were flying it would put them directly in the path of the dragon clans who called Jesirat al-Tennyn home. In fact, that was what the island's name translated to—Dragon's Isle. Those vicious, bloodthirsty clans were highly territorial and wouldn't take kindly to anyone venturing near their lands. They barely tolerated one another. Humans were seen as nothing more than snack food. Then they'd have to get past Satanazes—the demon island that was nestled close enough they'd have to approach it from the sea. Some twenty leagues west of Antillia, it would be directly in their path and would be tricky, as demons always were. A mist covered the island and shielded their presence. Some claimed the mist itself was a demon. The only ones who knew for certain were the unfortunate victims who'd been eaten or enslaved by the island's inhabitants. And none of them ever escaped to tell others what happened there. As for the Meropis island, rumors claimed it was inhabited by flesh-eating, soul-sucking creatures who preyed on any dumb enough to venture there. They were worse than even the demons, and were said to be far more unholy. Crueler. Those vanishing islands were directly responsible for many of the legends that made up the Caribbean. The monsters and mysterious disappearances. It would be hypocritical of her to not believe in them, given that her own race could turn into and live as trees. Still... She knew how humans could also twist, turn, and expound on reality. So what was told and what actually existed could be radically different. A little truth went a long way in an overactive imagination and the overblown legends people told for attention. Suddenly, she felt the air behind her stirring. A smile spread across her lips at the rich masculine scent that warmed her an instant before Du wrapped his arms around her and pressed his cheek to hers. "Sorry it took so long to get away. Janice took more convincing than I thought to get her to leave for Santiago's crew. But she'll be safer there for the time being." Closing her eyes, she savored the sensation of being engulfed by him. And a part of her wanted to kick herself at the centuries she'd deprived them of that could have been spent like this. And for what? Vanity? Stupidity? Stubbornness? Things that no longer seemed to matter. "Is anything amiss?" He glanced to Strixa. "Nay. Not where I'm concerned. What treachery has the she-bitch wrought?" "Pardon?" He stepped back. "If she's anything like Vine, I shudder at what lies, doubts, or half-truths she's filled your head with in my absence." Strixa squawked indignantly at his words. Mara laughed. "Fear not. I didn't listen." "Good. Because the only one to hear is me." But as he leaned against his desk to study the map, her gaze went to his battle-scarred hand that toyed with the hilt of the dagger that held the parchment in place. In spite of her bold words otherwise, doubt played in her head. Worse? It played in her heart. Strixa was right. Du was a creature of extreme and utter violence. Love didn't come easily or naturally to him. It was an alien concept. As foreign to him as generational war was to her. While she knew it existed, she wanted no part of it and didn't really understand those who partook of it or why they did so. And in that moment, she didn't see the loyal pirate captain in front of her. She saw the ancient warlord, covered in blood and dressed in his black armor. Saw his black braids and beard. The arrogance of his swagger as he returned from war and strode through their hall to claim Vine while his bloodlust still colored his cheeks. Reveling in his war and conquest, he'd been terrifying. His ferocity such that even the trained war hounds had fled, yelping, at his approach. Indeed, the air around him now, as then, sizzled with his unholy power and raw determination. It reached out like a living, breathing entity to cause the hair on the back of her arms to rise. The mere fact that he could effortlessly hold a witch as powerful as Strixa... I'm a corymeister. Du's words went through her head. He was the strongest sorcerer of his kind. No one could touch him when it came to the ability to bend the natural laws. Mara went ramrod stiff as that brought a new, horrifying thought in its wake. What if her feelings were nothing more than another spell he'd cast? How would she ever know the difference? Was any of this real? He glanced up and caught her gaze. "Mara?" She offered a smile and prayed he couldn't sense it was false. "Aye, sorry. Was lost in my thoughts. Did you ask something?" Suspicion clouded his gaze, as if he knew she was lying, but wasn't quite sure about what. "Are you all right?" "Fine. Worried about that coming conflict." That seemed to placate him. He glanced toward Strixa. "No fears, my lady. So long as you put your faith where it belongs, all shall be well." Mara wanted to believe that. Desperately. Yet she couldn't shake the ill feeling inside her that warned things were not what they seemed. And that Vine had something in store for them that neither of them could predict. * * * Thorn cursed as he pulled back with his men before he lost another one to the demonic horde that was pouring through the breach from their realm into that of mankind. Thankfully, this rupture was in the desert where no human was around to witness it. But it didn't make the dusk-lit battle any less bloody or intense. "Gabriel!" The Seraph general ducked barely before he would have lost his head to a sword stroke. Slightly taller than Michael, Gabriel was a huge bastard himself. In Seraph form, his darker complexion looked almost ashen, but his hair was every bit as white as the others', as were his wings and weapons. His gold armor was blinding in the dim light—a tactical advantage when battling demons whose eyes were sensitive from living in flame-lit darkness for so long. And a damn annoyance for Thorn, who was one of them and yet on Gabriel's side for this conflict. Lifting his hand, he squinted to see past the brightness that sent waves of agony through his skull. "They're slipping through to the right," he called out, warning Gabriel's soldiers to shore up the area where Thorn's men were growing thin. Thorn cursed again as he realized how right Michael had been. This was far worse than he'd imagined. It wasn't just the Carian Gate that had failed. Three had gone down. The Cimmerian forces were stronger now than they'd been in centuries. Thorn drove his blessed sword through the demon closest to him and took an unnatural pleasure at the sounds of its screaming. Normally, he'd only banish them back to their prisons. But today, he wasn't feeling merciful. Today, he wanted blood and soul. Most of all, he wanted to hear their cries of agony. "What happened to cause this surge?" he asked Gabriel. "The Malachai killed his son and absorbed new powers. When he did so, he broke the seals on the gates." Growling, Thorn renewed his fight. That would do it. "Who was the mother?" "A demon whore who wanted to get back into Noir's good graces. After the Malachai attacked her, she sought to barter the boy and Adarian's soul for her own freedom. Sad for the child when he tried to kill his father and learned firsthand that Adarian didn't let his fatherly devotion get in the way of his self-preservation." Thorn rolled his eyes at that bit of common knowledge about the Malachai, and at the clichéd ploy too many she-demons had used throughout the centuries to try and bring Adarian down. It was what had made the Malachai demon so incredibly powerful and dangerous. Because the Malachai alone took on the memories and powers of all his predecessors whenever he came of age and assumed his role as head badass, he became stronger with each generation. The current Malachai, Adarian, had lasted longer than any before him. Lucky for humanity, Adarian hated Noir and Azura—the two primal gods he served and was bound to—and had escaped them to hide in the mortal realm. So long as Adarian remained free and apart from them here in the human plane, the world wouldn't end. But if he were to ever make amends with them, or a she-demon ever mothered a Malachai son who could take down Adarian and assume his father's powers and those of the previous Malachai... Thorn would definitely kiss up to his father and sell out the world. It would be the only way to survive the ensuing holocaust. That was what they all feared. The one Malachai who was prophesied to end the world and bring about the eternal reign of the demons. Still, with that being said, the thought of Adarian absorbing new powers was even more terrifying to Thorn. Because sooner or later, whenever Adarian thought he had enough strength to pull off a coup, he'd go after Noir and Azura to get his complete freedom from the two of them, and that battle wouldn't be any better for the world. Might even be worse, given Adarian's inherent sense of entitlement and hatred. Worse still, his bloodlust. And Thorn ought to know. He'd been caught up in the previous such war that had almost ended all existence as humanity knew it. Because win, lose, or draw, the Malachai would not go back into his box, and Noir and Azura lacked the powers to kill him. They could only enslave their favorite pet. Which was also part of the prophecy. One day, the Malachai would slay the gods of old and replace them all. And once they were gone, and their curse with them, their Malachai demon would reign as the supreme power of the universe and rebuild his bloodline. Another army of Malachai would rise and no one would be able to stand against them. Neither god, nor man. Nor any preternatural creature. They would all burn and kowtow to him. The only hope was an obscure legend of the Excambiare Malachai. Like the firstborn Malachai, known as Monakribos, this one would be conceived from an equal share of the light and dark powers. Whereas Monakribos held a father of light and a mother of dark, the Excambiare would have a mother of light and a Malachai father of utter darkness. The Excambiare's birth would complete the Malachai cycle and restore the balance that had been shifted by the thousands of Malachai who'd come along after Monakribos. It would break the curse that had been placed on the Malachai bloodline by the primal gods, and shatter the Malachai's Cimmerian bonds. He would be free to serve himself, and no longer be bound solely to evil. After all these centuries, the Malachai would exist as a fully balanced creature. Regression to the mean. It was, after all, what the universe ever endeavored to achieve. And as one of those chosen tools it used to maintain such a balance, Thorn was well used to the games the universe played. But no one really believed in the legend. Mostly because of how a Malachai was conceived. They were born from acts of extreme and utter violence. It was why their mothers were almost always demons. Humans rarely survived sex with their hated breed, and the Malachai avoided the gods because divinity tended to heap even more curses upon their already damned bloodline. So the concept of a birth mother born on the side of light, loving her Malachai child, was inconceivable and about as likely as Thorn embracing his father and having a beer with the beast. Of course, it didn't help that as soon as any child of Adarian's reached the age of puberty and showed any signs of holding a Malachai's powers, Adarian slaughtered him and ate the boy's abilities whole. The last time that had happened, it'd been bloody enough. Now... "How is Adarian so strong if he's not living with Noir and Azura?" Gabriel grimaced as he killed the demon in front of him and swung around to face Thorn. "Like the parasite he is, he feeds on human hatred and violence. God knows, there's plenty of that to go 'round. He's found a way to channel it to his own powers, so when he slaughtered this most recent child, some of the gates crashed." "And his generals?" "So far, none of them have escaped their prisons to rush to his side. Let us pray it remains so." Definitely. That was the last thing they needed on top of this mess—the release of the Riders of the Apocalypse. Yeah, he'd like to avoid dealing with those pissed-off bitches for a bit longer. "I have to warn Bane and the others." Gabriel caught Thorn's arm as he started to withdraw. "You know the rules. You interfere now and you'll end their parole." Thorn's jaw went slack. "What of Michael's medallion?" "You can return it later. But for now..." Gabriel swept his gaze over the desert battlefield where they were slowly losing more ground. "We need you here." Thorn scoffed. "Sarim asking for my help? Seriously?" Yet this was what he'd always wanted. For them to accept him as one of them. Still, he knew not to put any faith in this day or their truce that wouldn't last. This was nothing more than necessity. There was no true camaraderie here. No love. He wasn't one of them and they all knew it. But it was a chance to prove to them that he wasn't the backbiting piece of his shit his father had been. So he'd stay and fight. However, as stated, he wasn't the backbiting piece of shit his father had been. And he wasn't about to leave the Deadmen out to hang either. Not with what was coming through this gate, or with the Carian. Not while they were depending on him to keep them notified and safe. He would never abandon his own men. In spite of his genes and what others thought of him. Rules and codes be damned. They were his friends. More than that, his Hellchasers were the closest thing to a family he'd ever known and he'd die before he let any of them down. Falling back into the shadows of a palm tree, he used his powers to summon his sharoc companion. "Sorza!" As dark as the sorrow she was named for, she appeared by his side. A mere wisp only he could see. Thorn pulled the medallion from his pocket and handed it to her. "I need you to take this to Devyl. He'll know what to do with it. And tell him that I haven't abandoned him. I'll be in touch as soon as I can." She scowled. "You're bidding me to do good?" "I am." That only baffled her more. But she faded away and left him to continue his fight. Thorn lifted his shield and chased after a demon that was flying for Adidiron's back. He didn't get far before the demon turned to face him with a snide grin that was all too familiar. Paimon. Damn him. "Hello, my son." Thorn shuddered at his "friendly" greeting. "Don't call me that." "Why? It's what you are, aren't you?" Thorn curled his lip. "Just because you carried my father's sperm doesn't make us related. Really, Paimon... you're just a two-bit pimp doing whatever you're told." "That makes your mother a whore, does it not?" Thorn dodged the sword strike that would have severed his head had it made contact. "Your words are as clumsy as your fighting skills. My mother sold her soul to conceive me. That's an undeniable fact. Call her what you will. Makes no never mind where I'm concerned." Mostly because his mother had hated him the moment he'd been born over said bargain. And Thorn hated everyone who'd had a hand in his conception—his mother, father, Jaden, Paimon, and Lucifer. End of the day, they'd all taken turns screwing him. Which was nothing compared to what his stepfather had done the day he'd learned of their bargain. And the fact that his "beloved son and heir" wasn't really his, but rather a cruel hoax played on his gullible stupidity by a conniving bitch and her demon lover so that she could maintain her position and her lover could connive to steal his throne. Aye, Thorn still had those scars. Outside and in. It was why he fought so hard now. No one should be used by others for their own gain. Damned because someone else was selfish and had sold them out without any regard for what it would mean to them once the truth became known. He'd had no choice in what had been done to him. That anger and hatred had turned him into a monster at a time in his human existence when he should have been carefree and looking forward to a life well spent. Instead, he'd become the very thing his stepfather had wanted him to be—had trained him to be. The fiercest warlord to ever lead his army over blood-saturated fields. And his stepfather's head had been one of the first Thorn had claimed as a trophy—payback for the betrayal of casting him aside so very brutally over something he couldn't help. There, for a time, Thorn had been content and happy to play the beast, and slaughter everything he came into contact with. Until the day he'd seen himself for what he really was. And that sight still haunted him in a way no demon or monster ever could. For he knew the truth. He was the scary thing that gave grown men and ruthless demons nightmares. But never again. Thorn raked a sneer over Paimon's horned, ghastly form. "Crawl home, you fetid bastard. Slither into your pit and stay there until you find some semblance of decency." Paimon laughed in his face. "You've been corrupted by humanity. How can you put faith in something so pathetic and weak?" He smirked. "We live by faith. Not by sight or proof." "How can you have faith after the way they've turned on you and done you?" Shrugging, Thorn answered with the simple truth. "The testing of faith produces perseverance, and faith without action is worthless." Paimon shrieked in his face. "And so are you!" * * * "I'm not so sure about this spell of yours, Du." Mara's eyes widened as she saw the size of the raven he'd convinced to lift them up and carry them. "When you said we'd fly, I thought you meant without additional aid." He smiled at her. "Nay, my precious blodwen. But fret never. It's not what you're thinking. We couldn't be in better talons. Trust me." Famous last words, that. She wasn't sure if anyone could control something this large. And he refused to tell her exactly how he'd conjured this giant beast of a bird. Even Belle appeared skeptical as they all gathered on deck to stare up at the fowl above them. With massive talons, it gripped the railings and lifted them through a sky as dark as the bird itself. Her heart pounding in fear, she clutched at the rope nearest her and gulped. The wind from its wings whipped against them. Cool and pleasant over the heat, yet disturbing in that it was so unnatural. William glanced over to Bart. "Thinking of feeding Roach to this beast as well?" "How'd you guess it?" "The expression on your face. You're quite transparent." Roach passed a less than amused glare at the pair of them that forced Mara to press her lips together to keep from laughing. But she deeply appreciated their humor, given the severity of this, and her trepidation over it. Only Duel seemed at ease. Damn him for that confidence. But then nothing ever seemed to rattle the beast. Her heart in her throat, she tightened her grip. As if sensing her unease, Du moved to stand behind her. "It'll be fine. I trust our raven." Problem was, she didn't. How could she? She knew nothing of the creature or where it came from. Worried, she turned toward Duel and the comfort he offered. Honestly, what she wanted most was to walk into his arms and have him hold her again. To bury her face against his chest and let the scent of his skin soothe her until it drove away the last bit of her fear and turmoil. And still a part of her was scared to be so close to him, for he was every bit as dangerous to both her sanity and reason. He met her gaze and frowned. "What?" The word was more a bark than a question, and that, right there, was part of her fear about this. He was ever unpredictable. Swallowing, she glanced up at the bird, then down to the man who controlled it. "Have you ever been afraid?" He reached to touch her hair, and hesitated as if he realized suddenly what he was doing and how many stood near enough to see. "Aye. Many times." She couldn't imagine it. Not Duel. He was always so confident and in charge of himself. She'd never really seen true fear from him. Not like what other men showed. "Name me one time." "Every time I reach for you," he whispered against her ear. "I'm terrified you'll rebuff me." She started to scoff at his answer, until she caught the sincerity in those dark eyes. "How could you ever fear me?" "I don't fear you, Mara. I fear the power you hold that reduces me to your mindless servant." "You flatter me." "I only speak the truth. Had you ever once looked at me, you would have seen it plainly. Vine knew it, and it's why I never held her full loyalty or her heart." And with that, he stepped away to check on the others. Tears welled in her eyes as she choked on the pain in her throat that his own anguished words had wrought. She wanted to call it a lie. To say he was playing her falsely and trying to weaken her. She couldn't. Because in the back of her mind, she saw him as he'd been. The times their gazes had met over the years when they'd lived in Tintagel and he'd sobered as if someone had punched him. More than that, she remembered the way he'd rush to her side if she ever felt ill or needed something. Even leaving her sister during such instances. Aye, it had infuriated Vine whenever he did such. Many times, she'd gone into a fetid rage at them both. Du had ignored her tirades and Mara had dismissed them as part of her sister's unreasonable jealousy. It was ever part of Vine's personality that she could become incensed over the smallest of things. So she'd thought nothing of it then. But now... Mara remembered the first time she'd appeared in Duel's court after he'd brought her home with him.... "She's a Deruvian whore! I say we should get some entertainment from the wench for the trouble they've put us through! Let us all have a turn at the bitch! We've earned it for the blood we've lost." Duel had ruthlessly gutted the soldier faster than she could blink. Faster than anyone, even said gutted man, could anticipate. Indeed, he'd been in the midst of his next sentence when Duel had struck without warning. His sword coated with the man's blood while the poor man had gasped his last breath, Duel had glared at the gathered nobles and warriors inside his dark, somber hall. "Anyone else takes issue with the lady, they take issue with me. You will respect her and speak to her as if she were one of our own. And a queen, no less. Never let me catch anyone near her, for any reason, or else I'll make you wish your own mother had gutted you the moment she made the mistake of whelping you." Mara had assumed those growled words were motivated by the fact she'd bound their lives together and he feared them killing her out of ignorance and spite, and ending his life in the process. Now... She winced as she realized how stupid she'd been. How unkind and selfish. But how could she have known he felt anything more than hatred for her, given what she'd done? That his protection of her had stemmed from something far more tender than his own self-preservation? I'm such a fool. Belle came up and touched her shoulder. "Let the past go, mum. 'Tis a fleeting shadow that can never be captured." "I'm so mad at myself, Lady Belle." "I feel that pain that lives in your heart, Mara. Think you there's not a one here who isn't a refugee from that monster called Past? On the surface, it appears we bartered our souls for another chance at freedom, but the truth is we're all hoping to find something we can hold on to that will kill that beast inside us. Something to quell our guilt and conscience. That is what we're hoping to salvage. Not our souls. Just our sanity." She squeezed Belle's hand. "You're a good friend. Much better than I deserve." "Nay. You never want to know what caused me to be damned, mum. Suffice it to say, I'm grateful the captain approved me pardon when Thorn offered him my service. Not many what would, given my crimes." She glanced around to the others. "He sees more than you credit him with." "How do you mean?" "Think about it. Thorn gave him the ability to veto any member of this crew for any reason, no questions asked. Makes you wonder what Captain Bane saw in this sorry lot that he thought us worth redeeming, doesn't it?" She jerked her chin toward the wheel. "And Sancha, you know why she drinks?" Mara shook her head. "She left her daughter alone with the man what fathered her, but he didn't want to be a father. Truth was, back then Sancha didn't want to be a mother, either. Not until she got home from carousing with friends only to find her daughter dead by the unfeeling hand of the blackguard she'd entrusted with her care. Too late, she realized how much she did love her girl, and that she didn't really mind the responsibility of motherhood, after all." Her eyes filling with tears, Mara gasped at the horror poor Sancha must have faced that night. No wonder she was so harsh now. "What did she do?" "Without a single word, she calmly picked up his flintlock and shot him where he sat. They say they found her sitting in her daughter's nursery, holding the babe while still coated in her husband's blood. Don't think she's been sober since. Because whenever she is, she sees her daughter's face and blames herself solely for what happened. And she can't bear the guilt of it. It's why she took on the name Sancha Delarosa—holy lady of sorrow. Her real name was Maria Esmeralda de la Vega y Tarancón. Or more to the point, Donna Maria Esmeralda de la Vega y Tarancón." "She was a noblewoman?" Nodding, Belle pressed her hand against the amulet she never removed from her neck. "And Kalder... he was mixed up in all kinds of evil in his day. Because of who and what he is, he thought himself above all human law." "They caught him?" Belle shook her head. "Those he'd cheated mistook his honest brother for him. Beat the poor lad to death in his stead." Wincing, Mara ground her teeth at the sheer misery that must haunt the poor merman. "Did they find him, too, after they took his brother? Is that how he died?" "Nay. Unlike his brother, he was a brawler, through and through. They'd have never taken him in a fight. Was his own mother what did it, when Kalder came home to pay respects. She said it was only right he join his brother in death, as he was the reason his brother had been on the docks that day. Apparently, Kalder had been wanting to meet with him for some scheme he had planned, and had gotten distracted by a buxom maid. So while his brother lay dying from the beating he should never have had, unable to get help, Kalder was occupied with baser needs." Mara felt sick to her stomach. It explained much about the Myrcian. "That's why he's been celibate." Belle nodded. "Because of the guilt, he's not wanted to go near another woman. Not until our Miss Jack. So while he might be flirting with one, he never sees the deed through." "Now he blames himself for what happened to her." "Aye." Mara glanced around as a shiver went down her spine. "Why are you telling me all of this?" "I wanted you to remember that the cross each of us bears isn't truly the one that be on our wrists. 'Tis the one of guilt we carry inside our hearts. And while those two cut to the bone, they are nothing compared to the double-crosses of our trusted friends and family that scorch us soul deep. That is what the red jack we fly truly stands for, Mara. A fanged skull to remind us of the eternal bite that comes from such nasty treachery. And the ribbon 'round it is the captain's eternal promise that he will never betray us. No matter what, he will keep faith and be at our backs through whatever nightmarish hell comes our way." "Captain!" Kat's voice rang out from the crow's nest high above her head, interrupting Belle's words. "Incoming!" So accustomed to the sea holding all their incoming threats, it took Mara a moment to realize that wasn't what he was warning them about. Nay, this threat came from the skies. There was a group of dragons, and they were headed straight for them. "Paden?" Cameron crawled toward her brother on trembling arms and knees that threatened to give way at any moment. He was so battered and bruised that she barely recognized him. Yet even through the misshapenness of his features and his strangely pale hair, she'd know him anywhere. Or so she thought. No sooner had she reached him than he looked up with coal black eyes that were shot through with bloodred veins. He hissed at her, baring fangs. Shrieking, she pulled back. "What have they done to you!" He let out an inhuman growl as he slid across the floor after her like a rabid dog intent upon her utter destruction. Terrified and unwilling to hurt him, she shrank into the corner and held her arms up to protect herself as best she could. Tears welled in her eyes. She whispered a prayer of protection. "In the name of St. Michael, dear God, deliver me from evil. Preserve me from violence and set Your shield around my body. In the name of the Father. The Son. And the Holy Spirit! Please, Paden, please! Mercy!" His breathing ragged, he paused an instant before he would have ripped out her throat. Drool dripped from his fangs to her neck while he hovered so close that his rancid breath scorched her flesh. "Cammy?" Her name was an anguished whisper. "Aye, brother." He let out a sob so deep that it seemed to come from the very bowels of his soul. His body shaking, he gathered her into his arms and clutched her tight against him while he wept tears of blood. "Ah, how precious and sweet." Paden tightened his grip on her to the point of pain. A heartbeat later, his wings sprang from his back. When he tried to rise, the demons grabbed his chains and dragged him away from her, then slammed him to the ground. She tried to help, but the voluptuous woman in bloodred armor used her powers to drive her back against the wall. And held her there with an ease that infuriated Cameron. Tsking, she smirked. "Now, now, little spawns of Michael, we can't be having any of this." "Let her go, Gadreyal!" Paden growled. "This has nothing to do with her!" "Oh, but it does. And had you wanted her left alone, you should have cooperated. Now..." She let out an evil, insidious laugh. "We shall play a little game called Plant the Seed. One of you will carry it, but neither of you will know who it is. At least not until it takes root and grows to such a beast that it can't be defeated and it's too late to be stopped." Her laugh echoed in the room. "Aye. I'll have the head of Dón-Dueli, and the spawn of Michael will be the one who brings it to me." Her laughter died an instant later when a demon manifested behind her and whispered in her ear. "What?" she growled. "Aye, my lady. They've broken through and are approaching the gate." Her features turned to stone. "Gather my army. 'Tis time we returned Thorn's Deadmen to the hell that spawned them." * * * Using his thoughts, Devyl commanded the raven to set them down on the sea barely a heartbeat before the dragons began their vicious attacks. Their incendiary breath lit the sky as they sought to sink the ship. Fireballs exploded all around. In a bright flash of light, the raven transformed back into Simon Dewing, which startled the rest of the crew, as they realized Devyl had used the witch's feathers for a spell to enlarge their striker's alternate incarnation. As a shapeshifter, Simon had come in handy a number of times for certain tasks. But never more so than today. Mara smirked at him. "You could have told us who the bird was, you know." Winking, he cracked a rare smile at her. "And miss the look upon all your faces? What be the fun in that, love? Got to have some enjoyment in me death." With a deep laugh, Simon moved to stand ready with Kat and Roach. He draped his arm around Kat, who shook his head at him and rolled his eyes. "I should have known it was you." "Aye, you should have. You'll never be hearing the end of it now. Didn't even miss me or ask after me.... And I saw the way you were eyeing Bart in me absence. Don't think I didn't. There'll be the devil to pay later over that, mark me words." Kat jerked his head toward Bane. "'Tis the other Devyl we have to pay right now that be worrying me most, me love." Simon wrapped his arm around Kat's shoulders and pulled him close so that he could kiss the side of his head. "No worries. Ain't no one getting their hands on you but me. They'll have to come through me first." He unsheathed his sword and used his powers to ignite the blade. Devyl and Bart took the first wave of dragons that flew in to attack the ship as William went to stand beside Mara so that he could protect her. Bart and Devyl deflected the dragons' fiery goo before it could land on deck or set the sails ablaze. Thank the gods that Bart and Will were as skilled with their magick as he was. Their being Simeon Magi was one of the main reasons Devyl had approved Will and Bart as first mate and quartermaster for his crew. They were old school. Highly trained and deadly in just such encounters. While their astral hands were tied whenever they were around baretos, or uninitiated humans who knew nothing of the real preternatural threats that surrounded them, out here on the open water, among their own... Bart and Will were every bit as lethal as he was, which was good, as he'd need them all to survive this day. "Roll the long nines!" Devyl shouted to his gunners while he reviewed the best way to defend the ship and crew against their incoming threats. Those would be their best regular defense. A demi-cannon wouldn't be accurate enough at the distance the dragons were flying and the culverins didn't shoot a heavy enough ball to penetrate dragon scales. Aye, that load would only piss them off. Same for their philosopher's fire. Since dragons breathed fire, it wasn't the most optimal weapon against them as they were heat-shielded for it. Their hides were thick and hard to pierce. Worse than trying to harpoon a whale with a sword. While it wasn't impossible to take down a dragon, it was a specialized skill and none on board were dragonslayers by trade. Damn me for that oversight. He should have thought ahead on that. But that was all right. Their gunners were all Aru Mages—courtesy of a most defiant Thorn. Normally, such demonic creatures were reserved by the Sarim only for Necrodemians. And they would be all kinds of furious to find them on board the Sea Witch at Devyl's command. Why? Because they were a secret weapon the Hell-Hunters didn't want to fall into the hands of their enemies under any circumstance. A special breed of demon, an Aru Mage was capable of assuming any metallic shape or object a Necrodemian might need for battle against the Cimmerian horde. And it was an advantage that might allow them to emerge victorious this day. Throwing his fire, Devyl brought down one dragon, which only angered another. Just how had the beasts seen the ship, anyway? They had all been using their powers to conceal their presence as they headed into the dragons' territory. It made no sense. None of them should have seen a single thread of sail. His answer came a few seconds later when bloodred clouds parted and he saw the other winged creatures flying beside their enemies.... I should have known. "Iri!" he shouted to warn his men so that they could prepare. These were the Seraphim who'd turned against their brethren—or the children of those betrayers who'd chosen to fight with their fathers and mothers against Gabriel and his Kalosum warriors—they were what the Necrodemians had been created specifically to fight. And they were a lot more powerful than the demons Devyl's crew had been recruited to return to their respective dimensions. These were the top-level commanders. The most powerful of their kind. More than that, they'd once been Devyl's allies. He cursed as he saw Gadreyal leading them. She was a nasty piece of work. The kind of demonic creature no man wanted to meet alone. Except for Devyl. He relished a good fight with an equal opponent. In particular, he wanted a piece of her highly attractive ass to mount to his wall for what she'd done to him. Right next to his ex-wife's head. "Gadreyal!" he called, summoning her away from his men as the cannons turned from firing on the dragons to aim at the new threat. The moment she saw him, her eyes lit up to a vibrant red and she dove for him straight away. While he'd been damned, she'd been his primary torturer. They had centuries of mutual hatred they'd nursed against each other. She bypassed his men and left her dragons and soldiers behind to deal with the rest and the cannon fire so that she could take Devyl on personally. Good thing, that. It was enough to make him smile. "Well, well," she sneered, flapping her wings. "If it isn't my favorite toy." She unsheathed her sword. "Ready to give me what I want now?" "I'm not imprisoned here, Gaddy." He blasted her. Shrieking, she landed before him and attacked. Devyl caught and deflected her thrust with his own sword and advanced with the skill that had won him countless battles. He wasn't bound by chains now, nor weakened by all-out starvation. While he might not still be up to full strength, he was a lot stronger than he'd been in centuries. She was in for a full-on battle and he was ready to give it to her with everything he had—mage fire, fangs, and swordplay. From the corner of his eye, he checked his men, who were locked in similar fights with the rest of her forces while cannon blasts rocked the ship beneath their feet and deafened him. Luckily, his crew seemed to be holding their own. Good. He didn't want any distractions. He only wanted her head on a pike. Gadreyal tsked at him. "Be a good boy, Duel. Surrender and we'll make it easy on all of you. Surely you want to be on the right side of the conflict again?" "You planning to give me Vine's throat for it?" "You know better. I can't do that." Well, that ended that discussion then. And any thoughts he had of ever switching sides. Not that it'd really crossed his mind. He'd given his loyalty to Thorn. And unlike the others, he never went back on his word. He swung for her head and blasted her with his fire. Sadly, she ducked and returned with a shot of her own. He went skidding across the deck on his shoulder. Damn, that hurt. Rolling to his feet, he shook the pain off and ignored the sight of the smeared blood he'd left behind on the boards. By God, he wasn't about to let any sort of agony get in the way of his fight. Or his victory. Gadreyal laughed as she launched herself to flight and landed before him. "You haven't asked me about your little Seraph. Have you forgotten her so soon?" His blood ran cold at the mention of Cameron. "What have you done?" Throwing her head back, she laughed. "I've done nothing. But she lacked your fortitude. Then again, most do." Rage clouded his sight. "If you've harmed her—" "Harmed?" She interrupted him. "I made her more powerful and reunited her with her precious brother. How is that a harm? It's what she wanted and better than you gave her." Bellowing in rage, he advanced on her with a renewed vigor, even though he knew it was all kinds of stupid. It was what she wanted. Only calm rationale won a fight. But he couldn't stop the fury inside him that wanted to feast on her entrails. Not when he was the one who'd brought Cameron into this. She wouldn't have been near this she-bitch but for him. He was directly responsible for her. Gadreyal tsked in his face. "Poor Duel. You can't even sell your soul to right this. Tell me? Was your bargain worth it?" "Release Miss Jack!" he growled between gritted teeth. "You don't have the power to command me." "Mayhap not, but I do have the power to crush you." He blasted her and sent her reeling. Now that made him smile. Until she rose up in her serpent form and gathered a group of her companions to her. In a giant cloud like swarming bees, they arched before him, then tumbled down to kill him in one massive wave. * * * Mara fell to her knees as she struggled to keep the ship upright under the fierce assault. William stood by her side, driving away the Irin who was attacking them. We're not going to make it. She didn't say the words out loud, but she felt them deep inside. And it terrified her. What were they going to do? She didn't see any way to drive the beasts back. There were just too many of them. Every heartbeat, they appeared to multiply. While the Deadmen couldn't, in theory, die, they could be overrun, and that was quickly happening. "Get Mara below! Protect her!" Du's voice was a fierce, stabilizing growl above the sounds of war. And his words caused a surge of tenderness to rush through her as she rolled with the ship. Even now when his thoughts should be on his own survival, they were on her welfare. In that moment, she saw him the day they'd met. Saw the look on his face as he hesitated to harm her. His dark eyes haunted and furious. For the first time, she fully understood what Belle had told her. What the Deadman's Cross on their arms really meant. Blood and bone, Devyl Bane would give it all to see them safe and their souls returned so that they could have their lives back. So long as there was breath inside his body, he would fight for them. He would fight for her. Her gaze went to him and his battle with the one Irin who hated him most. Long before Vine had killed Du, Gadreyal had wanted Duel's head for the simple fact that he'd shown her up and won favor in the war against Thorn and his army. Until Duel, Gadreyal had been the premier Cimmerian general in Britain. The chosen one of the ancient dark gods, and they'd doted on her for it. Yet in no time, he'd surpassed her success rate. No one could match Duel's ferocity. But as Mara watched them, she saw that he was still weak from his earlier attack. Because of the conditions of his release that forbade him from consuming human blood or the hearts of his enemies, he hadn't been feeding properly and therefore couldn't heal as fast as he should. His Aesir lineage held certain dietary necessities that were deemed rather gory to those unfamiliar with their race. Things she'd judged him for over the centuries. And Gadreyal knew it too. She was taking no mercy on him as she drove him back against the railing. If they didn't do something, Gadreyal would defeat him and return him to the hell Thorn had spared him from. "Help him, William!" He hesitated. "No offense, mum, but he'll have me head if I leave your side. And he's a mite big blighter with an awful temper. I'd rather not test it right when he's already upset, if you know what I mean. And I'm rather fond of me bullocks. I'd like to be keeping them a bit longer, if you don't mind." Biting her lip, she debated what to do. To attack Gadreyal would be all manner of stupid. Unlike her, the Irin had been born to battle. She had even more experience than Duel did. With no better idea, Mara lowered her chin and used her powers to smack Gadreyal with the mast. It worked. Tucking her wings down, she stumbled away from Duel with a foul curse. Proud of herself, Mara headed for Du, intending to check on him. She didn't make it. Something grabbed her from behind and sent her sprawling.... Devyl ran as he saw the demon tackle Mara. His heart pounding in fear for her safety, he leapt for them and, while airborne, took the bastard's head with one stroke of his sword for daring to touch her. He landed on the deck and rolled, making sure to grab Mara and pull her with him out of harm's way. They came to rest at the side of the ship, with her on top of him. "Are you all right?" he breathed. "Aye. You?" He nodded. "Why aren't you below like I said?" "You know I don't follow your orders worth a damn." Her teasing tone made him smile in spite of the danger they were in and undermined the anger he wanted to feel. He dropped his gaze to her parted lips and wished fervently they weren't in battle. No sooner had that thought gone through his mind than Gadreyal's troops pulled back. Shite! This can't be good. Dreading the sudden turn of events, he rose gently with Mara in his arms to face whatever hell-storm was coming for them. He kept one arm on her waist while he braced himself. In spite of the continued cannon fire, the dragons circled above, spewing fire down at them that Bart and William deflected. Fierce waves rocked against the ship. A screeching shriek came out from beneath the waves, letting him know that the Carian Gate wasn't the one that had broken. Nay, something far, far worse had happened. There were three major gates that led to Gehyne, or Azmodea as it was originally known. The land most of his crew would call hell. One was located in the desert. One in Jerusalem. The third in the sea. Because of the evil they held back from the world—because mankind could never protect themselves from the vile creatures who called that place home—the portals had been set and locked so that they couldn't be broken. Or so they thought. And to secure them even more, no one had ever known their exact locations. Until now. That was what was coming up from below. Devyl cursed as he understood what was happening. Through Paden and Cameron, they had access to Michael's blood. With it, the Cimmerian forces would have had the means to open any portal in any realm. Even those most sacred, secured gates. And to think, I handed it to the futtocking bastards.... If the world ended, he was the moron to blame. Worse, the Sea Witch was currently taking on water and listing to port. The boards creaked around them, letting him know that she was in mortal danger. Afraid for Mara, who wouldn't be able to stand much more assault, he turned toward her. "Separate yourself." "What?" "You heard me, woman. For once in your stubborn life, do as I say and be about it quickly. Pull out of the ship completely. Let the bastards have it before they use it to destroy you." To his utter amazement, she did so without any further argument. Which told him exactly how much pain she was in and holding back from him. And he knew the moment she pulled her consciousness from the wood. Color returned to her cheeks as her strength flooded back into her body. Grateful that at least one of them was recovering from this searing assault, he kissed her forehead. "Thank you." "What are you planning to do?" His gaze went past her, to the very visage of all futtocking hell realms that was rising from the sea and headed straight for them. Mara hadn't seen it yet, and for that he was truly grateful. So he gave her a cocky grin. "Best you not be asking me questions that have answers guaranteed to upset you, me blodwen." "Meaning?" "Duel!" Mara's cheeks paled again as she heard Vine's low growl. The ship tilted more, sending half the crew to the edge and some over, into the water. "Enough of this." Devyl felt his eyes change over as he summoned up every last bit of his powers and did the one thing he'd sworn he'd never do. But drastic times called for drastic measures. If Vine wanted a battle, let it be on solid ground where they couldn't drown his men. Stepping around Mara, he sent a blast toward Vine and hated that he missed her as she ducked it. "Och now, Vine, you always wanted to be me queen." He gave her a cold smile. "See you in Alfheim, if you dare it." And with that, he ruptured the very membrane of the human world and opened the door that was guaranteed to get him into all manner of shite later. So be it. The only thing that mattered to him was keeping everyone safe. He'd gotten his crew into this. By the gods, he'd get them out, whatever it took. And if the dragons wanted to follow... The Adoni Fey had their own special breed there that would be waiting to swallow them whole. Screams filled his ears as his men were sucked through the swirling darkness and carried away from the realm they'd known and into that of his grandfather's people. God help us all. Devyl had no idea what kind of reception they'd receive upon arrival. What they would find waiting on the other side. It was forbidden to do what he'd done. He wasn't technically one of his grandfather's people anymore, and his mother had brought them all into a war that had caused every one of them to be cursed. Aye, this most likely wasn't going to end well for him.... He just hoped he was the only one who suffered for his rash decision. Suddenly, he stopped falling and landed hard against a solid surface. With a fierce groan, he opened his eyes to find himself in a strange meadow. All around them was purple wheat that seemed as if it had a mind of its own. He glanced about to make sure everyone was here. While most of them had regained their feet, there were a couple who'd been wounded and had decided that sprawled flat upon the ground was more their suited style at present. Their repose was punctuated by unctuous moans and complaints—mainly against him and their concerns about his current mental state. Even more about the state of his parents' marriage at the time of his birth. Not that he blamed them. First, he was beginning to doubt his own reasoning skills. Because, face it, he was the one what brought them here. Secondly, he'd like to stretch out himself. Damn for being captain and having to set an example. Times like this, he was tempted to promote Death or Meers to his position. If only he could follow orders. And speaking of those incapable of listening to others, Mara approached him with a stern countenance he was sure had terrified lesser men. It was so fierce, it even shriveled a bit of his own personal anatomy. "You've brought us to Alfheim? Are you mad? Answer me honestly, is there any semblance of sanity left inside you at all? Or did that knock on the head from Gadreyal spill it all out?" "I thought it the safest place from your sister." "And what about the ship?" No doubt it was at the bottom of the ocean by now. He just hoped Santiago and his crew didn't follow it down to the locker. Hopefully, they'd seen enough to know to stay back, and as far away as possible. Since Devyl hadn't seen even so much as a sail from them during the fighting, he was praying it meant that Rafe's mother's magick had kept his crew shielded from all the hell that had rained down on them. "Warned you to separate yourself from it." "Aye," she said with a note of hysteria in her voice. "That you did. Had I known it was for this bit of lunacy, however, I'd have refrained. Just to..." Her voice trailed off as she glanced over his shoulder to see something in the distance. The color washed out of her face as her eyes widened. What the bloody hell now? More than a bit irritated, Devyl turned to face whatever fresh pandemonium was heading for them. And it was pandemonium indeed. He winced the moment he saw the approaching horsemen and the standards that adorned them. Though in theory they weren't demons, there wasn't much difference between the two breeds. In fact, he'd rather deal with a demon than these particular cod dangles. The irony that they still used his mother's family symbol of a tree and bird, white on black, wasn't lost on him. With hair as white as snow and darker skin that fair glistened in the mystical sunlight of the realm, they were more beautiful than any creature ever spat out of the universal abyss. And more loathsome and corrupt. These were the Adoni. Known as fair elves to much of the world, they were the bane of Devyl's existence, as was evidenced by the male's name, which said it all about not only the Adoni, but the character of this particular bastard's family.... Flaithrí Álfljótrsson. Álfljótr, meaning "ugly elf" or "horrible" or "treacherous." That had been his father's name, hence the "-sson" added to the end of it. The mere fact a mother had given such a moniker to her child also spoke volumes about their family dynamics and why Devyl was such a bastard himself, given that the same blood flowed through his veins. Devyl stepped past Mara to greet them away from his men. They slowed the instant they saw him. At first, he wasn't sure he was recognized. Not until Flaithrí's gaze swept over his body and his eyes widened. He held his gloved hand up to stay the ten Adoni warriors who were with him. William and Bart moved to stand at Devyl's back. "Friend or foe, Captain?" William asked. Devyl scratched at his chin as he considered how to answer. "Not sure." He narrowed his gaze on the riders. "So what's it to be, cousin Flowery? Are we friends?" His nostrils flared. "Flah-ree," he ground out between clenched teeth in the lyrical accent that marked all of their race. "As I said, Florian—" "FLAH-ree!" he growled even louder. William laughed. "Well then, nice to know I'm not the only one you antagonize in such a manner." Devyl cut a menacing glare to him. He held his hands up in surrender. "I'm not questioning your cantankerous nature, Captain. Far be it from me." Crossing his arms, he returned his attention to the matter at hand. "So, cousin Flowery, what's it to be? Blood or wine?" "I hate you, Dón-Dueli. Your mother should have drowned you the moment she went to wash the afterbirth from you." "And yours should have fed you to her hounds." Bart cleared his throat suddenly. "Um, Captain? Not questioning you in any way, sir. But is it wise to antagonize them so, given what's likely to show any second and renew what we just left?" He passed an irritated smirk at Bart. "Given that I be the rightful king of the throne Flowery's father currently parks his arse upon, aye. I dare them to question me." He turned back to his cousin. "That not right, Flowery? Or have you finally found the bullocks to behead your father and come for me?" He stiffened visibly in his saddle. "What would you have of me... Majesty?" The word was more insult than title of honor. Ignoring the slight, Devyl glanced over his shoulder as he felt the hairs on the back of his neck rise. Gadreyal was about to pierce the veil and come after them. He could feel it like a tangible touch on his skin. "You might want to gather up some troops." Flaithrí arched his brow. "Might I inquire as to why?" No sooner had he asked the question than Devyl's enemies brought down the shield and found their way into his grandfather's realm. Devyl smiled coldly at Flaithrí. "No particular reason, other than if you don't, you're going to have something a lot worse than me to worry about." Devyl's men scrambled to their positions as the Iri broke through and spilled into the meadow behind them. "Bloody hell," Flaithrí cursed as he stood in his stirrups to get a better look. Then he cast a hate-filled grimace down to Devyl. "Did you bring the whole lot of those fetid mongrels here?" Unsheathing his sword, Devyl shrugged. "Left a few of the smaller ones behind. No need in being greedy." Flaithrí began a rush of epithets for Devyl as he used his powers to summon his enchanted armor. He turned to his companion on the right. "Get to my father and summon the watch force. Tell him what we've got. Let's send these bastards back to where they crawled from." His companion's dappling horse stretched out wings from its side. He backed the horse up and launched him into flight. Devyl summoned his own armor. Now that they were out of the human realm, the rules of engagement were entirely different. And they were entirely his. "All right, me hearties! Let's show these futtocking bastards what we Deadmen be made of." He added fire to his own sword and made ready for battle. Time for holding back was gone. They were on dry land and in the realm of his grandfather's people. If Vine and Gadreyal wanted a fight, he was more than ready to give it.... With the full ferocity of his entire lineage burning deep within his heart and gullet. One thing about the Aesir, they caved to none, and nothing lit their fuses brighter than the promise of a good, coming brawl. Mara grasped his arm as he started past her. "Duel?" Pausing by her side, he waited for her to take him to task for his warring ways. Instead, she offered him a winsome smile. "Kick their tossling arses. Don't get hurt." He lifted the visor of his helm so that he could give her a quick kiss. He should probably show restraint before the others, especially given the amount of shocked gasps he heard, but in the event this was his last moment with her, he didn't want to die again with another regret. Let his men know that he and Mara had finally put the past behind them and come to terms that were agreeable to them both. Nay, they were better than agreeable. Better than anything he'd ever hoped to have. And if he must die this day, he wanted to go back to his hell with the taste and feel of her lips fresh in his memory. Aye, with that, he could die in peace and be all right. Mara fisted her hand in Duel's hauberk. It took everything she had to make herself let go, knowing he was about to face the Cimmerian army again. How strange that she'd once hated that enchanted black armor—had thought it the ugliest, most vile thing she'd ever laid eyes to. Now, she wished it were thicker and even more enchanted. Anything to keep him safe from harm. So she added her own spell to it. Please come back to me. Keeping herself together right now was the hardest thing she'd ever had to do. Especially when what she really wanted was to take on her tree form and wrap herself around him until she was an impenetrable cage that no one would break to get to him. If only he'd allow it.... His gaze scorched her as he pulled away and gently kissed her hand, then let go. It felt as if he ripped her heart out and carried it with him. Never had anything burned so badly. Or cut so deep. Without a word, he went toward Sallie. "Ready to free your fighting soul, Mr. Lucas?" "Be it safe here, Captain?" "Indeed. If it wreaks havoc in this realm before, during, or after the battle, more's the merrier." Sallie cracked a happy grin. "All right, then. Here's to me blessed mum and to all things what come of good rum!" He uncorked his bottle, and when he did, a fierce, shrieking wind tore out of it. One that quelled and captivated every Deadman near them. Better still, it spooked Flaithrí's and his companions' horses and dumped an arrogant Flaithrí straight on his arse. And when he rose, he came up cursing everything about Devyl. And his men. In virtual unison, their jaws dropped as the wind encircled Sallie, transforming him like a jinn into a huge, muscled berserker—complete with long braids and a double-headed axe. One he flexed over his head as he growled in grave invitation of the blood he planned to feed to his weapon this day. "God's pointed bodikin..." Bart turned to Devyl. "You knew about this, Captain?" Devyl flashed a wicked grin. "'Course. Captain knows everything about his ship and crew. It's why I kept telling the lot of you to leave the man's soul alone afore one of you foolishly let loose the beast in the bottle." Bart choked as he watched Sallie grow to stand even taller than he, and take on the youth that had cruelly been stripped from him when his soul had been savagely severed from his body without his permission. Zumari scowled. "I don't understand." With a knowing grin, Devyl shrugged. "'Twas a curse placed upon him when he came up short a sorcerer years ago. He can only let his soul out when he's on the battlefield. You don't want to know what happens when it's released during peace." "Let them learn it once, Captain," Sallie said with his own grin. "They'll never forget it thereafter." "Duly noted." Bart cleared his throat as he respectfully gave Sallie a bit more room to maneuver. "One more thing, Captain... any pointers on how we're to win this?" "Don't die. Be the last man standing." "Good to know. Pointers on how to kill them, then?" "Cut off the head. If that doesn't work? Run like hell, preferably faster than the poor bloke beside you. Might want to consider tripping him if he proves to be faster." "Beautiful. I so look forward to these deep, meaningful discussions and motivational speeches from you that leave me bullocks completely shrunk and shriveled." Laughing, Devyl lowered his visor for battle. "Better the bullocks than the brains. And better both than your courage." Bart snorted. "Not sure about that. Especially given what's coming at us." He saluted Devyl with his sword. "In case I go down and forget to say it... been an honor serving with you, sir." "And with you, Mr. Meers. Here's to taking them before they take us, and if they do, making sure they join us for the descent into hell." "Amen, coz. Amen." And with that, he left Devyl to head straight into the fray. As Devyl started forward, a foreign chill went up his spine. He turned to see if it was Zumari, but the man was already embroiled in a fierce fight. For a moment, he thought it might be Vine. Until a shadow on his left moved. Now that was all kinds of peculiar. Scowling, he braced himself for an assault. Instead, the shadow came to wrap around him and whisper in his ear with a soft, feminine lilt. "Thorn has sent me with a gift for you. He wants you to know that he hasn't abandoned you, but will be here as soon as he's able." With those words spoken, she pressed something into his palm. Then, as suddenly as she'd appeared, she was gone with nothing more than a mere breezy kiss across his flesh that was fully covered by his armor. His scowl deepened the instant he opened his hand and saw what she'd given him. Michael's Seraph medallion. The very one Cameron had entrusted to Thorn. So there it was.... He wasn't sure how he felt about that, what without Miss Jack being here and all. It didn't seem right for it to be returned now. And with that thought came the deluge of everything they had failed to accomplish. They hadn't found the bodies from the Fleet disaster. The plat-eyes still had control of those poor bastards. He'd allowed Vine to escape her prison by not stopping it. Gadreyal had captured both Cameron and her brother—two mortals born with Michael's blood. And another gate had fractured.... I seriously reek at my job. Why Thorn had chosen him for this, he did not know. Perhaps the beast was a masochist. Or he'd taken so many blows to the head in battle that they'd finally addled him. Devyl hadn't felt this low or incompetent since the day he'd found his sister. Despair threatened to overwhelm him. Until he glanced to Mara, who watched on with terrified fretting. I haven't lost anything yet. Other than a little dignity, and that he could take. Honestly, he didn't mourn its loss at all. Just don't let Mara get hurt. Losing her was the one thing he'd never come back from, and he knew it. Determined to see this through, he let out a fierce war cry and ran straight to Gadreyal. * * * "Marcelina?" Mara went cold at the sound of her sister's voice. Prepared to give nothing away as to her thoughts or feelings, she turned toward her and was immediately taken aback by her sister's incredible beauty. Strange how she'd forgotten just what a graceful, seductive creature Vine was. Why Duel would prefer her over Vine's confident femme-fatale persona, she couldn't imagine. The man must be insane. "Vine." She was proud of herself for keeping her voice so steady and calm. "You didn't free me as you said you would, sister." It was only then that Mara realized Vine had used her powers to completely freeze William beside her. He couldn't move at all. Wanting to check on him, but terrified her sister would kill him if she did, she diverted Vine's attention as best she could. "I was trying. Your friends sank my boat before I could get near your island." Vine tsked at her. "Think you I believe that lie?" "We had a bargain, did we not?" "Aye, we did." Vine's gaze went to Duel as he fought against the Cimmerian army. "But it seems you've been distracted. Not that I blame you. He is a fine specimen of manhood. Well formed and skilled in all the right ways." Mara barely caught the urge to slap her sister, and that wave of unexpected violence shocked her. She stilled her breathing and gathered her composure before it betrayed her and got them all killed. "You've never spoken so highly of him before." And then Mara saw it. Only a flash, but Vine's perfect, porcelain complexion was lined with the black veins that exposed her sister's illness. "Are you Wintering?" The veins flashed again. This time, the black twined over her flesh like a living creature, slithering its way to her lips and eyes to turn them jet black. Even her Titian hair and the sclera of her eyes turned. Mara wasn't sure what stunned her most about that. The fact that her sister was that far gone and she'd missed it, or the fact that Vine could be so beautiful even while disease-ridden. Unaware of her physical transformation, Vine glared at her. "What lies has he told you about me that you believe?" Mara wanted to laugh at the thought of Duel gossiping about anyone, but Vine was being serious. Dead serious. The Wintering had taken the deepest root imaginable. Was any part of this rotted creature the sister she'd once known? "What happened to you?" "What happened to me?" She laughed bitterly. "I was locked in a hole for hundreds of years! You... you"—she stabbed Mara in the chest with a long black fingernail—"my husband coddled and sent into a sleeping trance to protect. Meanwhile, he made sure I was to be tortured! Held so that I couldn't escape!" "You murdered him, Vine." She sneered at Mara. "Have you any idea what he had planned?" "Nay." "He was going to hand us over to our enemies." Mara froze at the mere thought. Surely Duel would never have done such a thing.... "Pardon?" "Aye. He wanted to put down his sword and start a family! Can you imagine? Dón-Dueli of the Dumnonii... the Dark One... the World-King wanted peace." She spat the word to make it sound like the worst sort of insult. Wincing, Mara hated herself for ever doubting Duel. "We are Deruvian Vanir. 'Tis what we dream of. You should have encouraged it." "As I did my first husband? A true Deruvian!" Her sneer lengthened, contorting her face into that of a hideous crone. "Let me tell you what such peace brought my first husband, child. A grave! And it's what would have become of us all!" She grabbed Mara's hand. "Now give me what I need to bury him, once and for all, or I'll make sure you die in a way you won't come back from!" Mara sucked her breath in sharply at the threat. She wanted to deny that this was her sister. But as those words rang in her ears, others followed. Duel was right. Vine had never loved him. She'd never really been capable of love. Even when they were children, her sister had been petty. Mara had overlooked Vine's faults, especially after so many of their family had been slaughtered and burned. Their charred ashes scattered to the winds so that they couldn't regenerate. She'd convinced herself that Duel and his kind were the real evil in the world. But evil didn't pick and choose who to corrupt. It took root like an insidious weed that sought to destroy whatever garden it could find succor in, no matter who, what, or where that garden originated from. Evil was never picky about its host. That was why it was so important to rip it out and toss it off before it could spread and rot the garden from the inside out. Take over and destroy the beauty that made the garden whole and healthy. Tears choked her. Mayhap had she seen it sooner, she could have saved her sister. Too late now. Vine didn't want to be saved. Unlike Duel, Vine didn't fight against the darkness or even try to tamp it down. Rather, she reveled in it. And Mara refused to sit back and watch Duel go down for such a worthless trifle as Vine. To see him die again while he fought so hard for others. Fought so hard against the evil that wanted him. She might not have seen the truth of him in Tintagel, but she saw him now. More than that, he was hers, and the one thing about Deruvians... they protected their own from any threat. Perhaps there's a little Aesir in me, after all. She was not going to protect herself or her sister. Not anymore. And not when she had someone else who now meant more to her. Summoning her own armor, she faced a startled Vine. "What is this?" Vine asked incredulously. "Me choosing to oppose you and your desires. I will give you nothing, except my contempt and disdain for your behavior. Shame on you, sister. Shame on you!" Vine arched a black brow. "You do this and I'll never separate your life force from Duel's." "Good. It will save me the trouble of having to bind it again later." Shrieking, Vine summoned her own armor. While Mara had chosen a light blue, silver, and white for hers, Vine's was a startling green that glowed with its unnatural power. The aura around it hummed and shimmered like a living, breathing membrane to protect her. But nothing was going to stop Mara from keeping Duel safe. Not today. Regretting her decision not to accept Duel's offer to teach her swordplay when she'd had the chance, she summoned the only weapon she'd ever used. Wind and Fire wheels. Though she was a bit out of practice with them, they were the weapons her people were known for. Two half circles very similar to a chakram, they had curved spikes protruding from the blades that were made to look like sunrays or fire. And they cut through flesh, both human and demon, as easily as they cut through the wind. Vine's eyes widened. "You truly plan to fight me?" "To keep Duel safe? Indeed." "What happened to you, big sister, that you'd dare choose an Aesir over family?" "He's been more family to me than you ever were." That caused Vine to attack, full force. With an ear-splitting scream, she manifested her spear and went for Mara's throat. Mara caught the tip against the edge of her right-hand wheel and twisted so that the protruding spike would lock to the blade. It seemed like a good idea until Vine twisted her weapon and almost wrenched Mara's arm out of its socket. Crying out, Mara struggled to remain standing. She couldn't let her sister kill her in this fight. If she did, Duel would die, too. Vine gave a cruel, sinister laugh. "Nay, he will not," she said as if she'd heard Mara's thoughts. She jerked Mara closer with her spear so that she could whisper in her ear. "News to you, big sister... I killed the bastard the day I realized he loved you so much that he sold his soul to give you your freedom so that you could live without him. He was going to tell you when I sliced his throat and then cut out his treacherous heart! That was why you lived on after he died. Why I put you into a sleeping spell." "You're lying!" Distracted by the thought, Mara turned to look out at Duel. The moment she did, Vine stabbed her through her stomach. Crying out in pain, she tried to hold her breath to keep the vicious, biting agony at bay. But it was no use. Every heartbeat drove more pain through her. Worse, Vine kept her upright and on her feet by holding on to the spear. "Half of it was a lie, dearest. I would tell you to figure out which, but you won't live long enough for that." Vine pinned Mara to the ground with her spear, then called for Strixa to join her. She flew in as an owl, then transformed into her human body. With a smile, Vine checked to make sure Mara was dead. Once assured, she ripped the harthfret from her throat. "Good death to you, sister." Strixa arched a brow as if she disapproved and wanted to say something, but didn't speak while Vine made her way over to Duel's henchman. How Duel had always been able to inspire such loyalty from those around him, Vine had never understood. And this particular little tossling pet of Duel's... he'd been a nuisance almost as much as her ex-husband, so it was time she put the bastard to use. Touching him on the brow, she cast her spell. "I think I shall let Duel kill you for me." * * * Devyl staggered as he felt something go through him like a hot poker. It sliced through his middle and left him in agony. For a moment, he thought Gadreyal had gotten through his defenses. Until he realized it was something far, far worse. Mara was dying. Kicking Gadreyal away from him, he ran to find her and cursed himself for not using his powers to send her away from here, her protests be damned. As he reached Mara and William's position, he started to yell at William for failing to keep her safe, then noticed that he was bespelled and had no way of assisting anyone. Not even himself. So he sank to his knees by her side and gathered Mara's cold, limp body into his arms and tried to wake her. She didn't move. Her skin was icy and cold. Her body completely unresponsive. Unable to breathe, Devyl cupped her precious cheek in his hand and pressed his forehead to hers as grief tore him asunder. In that moment, he felt shattered. Lost. Desolate. "Nay!" His eyes changed over an instant before he blasted William free from the spell holding him. "What happened!" "She gave Vine your harthfret? I know not what that is, but it sounded important." That only confused him more as he glanced down to his sword that was comprised of his wand—the same sword that held his stone. No one had taken his harthfret. It was intact. He could feel the power emanating from it. Mara would have known she didn't have his harthfret to give... Yet no sooner had that thought gone through his mind than he realized Mara's necklace was missing from her throat. "What did you do, Mara?" Tears stung his eyes. Had she given it over to her sister as a dupe to protect him? He went cold at the thought. If Vine had her harthfret, she could kill Mara forever. There would be no way to bring her back. Unable to stand it, he rose with Mara's body in his arms and handed her to William. "You better not get caught again. And you'd best make damn sure no one touches her. Do you hear me?" "Aye, Captain." Grinding his teeth against the grief and agony inside him, he balled his hand in her precious hair and bit back his tears, then teleported William and Mara to Santiago's ship, where they'd be safe. At least he prayed for that to be so. That bastard had better not have gone down during their fight. More than that, Santiago had best keep Mara safe from all harm until this was over and Devyl could get to her. Furious and terrified that he wouldn't be able to save her in spite of his magick, Devyl headed toward Gadreyal with only one thing on his mind. Saving the only person in this world who mattered to him. The world and all else be damned. "Where's Vine?" "Vine who?" "Don't play that game, she-bitch. I'm in no mood for it." He raked a glare over her blood-colored armor, wanting to add more red to it. And some brain matter as well. There was nothing left inside him now except a fury so raw and potent it would not be appeased until he tasted someone's heart and soul. He wasn't selective as to whose it had to be, either. The beast within was awake and it was salivating. Gadreyal threw a bolt at him. He absorbed it and shot it back to her, with interest. Then he added another. And another. He summoned the lightning and shot it at her. She shrank away in terror. You better run, trollop! He was done with them all. There was no Aesir left in him now. None whatsoever. Devyl swept his gaze over the battle, seeking Vine. It was an even split as to who was winning. His Deadmen were holding their own. But the demons were fierce. As one of Gadreyal's men ran at him, he shot a mage blast at the moron and disintegrated him. "Vine!" he snarled, wanting her head. "She is here." He hesitated at the feminine voice in his head. "Strixa?" "Aye. And it's not a trap." "Why would you help me?" Strixa hesitated before she answered. "Vine has broken the code of sisterhood. I will not tolerate that. She has the harthfret and is planning to plant it to kill your Marcelina." Devyl let out a curse as she pierced his brain with an image of where Vine was. Damn, that hurt. But he was grateful beyond measure. And it was too bad the stupid twitling didn't have his stone instead of Mara's. Where she was burying it would have fed his powers even more. But he had no idea what it would do to Mara. Tiveden, or Tyr's Wood, was said to be some of the most fertile land here. It's where the god had once planted his own seeds to grow his warriors. Those preternatural soldiers who'd been born of Tyr's brook now comprised the bulk of his uncle's Royal Guard. That gave him an idea. Pulling the Seraph medallion out, he placed it in the same cage as his own harthfret. The moment the two touched, it sent a jolt through his entire body. One that left him breathless and warm. Heat spread throughout his body, and for a moment, he heard more than just the aether around him. He could taste it, even. It also brought him to Gadreyal's full attention as she felt the awakening of the Seraph blood mixing with his. That caused every member of her horde to disengage from their opponent and head toward him. Which was great for his men. For him? Not so much. Belle wiped the blood from her sword before she and Sancha came to take up positions by his side. "What's it to be, Captain?" "All-out bloodletting. No prey, no pay." With that, Bart threw out his hand and raised his own army of soldiers made of blackthorns. They twisted up from the ground and into monstrous beasts, complete with thorny swords, standing ready to fight to the end. Valynda summoned Ghede Nibo—the Vodou loa. He was the leader of the spirits of the dead, and the one Thorn had bargained with for Valynda's parole. They were also close friends. How close, Devyl wasn't sure. But he'd heard Valynda speaking to him whenever she thought no one else was around. And obviously, Nibo thought enough of her that he'd negotiated with Baron Samedi to bring her back to life so that she could join their crew. It wasn't something either of them did lightly. Or anything they were known for. Dressed in a black coat with a bright purple sash and shirt, Nibo was in his human form—ethereally beautiful, with dark curly hair and chiseled features. As usual, he was accompanied by his "twin" companions, Masaka and Oussou. Yet for being called twins, they were complete opposites of each other. Masaka a tall, androgynous woman who wore a small white tricorne emblazoned with skulls that matched her jacket and breeches, and a black ruffled shirt. Her skin was as dark as Oussou's was pale. And while her hair was black, Oussou's matched her bone-colored coat. Dressed in a black gravedigger's jacket that held a white cross on each sleeve, he had his pale braids covered with a black tricorne that was festooned with mauve feathers. A smile spread across Oussou's handsome face that said he was savoring the coming battle as he handed Nibo his skull cane. In turn, Nibo passed to Oussou his bottle of white rum that held medicinal herbs. Oussou took a deep drink of the rum while Nibo pulled the head of the cane to reveal the sharp saber inside it. He handed the scabbard to Masaka. She held it up and bent it in the center. It immediately broke apart and crawled down her sleeves like twin snakes to form a thorny set of knives along her forearms. Though they were members of the Ghede loa nanchon, they had much more in common with their warring Petro cousins. Fiery to their bones. There was nothing the three of them liked more than to raise hell and brawl. Well, there was one thing they liked better. But the fury in their eyes said that their passion right now wasn't carnal. They craved the same blood Devyl could taste. And their combined presence here made Gadreyal shrink back. She hovered over the ground with a jaundiced eye at the increase in their number. "You can't wield Michael's blood," she snarled at Devyl. "It's more likely to kill you than serve you." "Then why are you so afraid all of a sudden?" She threw her axe at him. Devyl caught it in his hand, kissed it, and hurled it back. His reward was another shrill shriek. And he knew this was a ruse to buy Vine more time. Every second that passed was critical for Mara. They all knew it. While his cousin led in his own attack, Devyl gave the signal to his crew to renew their battle with everything they had. He hated to leave them, but he had no choice. For the first time ever, he understood the Deruvian code—that one life was indeed far more precious than all others combined. Aye, it was that very selfishness he'd once hated Vine and her entire Vanir race over. Maybe he was more Vanir than he wanted to admit. But right now, nothing mattered to him. Nothing except Mara. The world could burn for all he cared. Without Mara, it didn't deserve to be here. He could hear his heartbeat thrumming in his ears as he left the field of battle to teleport to Tiveden. No sooner had he materialized on the side of the tallest hill than he drew up short to find his ex-wife in all her fiery glory. Right down to the orange and red dress that appeared to move like living flames in the fading sun. "You're too late," Vine gloated the moment she saw him. "I've planted you here and here you will stay." His knees went weak at her declaration. "You didn't plant me here—'twas Mara's harthfret you stole." She paled. For a moment, the black veins left her skin as confusion lined her brow. It was obvious she was trying to discern whether or not he was lying. "What?" "Had you asked, I'd have gladly given you mine to keep her safe. You should have known that, Vine. I always protected Mara over anyone." That had the desired effect on her. She let loose an insane cry before she started toward him. Yet before she could reach him, the ground on the hill began to tremble and boil. Like a living, starving beastie, it rose and fell, and percolated with such force that Vine squealed and danced away from it. Half expecting something foul to emerge out of the chaos, Devyl stumbled and barely caught himself before he went sprawling. "What have you done?" Vine gasped accusingly. He shook his head as he struggled to comprehend it. Never had he seen the like. "Nothing. That is not me." Smoke billowed up in sharp, inky black spirals. They danced in an invisible breeze until they began to slowly twine about and take the shape and form of a woman. Devyl held his breath, praying silently for a miracle. But to his utter disappointment it wasn't Mara they formed. The shape was too short and flat about the bosom to be his better half. Yet there was something vaguely familiar to that outline. Something that wiggled in the back of his mind. Suddenly, he knew exactly why. Nay... this could not be. It's not possible. His breath catching in his throat, Devyl froze as shock claimed him fully. And still there was no denying the woman who manifested in front of them. "Elf?" His voice shook with uncertainty. "Is it really you, lass?" Like a newborn fawn, she worked her face as if trying to remember how to speak. How to see. She stared down at her hands and wiggled her fingers, then scowled at Vine. Color flooded into his sister's pale cheeks. The air began to stir to a fierce level. It whipped at Elf's hair, spiraling it into tendrils and plastering her burgundy dress against her lithe body. "You sought to harm my brother?" she finally spoke. Her features pale, Vine stumbled back. She glanced at Strixa and then Devyl. "What is this?" Her mouth worked soundlessly before she choked out, "How is this?" He wasn't sure, except for one thing.... "You must have buried Elf's harthfret instead of Mara's." Though how it could regenerate her after all these centuries, he had no idea. He'd never heard of such. It wasn't possible. On furious impulse, he'd reclaimed Elf's harthfret that day when he'd gone into Mara's nemeton. Like a frenzied beast, he'd dug through the wood and earth until he found it at the base of the tree where she'd planted it. For years, he'd tried to regenerate her. Nothing had ever worked. Never had it taken root, and so he'd set it into a signet ring to keep it forever with him. So aye, he was with Vine in one way only... how the futtocking hell was this possible? Vine started to leave, but something held her in place. Elf's breathing turned ragged as she stalked toward his ex-wife like a vicious predator with cornered prey. "You do not escape here. You do not escape me." Her voice was no longer the sweet lilt he'd known from his younger sister. It was demonic and fierce. "You wanted war?" Elf blasted her. "By all means, have some!" Vine screamed as fire consumed her. Holding her hands up, she tried to save herself, but it was useless. The fire spread quick and fast, and engulfed her entirely. Then Elf turned to him. Devyl braced himself for her attack, especially when she came running toward him, full speed. But instead of attacking, she threw herself into his arms and held him close, as she'd done when they were young. "I should have listened to you!" She sobbed in his arms. Dumbfounded, he held her in an awkward embrace, still not completely convinced this was his sister. It was just the sort of cruel trick Vine specialized in. Among many others. Not until Strixa moved closer to them and reached out to touch his arm in a comforting gesture of solidarity did he begin to have some belief that this might not be a massively cruel jape. "Mara stole the harthfret from you. She was working to see if there was some way she could bring your sister back. While I may not think much of you, demonspawn, the Lady Marcelina loves you." "This is real then?" His voice trembled. Strixa nodded. "It would never have worked had Vine not planted Elyzabel here, where Tyr's blood saturated the fields, and had your sister not died unjustly before her time." "Because Tyr's a god of justice." She nodded. "And is part of your family. His blood is her blood. It rejuvenated her. Yet even so, it wouldn't have been enough had Nibo not come here with his magick." Because regenerating the dead was one of his specialties. And that gave him another thought. "Where's Mara's stone?" Strixa tsked at him and lifted the hand he had on Elf's shoulder. "She left her heart with you." It took him a second to realize that Mara had swapped her stone with Elf's in his ring. He'd worn the ring for so long, but because it reminded him of his failings, he seldom looked at it. Until now. Now he let the warmth of Mara's life force heat his entire body. "Elf?" he breathed, kissing the top of her head. "There's something I must do." "Save Mara?" He scowled at her. "How do you know about Mara?" "Once you carried my stone with you, I could hear everything you said." Heat scalded his cheeks as he realized some of the other things she might have overheard. In that familiar teasing way, she tugged at his whiskers. "Aye, my brother. Even that." He groaned out loud. "I'm so sorry." "For what? Not abandoning me? You did nothing wrong, Duey. Now let's go save your wife." * * * Devyl drew up short as he reappeared on the battlefield where he'd left his men. He had to give the Deadmen credit—they didn't withdraw from conflict. Ever. And this was a bloodbath. Gadreyal and her forces weren't going down easily. Lightning flashed. The sound of battle rang in his ears. This was what he'd grown up on. And as he took his sister's hand, he hesitated for the first time in his life. "I failed to protect you." "Nay," Elf breathed, reaching up to cup his face in her hand. "My fiancé failed me. At their behest." She jerked her chin toward Gadreyal. "She was the one who set me up, and you. She wanted you out of the way." He felt his fangs elongate at her words as the demonic beast inside came to the forefront. Elf stepped back and inclined her head, then turned herself into a small sprite. She flew to kiss his cheek and whisper in his ear. "None shall see me, big brother. Do what you do best and worry not this time. I'll be right here." She pressed herself against his jugular and became a part of his skin. Knowing she was safe so long as he didn't take a blow there, he lowered his visor and headed straight for Gadreyal. This time when he caught her with his sword, it knocked her reeling. But he gave her no quarter. Not now. Not ever again. "Where is Cameron?" he growled. "Her life is all that will spare yours." Gadreyal staggered back from his blows. She tried to fly away, but he sliced her hard across the wings, almost completely severing one. His time for mercy had passed. Her time for living was growing perilously short. "Release my men and give us back our Miss Jack! I shan't say it again." Gadreyal hissed and twisted, then blasted him. But he didn't feel it. He was too angry. "Thorn can't save you!" "I'm not looking for him to." Devyl kicked her back. "Captain!" He hesitated at Hinder's and Belle's shouts. Glancing to them, he saw that his cousin had opened a gate and allowed Thorn and a group of Sarim inside this realm. The moment Gadreyal saw them, she gathered her warriors and vanished. "Nay!" Devyl started after her, but Thorn caught him and prevented it. "We have Cameron and her brother." Those words barely registered. "What? How?" Thorn tightened his grip on Devyl's arm. "We've found them, but we need the blood of a Deruvian or Myrcian to unlock the gate that holds them. It's why we're here." He glanced around the field. "Where's Mara?" Devyl choked on the answer, then forced himself to speak past the agony that seized him. "Vine killed her." Thorn's eyes widened. Because he knew what Devyl did. Deruvians didn't always come back from their graves. "You gave me your word, Leucious. Can I hold you to it?" Thorn nodded glumly. "What of Cameron?" Devyl handed him the sword. "Her medallion's inside. I will take her place and let them out, but you have to finish this." Before Thorn could take him up on it, Kalder came forward. "Nay, let me go, Captain. My life for Miss Jack and her brother." "Kal—" "No argument, Bane." Kalder glanced around at the Deadmen. "I'm the most expendable here. But you and the Lady Ship... the crew needs you both." "We're pirates," Sancha said as she wiped at the blood on her cheek. "We vote." William grimaced. "I vote we lose no one." Thorn scoffed at his suggestion. "It doesn't work that way. One of you has to go. There's no other way for it." Kalder nodded. "Matter's settled, then. We need our ship and our captain. We don't need a mermaid." It still sat ill with Devyl. And for once, he was coming around to the way the Vanir saw things. He didn't like the thought of sacrificing the one to save the many. "I'll find a way to get you back." "God, I hope so, Bane." Kalder winked at him. "'Cause one way or another, I plan to return for Miss Jack. Please tell her I said that." Devyl held his tongue as he watched Michael and Gabriel take Kalder. He didn't have the heart to warn the merman of the truth. Either way, he was dead. Most likely, they both were. His heart heavy, he locked gazes with Thorn. "Well?" Thorn grimaced at the question. "Well, what?" "We have to get Mara back." "I can't do anything. You know that. She's beyond my reach." When Devyl started forward, Valynda stopped him from grabbing Thorn and ripping out his throat. "It's not final, Captain." She turned to Nibo. "You can help her, can you not?" Eyes wide, he exchanged a nervous grimace with his twin companions. "Is not so easy, ma petite ange." "But not impossible. Especially for you, Papa." She reached up and caressed his cheek. "You can do this for me, can't you?" Nibo practically melted at her touch. "Oui. I will try." "Nay, love. You will succeed." * * * In every culture, crossroads were significant. As an Aesir, Devyl had been taught to be wary of them, as they were oft haunted by the cŵn annwn, cyhyraeth, Adoni, or Gwrach y Rhibyn, who preyed on unwary travelers, seeking souls or victims for nefarious ends. Nothing good ever happened in such places. And this evening was no exception. For it was here in his grandfather's kingdom that he was being returned to the hell Thorn had saved him from. Nibo let out a tired sigh as he finished his chant. "You're sure about this?" Devyl nodded. "She doesn't belong there. Are you sure this will work?" "Aye. The parties have agreed. They would rather torture you, as you have earned damnation, while she has not." He gestured toward his companion. "Masaka will lead you in and then return with Marcelina." Devyl narrowed his gaze on the loa. "No tricks?" Nibo quirked an amused grin. "You are wise to be suspicious. But on this, I gave me word to Valynda. I assure you that I won't break her heart." "Nor will he cross me." Thorn cleared his throat abruptly. The laugh Nibo let out contradicted Thorn's arrogance. But that was all the loa had to say on the matter. "If you're ready?" Almost. Devyl swallowed hard against the painful knot in his throat as he met the tear-filled gaze of his sister. "I'm sorry to be leaving you alone in this world, Elf." Sniffing, she nodded. "I understand. I just hate to lose you again." He kissed her hand and held it for a moment longer. "Tell Mara that I've always loved her. And that she's never to feel guilty for this. I would rather she think of me fondly, if she's able. And only smile whenever she does so." A tear slid down her cheek as she nodded. "I love you, Duey." "My precious Elf." He kissed her forehead. "Take care." And with that, he stepped back and glared at Thorn. "Let no harm come to my girls." "On my honor, Dón-Dueli. It's been a privilege." "I wouldn't go that far. You're still a thorn in my arse." Thorn laughed, but his eyes were as sad as the others' as Masaka placed her hand on Devyl's shoulder and they faded back into the hell Devyl knew he'd be forced to endure for all eternity. Think of Mara. This was for her. She was safe now. She had her life back. Free of him. But that didn't help. Not really. Because in the end, the greatest hell wasn't the physical agony he knew awaited him. It was the mental and emotional torment that came from knowing that she finally loved him and that now he would be forced to live without her. Forever. * * * Kalder hesitated as he saw the dense crystal wall that kept Paden and Cameron imprisoned. They were frozen in a sheet so thick, they barely looked human. But the worst part of all was the expressions of horror frozen upon their faces—as if they were caught in the midst of a nightmare only they could see. "What have they done to them?" Rage darkened Thorn's eyes to a vibrant green glow. "It's not what's there that's terrifying, Myrcian. It's what's not." "How do you do mean?" Thorn placed his hand on Kalder's shoulder. The instant he did so, pain tore through Kalder's head and ripped back the layer of this world so that he could see the reality where Cameron and Paden currently lived. The realm where their souls had been cast by Vine's evilness. Gasping, he felt a fiery chill that was so cold it burned. Felt Cameron's despair and her brother's terror that he was going to kill his own sister, and that Paden would be powerless to stop the hunger inside him that demanded her innocent blood. Thorn let go and stepped away from him. Kalder staggered as his vision cleared and he returned to this reality. His breathing ragged, he blinked rapidly, looking from Thorn to Michael and finally Gabriel. "Can you always see like that?" They nodded in turn. "Not fun, is it?" Thorn said bitterly. "To know what lies behind the human veil and not be able to interfere. It's its own form of hell." Kalder wiped at the tears as he struggled to even out his breathing. "Is that why you came for us?" Thorn passed a sullen glare to the other two. "Aye. Unlike some, I can't abide injustice." Michael turned on him with a vicious hiss, exposing a set of fangs that Kalder hadn't noticed before. "Never speak to me of injustice, demon! You've no right! You know nothing of me or mine." Thorn held his hands up. "Point being, I believe in second chances." Michael curled his lip. "Most demons do, as the second strike usually cuts even deeper than the first." Now it was Thorn's turn to go for Michael, but Gabriel caught him and forced him back. "Enough! Both of you! We're not here to fight each other." He jerked his chin toward Paden and Cameron. "Every second you bicker, we risk losing them forever." "If we haven't already," Michael said under his breath. Kalder winced as he pressed his hand against the cold rock that kept him from Cameron's warmth. How strange that he barely knew her and yet she'd sparked something inside him that he'd never known he possessed. A heart. He hadn't even kissed her and yet here he was willing to die to save her. It made no sense whatsoever. But then life seldom did. Perhaps it was that innocent optimism she held in spite of all the shite life had heaped upon her that had restarted the dead organ in his chest. Or the loving light in those hazel eyes that sparked whenever she spoke of her brother. The way she kept faith even when it seemed there was no hope whatsoever. No one had ever held such regard for him. He'd never wanted them to. Until now. By all that was holy and not, he wanted her to look at him like that. To see her eyes light up and twinkle for him in the same manner as they did for Paden. Nay, that was a lie and he knew it. He wanted much more from her than that. He wanted to have one woman, just once, see him the way she saw her brother. As a noble hero. As her noble hero and champion. One she was willing to sacrifice her life for. He wanted someone to love him like that. Completely and without question. With total loyalty and devotion. To love him the way his mother had loved his brother. To have someone mourn his passing and regret that he was no longer part of her life. No one had even shown up for his burial after his mother had gutted him. Not even a priest. The watchmen had taken him out and dumped his body in a common grave like garbage. No pomp. No last rites. Nothing. Not a single kind word. After all the years he'd lived, he'd meant nothing to anyone. Only Cameron had ever teased him like a friend and made him feel noble or welcome. Damn him for craving it. Because now that he knew the taste of it, he couldn't go back to his ignorance. It was a raw, fetid hunger that wouldn't leave him in peace. He couldn't return to the way he'd been. Numb and oblivious. She'd opened his eyes and awakened him. And if he had to die to bring her back, so be it. Unlike him, she was a vibrant soul who brought happiness to the world, and to those around her. As did her brother. He had a woman waiting for him, and a child who needed a father to claim it. They were rare lights that shone brightly in this dim, awful world. No one will ever miss you, Kal. "Let's do this," he said to the Sarim. "I don't want her to suffer another moment." Thorn inclined his head to Kalder, then passed a harsh, condemning glare to the Sarim. "Tell me again how the damned are beyond redemption?" They looked away sheepishly. He clapped Kalder on the back. "Know that it sickens me to do this to you. If there's any way to save you, we will find it." Kalder nodded. "Tell Cameron that it was my honor to spare her." He pulled the necklace off that had belonged to his brother and handed it to Thorn. "And give her this from me. Ask her to pray for my brother's soul." "Not yours?" He let out a bitter laugh. "We both know where mine belongs and where it be headed." Thorn took the necklace and tucked it into his pocket. What he had to do sickened him to the core of his worthless soul. But he had no choice. The two bitches with him weren't about to spare him this, and he knew it. They would never spare him any nightmare. Cursing his father and himself, he pulled out his dagger and as quickly and painlessly as possible, he sliced Kalder's artery so that his blood coated the floor. The Myrcian staggered, but Thorn caught him and kept him from falling to the cold ground like garbage. He held him in his arms as his life faded. "Sleep in peace, little brother," he whispered against his ear. "I won't let you die alone this time. And you will be mourned and missed. You are a good man, Kalder. Let no one ever tell you otherwise. Not even you." Sinking to the ground, Thorn cradled him in his arms and held him there until he bled out and was gone. Tears filled his eyes as he hated everything about himself and the choices he was forced to make. Choices they were all forced to make. Michael didn't say a word as he gathered Kalder's blood and used it for the incantations he needed to free his progeny. Gabriel knelt by his side. "Thorn?" He blinked slowly, unable to answer for the pain inside him that churned and ached so deep that it left him hollow and numb. "You need to let him go." Yet he couldn't bring himself to do it. Not when he knew the horrors that had haunted Kalder. "He's not garbage." "I know." Nay, he didn't know. Not really. Closing his eyes, Thorn clutched at Kalder's head and swore to them both that he would find some miracle to free the Myrcian. Even if he had to unravel the universe to do it. "Kalder?" Blinking, Thorn looked up as Cameron came out of the wall to see them on the floor, saturated in blood. With a fierce sob, she rushed to them. Her hands trembled as she sobbed and clutched at Kalder's jacket. "Nay! Nay! I can't lose him! Not like this!" Thorn pulled her against him to comfort her. "Shh, child. He only sleeps." She stared at him as if he were crazy. And he was, indeed. For only a crazy person would have defied the powers that be to create the Hellchasers as Thorn had done. He felt his eyes turn bright red before he offered her a determined grin. "I brought him back when he had absolutely nothing to live for. Do you really think he'll stay down now that he has so much to lose?" * * * Mara came awake to the most peculiar warmth. Until she remembered her sister's treachery. Furious, she sat up and... What the devil? She was on board a ship, but it wasn't her body that made up this vessel. "Du?" she called, glancing around the small, unfamiliar cabin. Instead of Duel, Thorn came in to stand beside her bunk. "How are you feeling?" "Very confused. Where's Du?" How had she gotten here? She couldn't remember anything. Not really. Everything was so vague. Like a strange, flimsy dream. Thorn didn't answer. Rather, he stepped aside for another woman to enter the room through the door behind him. "I don't think the two of you have ever met." Nay, she'd never seen the... Her heart stopped beating as she realized who this was. It was a face she'd only seen in her visions. "Elyzabel?" She inclined her head to Mara. "Aye, my lady. How are you?" "Where's your brother?" Elf glanced nervously to Thorn. When they didn't answer right away, a bad, horrible dread went through her. She tried to leave the bed, but Thorn prevented it. "You're still weak." "Tell me where Duel is!" Thorn continued to hedge. "Well... you know where you were." "Aye." She was finally beginning to remember the hellish hole where Vine had cast her. She couldn't imagine how Duel had stood it for so long. "To get you out, we had to have someone sacrifice their life and harthfret for yours." Oh dear God, no! The blood faded from her cheeks as tears welled in her eyes. Surely Thorn wasn't telling her what she feared he was saying. Nay, Du wouldn't be so stupid. You know better! Of course, he'd be that stupid! Agony and grief wrapped around her heart and set it to pounding. "Tell me he didn't," she breathed as dread washed over her and brought tears to her eyes. Elf nodded. "He wouldn't be swayed. For you, he was willing to do anything. Sacrifice all his crew. He wanted me to tell you that he's always loved you and that you are not to feel guilty. That you are to remember him fondly and only smile when you think of him." Silent tears streamed down her face. "Nay!" She struggled to breathe past the pain that choked her. "We must get to him." Rising to her feet, she shoved Thorn out of her way. "I... I..." Her legs gave way and sent her to the floor, where she broke down into fierce, racking sobs. The agony of his loss was unlike anything she'd ever known. Du! Oh gods... She couldn't do this. She couldn't make it without him. Especially knowing that it was her fault he was gone. That he'd done this to spare her. Suddenly, strong arms surrounded her and held her against a hard, muscular chest. She started to struggle for release until the scent of this man's skin hit her. That sweet sea musk scent wasn't Thorn's. Shocked and stunned even more, she looked up into a pair of angry red eyes. "Thorn! You rank futtocking bastard! What did you do?" "Du?" She reached to touch his face, then sobbed even harder. "Shh," he breathed, rocking her in his arms. "All's well, my love." Her breathing ragged, she glared at Thorn. "What cruelty was this?" Crossing his arms over his chest, Thorn smirked. "No cruelty. All of it was the honest truth. Devyl took your place in order to set you free." Elf nodded. "He said to tell you every word I spoke." Mara scowled at them. "I don't understand." Du wiped at the tears on her cheeks, then offered her a crooked grin. "I'm such a cantankerous bastard, they refused to keep me. Apparently, my face is not nearly as sweet as yours." Thorn scoffed. "Not entirely true. When I signed Devyl on, it was with one understanding." "You were never to be harmed, Mara." Devyl brushed the hair back from her face. "Aye." Thorn sobered. "He gave his soul to unbind your lives and by doing that and then sacrificing his life so that you could live again...." Du held up his wrist for her to see that his Deadman's Cross was gone. "I bought my freedom." Thorn nodded and smiled. "He made his sacrifice. His slate is wiped completely clean. And rather than flee and start his mortal life anew, he chose to stay on with his crew and to wait and see what you wanted to do with your freedom." Gasping, she ran her fingers over his arm where his brand had been. "You're free?" "Aye, thanks to you." Thorn and Elf gave them the cabin. Aghast, Mara stared up at him. "And Vine?" "Dead. I killed her. We're on Santiago's ship and—" She interrupted his words with a kiss. And then another. "I will make our ship again with my body as soon as I'm strong enough." Devyl nipped her lips, then brushed his nose against hers. "Our?" Laughing, she nodded. "Aye, Captain Bane. You don't think I'm about to let you sail without me, do you?" "You're sure?" "Absolutely." His eyes turning even darker, he reached for the laces on her gown. Mara's breath caught as he gave her a kiss so hot it scorched her. His hunger was absolute and it matched her own. More than that, it inflamed hers. She still couldn't believe this was real. That she was back from the dead and that he was here in her arms. "What were you thinking when you switched places with me?" "That you had no business there." His tongue teased her earlobe, sending chills over her as he laid her back against the bunk. "And that I couldn't live knowing you had died because of me." "You are a fool, Dón-Dueli." He pulled back to flash his dimples at her. "Aye, but only for you." That was true. Her breath caught as he swept her gown off her body and the cool air hit her skin. Desperate to feel his flesh against hers, she pulled his shirt over his head. And leaned against him so that she could savor his embrace. "We've much to do, you know." "True." He nipped her chin with his teeth while he held her gently in his arms and cradled her body with his. "Santiago has signed on to be our backup until we see this finished." "And Thorn agreed?" "Free will. Agreeing's got nothing to do with it. He can't stop him." She shook her head at the poor pirate who had no idea what he and his crew were in for. "What else have I missed?" A boyish grin played along the edges of his lips while he drew small circles around her breasts and nibbled the outline of her jaw. "Much bickering. A lot of soul-searching as we tried to put Sallie's soul back in its bottle and Strixa decided to stay on with us as well." She arched a brow at that. "Really?" He pulled back with an irritable grimace. "Aye, but is this truly what you want to be focusing on right now, love?" She dropped her hand down the waistband of his breeches and noted the way he held his breath. And the instant softening of his glower. "Not really." His breathing turned ragged the moment she dipped her hand inside to gently stroke him. His features relaxed and turned gentle and sweet. Biting her lip, Mara took pleasure at the power she had over her captain. A dark and fearsome sorcerer corymeister he might be, but it was a Deruvian magelyn who owned his heart and could change his mood at her merest whim. "I will always fight for you, Du. Come the morrow, I want you to teach me how to wield a sword." He arched a brow at that. "You're sure?" She nodded. "You were right. We're only as strong as our weakest link, and I will not be the means to defeat you." Devyl cupped her cheek before he kissed her. "You are never my weakness, Mara. You are my strength. And I will teach you to be the best swordsman in all the world." "Good." She slid his pants from his hips. "Now come here, husband, and show me some of your finer, most skilled moves." Laughing, he laid her back against the bunk and gently slid himself home. Mara sucked her breath in sharply at the sensation of Duel deep inside her as she cradled him with her body. She should be afraid of the future. The gates were still cracked. And they'd lost a number of their crew. Paden's unborn child carried with it the blood of Michael that could open all the gates and unleash the worst of all evils upon the earth. And yet in Duel's arms, she felt completely safe. Because she knew her Devyl would never allow any harm to befall her. Nay—so long as this Devyl and his Deadmen were on the side of right, evil didn't stand a chance. EPILOGUE Gadreyal hesitated as she neared the only creature she answered to... the one being even more corrupt and dangerous than she was. Papa Noir. Dark and sinister, he sat on his throne with his sister Azura by his side, glaring at her. "You failed." "Not yet. I merely positioned my pieces." Noir rolled his eyes. "You failed," he repeated. Gadreyal could have handled it a lot better had Jaden not picked that moment to enter the room. He was a handsome beast, except for those unnerving eyes. One a bright, bright green and the other a deep earth brown. Like Noir and Azura, he was a primal power who would have been invincible— Had Jaden not sold himself to them to protect one of Gadreyal's greatest enemies. "Is it done?" Noir demanded of Jaden. He took a long minute to glare at his owner until he finally nodded. "I wasn't given dominion over trees for nothing." He snapped his fingers. After a few tense moments, Vine slowly unfurled from the floor until she blossomed back into the great beauty she'd been. Her eyes were dark and deadly as she glanced around them. But Noir was unimpressed. "You two know your target. Do not fail again." Gadreyal inclined her head to him before she took Vine's hand and led her from his study. Vine didn't speak until they were alone. "I can't believe I live again." "It's temporary. And if we don't succeed this time—" Vine interrupted her with a laugh. "Don't worry. We have the element of surprise on our side. More than that..." She held up the medallion she'd traded out. The medallion that gave them complete control of Cameron Jack and her bastard Seraph brother. This wasn't over. It was just beginning. Also by Sherrilyn Kenyon THE DARK-HUNTERS Night Embrace Dance with the Devil Kiss of the Night Night Play Seize the Night Sins of the Night Unleash the Night Dark Side of the Moon The Dream-Hunter Devil May Cry Upon the Midnight Clear Dream Chaser Acheron One Silent Night Dream Warrior Bad Moon Rising No Mercy Retribution The Guardian The Dark-Hunter Companion Time Untime Styxx Dark Bites Son of No One Dragonbane Dragonmark Deadmen Walking THE LEAGUE Born of Night Born of Fire Born of Ice Born of Shadows Born of Silence Born of Fury Born of Defiance Born of Betrayal Born of Legend Born of Vengeance CHRONICLES OF NICK Infinity Invincible Infamous Inferno Illusion Instinct Invision About the Author New York Times bestselling author SHERRILYN KENYON is a regular in the #1 spot. This extraordinary bestseller continues to top every genre in which she writes, including manga and graphic novels. More than seventy million copies of her books are in print in more than one hundred countries. Her current series include The Dark-Hunters®, The League®, Deadman's Cross™, Chronicles of Nick®, Hellchasers™, Mikro Chasers™, and the Lords of Avalon®. Her Chronicles of Nick® and Dark-Hunters® series are soon to be major motion pictures. Information about her series can be found at www.sherrilynkenyon.com, www.dark-hunter.com, and www.officialsanctuary.com, or sign up for email updates here. Thank you for buying this Tom Doherty Associates ebook. To receive special offers, bonus content, and info on new releases and other great reads, sign up for our newsletters. Or visit us online at us.macmillan.com/newslettersignup For email updates on the author, click here. Contents Title Page Copyright Notice Dedication Acknowledgments Prologue Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Epilogue Also by Sherrilyn Kenyon About the Author Copyright This is a work of fiction. All of the characters, organizations, and events portrayed in this novel are either products of the author's imagination or are used fictitiously. DEADMEN WALKING Copyright © 2017 by Sherrilyn Kenyon All rights reserved. Dark-Hunters® and Lords of Avalon® are registered trademarks of Sherrilyn Kenyon. Other marks and symbols used on the book cover and throughout the book are trademarks of Sherrilyn Kenyon, including but not limited to Deadman's Cross, Hellchasers, Deadmen, Hell-Hunters, the Deadman's Cross skull and crossbones design, and all words and symbols used in connection with the chapter headings. Cover art by Stephen Youll Cover design by Russell Trakhtenberg A Tor Book Published by Tom Doherty Associates 175 Fifth Avenue New York, NY 10010 www.tor-forge.com Tor® is a registered trademark of Macmillan Publishing Group, LLC. The Library of Congress Cataloging-in-Publication Data is available upon request. ISBN 978-0-7653-8568-0 (hardcover) ISBN 978-0-7653-9840-6 (signed edition) ISBN 978-0-7653-8569-7 (e-book) e-ISBN 9780765385697 Our e-books may be purchased in bulk for promotional, educational, or business use. Please contact the Macmillan Corporate and Premium Sales Department at 1-800-221-7945, extension 5442, or by e-mail at MacmillanSpecialMarkets@macmillan.com. First Edition: May 2017 ## Contents 1. Title Page 2. Copyright Notice 3. Dedication 4. Acknowledgments 5. Prologue 6. Chapter 1 7. Chapter 2 8. Chapter 3 9. Chapter 4 10. Chapter 5 11. Chapter 6 12. Chapter 7 13. Chapter 8 14. Chapter 9 15. Chapter 10 16. Chapter 11 17. Chapter 12 18. Chapter 13 19. Chapter 14 20. Chapter 15 21. Chapter 16 22. Chapter 17 23. Chapter 18 24. Chapter 19 25. Epilogue 26. Also by Sherrilyn Kenyon 27. About the Author 28. Newsletter Sign-up 29. Copyright ## Guide 1. Cover 2. Table of Contents
{ "redpajama_set_name": "RedPajamaBook" }
1,516
Quadir, Treslott, Aldo and Rhobar Sierra leone Since that schedule, there tease been relevant improvements in | Краснодарский край. Since that schedule, there tease been relevant improvements in sympathetic grief in the service of patients receiving che- motherapy, including intimacy with catheter employment techniques and guidance of catheter-related complica- tions 6]. Instead, the developers of latest and tomorrow's software systems be struck by to explicitly incorpo- rebuke parallelism before splitting up algorithms across computing units or executing odd operations concurrently. Much than 1 jillion colds are shrunken by children and adults apiece class in the U generic 250mg keppra free shipping medicine information. In 2002, the National Cancer Guild of Canada published their results of 259 patients with stage IBВ­IVA cer- vical SCC who were randomly assigned to extrinsic brace diffusion together with brachytherapy or emission and concurrent cis- platin (40 mg/m2 weekly) 3]. However, it took more than a decade and thousands of worldwide research institutes to turn and decode the highest hu- houseman genome sequence. It prefabricated the animals much lipotropic order 20 mg paxil fast delivery treatment genital herpes. Locations and innervation of chamber bodies of sympathetic neurons projecting to the gastrointestinal tract in the rat. A trade in the declination of plasma concentrations after a distinct intravenous prescribe of 15 mg/kg (approximately 1,200 mg) was observed. Imprint appears to dissemble many women than men buy lopid 300 mg fast delivery medicine 832. The isotope inclination be incorporated into Bring up 1 Magnusson and Kligman prorate increase Plat probe counteraction Grading range No observable change 0 Discontinuous or patchy erythema 1 Diminish and confluent erythema 2 Intense erythema and/or swelling 3 Study of Ocular Medical Devices 249 The using software is contest version. In over, endogenous components in ocular tissues, such as melanin, can bind some drugs pantihose and want the development of more rigorous extrac- tion techniques than with other biological matrices. Morgera A, Haase M, Kuss T, et al cheap 50mg fluconazole visa antifungal bathroom cleaner. The modeling approach with activities that undeviatingly map to a teleplay on the server is closer to the technical unseen since the underlying continuity could frame all parameters re-definable, with the user picking those he wants to adjust from their type values. Adults convey an accumulated assets of experiences to each healthiness care meet; this provides a flush base for uncharted learning. I Novel Weight- reduction Acitvity of Galega Officinalis in Mice buy shallaki 60 caps without prescription muscle relaxant 551. It is now showily established that infection with oncogenic philanthropist papillomavirus (HPV) is the causal factor in the devel- opment of cancer of the cervix and HPV has a impersonation in diverse other cancers of the anogenital arrondissement and boss and neck in both males and females. Pathologic approximation of inguinal picket lymph nodes in vulvar cancer patients: a juxtaposition of immunohistochemical staining versus ultrastaging with hematoxylin and eosin staining. s, underling of Merck KGaA, Darmstadt, FRG generic florinef 0.1mg on-line gastritis diet новости.
{ "redpajama_set_name": "RedPajamaC4" }
3,044
\section{Introduction} S.~Schanuel proposed the following conjecture while attending a course given by S.~Lang at Columbia University in the 1960's. Most of the known results in the transcendental number theory about the values of the exponential function are encompassed by Schanuel's conjecture, and they can be derived as its consequence. \begin{conj}[Schanuel]\label{Schanuel} Let $x_1,\ldots,x_n \in {\mathbb C}$ be such that they are linearly independent over ${\mathbb Q}$. Then the transcendence degree of the field $$ {\mathbb Q}(x_1,\ldots,x_n,e^{x_1},\ldots,e^{x_n}) $$ over ${\mathbb Q}$ is at least $n$. \end{conj} For example, C.~Cheng et al. have shown in \cite{CDHHKMMMW} how to derive from \conjref{Schanuel}, the linear disjointness of the two fields constructed over ${\mathbb Q}$ by adjoining repeatedly the algebraic closure of the field generated by the values of the exponential and logarithm functions respectively. The only known cases of \conjref{Schanuel} are $n=1$ and $x_1,\ldots,x_n \in \overline{\mathbb Q}$ for general $n$. The $n=1$ case is a consequence of the Hermite-Lindemann theorem, whereas the latter case is known as the Lindemann-Weierstrass theorem. But these two special cases were known much before the inception of this conjecture. Schanuel's conjecture has been generalised to various other contexts. The elliptic analogue of Schanuel's conjecture is well-studied. Let $\Lambda$ be a lattice in ${\mathbb C}$ and $\wp$ denote the associated Weierstrass $\wp$-function, $$ \wp(z)=\wp(\Lambda;z):= \frac{1}{z^2}+ \sum_{\omega \in \Lambda \setminus \{0\}} \left( \frac{1}{(z-\omega)^2} - \frac{1}{\omega^2} \right) $$ for $z \in {\mathbb C} \setminus \Lambda$. The Weierstrass $\wp$-function is an elliptic function with double poles at the points of $\Lambda$ and holomorphic in ${\mathbb C} \setminus \Lambda$. Moreover, for all $z \in {\mathbb C} \setminus \Lambda$, we have the relation $$ \wp'(z)^2=4 \wp(z)^3 - 60 G_4(\Lambda) \wp(z) - 140 G_6(\Lambda). $$ Here for $k \ge 2$, $G_{2k}(\Lambda):= \sum_{\omega \in \Lambda \setminus \{0\}} \omega^{-2k}$ is the associated Eisenstein series of weight $2k$. Let $g_2=60 G_4(\Lambda)$ and $g_3=140 G_6(\Lambda)$. Then the modular invariant $j(\Lambda)$ is defined by $$ j(\Lambda):=1728 \frac{g_2^3}{g_2^3-27g_3^2}. $$ and the associated Weierstrass $\zeta$-function is defined by $$ \zeta(z)=\zeta(\Lambda;z):= \frac{1}{z}+ \sum_{\omega \in \Lambda \setminus \{0\}} \left( \frac{1}{z-\omega} + \frac{1}{\omega}+ \frac{z}{\omega^2} \right), $$ where the series above converges absolutely and uniformly in any compact subset of ${\mathbb C} \setminus \Lambda$. Thus it is holomorphic in ${\mathbb C} \setminus \Lambda$. If $\omega_1,\omega_2$ denote the fundamental periods of $\Lambda$, then the quasi-periods $\eta_1,\eta_2$ are defined by $\eta_i:=\zeta(z+\omega_i)-\zeta(z)$ for $i=1,2$. With these notations, the elliptic Schanuel conjecture reads as follows (see \cite{CB}) : \begin{conj}[elliptic Schanuel]\label{eS} Let $\Lambda$ be a lattice and $\wp,\zeta$ denote the associated Weierstrass functions. Let $K$ be the field of endomorphisms of $\Lambda$ and $x_1,\ldots,x_n \in {\mathbb C} \setminus \Lambda$ such that they are linearly independent over $K$. Then $$ \text{\rm trdeg}_{\mathbb Q} {\mathbb Q}(g_2,g_3,\omega_1,\omega_2,\eta_1,\eta_2, x_1,\ldots,x_n, \wp(x_1),\ldots,\wp(x_n),\zeta(x_1),\ldots,\zeta(x_n)) \ge 2n+ \frac{4}{[K:{\mathbb Q}]}. $$ \end{conj} Often the weaker statement \begin{equation}\label{weak-elliptic} \text{\rm trdeg}_{\mathbb Q} {\mathbb Q}(g_2,g_3, x_1,\ldots,x_n, \wp(x_1),\ldots,\wp(x_n)) \ge n \end{equation} is also considered for application of the elliptic Schanuel conjecture. Here also the $n=1$ case is known and it can be deduced as a consequence of a more general theorem of T. Schneider and S. Lang about transcendental values of meromorphic functions. The analogue of Lindemann-Weierstrass theorem when the Weierstrass $\wp$-function with algebraic invariants $g_2,g_3$ has complex multiplication, was proved independently by the first author \cite{PP} and G. W\"ustholtz \cite{GW}. We also have A. Grothendieck's period conjecture for an abelian variety $A$, defined over $\overline{\mathbb Q}$. It states that the transcendence degree of the period matrix of $A$ is the same as the dimension of the associated Mumford-Tate group. From the work of P. Deligne \cite[Cor. 6.4, p.76]{PD} one gets that this dimension is at least an upper bound for the transcendence degree of the period matrix. Y. Andr\'e \cite[Chap. 23]{YA} suggested a more general conjecture which is now known as the generalised period conjecture. This concerns periods of $1$-motives, which are defined over a subfield of ${\mathbb C}$, not necessarily algebraic. In fact, Grothendieck's period conjecture can be seen as a special case of Andr\'e's conjecture, using Deligne's work. Further, C. Bertolin \cite{CB} has shown that this generalised period conjecture includes Schanuel's conjecture as a special case. We now consider the following weaker version of Andr\'e's generalised period conjecture. Let $A({\mathbb C})$ be an abelian variety of dimension $g$ defined over $\overline{\mathbb Q}$ and $\exp_A: {\mathbb C}^g \to A({\mathbb C})$ denote the exponential map, which is periodic with respect to a lattice $\Lambda_A$. Let $\omega_1,\dots,\omega_g$ be a basis of the holomorphic differential 1-forms and $\eta_1,\dots,\eta_g$ be a basis of the meromorphic differential 1-forms with residue $0$ on $A$. Next let $\gamma_1,\dots,\gamma_{2g}$ be a basis of the homology of $A$. So the matrix of period $\tilde\Lambda_A$ is the $2g\times 2g$ matrix with entries $\int_{\gamma_j}\omega_i$ and $\int_{\gamma_j}\eta_i$, $i=1,\dots,g$, $j=1,\dots,2g$, while the matrix of the lattice $\Lambda_A$ is the $g\times 2g$ matrix with entries $\int_{\gamma_j}\omega_i$. Let $u\in{{\mathbb C}}^g$ and $y = \exp_A(u)$. The relevant 1-motive here is $M = [{{\mathbb Z}} \to A]$, $1 \mapsto y$, which is defined over ${\overline{\mathbb Q}}(\exp_A(u))$. Let $MT(M)$ denote its Mumford-Tate group. The periods of the 1-motive $M$ include the periods of $A$ and the components of $u$ i.e. the numbers $\int_0^u\omega_i$, and also the integrals $\int_0^u\eta_i$. Let $\zeta_A(u)$ denote the vector with components $\int_0^u\eta_i$, $i=1,\dots,g$. \begin{conj}[weak abelian Schanuel]\label{aS} With the notations as above, let $\overline{\mathbb Q}(\tilde\Lambda_A)$ denote the field generated by the periods and quasi-periods over $\overline{\mathbb Q}$. Let $u\in{{\mathbb C}}^g$ and $H$ be the smallest algebraic subgroup of $A$ containing the point $\exp_A(u)$. Then \begin{equation}\label{qp-2} \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} \overline{\mathbb Q}(\tilde\Lambda_A,\exp_{A}(u),u,\zeta_A(u)) \ge 2\dim(H). \end{equation} \end{conj} In a discussion, Daniel Bertrand told us that it is possible to deduce \conjref{aS} from Andr\'e's conjecture based on \cite[Proposition 1]{YA1} and extending the methods of \cite{CB}. With due consent, we reproduce an indication of this argument here. The generalised period conjecture of Andr\'e for $M$ implies $$ \text{\rm trdeg}_{\overline{\mathbb Q}}\overline{\mathbb Q}(\tilde\Lambda_A,\exp_{A}(u),u,\zeta_A(u)) \ge \dim MT(M). $$ Since $A$ is defined over $\overline{\mathbb Q}$, Grothendieck's conjecture (which is a particular case of Andr\'e's conjecture) gives $\text{\rm trdeg}_{\overline{\mathbb Q}}\overline{\mathbb Q}(\tilde\Lambda_A) = \dim(MT(A))$. Hence \begin{equation}\label{tr-deg} \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} \overline{\mathbb Q}(\tilde\Lambda_A,\exp_{A}(u),u,\zeta_A(u)) \ge \dim MT(M) - \dim MT(A). \end{equation} If $U(M)$ denotes the unipotent radical of $MT(M)$, then $MT(M)/U(M)$ is the (reductive) group $MT(A)$. Hence the right hand side of \eqref{tr-deg} equals $\dim(U(M))$. Furthermore, by \cite[Proposition 1]{YA1}, $U(M)$ is known to be equal to $H^1_{Betti}(H^\circ)$, where $H^\circ$ is the connected component of $H$ containing the trivial element. Thus $\dim(U(M))=2\dim(H)$ and we therefore get \eqref{qp-2}, i.e. \begin{equation*} \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} \overline{\mathbb Q}(\tilde\Lambda_A,\exp_{A}(u),u,\zeta_A(u)) \ge 2\dim(H). \end{equation*} Thus \conjref{aS} follows from the generalised period conjecture of Andr\'e. \begin{rmk}\label{rmk-aS-qp}\rm Note that $$ \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} \overline{\mathbb Q}(\tilde\Lambda_A,\exp_{A}(u),u,\zeta_A(u)) \le \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} \overline{\mathbb Q}(\tilde\Lambda_A,\exp_{A}(u),u) + \dim(H). $$ Hence from \eqref{qp-2} we can deduce, \begin{equation}\label{qp-1} \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} \overline{\mathbb Q}(\tilde\Lambda_A,u, \exp_A(u)) \ge \dim(H), \end{equation} and therefore \begin{equation}\label{qp-0} \text{\rm trdeg}_{\overline{\mathbb Q}(\Lambda_A)} \overline{\mathbb Q}(\Lambda_A, u, \exp_A(u)) \ge \dim(H). \end{equation} So we get \eqref{qp-1} and \eqref{qp-0} as consequence of \eqref{qp-2}. \end{rmk} \begin{rmk}\rm \conjref{aS} can further be considered for abelian varieties defined over a subfield of ${\mathbb C}$, not necessarily algebraic. G. Vall\'ee \cite{GV} has formulated the relevant statement from Andr\'e's generalised period conjecture, and his statement includes \conjref{aS} as a special case. \end{rmk} We therefore have supporting evidence for considering \conjref{aS}. With this conjecture in place we want to extend the results in C.~Cheng et al.~\cite{CDHHKMMMW} to this setting, that is prove the linear disjointness of the two fields defined below. For the sake of completeness we recall the definition of linear disjointness (see \cite[Chap. VIII, \S3]{SL}). \begin{defn} Let $F$ be a field and $F_1,F_2$ two of its field extensions contained in a larger field $G$. Then $F_1$ is said to be linearly disjoint ({\it resp.} free) from $F_2$ over $F$ if any finite $F$-linearly ({\it resp.} algebraically) independent subset of $F_1$ is also $F_2$-linearly ({\it resp.} algebraically) independent (as a subset of $G$). \end{defn} Though the above definition is asymmetric, it can be shown that the property of being linearly disjoint ({\it resp.} free) is actually symmetric for $F_1$ and $F_2$. It is easy to see that if $F_1$ and $F_2$ are linearly disjoint over $F$ then $F_1 \cap F_2 = F$. Also if $F_1$ and $F_2$ are linearly disjoint over $F$ then one can deduce that $F_1$ and $F_2$ are free over $F$ (see \cite[Chap. VIII, Prop. 3.2]{SL}). The converse is true in special cases (see \cite[Chap. VIII, Theorem 4.12]{SL} and \lemref{l3} below). The property of being free is also called as $F_1$ and $F_2$ being algebraically independent over $F$. We now setup the relevant notations for our theorem. Recall, $A$ is an abelian variety over $\overline{\mathbb Q}$ and $\tilde\Lambda_A$ denote the matrix of periods. We consider two recursively defined sets ${\mathcal E},{\mathcal L}$. Let us define \footnote{As previously for the field ${\mathbb Q}$, we denote with a bar $\overline{K}$ the algebraic closure in ${\mathbb C}$ of a subfield $K\subset{\mathbb C}$.} $$ {\mathcal E} =\bigcup_{n \ge 0} {\mathcal E}_n \ \ \text{and} \ \ {\mathcal L} =\bigcup_{n \ge 0} {\mathcal L}_n $$ where ${\mathcal E}_0=\overline{\mathbb Q}$, ${\mathcal L}_0 = \overline{{\mathbb Q}(\tilde\Lambda_A)}$ and for $n \ge 1$, $$ {\mathcal E}_n = \overline{{\mathcal E}_{n-1}(\{\text{components of }\exp_A(u) : u \in {\mathcal E}_{n-1}^g\})} $$ and $$ {\mathcal L}_n = \overline{{\mathcal L}_{n-1}(\{\text{components of }u, \zeta_A(u) : \exp_A(u) \in A({\mathcal L}_{n-1})\})}. $$ Often, as in \cite{GV}, for a point $P$ of $A({\mathbb C})$, one uses $\log_A P$ ({\it resp.} $\tilde\log_A P$) to denote the point $u=\exp_A^{-1}(P)$ ({\it resp.} $(u,\zeta_A(u))$). By convention we take $\exp_A(\tilde\log_A P)=\exp_A(\log_A P)=P$. Given a suitable set $S$, we denote $\exp_A(S)$ ({\it resp.} $\log_A(S)$, $\tilde\log_A(S)$) the set of elements $\exp_A(u)$ for $u\in S$ ({\it resp.} $\log_A(P)$, $\tilde\log_A(P)$ for $P\in S$). Then, by induction, one can see that for $n \ge 1$, $$ {\mathcal E}_n = \overline{{\mathbb Q}(\text{components of } \exp_A({\mathcal E}_{n-1}^g))} \ \ \text{and} \ \ {\mathcal L}_n = \overline{{\mathbb Q}(\Lambda_A,\text{components of } \tilde\log_A(A({\mathcal L}_{n-1})))}. $$ Below we state our main theorem about ${\mathcal E}$ and ${\mathcal L}$, where we take the field $G$ in Definition 1 to be ${\mathbb C}$. \begin{thm}\label{lin-dis} If \conjref{aS} is true, then ${\mathcal E}$ and ${\mathcal L}$ are linearly disjoint over $\overline{\mathbb Q}$. Since ${\mathcal E},{\mathcal L}$ are algebraically closed, it is equivalent to say that they are algebraically independent over $\overline{\mathbb Q}$. \end{thm} Proof of this theorem follows the structure of the proof of the main theorem of \cite{CDHHKMMMW}, but a good part of it differs towards the end of our proof. It will be interesting to consider similar problem for semi-abelian varieties to encompass the cases treated here and in \cite{CDHHKMMMW}. \begin{rmk}\rm In \thmref{lin-dis}, one can consider abelian varieties defined over a subfield of ${\mathbb C}$, not necessarily algebraic, as considered by G. Vall\'ee \cite{GV}. However, the statement is not true as it stands. In \S4.1, we exhibit an elliptic curve such that ${\mathcal E}_1 \cap {\mathcal L}_1 \supsetneq {\mathcal E}_0 \cap {\mathcal L}_0$ for the natural candidate of ${\mathcal E}_0$ and ${\mathcal L}_0$. The difficulty in this case is coming from the fact that we no more have the equality in Grothendieck's period conjecture (also see \cite[Chap. 23.4]{YA}). \end{rmk} \begin{rmk} \rm We get an immediate application of \thmref{lin-dis} for elliptic curves over $\overline{\mathbb Q}$. See \S4 for more details. \end{rmk} \section{Intermediate lemmas} In this section we deduce some intermediate results to prove \thmref{lin-dis}. \begin{lem}\label{l3} Let $K_1,K_2$ be two sub-fields of ${\mathbb C}$, which are algebraically closed over $K_1 \cap K_2$. Then they are algebraically independent over $K_1 \cap K_2$ if and only if they are linearly disjoint over $K_1 \cap K_2$. \end{lem} \begin{proof} It follows immediately from Theorem 4.12 and Proposition 3.2 of \cite[Chap. VIII]{SL}. \end{proof} \begin{lem}\label{l1} Let $A_n$ be a finite subset of ${\mathcal E}_n$. Then there exists a finite subset ${\mathcal A}$ of ${\mathcal E}_{n-1}$ such that ${\mathcal A} \cup A_n$ is algebraic over $\overline{\mathbb Q}(\text{components of }\exp_A({\mathcal A}^g))$. \end{lem} \begin{proof} Since $A_n \subset {\mathcal E}_n$, for each $x \in A_n$, there exists a finite subset $C_x$ of ${\mathcal E}_{n-1}$ such that $x$ is algebraic over $\overline{\mathbb Q}(\text{components of }\exp_A(C_x^g))$. Let $A_{n-1}:= \cup_{x \in A_n} C_x \subset {\mathcal E}_{n-1}$. Then $A_{n-1}$ is a finite subset of ${\mathcal E}_{n-1}$. We repeat the process to get sets $\{A_i\}_{0 \le i \le n-2}$ such that for each $i$, $A_i$ is a finite subset of ${\mathcal E}_i$ and $A_{i+1}$ is algebraic over $\overline{\mathbb Q}(\text{components of }\exp_A(A_i^g))$. We take ${\mathcal A}:= \cup_{0 \le i \le n-1} A_i \subset {\mathcal E}_{n-1}$. Then ${\mathcal A} \cup A_n$ is algebraic over $\overline{\mathbb Q}(\text{components of }\exp_A({\mathcal A}^g))$. \end{proof} \begin{lem}\label{l2} Let $C$ be a finite subset of ${\mathcal L}_n$. Then there exists a finite set ${\mathcal C} \subset {\mathcal L}_{n}^{2g}$ with $\exp_A({\mathcal C}) \subset A({\mathcal L}_{n-1})$ such that the set $\{\text{components of }\exp_A({\mathcal C})\} \ \cup \ C$ is algebraic over the field $\overline{\mathbb Q}(\tilde\Lambda_A,\text{components of }{\mathcal C})$. \end{lem} \begin{proof} Since $C \subset {\mathcal L}_n$, for each $y \in C$, there exists a finite subset $D_y$ of $A({\mathcal L}_{n-1})$ such that $y$ is algebraic over $\overline{\mathbb Q}(\tilde\Lambda_A,\text{components of }\tilde\log_A(D_y))$. Define $B_{n-1}:=\tilde\log_A(\cup_{y \in C}D_y)$, so that $C$ is algebraic over $\overline{\mathbb Q}(\tilde\Lambda_A,\text{components of }B_{n-1})$. Then $B_{n-1}\subset \tilde\log_A(A({\mathcal L}_{n-1})) \subset {\mathcal L}_{n}^{2g}$. Hence $\exp_A(B_{n-1}) \subset A({\mathcal L}_{n-1})$, i.e. the components of $\exp_A(B_{n-1})$ is a finite subset of ${\mathcal L}_{n-1}$. We repeat this process for the components of $\exp_A(B_{n-1})$ in place of $C$ and so on, to get sets $\{B_i\}_{0 \le i \le n-2}$ such that for each $i$, $\exp_A(B_{i}) \subset A({\mathcal L}_{i})$ and components of $\exp_A(B_{i+1})$ is algebraic over $\overline{\mathbb Q}(\tilde\Lambda_A,\text{components of }B_i)$. We set ${\mathcal C}:= \cup_{0 \le i \le n-1} B_i$ to complete the proof. \end{proof} \section{Proof of \thmref{lin-dis}} In view of \lemref{l3}, we show that ${\mathcal E}$ and ${\mathcal L}$ are algebraically independent over $\overline{\mathbb Q}$. It is enough to prove that ${\mathcal E}_m$ and ${\mathcal L}_n$ are algebraically independent over $\overline{\mathbb Q}$ for all $m,n$. Now suppose that there exists a pair $(m,n) \in {\mathbb N}^2$ such that ${\mathcal E}_m$ and ${\mathcal L}_n$ are not algebraically independent over $\overline{\mathbb Q}$. We choose such a pair $(m,n)$ with the property that if $(a,b) < (m,n)$, then ${\mathcal E}_a$ and ${\mathcal L}_b$ are algebraically independent over $\overline{\mathbb Q}$. Here the ordering `$<$' is the ordering on ${\mathbb N}^2$ where $(a,b) < (m,n)$ if and only if either $a \le m$ and $b < n$, or $a < m$ and $b \le n$. Clearly $m,n \ge 1$. As ${\mathcal E}_m$ and ${\mathcal L}_n$ are not algebraically independent over $\overline{\mathbb Q}$, there exists an element $\ell$ of ${\mathcal L}_n \setminus \overline{\mathbb Q}$ which is algebraic over ${\mathcal E}_m$ i.e. there exists a finite subset $\{e_1,\ldots,e_k\}$ of non-zero elements of ${\mathcal E}_m$ such that $\ell$ is algebraic over $\overline{\mathbb Q}(e_1, \ldots, e_k)$. Now from \lemref{l1}, we know that there exists a finite subset ${\mathcal A}$ of ${\mathcal E}_{m-1}$ such that ${\mathcal A} \cup \{e_1, \ldots, e_k\}$ is algebraic over $\overline{\mathbb Q}(\text{components of }\exp_A({\mathcal A}^g))$. Similarly by \lemref{l2}, we have a finite set ${\mathcal C} \subset {\mathcal L}_{n}^{2g}$ with $\exp_A({\mathcal C}) \subset A({\mathcal L}_{n-1})$ such that $\{\text{components of }\exp_A({\mathcal C})\} \ \cup \ \{ \ell \}$ is algebraic over $\overline{\mathbb Q}(\tilde\Lambda_A,\text{components of }{\mathcal C})$. Let $|{\mathcal A}^g|=n_1$ and $|{\mathcal C}|=n_2$. Define ${\bf u_1}:=(u : u \in {\mathcal A}^g) \in TA^{n_1}$ by concatenating elements of ${\mathcal A}^g$ one after another. Here $TA^{n_1}$ denotes the tangent space of the abelian variety $A^{n_1}$. Let $A_1$ be the smallest algebraic subgroup of $A^{n_1}$ containing the point $\exp_{A^{n_1}}({\bf u_1})$. Similarly define ${\bf u_2}:=( u : u \in {\mathcal C}) \in TA^{n_2}$ Let $A_2$ be the smallest algebraic subgroup of $A^{n_2}$ containing the point $\exp_{A^{n_2}}({\bf u_2})$. Let $$ K_1:=\overline{{\mathbb Q}({\bf u_1},\exp_{A^{n_1}}({\bf u_1}),\zeta_{A^{n_1}}({\bf u_1}))} \ \text{and} \ K_2:=\overline{{\mathbb Q}(\tilde\Lambda_A,{\bf u_2},\exp_{A^{n_2}}({\bf u_2}),\zeta_{A^{n_2}}({\bf u_2}))} $$ Then $\overline{\mathbb Q}(e_1, \ldots, e_k) \subset K_1 = \overline{{\mathbb Q}(\exp_{A^{n_1}}({\bf u_1}),\zeta_{A^{n_1}}({\bf u_1}))}$ by \lemref{l1} and $\overline{\mathbb Q}(\ell) \subset K_2 = \overline{{\mathbb Q}(\tilde\Lambda_A,{\bf u_2},\zeta_{A^{n_2}}({\bf u_2}))}$ by \lemref{l2}. By \conjref{aS}, we get $$ \text{\rm trdeg}_{\overline{\mathbb Q}} K_1 \ge 2\dim(A_1) \ \text{and} \ \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} K_2 \ge 2\dim(A_2) $$ for $i=1,2$. Since $\exp_{A^{n_1}}({\bf u_1}) \in A_1$ and ${\bf u_2} \in TA_2$, we get that $$ \text{\rm trdeg}_{\overline{\mathbb Q}} K_1 \le 2\dim(A_1) $$ and $$ \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} K_2 \le 2\dim(TA_2) = 2\dim(A_2). $$ Hence $$ \text{\rm trdeg}_{\overline{\mathbb Q}} K_1 = 2\dim(A_1) \ \text{and} \ \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} K_2 = 2\dim(A_2). $$ We want to show that \begin{equation}\label{to-prove} \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} K_1 K_2 = 2\dim(A_1 \times A_2) =\text{\rm trdeg}_{\overline{\mathbb Q}} K_1+\text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} K_2. \end{equation} Adding $\text{\rm trdeg}_{\overline{\mathbb Q}} \overline{\mathbb Q}(\tilde\Lambda_A)$ to both sides of \eqref{to-prove}, we would get $$ \text{\rm trdeg}_{\overline{\mathbb Q}} K_1 K_2 =\text{\rm trdeg}_{\overline{\mathbb Q}} K_1+\text{\rm trdeg}_{\overline{\mathbb Q}} K_2. $$ This would prove that the fields $K_1$ and $K_2$ are algebraically independent over $\overline{\mathbb Q}$. We will thus get a contradiction to our assumption. Define ${\bf u_3}:=({\bf u_1},{\bf u_2})$. Let $B$ be the smallest algebraic subgroup of $A^{n_1+n_2}$ containing the point $\exp_{A^{n_1+n_2}}({\bf u_3})$. Then by \conjref{aS}, we get $$ \text{\rm trdeg}_{\overline{\mathbb Q}(\tilde\Lambda_A)} K_1 K_2 \ge 2\dim(B). $$ Thus we are reduced to prove that $\dim(B)=\dim(A_1) + \dim(A_2)$. If they are torsion subgroups then we have nothing to prove. So we assume that at least one of $A_1$ and $A_2$ is not a torsion subgroup. We first assume $A$ to be simple. For ${\bf u_i} \in TA_i \hookrightarrow TA^{n_i}$, we choose a basis and write ${\bf u_i}=(u_{i1},\ldots,u_{in_i})$ with $u_{ij} \in TA$ for $i=1,2$ and $j=1,\ldots,n_i$. We consider any of the defining relation for $TB$, \begin{equation}\label{def-TB} \sum_{1\le j \le n_1} \delta_{1j} x_{1j} - \sum_{1 \le j \le n_2} \delta_{2j} x_{2j}=0, \end{equation} where $\delta_{ij} \in End(A)$ for $i=1,2$ and $j=1,\ldots,n_i$. Let $u:= \sum_{1\le j \le n_1} \delta_{1j} u_{1j} = \sum_{1 \le j \le n_2} \delta_{2j} u_{2j}$. Then $u \in {\mathcal E}_{m-1}^g \cap {\mathcal L}_{n}^g$ as each $u_{1j} \in {\mathcal A}^g$ and $u_{2j} \in {\mathcal C}$. Thus $u \in \overline{\mathbb Q}^g$, by the choice of $m,n$. On the other hand $\exp_A(u)=\sum_{1\le j \le n_1} \delta_{1j} \exp_A(u_{1j}) = \sum_{1 \le j \le n_2} \delta_{2j} \exp_A(u_{2j})$. For similar reason $\exp_A(u) \in A({\mathcal E}_m) \cap A({\mathcal L}_{n-1})$. Again ${\mathcal E}_m \cap {\mathcal L}_{n-1} =\overline{\mathbb Q}$, and hence $\exp_A(u) \in A(\overline{\mathbb Q})$. Thus, $$ \text{\rm trdeg}_{\overline{\mathbb Q}} \overline{\mathbb Q}(u, \exp_A(u))=0 $$ Now if $H$ is the smallest algebraic subgroup of $A$ containing $\exp_A(u)$, then $\dim(H)=0$, by \conjref{aS}, i.e. $H$ is torsion subgroup. In particular, $n u \in \overline{\mathbb Q}^g$ and $\exp_A(nu)=0$, for a suitable integer $n$. Thus, $\exp_A(nu)=\sum_{1\le j \le n_1} \delta_{1j} \exp_A(nu_{1j}) = \sum_{1 \le j \le n_2} \delta_{2j} \exp_A(nu_{2j})=0$. Now $A_i$ is the smallest algebraic subgroup of $A^{n_i}$ containing the point $\exp_{A^{n_i}}({\bf u_i})$ for $i=1,2$. Thus, $\sum_{1\le j \le n_i} \delta_{ij} \exp_A(nx_{ij})=0$ for any point $\exp_{A^{n_i}}({\bf x_i}) \in A_i$ for $i=1,2$. Since at least one of $A_1$ or $A_2$ is not a torsion subgroup, there exists $i\in\{1,2\}$, such that $\sum_{1\le j \le n_i} \delta_{ij} n x_{ij}=0$ on $TA_i$. Hence $\sum_{1\le j \le n_i} \delta_{ij} x_{ij}=0$ on $TA_i$, and therefore defining relations for $TB$ separate into disjoint relations defining $TA_1$ and $TA_2$. Thus we have $\dim(B)=\dim(A_1) + \dim(A_2)$. Now we treat the case when $A$ is not a simple abelian variety. In this case, we would like to write down the generic form of a defining relation for $TB$ and we show that it is a collection of relations of the form \eqref{def-TB}. Then the proof will follow as above. We suppose that $A^{n_1+n_2}$ is isogenous to $V_1^{r_1} \times \cdots \times V_l^{r_l}$, where for $1 \le i \neq j \le l$, $V_i$ is an abelian variety not isogenous to $V_j$. Thus, the tangent space $TA^{n_1+n_2}$ has the form $$ \underbrace{TV_1\oplus \cdots \oplus TV_1}_{r_1 \text{ times}} \oplus \cdots \oplus \underbrace{TV_l\oplus \cdots \oplus TV_l}_{r_l \text{ times}}. $$ Now $B \subset A_1 \times A_2 \subset A^{n_1+n_2}$. Hence, $A^{n_1+n_2}/B$ can be written in the form $V_1^{s_1} \times \cdots \times V_l^{s_l}$, where for each $1 \le i \le l$, $s_i \le r_i$. Now $B$ is the kernel of the natural map from $A^{n_1+n_2} \to A^{n_1+n_2}/B$. So for this we find the corresponding map $V_1^{r_1} \times \cdots \times V_l^{r_l} \to V_1^{s_1} \times \cdots \times V_l^{s_l}$, for which $B$ is isogenous to the kernel. Such a map is expressed as a block diagonal matrix of order $(s_1+\cdots+s_l,r_1+\cdots+r_l)$. This matrix has diagonal blocks of order $(s_i,r_i)$ with entries from $End(V_i)$, for each $1 \le i \le l$. Now such a matrix acts on an element $(x_{11}, \ldots, x_{1r_1}, \ldots , x_{l1}, \ldots, x_{l r_l})$ of $TA^{n_1+n_2}$, written as a column. Under this action an element of $TB$ is mapped to the zero vector i.e. \begin{equation}\label{def-TB-2} \left( \begin{array}{c c c c} (\delta_{1jk})_{s_1 \times r_1} & (0)_{s_1 \times r_2} & \cdots & (0)_{s_1 \times r_l}\\ (0)_{s_2 \times r_1} & (\delta_{2jk})_{s_2 \times r_2} & \cdots & (0)_{s_2 \times r_l}\\ \vdots & \vdots & \ddots & \vdots\\ (0)_{s_l \times r_1} & (0)_{s_l \times r_2} & \cdots & (\delta_{ljk})_{s_l \times r_l} \end{array} \right) \left( \begin{array}{c} {{\bf x}_{1}} \\ {{\bf x}_{2}}\\ \vdots \\ {{\bf x}_{l}} \end{array} \right) = {\bf 0}, \end{equation} where for $1 \le i \le l$, ${{\bf x}_{i}}=\left( \begin{array}{c} {x_{i1}} \\ \vdots \\ x_{i r_i} \end{array} \right)$. Since the matrix is block diagonal, we get that a defining relation for $TB$ is given as the relations of the form $$ \sum_{k=1}^{r_i} \delta_{ijk} x_{ik} = 0 $$ for some $\delta_{ijk} \in End(V_i)$ with $1 \le i \le l, 1\le j \le s_i$ and $1 \le k \le r_i$. This completes the proof. \subsection{A special case} Let us consider the following two sub-fields of ${\mathcal E}$ and ${\mathcal L}$ : $$ {\mathcal E}' =\bigcup_{n \ge 0} {\mathcal E}_n' \ \ \text{and} \ \ {\mathcal L}' =\bigcup_{n \ge 0} {\mathcal L}_n' $$ where ${\mathcal E}_0'=\overline{\mathbb Q}$, ${\mathcal L}_0' = \overline{\mathbb Q}(\Lambda_A)$ and for $n \ge 1$, $$ {\mathcal E}_n' = \overline{{\mathcal E}_{n-1}'(\{\text{components of }\exp_A(u) : u \in {\mathcal E}_{n-1}^{'g}\})} $$ and $$ {\mathcal L}_n' = \overline{{\mathcal L}_{n-1}'(\{\text{components of }u : \exp_A(u) \in A({\mathcal L}_{n-1}')\})}. $$ In fact, by induction, one can see that for $n \ge 1$, $$ {\mathcal E}_n' = \overline{{\mathbb Q}(\text{components of } \exp_A({\mathcal E}_{n-1}^{'g}))} \ \ \text{and} \ \ {\mathcal L}_n' = \overline{{\mathbb Q}(\Lambda_A,\text{components of } \exp_A^{-1}(A({\mathcal L}_{n-1}')))}. $$ Arguments as in our proof of \thmref{lin-dis} immediately yields the following : \begin{thm}\label{lin-dis-1} If \eqref{qp-0} is true, then ${\mathcal E}'$ and ${\mathcal L}'$ are linearly disjoint over $\overline{\mathbb Q}$. \end{thm} \section{An application} Now we consider the two recursively defined sets ${\mathcal E},{\mathcal L}$ related to the Weierstrass $\wp$-function associated to a lattice $\Lambda$ with algebraic invariants $g_2,g_3$, defined as follows $$ {\mathcal E} =\bigcup_{n \ge 0} {\mathcal E}_n \ \ \text{and} \ \ {\mathcal L} =\bigcup_{n \ge 0} {\mathcal L}_n $$ where ${\mathcal E}_0=\overline{\mathbb Q}, {\mathcal L}_0 = \overline{{\mathbb Q}(\Lambda)}$ and for $n \ge 1$, $$ {\mathcal E}_n = \overline{{\mathcal E}_{n-1}(\{\wp(x) : x \in {\mathcal P}_{n-1} \setminus \Lambda\})} \ \ \text{and} \ \ {\mathcal L}_n = \overline{{\mathcal L}_{n-1}(\{x : \wp(x) \in {\mathcal L}_{n-1} \cup \{\infty\}\})}. $$ In fact, by induction, one can see that for $n \ge 1$, $$ {\mathcal E}_n = \overline{{\mathbb Q}(\wp({\mathcal E}_{n-1} \setminus \Lambda))} \ \ \text{and} \ \ {\mathcal L}_n = \overline{{\mathbb Q}(\wp^{-1}({\mathcal L}_{n-1} \cup \{\infty\}))}. $$ As a corollary to \thmref{lin-dis}, we obtain the following result. \begin{cor}\label{lin-dis-2} If \conjref{eS} is true, then ${\mathcal E}$ and ${\mathcal L}$ are linearly disjoint over $\overline{\mathbb Q}$. \end{cor} In fact, in view of \thmref{lin-dis-1}, the conclusion of the above corollary also holds if \eqref{weak-elliptic} is true. We know that when $g_2,g_3$ are algebraic, $\omega \in \Lambda\setminus\{0\}$ is transcendental. Hence as a corollary to \corref{lin-dis-2} we obtain that $\omega \notin {\mathcal E}$. In particular, $\omega$ can not be a value of the $\wp$ function iterated at an algebraic point. \subsection{An example} We now exhibit an example in the elliptic case which shows that if the curve is not defined over $\overline{\mathbb Q}$, then the conclusion of our \thmref{lin-dis} (or, \corref{lin-dis-2}) does not follow from the same hypothesis. For a fixed real algebraic irrational number $\alpha$, our aim is to find out a lattice ${\mathbb Z} + {\mathbb Z} \tau$ such that $\wp(\tau;\alpha)=\wp({\mathbb Z}+{\mathbb Z}\tau;\alpha)$ can be written as a polynomial in $\tau$ with algebraic coefficients. We first claim that we can find $\tau_0$ such that $\frac{d}{d \tau} \wp(\tau;\alpha) |_{\tau=\tau_0} \neq \frac{\wp(\tau_0;\alpha)}{\tau_0}$. If not, then we have $\frac{d \wp(\tau;\alpha)}{\wp(\tau;\alpha)}|_{\tau=\tau_0} = \frac{d \tau}{\tau}|_{\tau=\tau_0}$ for all $\tau_0$ in the complex upper half plane. Thus $d (\log(\wp(\tau;\alpha)))|_{\tau=\tau_0} =d (\log \tau)|_{\tau=\tau_0}$ i.e. $\wp(\tau_0;\alpha)=c_\alpha \tau_0$ for all $\tau_0$, where $c_\alpha$ is a constant depending on $\alpha$. But this is not possible, as can be checked from the $q$-expansion of $\wp$. So we choose $\tau_0$ such that $\frac{d}{d \tau} \wp(\tau;\alpha) |_{\tau=\tau_0} \neq \frac{\wp(\tau_0;\alpha)}{\tau_0}$ and denote the ratio $\frac{\wp(\tau_0;\alpha)}{\tau_0}$ by $\lambda_0$. We now choose $\lambda$ close to $\lambda_0$ such that $\lambda \in \overline{\mathbb Q}$ and $\frac{d}{d \tau} \wp(\tau;\alpha) |_{\tau=\tau_0} \neq \lambda$. Consider the function $f(\tau)=\wp(\tau;\alpha)- \lambda \tau$. Then we get that $f'(\tau)|_{\tau=\tau_0} \neq 0$. Hence $f$ has a local inverse at $\tau_0$, say $g$, which is defined in a neibourghood of $f(\tau_0)$. Choose $\beta \in \overline{\mathbb Q}$ sufficiently close to $f(\tau_0)$ and set $\tau_1=g(\beta)$. Then $\beta=f(\tau_1)=\wp(\tau_1;\alpha)- \lambda \tau_1$. Thus $\wp(\tau_1;\alpha)$ can be written as a polynomial in $\tau_1$ with algebraic coefficients. The elliptic Schanuel conjecture implies that $\tau_1$ is transcendental. Indeed, if $\tau_1$ is a quadratic irrational, then the associated $j$ invariant is algebraic. Hence $g_2,g_3$ are algebraically related and $\eta_1,\eta_2$, satisfying Masser's relation, are algebraically dependent over $\overline{{\mathbb Q}(g_2,g_3)}$. Now from \conjref{eS} we get a contradiction by taking $n=1$ and $x_1=\alpha$. If $\tau_1$ is algebraic of degree larger than 2, then \conjref{eS} gives a contradiction again for $n=1$ and $x_1=\alpha$. Now for this choice of $\tau_1$, we see that $\tau_1$ belongs to both ${\mathcal E}_1$ and ${\mathcal L}_1$, where the tower of fields ${\mathcal E}_i$'s and ${\mathcal L}_i$'s are constructed as in the beginning of this section, but with $\overline{\mathbb Q}$ replaced by the corresponding field of definition $\overline{{\mathbb Q}(g_2,g_3)}$. However, we show below that $\tau_1$ is transcendental over ${\mathbb Q}(g_2,g_3)$. This gives $\text{\rm trdeg}_{{\mathcal E}_0} {\mathcal E}_1 \cap {\mathcal L}_1 \ge 1$, which implies ${\mathcal E}_1 \cap {\mathcal L}_1 \neq {\mathcal E}_0$ and therefore ${\mathcal E}_1$ and ${\mathcal L}_1$ are not linearly disjoint over ${\mathcal E}_0$. To prove that $\tau_1$ is transcendental over ${\mathbb Q}(g_2,g_3)$, note that $1,\tau_1$ and $\alpha$ are ${\mathbb Q}$ linearly independent. Then the elliptic Schanuel conjecture yields $\text{\rm trdeg}_{\mathbb Q} {\mathbb Q}(g_2,g_3,1,\tau_1,\alpha,\wp(\tau_1;\alpha)) \ge 3$. Now from our construction we see that $\text{\rm trdeg}_{\mathbb Q} {\mathbb Q}(g_2,g_3,1,\tau_1,\alpha,\wp(\tau_1;\alpha)) =\text{\rm trdeg}_{\mathbb Q} {\mathbb Q}(g_2,g_3,\tau_1)$. Thus $\tau_1$ is transcendental over ${\mathbb Q}(g_2,g_3)$. \medskip \noindent {\bf Acknowledgement:} The authors would like to thank D. Bertrand for helpful discussions and useful comments on an earlier version of this article. The second and the third author would like to thank the Institut de Math\'ematiques de Jussieu for hospitality during academic visits in the frame of the IRSES Moduli and LIA. Research of the second author is also supported by SERB-DST-NPDF grant vide PDF/2016/002938.
{ "redpajama_set_name": "RedPajamaArXiv" }
7,203
Q: Second website on subfolder doesn't work: how to debug? I want to create secondary website to be accessed in a subfolder. My base magento installation folder is in domain's root http://mydomain.com/. I am setting up secondary website in http://mydomain.com/ws2/. I have created the secondary website in Magento Admin, given the code ws2 and set unsecure and secure base urls to http://mydomain.com/ws2/. Since I am on a shared hosting, and I don't have access to apache configuration, I have followed this tutorial with Step 2- Method 1 Separate Directories for Each Store. Essentially, I have created a new folder, copied there index.php and .htaccess. I have created the symlinks pointing at the app, include, js, lib, media, skin, var folders of the root installation. I have edited index.php in ws2 folder, changing last line to: Mage::run('ws2', 'website'); Unfortunately, when I access the url http://mydomain.com/ws2/, I get 404 Page Not Found error. Have I made a big mistake? If no, how can I debug this? A: If 404 Error is generated by Magento, it means that everything is fine. Just magento's home page is cms page and by default is configured to be displayed on default website. Go to admin section to CMS->Pages and edit "Home" page to be displayed on all websites. Or create one more home page which will be displayed only on your new website.
{ "redpajama_set_name": "RedPajamaStackExchange" }
3,379
Robert Longo burst onto the New York art scene as a brash 25-year-old with "Men in the Cities," his iconic 1983 large-scale charcoal drawings of businessmen posing in uncanny contortions. "I always imagine that I want to make art that is going to kill you," he said in 1984. "Whether it's going to do it visually or physically, I'll take either way." Longo works and reworks his charcoal into thick-textured surfaces, giving his velvety drawings deep, blackened expanses and sharply contrasting whites; his forms are at once representational and softly elusive.
{ "redpajama_set_name": "RedPajamaC4" }
1,662
Q: Electric force in DNA molecule Given that distance between O-H and N-H bonds are 0.11 nm and How do I compute the net force exerted from Thymine and Adenine? A hint given is: Hint: To keep calculations fairly simple, yet reasonable, consider only the forces due to the O–H–N and the N–H–N combinations, assuming that these two combinations are parallel to each other. Do I compute the force on O due to H and N like: $$F_{OH} = k \frac{e^2}{(0.17 \times 10^{-9})^2}$$ $$F_{ON} = k \frac{e^2}{(0.28 \times 10^{-9})^2}$$ $$F_{O} = k \frac{e^2}{(0.17 \times 10^{-9})^2} - k \frac{e^2}{(0.28 \times 10^{-9})^2}$$ Then about the HN part? Do I consider that 1 molecule or something? A: It's not going to be so easy, if you want anything better than a very crude estimate. The + and - charges indicated on illustrations of molecules depict a relative absence or gathering of electron probability clouds in the region, respectively failing to balance with the positive nuclear charge or overwhelming it. You'd have to know the wavefunctions of the electrons, their molecular orbitals, and compute integrals over those all pairs of volume elements in the clouds for both regions. As a practical approximation, there might some sense in using some average central point, a sort of center of mass, for each charged region of each molecule, and apply Coulomb's law. But this isn't likely to be accurate. It could be if the charged regions were spherical, then just as with gravity the integrals work out to be the same as the simple Coulomb's law. Unfortunately molecules aren't shaped like that. If you are wanting to know the force between two molecules, or parts of a molecule, you should know that the charged regions will change shape - as the molecules move closer, the electrons, and whole atoms, "feel" the presence of other charges and are tugged. The molecules will electrically polarize each other. So, instead of using Coulomb to estimate the force, it's better to calculate the electrostatic potential energy as a function of position, accounting for the way the molecules will distort each other at any given distance. Of course, even better is to do a full-blown quantum mechanical calculation including spins and fully anti-symmetric wavefunctions and all that, but for DNA or even just a single base pair, that's a lot of number crunching.
{ "redpajama_set_name": "RedPajamaStackExchange" }
3,205
**PostgreSQL 10 Administration Cookbook** Over 165 effective recipes for database management and maintenance in PostgreSQL 10 Simon Riggs Gianni Ciolli ****BIRMINGHAM - MUMBAI**** # PostgreSQL 10 Administration Cookbook Copyright © 2018 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. **Commissioning Editor:** Amey Varangaonkar **Acquisition Editor:** Namrata Patil **Content Development Editor:** Amrita Noronha **Technical Editor:** Sneha Hanchate **Copy Editor:** Safis **Project Coordinator:** Shweta Birwatkar **Proofreader:** Safis Editing **Indexer:** Pratik Shirodkar **Graphics:** Jisha Chirayil **Production Coordinator:** Shraddha Falebhai First published: April 2017 Production reference: 1070518 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78847-492-4 www.packtpub.com mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. # Why subscribe? * Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals * Improve your learning with Skill Plans built especially for you * Get a free eBook or video every month * Mapt is fully searchable * Copy and paste, print, and bookmark content # PacktPub.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at `service@packtpub.com` for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. # Contributors # About the authors **Simon Riggs** is the CTO of 2ndQuadrant, having contributed to PostgreSQL as a major developer and committer for 14 years. He has written and designed features for replication, performance, BI, management, and security. Under his guidance, 2ndQuadrant is now a leading developer of open source PostgreSQL, serving hundreds of clients in USA, Europe, and worldwide. Simon is a frequent speaker at many conferences on PostgreSQL Futures. He has worked as a database architect for 30 years. **Gianni** **Ciolli** is the head of professional services at 2ndQuadrant. PostgreSQL consultant, trainer, and speaker at many PostgreSQL conferences in Europe and abroad since the last 10 years. He has a PhD in Mathematics from the University of Florence. He has worked with free and open source software since the 1990s and is active in the community (Prato Linux User Group and Italian PostgreSQL Users Group). He lives in London with his son. His other interests include music, drama, poetry, and athletics. # About the reviewer **Sheldon Strauch** is a 23-year veteran of software consulting at IBM, Sears, Ernst & Young, and Kraft Foods. Having a bachelor's degree in business administration, he leverages his technical skills to improve business' self-awareness. He is interested in data gathering, management, and mining; maps and mapping; business intelligence; and application of data analysis. He is currently focusing on the development of data management and mining at Enova International at Chicago. At his leisure, he enjoys performing arts, music, and traveling with his wife, Marilyn. # Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. # Table of Contents 1. Title Page 2. Copyright and Credits 1. PostgreSQL 10 Administration Cookbook 3. Packt Upsell 1. Why subscribe? 2. PacktPub.com 4. Contributors 1. About the authors 2. About the reviewer 3. Packt is searching for authors like you 5. Preface 1. Who this book is for 2. What this book covers 3. To get the most out of this book 1. Download the example code files 2. Download the color images 3. Conventions used 4. Sections 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 5. Get in touch 1. Reviews 6. First Steps 1. Introduction 1. Introducing PostgreSQL 10 1. What makes PostgreSQL different? 1. Robustness 2. Security 3. Ease of use 4. Extensibility 5. Performance and concurrency 6. Scalability 7. SQL and NoSQL 8. Popularity 9. Commercial support 10. Research and development funding 2. Getting PostgreSQL 1. How to do it... 2. How it works... 3. There's more... 3. Connecting to the PostgreSQL server 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 4. Enabling access for network/remote users 1. How to do it... 2. How it works... 3. There's more... 4. See also 5. Using graphical administration tools 1. How to do it... 2. How it works... 6. OmniDB 1. See also 7. Using the psql query and scripting tool 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 8. Changing your password securely 1. How to do it... 2. How it works... 9. Avoiding hardcoding your password 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 10. Using a connection service file 1. How to do it... 2. How it works... 11. Troubleshooting a failed connection 1. How to do it... 2. There's more... 7. Exploring the Database 1. Introduction 2. What version is the server? 1. How to do it... 2. How it works... 3. There's more... 3. What is the server uptime? 1. How to do it... 2. How it works... 3. See also 4. Locating the database server files 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. Locating the database server's message log 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 6. Locating the database's system identifier 1. Getting ready 2. How to do it... 3. How it works... 7. Listing databases on this database server 1. How to do it... 2. How it works... 3. There's more... 8. How many tables are there in a database? 1. How to do it... 2. How it works... 3. There's more... 9. How much disk space does a database use? 1. How to do it... 2. How it works... 10. How much disk space does a table use? 1. How to do it... 2. How it works... 3. There's more... 11. Which are my biggest tables? 1. How to do it... 2. How it works... 12. How many rows are there in a table? 1. How to do it... 2. How it works... 13. Quickly estimating the number of rows in a table 1. How to do it... 2. How it works... 3. There's more... 1. Function 1 – Estimating the number of rows 2. Function 2 – Computing the size of a table without locks 14. Listing extensions in this database 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 15. Understanding object dependencies 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 8. Configuration 1. Introduction 2. Reading the fine manual 1. How to do it... 2. How it works... 3. There's more... 3. Planning a new database 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 4. Changing parameters in your programs 1. How to do it... 2. How it works... 3. There's more... 5. Finding the current configuration settings 1. How to do it... 2. There's more... 3. How it works... 6. Which parameters are at non-default settings? 1. How to do it... 2. How it works... 3. There's more... 7. Updating the parameter file 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 8. Setting parameters for particular groups of users 1. How to do it... 2. How it works... 9. The basic server configuration checklist 1. Getting ready 2. How to do it... 3. There's more... 10. Adding an external module to PostgreSQL 1. Getting ready 2. How to do it... 1. Installing modules using a software installer 2. Installing modules from PGXN 3. Installing modules from a manually downloaded package 4. Installing modules from source code 3. How it works... 11. Using an installed module 1. Getting ready 2. How to do it... 3. How it works... 12. Managing installed extensions 1. How to do it... 2. How it works... 3. There's more... 9. Server Control 1. Introduction 2. Starting the database server manually 1. Getting ready 2. How to do it... 3. How it works... 3. Stopping the server safely and quickly 1. How to do it... 2. How it works... 3. See also 4. Stopping the server in an emergency 1. How to do it... 2. How it works... 5. Reloading the server configuration files 1. How to do it... 2. How it works... 3. There's more... 6. Restarting the server quickly 1. How to do it... 2. There's more... 7. Preventing new connections 1. How to do it... 2. How it works... 8. Restricting users to only one session each 1. How to do it... 2. How it works... 9. Pushing users off the system 1. How to do it... 2. How it works... 10. Deciding on a design for multitenancy 1. How to do it... 2. How it works... 11. Using multiple schemas 1. Getting ready 2. How to do it... 3. How it works... 12. Giving users their own private database 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 13. Running multiple servers on one system 1. Getting ready 2. How to do it... 3. How it works... 14. Setting up a connection pool 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 15. Accessing multiple servers using the same host and port 1. Getting ready 2. How to do it... 3. There's more... 10. Tables and Data 1. Choosing good names for database objects 1. Getting ready 2. How to do it... 3. There's more... 2. Handling objects with quoted names 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 3. Enforcing the same name and definition for columns 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 4. Identifying and removing duplicates 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. Preventing duplicate rows 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Duplicate indexes 2. Uniqueness without indexes 3. Real-world example – IP address range allocation 4. Real-world example – range of time 5. Real-world example – prefix ranges 6. Finding a unique key for a set of data 1. Getting ready 2. How to do it... 3. How it works... 7. Generating test data 1. How to do it... 2. How it works... 3. There's more... 4. See also 8. Randomly sampling data 1. How to do it... 2. How it works... 9. Loading data from a spreadsheet 1. Getting ready 2. How to do it... 3. How it works... 1. There's more... 10. Loading data from flat files 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 11. Security 1. Introduction 1. Typical user role 2. The PostgreSQL superuser 1. How to do it... 2. How it works... 3. There's more... 1. Other superuser-like attributes 2. Attributes are never inherited 4. See also 3. Revoking user access to a table 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Database creation scripts 2. Default search path 3. Securing views 4. Granting user access to a table 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Access to the schema 2. Granting access to a table through a group role 3. Granting access to all objects in a schema 5. Granting user access to specific columns 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 6. Granting user access to specific rows 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 7. Creating a new user 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 8. Temporarily preventing a user from connecting 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Limiting the number of concurrent connections by a user 2. Forcing NOLOGIN users to disconnect 9. Removing a user without dropping their data 1. Getting ready 2. How to do it... 3. How it works... 10. Checking whether all users have a secure password 1. How to do it... 2. How it works... 11. Giving limited superuser powers to specific users 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Writing a debugging_info function for developers 12. Auditing database access 1. Getting ready 1. Auditing SQL 2. Auditing table access 3. Managing the audit log 4. Auditing data changes 13. Always knowing which user is logged in 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Not inheriting user attributes 14. Integrating with LDAP 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Setting up the client to use LDAP 2. Replacement for the User Name Map feature 5. See also 15. Connecting using SSL 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Getting the SSL key and certificate 2. Setting up a client to use SSL 3. Checking server authenticity 16. Using SSL certificates to authenticate 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Avoiding duplicate SSL connection attempts 2. Using multiple client certificates 3. Using the client certificate to select the database user 5. See also 17. Mapping external usernames to database roles 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 18. Encrypting sensitive data 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. For really sensitive data 2. For really, really, really sensitive data! 5. See also 12. Database Administration 1. Introduction 2. Writing a script that either succeeds entirely or fails entirely 1. How to do it... 2. How it works... 3. There's more... 3. Writing a psql script that exits on the first error 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 4. Using psql variables 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. Placing query output into psql variables 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 6. Writing a conditional psql script 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 7. Investigating a psql error 1. Getting ready 2. How to do it... 3. There's more... 8. Performing actions on many tables 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 9. Adding/removing columns on a table 1. How to do it... 2. How it works... 3. There's more... 10. Changing the data type of a column 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 11. Changing the definition of a data type 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 12. Adding/removing schemas 1. How to do it... 2. There's more... 3. Using schema-level privileges 13. Moving objects between schemas 1. How to do it... 2. How it works... 3. There's more... 14. Adding/removing tablespaces 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Putting pg_wal on a separate device 2. Tablespace-level tuning 15. Moving objects between tablespaces 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 16. Accessing objects in other PostgreSQL databases 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. There's more... 17. Accessing objects in other foreign databases 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 18. Updatable views 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 19. Using materialized views 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 13. Monitoring and Diagnosis 1. Providing PostgreSQL information to monitoring tools 1. Finding more information about generic monitoring tools 2. Real-time viewing using pgAdmin or OmniDB 1. Getting ready 2. How to do it... (with pgAdmin) 3. How to do it... (with OmniDB) 3. Checking whether a user is connected 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 4. Checking whether a computer is connected 1. How to do it... 2. There's more... 5. Repeatedly executing a query in psql 1. How to do it... 2. There's more... 6. Checking which queries are running 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Catching queries that only run for a few milliseconds 2. Watching the longest queries 3. Watching queries from ps 5. See also 7. Checking which queries are active or blocked 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. No need for the = true part 2. Do we catch all queries waiting on locks? 8. Knowing who is blocking a query 1. Getting ready 2. How to do it... 3. How it works... 9. Killing a specific session 1. How to do it... 2. How it works... 3. There's more... 1. Try to cancel the query first 2. What if the backend won't terminate? 3. Using statement_timeout to clean up queries that take too long to run 4. Killing idle in transaction queries 5. Killing the backend from the command line 10. Detecting an in-doubt prepared transaction 1. How to do it... 11. Knowing whether anybody is using a specific table 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. The quick-and-dirty way 2. Collecting daily usage statistics 12. Knowing when a table was last used 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 13. Usage of disk space by temporary data 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Finding out whether a temporary file is in use any more 2. Logging temporary file usage 14. Understanding why queries slow down 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Do the queries return significantly more data than they did earlier? 2. Do the queries also run slowly when they are run alone? 3. Is the second run of the same query also slow? 4. Table and index bloat 5. See also 15. Investigating and reporting a bug 1. Getting ready 2. How to do it... 3. How it works... 16. Producing a daily summary of log file errors 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 17. Analyzing the real-time performance of your queries 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 14. Regular Maintenance 1. Controlling automatic database maintenance 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 2. Avoiding auto-freezing and page corruptions 1. How to do it... 3. Removing issues that cause bloat 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 4. Removing old prepared transactions 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. Actions for heavy users of temporary tables 1. How to do it... 2. How it works... 6. Identifying and fixing bloated tables and indexes 1. How to do it... 2. How it works... 3. There's more... 7. Monitoring and tuning vacuum 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 8. Maintaining indexes 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 9. Adding a constraint without checking existing rows 1. Getting ready 2. How to do it... 3. How it works... 10. Finding unused indexes 1. How to do it... 2. How it works... 11. Carefully removing unwanted indexes 1. Getting ready 2. How to do it... 3. How it works... 12. Planning maintenance 1. How to do it... 2. How it works... 15. Performance and Concurrency 1. Introduction 2. Finding slow SQL statements 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 3. Collect regular statistics from pg_stat* views 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 1. Another statistics collection package 4. Finding out what makes SQL slow 1. Getting ready 2. How to do it... 3. There's more... 1. Not enough CPU power or disk I/O capacity for the current load 2. Locking problems 3. EXPLAIN options 4. See also 5. Reducing the number of rows returned 1. How to do it... 2. There's more... 3. See also 6. Simplifying complex SQL queries 1. Getting ready 2. How to do it... 3. There's more... 1. Using materialized views (long-living, temporary tables) 2. Using set-returning functions for some parts of queries 7. Speeding up queries without rewriting them 1. How to do it... 1. Increasing work_mem 2. More ideas with indexes 2. There's more... 1. Time Series Partitioning 2. Using a TABLESAMPLE view 3. In case of many updates, set fillfactor on the table 4. Rewriting the schema – a more radical approach 8. Discovering why a query is not using an index 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 9. Forcing a query to use an index 1. Getting ready 2. How to do it... 3. There's more... 4. There's even more 10. Using parallel query 1. How to do it... 2. How it works... 3. There's more... 11. Using optimistic locking 1. How to do it... 2. How it works... 3. There's more... 12. Reporting performance problems 1. How to do it... 2. There's more... 16. Backup and Recovery 1. Introduction 2. Understanding and controlling crash recovery 1. How to do it... 2. How it works... 3. There's more... 3. Planning backups 1. How to do it... 4. Hot logical backups of one database 1. How to do it... 2. How it works... 3. There's more... 4. See also 5. Hot logical backups of all databases 1. How to do it... 2. How it works... 3. See also 6. Backups of database object definitions 1. How to do it... 2. There's more... 7. Standalone hot physical database backup 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 8. Hot physical backup and continuous archiving 1. Getting ready 2. How to do it... 3. How it works... 9. Recovery of all databases 1. Getting ready 2. How to do it... 1. Logical – from custom dump taken with pg_dump -F c 2. Logical – from the script dump created by pg_dump -F p 3. Logical – from the script dump created by pg_dumpall 4. Physical 3. How it works... 4. There's more... 5. See also 10. Recovery to a point in time 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 11. Recovery of a dropped/damaged table 1. How to do it... 1. Logical - from custom dump taken with pg_dump -F c 2. Logical – from the script dump 3. Physical 2. How it works... 3. See also 12. Recovery of a dropped/damaged database 1. How to do it... 1. Logical – from the custom dump -F c 2. Logical – from the script dump created by pg_dump 3. Logical – from the script dump created by pg_dumpall 4. Physical 13. Improving performance of backup/recovery 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 14. Incremental/differential backup and restore 1. How to do it... 2. How it works... 3. There's more... 15. Hot physical backups with Barman 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 16. Recovery with Barman 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 17. Replication and Upgrades 1. Replication concepts 1. Topics 2. Basic concepts 3. History and scope 4. Practical aspects 5. Data loss 6. Single-master replication 7. Multinode architectures 8. Clustered or massively parallel databases 9. Multimaster replication 10. Scalability tools 11. Other approaches to replication 2. Replication best practices 1. Getting ready 2. How to do it... 3. There's more... 3. Setting up file-based replication – deprecated 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 4. Setting up streaming replication 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. Setting up streaming replication security 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 6. Hot Standby and read scalability 1. Getting ready 2. How to do it... 3. How it works... 7. Managing streaming replication 1. Getting ready 2. How to do it... 3. There's more... 4. See also 8. Using repmgr 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 9. Using replication slots 1. Getting ready 2. How to do it... 3. There's more... 4. See also 10. Monitoring replication 1. Getting ready 2. How to do it... 3. There's more... 11. Performance and synchronous replication 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 12. Delaying, pausing, and synchronizing replication 1. Getting ready 2. How to do it... 3. There's more... 4. See also 13. Logical replication 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 5. See also 14. Bi-directional replication 1. Getting ready 2. How to do it... 3. How it works... 4. There's more... 15. Archiving transaction log data 1. Getting ready 2. How to do it... 3. There's more... 4. See also 16. Upgrading minor releases 1. Getting ready 2. How to do it... 3. How it works... 17. Major upgrades in-place 1. Getting ready 2. How to do it... 3. How it works... 18. Major upgrades online 1. How to do it... 2. How it works... 18. Other Books You May Enjoy 1. Leave a review - let other readers know what you think # Preface PostgreSQL is an advanced SQL database server, available on a wide range of platforms and is fast becoming one of the world's most popular server databases with an enviable reputation for performance, stability, and an enormous range of advanced features. PostgreSQL is one of the oldest open source projects, completely free to use, and developed by a very diverse worldwide community. Most of all, it just works! One of the clearest benefits of PostgreSQL is that it is open source, meaning that you have a very permissive license to install, use, and distribute PostgreSQL without paying anyone any fees or royalties. On top of that, PostgreSQL is well-known as a database that stays up for long periods, and requires little or no maintenance in many cases. Overall, PostgreSQL provides a very low total cost of ownership. PostgreSQL Administration Cookbook offers the information you need to manage your live production databases on PostgreSQL. The book contains insights direct from the main author of the PostgreSQL replication and recovery features and the rest of the team at 2ndQuadrant. This hands-on guide will assist developers working on live databases, supporting web or enterprise software applications using Java, Python, Ruby, and .Net from any development framework. It's easy to manage your database when you've got PostgreSQL 10 Administration Cookbook at hand. This practical guide gives you quick answers to common questions and problems, building on the author's experience as trainers, users, and core developers of the PostgreSQL database server. Each technical aspect is broken down into short recipes that demonstrate solutions with working code, and then explain why and how that works. The book is intended to be a desk reference for both new users and technical experts. The book covers all the latest features available in PostgreSQL 10. Soon you will be running a smooth database with ease! # Who this book is for This book is for system administrators, database administrators, architects, developers, and anyone with an interest in planning for or running live production databases. This book is most suited to those who have some technical experience. # What this book covers Chapter 1, _First Steps_ , covers topics such as an introduction to PostgreSQL 10, downloading and installing PostgreSQL 10, connecting to a PostgreSQL server, enabling server access to network/remote users, using graphical administration tools, using psql query and scripting tools, changing your password securely, avoiding hardcoding your password, using a connection service file, and troubleshooting a failed connection. Chapter 2, _Exploring the Database_ , helps you identify the version of the database server you are using and also the server uptime. It helps you locate the database server files, database server message log, and database's system identifier. It lets you list a database on the database server, contains recipes that let you know the number of tables in your database, how much disk space is used by the database and tables, which are the biggest tables, how many rows a table has, how to estimate rows in a table, and how to understand object dependencies. Chapter 3, _Configuration_ , covers topics such as reading the fine manual (RTFM), planning a new database, changing parameters in your programs, the current configuration settings, parameters that are at non-default settings, updating the parameter file, setting parameters for particular groups of users, basic server configuration checklist, adding an external module into the PostgreSQL server, and running the server in power saving mode. Chapter 4, _Server Control_ , provides information about starting the database server manually, stopping the server quickly and safely, stopping the server in an emergency, reloading the server configuration files, restarting the server quickly, preventing new connections, restricting users to just one session each, and pushing users off the system. It contains recipes that help you decide on a design for multi-tenancy, how to use multiple schemas, giving users their own private database, running multiple database servers on one system, and setting up a connection pool. Chapter 5, _Tables and Data_ , guides you through the process of choosing good names for database objects, handling objects with quoted names, enforcing same name, same definition for columns, identifying and removing duplicate rows, preventing duplicate rows, finding a unique key for a set of data, generating test data, randomly sampling data, loading data from a spreadsheet, and loading data from flat files. Chapter 6, _Security_ , provides recipes on revoking user access to a table, granting user access to a table, creating a new user, temporarily preventing a user from connecting, removing a user without dropping their data, checking whether all users have a secure password, giving limited super user powers to specific users, auditing DDL changes, auditing data changes, integrating with LDAP, connecting using SSL, and encrypting sensitive data. Chapter 7, _Database Administration_ , provides recipes on useful topics such as writing a script wherein either all succeed or all fail, writing a psql script that exits on the first error, performing actions on many tables, adding/removing columns on tables, changing the data type of a column, adding/removing schemas, moving objects between schemas, adding/removing tablespaces, moving objects between tablespaces, accessing objects in other PostgreSQL databases, and making views updateable. Chapter 8, _Monitoring and Diagnosis_ , provides recipes that answer questions such as is the user connected?, what are they running?, are they active or blocked?, who is blocking them?, is anybody using a specific table?, when did anybody last use it?, how much disk space is used by temporary data?, and why are my queries slowing down? It also helps you in investigating and reporting a bug, producing a daily summary report of logfile errors, killing a specific session, and resolving an in-doubt prepared transaction. Chapter 9, _Regular Maintenance_ , provides useful recipes on controlling automatic database maintenance, avoiding auto freezing and page corruptions, avoiding transaction wraparound, removing old prepared transactions, actions for heavy users of temporary tables, identifying and fixing bloated tables and indexes, maintaining indexes, finding unused indexes, carefully removing unwanted indexes, and planning maintenance. Chapter 10, _Performance and Concurrency_ , covers topics such as finding slow SQL statements, collecting regular statistics from pg_stat* views, finding what makes SQL slow, reducing the number of rows returned, simplifying complex SQL, speeding up queries without rewriting them, why is my query not using an index?, how do I force a query to use an index?, using optimistic locking, and reporting performance problems. And of course, the new parallel query features. Chapter 11, _Backup and Recovery_ , insists that backups are essential, though they also devote only a very small amount of time to thinking about the topic. So, this chapter provides useful information about backup and recovery of your PostgreSQL database through recipes on understanding and controlling crash recovery, planning backups, hot logical backup of one database, hot logical backup of all databases, hot logical backup of all tables in a tablespace, backup of database object definitions, standalone hot physical database backup, hot physical backup and continuous archiving. It also includes topics such as recovery of all databases, recovery to a point in time, recovery of a dropped/damaged table, recovery of a dropped/damaged database, recovery of a dropped/damaged tablespace, improving performance of backup/recovery, and incremental/differential backup and restore. Chapter 12, _Replication and Upgrades_ , explains that replication isn't magic, though it can be pretty cool. It's even cooler when it works, and that's what this chapter is all about. This chapter covers replication concepts, replication best practices, setting up file-based log shipping replication, setting up streaming log replication, managing log shipping replication, managing Hot Standby, synchronous replication, upgrading to a new minor release, in-place major upgrades, major upgrades online, plus logical replication and Postgres-BDR. # To get the most out of this book In order for this book to be useful, you need at least access to a PostgreSQL client that is allowed to execute queries on a server. Ideally, you'll also be the server administrator. Full client and server packages for PostgreSQL are available for most popular operating systems at <http://www.postgresql.org/download/>. All the examples here are executed at a Command Prompt, usually running the psql program. This makes them applicable to most platforms. It's straightforward to do many of these operations instead using a GUI tool for PostgreSQL, such as pgAdmin or OmniDB. # Download the example code files You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps: 1. Log in or register at www.packtpub.com. 2. Select the SUPPORT tab. 3. Click on Code Downloads & Errata. 4. Enter the name of the book in the Search box and follow the onscreen instructions. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of: * WinRAR/7-Zip for Windows * Zipeg/iZip/UnRarX for Mac * 7-Zip/PeaZip for Linux The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/PostgreSQL-10-Administration-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository. We also have other code bundles from our rich catalog of books and videos available at **<https://github.com/PacktPublishing/>**. Check them out! # Download the color images We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/PostgreSQL10AdministrationCookbook_ColorImages.pdf. # Conventions used There are a number of text conventions used throughout this book. `CodeInText`: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded `WebStorm-10*.dmg` disk image file as another disk in your system." A block of code is set as follows: CREATE USER repuser SUPERUSER LOGIN CONNECTION LIMIT 1 ENCRYPTED PASSWORD 'changeme'; When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: SELECT *FROM mytable WHERE (col1, col2,... ,colN) IN (SELECT col1, col2,... ,colN FROM mytable GROUP BY col1, col2,... ,colN **HAVING count(*) > 1**); Any command-line input or output is written as follows: **$ postgres --single -D /full/path/to/datadir postgres** **Bold** : Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel." Warnings or important notes appear like this. Tips and tricks appear like this. # Sections In this book, you will find several headings that appear frequently ( _Getting ready_ , _How to do it..._ , _How it works..._ , _There's more..._ , and _See also_ ). To give clear instructions on how to complete a recipe, use these sections as follows: # Getting ready This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe. # How to do it... This section contains the steps required to follow the recipe. # How it works... This section usually consists of a detailed explanation of what happened in the previous section. # There's more... This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe. # See also This section provides helpful links to other useful information for the recipe. # Get in touch Feedback from our readers is always welcome. **General feedback** : Email `feedback@packtpub.com` and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at `questions@packtpub.com`. **Errata** : Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details. **Piracy** : If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at `copyright@packtpub.com` with a link to the material. **If you are interested in becoming an author** : If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com. # Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about Packt, please visit packtpub.com. # First Steps In this chapter, we will cover the following recipes: * Getting PostgreSQL * Connecting to the PostgreSQL server * Enabling access for network/remote users * Using graphical administration tools * Using the psql query and scripting tool * Changing your password securely * Avoiding hardcoding your password * Using a connection service file * Troubleshooting a failed connection # Introduction PostgreSQL is a feature-rich, general-purpose, database management system. It's a complex piece of software, but every journey begins with the first step. We'll start with your first connection. Many people fall at the first hurdle, so we'll try not to skip that too swiftly. We'll quickly move on to enabling remote users, and from there we will move on to access through GUI administration tools. We will also introduce the `psql` query tool, which is the tool used to load our sample database, as well as many other examples in the book. For additional help, we've included a few useful recipes that you may need for reference. # Introducing PostgreSQL 10 PostgreSQL is an advanced SQL database server, available on a wide range of platforms. One of the clearest benefits of PostgreSQL is that it is open source, meaning that you have a very permissive license to install, use, and distribute PostgreSQL, without paying anyone any fees or royalties. On top of that, PostgreSQL is well-known as a database that stays up for long periods and requires little or no maintenance, in most cases. Overall, PostgreSQL provides a very low total cost of ownership. PostgreSQL is also noted for its huge range of advanced features, developed over the course of more than 30 years of continuous development and enhancement. Originally developed by the Database Research Group at the University of California, Berkeley, PostgreSQL is now developed and maintained by a huge army of developers and contributors. Many of these contributors have full-time jobs related to PostgreSQL, working as designers, developers, database administrators, and trainers. Some, but not many, of these contributors work for companies that specialize in support for PostgreSQL, like we (the authors) do. No single company owns PostgreSQL, nor are you required (or even encouraged) to register your usage. PostgreSQL has the following main features: * Excellent SQL standards compliance, up to SQL: 2016 * Client-server architecture * Highly concurrent design, where readers and writers don't block each other * Highly configurable and extensible for many types of applications * Excellent scalability and performance, with extensive tuning features * Support for many kinds of data models, such as relational, post-relational (arrays, nested relations via record types), document (JSON and XML), and key/value # What makes PostgreSQL different? The PostgreSQL project focuses on the following objectives: * Robust, high-quality software with maintainable, well-commented code * Low maintenance administration for both embedded and enterprise use * Standards-compliant SQL, interoperability, and compatibility * Performance, security, and high availability What surprises many people is that PostgreSQL's feature set is more comparable with Oracle or SQL Server than it is with MySQL. The only connection between MySQL and PostgreSQL is that these two projects are open source; apart from that, the features and philosophies are almost totally different. One of the key features of Oracle, since Oracle 7, has been snapshot isolation, where readers don't block writers and writers don't block readers. You may be surprised to learn that PostgreSQL was the first database to be designed with this feature, and it offers a complete implementation. In PostgreSQL, this feature is called **Multiversion Concurrency Control** ( **MVCC** ), and we will discuss this in more detail later in the book. PostgreSQL is a general-purpose database management system. You define the database that you would like to manage with it. PostgreSQL offers you many ways to work. You can either use a normalized database model, augmented with features such as arrays and record subtypes, or use a fully dynamic schema with the help of JSONB and an extension named `hstore`. PostgreSQL also allows you to create your own server-side functions in any of a dozen different languages. PostgreSQL is highly extensible, so you can add your own data types, operators, index types, and functional languages. You can even override different parts of the system, using plugins to alter the execution of commands, or add a new optimizer. All of these features offer a huge range of implementation options to software architects. There are many ways out of trouble when building applications and maintaining them over long periods of time. Regrettably, we simply don't have space in this book for all the cool features for developers; this book is about administration, maintenance, and backup. In the early days, when PostgreSQL was still a research database, the focus was solely on the cool new features. Over the last 20 years, enormous amounts of code have been rewritten and improved, giving us one of the largest and most stable software servers available for operational use. You may have read that PostgreSQL was, or is, slower than _My Favorite DBMS_ , whichever that is. It's been a personal mission of mine over the last ten years to improve server performance, and the team has been successful in making the server highly performant and very scalable. That gives PostgreSQL enormous headroom for growth. Who is using PostgreSQL? Prominent users include Apple, BASF, Genentech, Heroku, IMDB, Skype, McAfee, NTT, the UK Met Office, and the U. S. National Weather Service. Early in 2010, PostgreSQL received well in excess of one million downloads per year, according to data submitted to the European Commission, which concluded, _PostgreSQL is considered by many database users to be a credible alternative_. We need to mention one last thing. When PostgreSQL was first developed, it was named Postgres, and therefore many aspects of the project still refer to the word _Postgres_ ; for example, the default database is named `postgres`, and the software is frequently installed using the postgres user ID. As a result, people shorten the name PostgreSQL to simply Postgres, and in many cases use the two names interchangeably. PostgreSQL is pronounced as _post-grez-q-l_. Postgres is pronounced as _post-grez_. Some people get confused and refer to it as _Postgre_ , which is hard to say and likely to confuse people. Two names are enough, so don't use a third name! The following sections explain the key areas in more detail. # Robustness PostgreSQL is robust, high-quality software, supported by automated testing for both features and concurrency. By default, the database provides strong disk-write guarantees, and the developers take the risk of data loss very seriously in everything they do. Options to trade robustness for performance exist, though they are not enabled by default. All actions on the database are performed within transactions, protected by a transaction log that will perform automatic crash recovery in case of software failure. Databases may optionally be created with data block checksums to help diagnose hardware faults. Multiple backup mechanisms exist, with full and detailed **Point-in-time recovery** ( **PITR** ), in case of the need for detailed recovery. A variety of diagnostic tools are available as well. Database replication is supported natively. Synchronous Replication can provide greater than _5 nines_ (99.999 percent) availability and data protection, if properly configured and managed or even higher with appropriate redundancy. # Security Access to PostgreSQL is controllable via host-based access rules. Authentication is flexible and pluggable, allowing for easy integration with any external security architecture. The latest Salted Challenge Response Authentication Mechanism (SCRAM) provides full 256-bit protection. Full SSL-encrypted access is supported natively for both user access and replication. A full featured cryptographic function library is available for database users. PostgreSQL provides role-based access privileges to access data, by command type. PostgreSQL also provides Row Level Security for privacy, medical and military grade security. Functions may execute with the permissions of the definer, while views may be defined with security barriers to ensure that security is enforced ahead of other processing. All aspects of PostgreSQL are assessed by an active security team, while known exploits are categorized and reported at http://www.postgresql.org/support/security/. # Ease of use Clear, full, and accurate documentation exists as a result of a development process where documentation changes are required. Hundreds of small changes occur with each release that smooth off any rough edges of usage, supplied directly by knowledgeable users. PostgreSQL works on small and large systems in the same way, and across operating systems. Client access and drivers exist for every language and environment, so there is no restriction on what type of development environment is chosen now, or in the future. The SQL standard is followed very closely; there is no weird behavior, such as silent truncation of data. Text data is supported via a single data type that allows storage of anything from 1 byte to 1 gigabyte. This storage is optimized in multiple ways, so 1 byte is stored efficiently, and much larger values are automatically managed and compressed. PostgreSQL has the clear policy of minimizing the number of configuration parameters, and with each release, we work out ways to auto-tune the settings. # Extensibility PostgreSQL is designed to be highly extensible. Database extensions can be easily loaded by using `CREATE EXTENSION`, which automates version checks, dependencies, and other aspects of configuration. PostgreSQL supports user-defined data types, operators, indexes, functions, and languages. Many extensions are available for PostgreSQL, including the PostGIS extension, which provides world-class **Geographical Information System** ( **GIS** ) features. # Performance and concurrency PostgreSQL 10 can achieve more than one million reads per second on a four socket server, and it benchmarks at more than 30,000 write transactions per second with full durability. With advanced hardware even higher levels of performance are possible. PostgreSQL has an advanced optimizer that considers a variety of join types, utilizing user data statistics to guide its choices. PostgreSQL provides the widest range of index types of any commonly available database server, fully supporting all data types. PostgreSQL provides MVCC, which enables readers and writers to avoid blocking each other. Taken together, the performance features of PostgreSQL allow a mixed workload of transactional systems and complex search and analytical tasks. This is important because it means we don't always need to unload our data from production systems and reload it into analytical data stores just to execute a few ad hoc queries. PostgreSQL's capabilities make it the database of choice for new systems, as well as the right long-term choice in almost every case. # Scalability PostgreSQL 10 scales well on a single node up to four CPU sockets. PostgreSQL scales well up to hundreds of active sessions, and up to thousands of connected sessions when using a session pool. Further scalability is achieved in each annual release. PostgreSQL provides multi-node read scalability using the **Hot Standby** feature. Multi-node write scalability is under active development. The starting point for this is _Bi-Directional Replication_ (discussed in Chapter 12, _Replication and Upgrades_ ). # SQL and NoSQL PostgreSQL follows the SQL standard very closely. SQL itself does not force any particular type of model to be used, so PostgreSQL can easily be used for many types of models at the same time, in the same database. With PostgreSQL acting as a relational database, we can utilize any level of denormalization, from the full third normal form (3NF), to the more normalized Star Schema models. PostgreSQL extends the relational model to provide arrays, row types, and range types. A document-centric database is also possible using PostgreSQL's text, XML, and binary JSON (JSONB) data types, supported by indexes optimized for documents and by full text search capabilities. Key/value stores are supported using the `hstore` extension. # Popularity When MySQL was taken over by a commercial database vendor some years back, it was agreed in the EU monopoly investigation that followed that PostgreSQL was a viable competitor. That's certainly been true, with the PostgreSQL user base expanding consistently for more than a decade. Various polls have indicated that PostgreSQL is the favorite database for building new, enterprise-class applications. The PostgreSQL feature set attracts serious users who have serious applications. Financial services companies may be PostgreSQL's largest user group, though governments, telecommunication companies, and many other segments are strong users as well. This popularity extends across the world; Japan, Ecuador, Argentina, and Russia have very large user groups, and so do USA, Europe, and Australasia. Amazon Web Services' chief technology officer Dr. Werner Vogels described PostgreSQL as " _An amazing database_ ," going on to say that " _PostgreSQL has become the preferred open source relational database for many enterprise developers and start-ups, powering leading geospatial and mobile applications. AWS have more recently revealed that PostgreSQL is their fastest_ _growing service."_ # Commercial support Many people have commented that strong commercial support is what enterprises need before they can invest in open source technology. Strong support is available worldwide from a number of companies. The authors work for 2ndQuadrant, which provides commercial support for open source PostgreSQL, offering 24/7 support in English and Spanish with bug-fix resolution times. Many other companies provide strong and knowledgeable support to specific geographic regions, vertical markets, and specialized technology stacks. PostgreSQL is also available as a hosted or cloud solution from a variety of companies, since it runs very well in cloud environments. A full list of companies is kept up to date at http://www.postgresql.org/support/professional_support/. # Research and development funding PostgreSQL was originally developed as a research project at the University of California, Berkeley, in the late 1980s and early 1990s. Further work was carried out by volunteers until the late 1990s. Then, the first professional developer became involved. Over time, more and more companies and research groups became involved, supporting many professional contributors. Further funding for research and development was provided by the NSF. The project also received funding from the EU FP7 Programme in the form of the 4CaaST project for cloud computing and the AXLE project for scalable data analytics. AXLE deserves a special mention because it was a three year project aimed at enhancing PostgreSQL's business intelligence capabilities, specifically for very large databases. The project covered security, privacy, integration with data mining, and visualization tools and interfaces for new hardware. Further details are available at http://www.axleproject.eu. Other funding for PostgreSQL development comes from users who directly sponsor features and companies selling products and services based around PostgreSQL. # Getting PostgreSQL PostgreSQL is 100 % open source software. PostgreSQL is freely available to use, alter, or redistribute in any way you choose. Its license is an approved open source license, very similar to the **Berkeley Software Distribution (BSD)** license, though only just different enough that it is now known as **The PostgreSQL License** ( **TPL** ). # How to do it... PostgreSQL is already being used by many different application packages, so you may find it already installed on your servers. Many Linux distributions include PostgreSQL as part of the basic installation, or include it with the installation disk. One thing to be wary of is that the included version of PostgreSQL may not be the latest release. It would typically be the latest major release that was available when that operating system release was published. There is usually no good reason to stick to that level—there is no increased stability implied there—and later production versions are just as well supported by the various Linux distributions as the earlier versions. If you don't have a copy yet, or you don't have the latest version, you can download the source code or binary packages for a wide variety of operating systems from http://www.postgresql.org/download/. Installation details vary significantly from platform to platform, and there aren't any special tricks or recipes to mention. Just follow the installation guide, and away you go! We've consciously avoided describing the installation processes here to make sure we don't garble or override the information published to assist you. If you would like to receive email updates of the latest news, then you can subscribe to the PostgreSQL announce mailing list, which contains updates from all the vendors that support PostgreSQL. You'll get a few emails each month about new releases of core PostgreSQL, related software, conferences, and user group information. It's worth keeping in touch with these developments. For more information about the PostgreSQL announce mailing list, visit <http://archives.postgresql.org/pgsql-announce/>. # How it works... Many people ask questions such as _How can this be free?,_ _Are you sure I don't have to pay someone?,_ or _Who gives this stuff away for nothing?_ Open source applications such as PostgreSQL work on a community basis, where many contributors perform tasks that make the whole process work. For many of these people, their involvement is professional, rather a hobby, and they can do this because there is generally great value for both the contributors and their employers alike. You might not believe it. You don't have to, because i _t just works!_ # There's more... Remember that PostgreSQL is more than just the core software. There is a huge range of websites offering add-ons, extensions, and tools for PostgreSQL. You'll also find an army of bloggers describing useful tricks and discoveries that will help you in your work. Besides these, a range of professional companies can offer you help when you need it. # Connecting to the PostgreSQL server How do we access PostgreSQL? Connecting to the database is the first experience of PostgreSQL for most people, so we want to make it a good one. Let's do it now, and fix any problems we have along the way. Remember that a connection needs to be made securely, so there may be some hoops for us to jump through to ensure that the data we wish to access is secure. Before we can execute commands against the database, we need to connect to the database server, giving us a session. Sessions are designed to be long-lived, so you connect once, perform many requests, and eventually disconnect. There is a small overhead during connection. It may become noticeable if you connect and disconnect repeatedly, so you may wish to investigate the use of connection pools. Connection pools allow pre-connected sessions to be quickly served to you when you wish to reconnect. # Getting ready First, catch your database. If you don't know where it is, you'll probably have difficulty accessing it. There may be more than one database, and you'll need to know the right one to access, and also have the authority to connect to it. # How to do it... You need to specify the following parameters to connect to PostgreSQL: * Host or host address * Port * Database name * User * Password (or other means of authentication, if any) To connect, there must be a PostgreSQL server running on `host`, listening to port number `port`. On that server, a database named `dbname` and a user named `user` must also exist. The host must explicitly allow connections from your client (this is explained in the next recipe), and you must also pass authentication using the method the server specifies; for example, specifying a password won't work if the server has requested a different form of authentication. Almost all PostgreSQL interfaces use the `libpq` interface library. When using `libpq`, most of the connection parameter handling is identical, so we can discuss that just once. If you don't specify the preceding parameters, PostgreSQL looks for values set through environment variables, which are as follows: * `PGHOST` or `PGHOSTADDR` * `PGPORT` (set this to `5432` if it is not set already) * `PGDATABASE` * `PGUSER` * `PGPASSWORD` (this is definitely not recommended) If you somehow specify the first four parameters, but not the password, then PostgreSQL looks for a password file, discussed in the _Avoiding hardcoding your password_ recipe. Some PostgreSQL interfaces use the client-server protocol directly, so the ways the defaults are handled may differ. The information we need to supply won't vary significantly, so check the exact syntax for that interface. Connection details can also be specified using a **Uniform Resource Identifier** ( **URI** ) format, as follows: **psql postgresql://myuser:mypasswd@myhost:5432/mydb** This specifies that we will connect the psql client application to the PostgreSQL server at `myhost` host, `5432` port, `mydb` database name, `myuser` user, and `mypasswd` password. # How it works... PostgreSQL is a client-server database. The system it runs on is known as the host. We can access the PostgreSQL server remotely, through the network. However, we must specify `host`, which is a hostname, or `hostaddr`, which is an IP address. We can specify a host as `localhost` if we wish to make a TCP/IP connection to the same system. It is often better to use a Unix socket connection, which is attempted if the host begins with a slash (`/`) and the name is presumed to be a directory name (the default is `/tmp`). On any system, there can be more than one database server. Each database server listens to exactly one well-known network port, which cannot be shared between servers on the same system. The default port number for PostgreSQL is `5432`, which has been registered with the **Internet Assigned Numbers Authority** ( **IANA** ) and is uniquely assigned to PostgreSQL (you can see it used in the `/etc/services` file on most *nix servers). The port number can be used to uniquely identify a specific database server, if many exist. The IANA (http://www.iana.org) is the organization that coordinates the allocation of available numbers for various internet protocols. A database server is also sometimes known as a database cluster, because the PostgreSQL server allows you to define one or more databases on each server. Each connection request must identify exactly one database, identified by its `dbname`. When you connect, you will only be able to see only the database objects created within that database. A database user is used to identify the connection. By default, there is no limit on the number of connections for a particular user; in a later recipe, we will cover how to restrict that. In the more recent versions of PostgreSQL, users are referred to as login roles, though many clues remind us of the earlier nomenclature, and that still makes sense in many ways. A login role is a role that has been assigned the `CONNECT` privilege. Each connection will typically be authenticated in some way. This is defined at the server level: client authentication will not be optional at connection time, if the administrator has configured the server to require it. Once you've connected, each connection can have one active transaction at a time and one fully active statement at any time. The server will have a defined limit on the number of connections it can serve, so a connection request can be refused if the server is oversubscribed. # There's more... If you are already connected to a database server with `psql` and you want to confirm that you've connected to the right place and in the right way, you can execute some, or all, of the following commands. Here is the command that shows the `current_database`: **SELECT current_database();** The following command shows the `current_user` ID: **SELECT current_user;** The next command shows the IP address and port of the current connection, unless you are using Unix sockets, in which case both values are `NULL`: **SELECT inet_server_addr(), inet_server_port();** A user's password is not accessible using general SQL, for obvious reasons. You may also need the following: **SELECT version();** From PostgreSQL version `9.1` onwards, you can also use psql's new meta-command, `\conninfo`. It displays most of the preceding information in a single line: **postgres=# \conninfo ** **You are connected to database postgres, as user postgres, via socket in /var/run/postgresql, at port 5432.** # See also There are many other snippets of information required to understand connections. Some of them are mentioned in this chapter, and others are discussed in Chapter 6, _Security_. For further details, refer to the PostgreSQL server documentation. # Enabling access for network/remote users PostgreSQL comes in a variety of distributions. In many of these, you will note that remote access is initially disabled as a security measure. # How to do it... By default, PostgreSQL gives access to clients who connect using Unix sockets, provided that the database user is the same as the system's username. Here, we'll show you how to enable other connections. In this recipe, we mention configuration files, which can be located as shown in the _Finding the current configuration settings_ recipe in Chapter 3, _Configuration_. The steps are as follows: 1. Add or edit this line in your `postgresql.conf` file: **listen_addresses = '*'** 2. Add the following line as the first line of `pg_hba.conf` to allow access to all databases for all users with an encrypted password: **# TYPE DATABASE USER CIDR-ADDRESS METHOD** **host all all 0.0.0.0/0 md5** 3. After changing `listen_addresses`, we restart the PostgreSQL server, as explained in the _Updating the parameter file_ recipe in Chapter 3, _Configuration_. This recipe assumes that `postgresql.conf` does not include any other configuration file, which is the case in a default installation. If changing `listen_addresses` in `postgresql.conf` does not seem to work, perhaps that setting is overridden by another configuration file. Check out the _Updating the parameter file_ recipe in Chapter 3, _Configuration_ , for more details. # How it works... The `listen_addresses` parameter specifies which IP addresses to listen to. This allows you to flexibly enable and disable listening on interfaces of multiple network cards (NICs) or virtual networks on the same system. In most cases, we want to accept connections on all NICs, so we use `*`, meaning _all IP addresses_. The `pg_hba.conf` file contains a set of host-based authentication rules. Each rule is considered in sequence, until one rule fires or the attempt is specifically rejected with a `reject` method. The preceding rule means that a remote connection that specifies any user or database on any IP address will be asked to authenticate using an MD5-encrypted password. Precisely, the following: * **Type** : For this, `host` means a remote connection. * **Database** : For this, `all` means _for all databases_. Other names match exactly, except when prefixed with a plus (`+`) symbol, in which case we mean a group role rather than a single user. You can also specify a comma-separated list of users, or use the `@` symbol to include a file with a list of users. You can even specify `sameuser`, so that the rule matches when you specify the same name for the user and database. * **User** : For this, `all` means _for all users_. Other names match exactly, except when prefixed with a plus (`+`) symbol, in which case we mean a group role rather than a single user. You can also specify a comma-separated list of users, or use the `@` symbol to include a file with a list of users. * **CIDR-ADDRESS** : This consists of two parts: IP address and subnet mask. The subnet mask is specified as the number of leading bits of the IP address that make up the mask. Thus, `/0` means 0 bits of the IP address, so that all IP addresses will be matched. For example, `192.168.0.0/24` would mean match the first 24 bits, so any IP address of the form 192.168.0.x would match. You can also use `samenet` or `samehost`. * **Method** : For this, `md5` means that PostgreSQL will ask the client to provide a password encrypted with MD5. Another common setting is `trust`, which effectively means no authentication. Other authentication methods include GSSAPI, SSPI, LDAP, RADIUS, and PAM. PostgreSQL connections can also be made using SSL, in which case client SSL certificates provide authentication. See the _Using SSL certificates to authenticate the client_ recipe in Chapter 6, _Security_ , for more details about this. Don't use the `password` setting, as this sends the password in plain text. This is not a real security issue if your connection is encrypted with SSL, and there are normally no downsides with MD5 anyway, and you have extra security for non-SSL connections. # There's more... In earlier versions of PostgreSQL, access through the network was enabled by adding the `-i` command line switch when you started the server. This is still a valid option, but now it means the following: **listen_addresses = '*'** So, if you're reading some notes about how to set things up and this is mentioned, be warned that those notes are probably long out of date. They are not necessarily wrong, but it's worth looking further to see whether anything else has changed. # See also Look at installer and/or operating system-specific documentation to find the standard location of the files. # Using graphical administration tools Graphical administration tools are often requested by system administrators. PostgreSQL has a range of tool options. In this book, we'll cover pgAdmin4, and also OmniDB, which offers access to PostgreSQL and other databases. Both of these tools are client applications that send and receive SQL to PostgreSQL, displaying the results for you. The admin client can access many databases servers, allowing you to manage a fleet of servers. Both tools work in standalone app mode and within web browsers. # How to do it... **pgAdmin 4** is usually named just pgAdmin. The " _4_ " at the end has a long history, but isn't that important. It is not the release level; the release level at the time of writing this book is 3.0. **pgAdmin 4** replaces the earlier pgAdmin 3. When you start pgAdmin, you will be prompted to register a new server. Give your server a name on the **General** tab, then click **Connection** and fill in the five basic connection parameters, as well as the other information. You should uncheck the **Save password?** box: If you have many database servers, you can group them together. I suggest keeping any replicated servers together in the same Server Group. Give each server a sensible name. Once you've added a server, you can connect to it and display information about it. The default screen is the Dashboard, which presents a few interesting graphs based on the data it polls from the server. That's not very useful, so click on the Statistics tab. You will then get access to the main browser screen, with the object tree view on the left and statistics on the right, as shown in the following screenshot: pgAdmin easily displays much of the data that is available from PostgreSQL. The information is context-sensitive, allowing you to navigate and see everything quickly and easily. The information is not dynamically updated; this will occur only when you click to refresh, so keep it in mind when using the application. pgAdmin also provides Grant Wizard. This is useful for DBAs for review and immediate maintenance: The pgAdmin query tool allows you to have multiple active sessions. The query tool has a good-looking Visual Explain feature, which displays the `EXPLAIN` plan for your query. # How it works... pgAdmin provides a wide range of features, many of which are provided by other tools as well. This gives us the opportunity to choose which of those tools we want. For many reasons, it is best to use the right tool for the right job, and that is always a matter of expertise, experience, and personal taste. pgAdmin submits SQL to the PostgreSQL server, and displays the results quickly and easily. As a browser, it is fantastic. For performing small DBA tasks, it is ideal. As you might've guessed from these comments, I don't recommend pgAdmin for every task. Scripting is an important technique for DBAs. You keep a copy of the task executed, and you can edit and resubmit if problems occur. It's also easy to put all the tasks in a script into a single transaction, which isn't possible using the current GUI tools. pgAdmin provides pgScript, which only works with pgAdmin, so it is more difficult to port. For scripting, I strongly recommend the psql utility, which has many additional features that you'll increasingly appreciate over time. Although I recommend psql as a scripting tool, many people find it convenient as a query tool. Some people may find this strange, and assume it is a choice for experts only. Two great features of psql are the online help for SQL and the tab completion feature, which allows you to build up SQL quickly without having to remember the syntax. See the _Using the psql query and scripting tool_ recipe for more information. pgAdmin also provides pgAgent, a task scheduler. Again, more portable schedulers are available, and you may wish to use those instead. Schedulers aren't covered in this book. A quick warning! When you create an object in pgAdmin, the object will be created with a mixed case name if you use capitals anywhere in the object name. If I ask for a table named MyTable, then the only way to access that table is by referring to it in double quotes as "MyTable". See the _Handling objects with quoted names_ recipe in Chapter 5, _Tables and Data_. # OmniDB OmniDB is designed to access PostgreSQL, MySQL and Oracle in one interface, though makes sure it provides full features for the PostgreSQL database. OmniDB is developing quickly, with monthly feature releases so I recommend you check out the latest information at <https://omnidb.org/>. OmniDB provides a very responsive interface and is designed with full security in mind. It has the standard tree-view browsing interface, with multi-tab access for each database server you access. It's easy to be connected to multiple PostgreSQL, MySQL and Oracle database servers all at the same time: OmniDB has an SQL editor that has code completion and debugging. `EXPLAIN ANALYZE` output is colored to highlight the areas of the plan taking the most time: There are some very cool graphics features that are best seen using live data, so give it a try. # See also You may also be interested in commercial tools of various kinds for PostgreSQL. A full listing is given in the PostgreSQL software catalog at <http://www.postgresql.org/download/products/1>. # Using the psql query and scripting tool `psql` is the query tool supplied as a part of the core distribution of PostgreSQL, so it is available in all environments, and works similarly in them all. This makes it an ideal choice for developing portable applications and techniques. `psql` provides features for use as both an interactive query tool and a a scripting tool. # Getting ready From here on, we will assume that the `psql` command is enough to allow you access to the PostgreSQL server. This assumes that all your connection parameters are defaults, which may not be true. Written in full, the connection parameters would be either of these options: **psql -h myhost -p 5432 -d mydb -U myuser** **psql postgresql://myuser@myhost:5432/mydb** The default value for the port (`-p`) is `5432`. By default, `mydb` and `myuser` are both identical to the operating system's username. The default `myhost` on Windows is localhost, while on Unix, we use the default directory for Unix socket connections. The location of such directories varies across distributions and is set at compile time. However, note that you don't actually need to know its value, because on local connections both the server and the client are normally compiled together, so they use the same default. # How to do it... The command that executes a single SQL command and prints the output is the easiest, as shown here: **$ psql -c "SELECT current_time"** **timetz** **-----------------** **18:48:32.484+01** **(1 row)** The `-c` command is non-interactive. If we want to execute multiple commands, we can write those commands in a text file and then execute them using the `-f` option. This command loads a very small and simple set of examples: **$ psql -f examples.sql** It produces the following output when successful: **SET** **SET** **SET** **SET** **SET** **SET** **DROP SCHEMA** **CREATE SCHEMA** **SET** **SET** **SET** **CREATE TABLE** **CREATE TABLE** **COPY 5** **COPY 3** The `examples.sql` script is very similar to a dump file produced by PostgreSQL backup tools, so this type of file and the output it produces are very common. When a command is executed successfully, PostgreSQL outputs a _command tag_ equal to the name of that command; this is how the preceding output was produced. The `psql` tool can also be used with both the `-c` and `-f` modes together; each one can be used multiple times. In this case, it will execute all the commands consecutively: **$ psql -c "SELECT current_time" –f examples.sql -c "SELECT current_time" ** **timetz ** **----------------- ** **18:52:15.287+01 ** **(1 row) ** **...output removed for clarity... ** **timetz ** **----------------- ** **18:58:23.554+01 ** **(1 row)** The `psql` tool can also be used in interactive mode, which is the default, so it requires no option: **$ psql** **postgres=#** The first interactive command you'll need is the following: **postgres=# help** You can then enter SQL or other commands. The following is the last interactive command you'll need: **postgres=# \quit** Unfortunately, you cannot type `quit` on its own, nor can you type `\exit`, or other options. Sorry, just `\quit`, or `\q` for short! # How it works... In psql, you can enter the following two types of commands: * psql meta-commands * SQL A meta-command is a command for the psql client, whereas SQL is sent to the database server. An example of a meta-command is `\q`, which tells the client to disconnect. All lines that begin with `\` (backslash) as the first nonblank character are presumed to be meta-commands of some kind. If it isn't a meta-command, then it's SQL. We keep reading SQL until we find a semicolon, so we can spread SQL across many lines and format it any way we find convenient. The `help` command is the only exception. We provide this for people who are completely lost, which is a good thought; so let's start from there ourselves. There are two types of `help` commands, which are as follows: * `\?`: This provides help on psql meta-commands * `\h`: This provides help on specific SQL commands Consider the following snippet as an example: **postgres=# \h DELETE ** **Command: DELETE ** **Description: delete rows of a table ** **Syntax: ** **[ WITH [ RECURSIVE ] with_query [, ...] ] ** **DELETE FROM [ ONLY ] table [ [ AS ] alias ] ** **[ USING usinglist ] ** **[ WHERE condition | WHERE CURRENT OF cursor_name ] ** **[ RETURNING * | output_expression [ AS output_name ] [,]]** I find this a great way to discover and remember options and syntax. You'll also like the ability to scroll back through the previous command history. You'll get a lot of benefit from tab completion, which will fill in the next part of the syntax when you press the _Tab_ key. This also works for object names, so you can type in just the first few letters and then press _Tab_ ; all the options will be displayed. Thus, you can type in just enough letters to make the object name unique, and then hit Tab to get the rest of the name. One-line comments begin with two dashes, as follows: **-- This is a single-line comment** Multi-line comments are similar to those in C and Java: **/* ** *** Multi-line comment ** ***/** You'll probably agree that psql looks a little daunting at first, with strange backslash commands. I do hope you'll take a few moments to understand the interface and keep digging for more information. The `psql` tool is one of the most surprising parts of PostgreSQL, and it is incredibly useful for database administration tasks when used alongside other tools. # There's more... `psql` works across releases and works well with older versions. It may not work at all with newer server versions, so use the latest client whatever level of server you are accessing. # See also Check out some other useful features of psql, which are as follows: * Information functions * Output formatting * Execution timing using the `\timing` command * Input/output and editing commands * Automatic start up files, such as `.psqlrc` * Substitutable parameters (variables) * Access to the OS command line # Changing your password securely If you are using password authentication, then you may wish to change your password from time to time. # How to do it... The most basic method is to use the `psql` tool. The `\password` command will prompt you once for a new password and again to confirm. Connect to the `psql` tool and type the following: **\password** Enter a new password. This causes psql to send an SQL statement to the PostgreSQL server, which contains an already encrypted password string. An example of the SQL statement sent is as follows: **ALTER USER postgres PASSWORD 'md53175bce1d3201d16594cebf9d7eb3f9d';** Whatever you do, don't use `postgres` as your password. This will make you vulnerable to idle hackers, so make it a little more difficult than that! Make sure you don't forget your password either. It may prove difficult to maintain your database if you can't get access to it later. # How it works... As changing the password is just an SQL statement, any interface can do this. Other tools also allow this, such as the following: * pgAdmin4 * phpPgAdmin If you don't use one of the main routes to change the password, you can still do it yourself, using SQL from any interface. Note that you need to encrypt your password, because if you do submit a password in plain text, like the following, then it will be shipped to the server in plain text: **ALTER USER myuser PASSWORD 'secret'** Luckily, the password in this case will still be stored in an encrypted form. It will also be recorded in plain text in psql's history file, as well as in any server and application logs, depending on the actual log-level settings. PostgreSQL doesn't enforce a password change cycle, so you may wish to use more advanced authentication mechanisms, such as GSSAPI, SSPI, LDAP, RADIUS, and so on. # Avoiding hardcoding your password We all agree that hardcoding your password is a bad idea. This recipe shows you how to keep your password in a secure password file. # Getting ready Not all database users need passwords; some databases use other means of authentication. Don't perform this step unless you know you will be using password authentication, and you know your password. First, remove the hardcoded password from where you set it previously. Completely remove the `password = xxxx` text from the connection string in a program. Otherwise, when you test the password file, the hardcoded setting will override the details you are about to place in the file. Keeping the password hardcoded and in the password file is not any better. Using `PGPASSWORD` is not recommended either, so remove that also. If you think someone may have seen the password, then change your password before placing it in the secure password file. # How to do it... A password file contains the usual five fields that we require when connecting, as shown here: **host:port:dbname:user:password** Change this to the following: **myhost:5432:postgres:sriggs:moresecure** The password file is located using an environment variable named `PGPASSFILE`. If `PGPASSFILE` is not set, then a default filename and location must be searched for, as follows: * On *nix systems, look for `~/.pgpass` * On Windows systems, look for `%APPDATA%\postgresql\pgpass.conf`, where `%APPDATA%` is the application data subdirectory in the path (for me, that would be `C:\`) Don't forget to set the file permissions on the file, so that security is maintained. File permissions are not enforced on Windows, though the default location is secure. On *nix systems, you must issue the following: `chmod 0600 ~/.pgpass`. If you forget to do this, the PostgreSQL client will ignore the `.pgpass` file. While the `psql` tool will issue a clear warning, many other clients will just fail silently, so don't forget! # How it works... Many people name the password file `.pgpass`, whether or not they are on Windows, so don't get confused if they do this. The password file can contain multiple lines. Each line is matched against the requested `host:port:dbname:user` combination until we find a line that matches. Then, we use that password. Each item can be a literal value or `*`, a wildcard that matches anything. There is no support for partial matching. With appropriate permissions, a user can potentially connect to any database. Using the wildcard in the `dbname` and `port` fields makes sense, but it is less useful in other fields. Here are a few examples: * `myhost:5432:*:sriggs:moresecurepw` * `myhost:5432:perf:hannu:okpw` * `myhost:*:perf:gianni:sicurissimo` # There's more... This looks like a good improvement if you have a small number of database servers. If you have many different database servers, you may want to think about using a connection service file instead (see the next recipe), or perhaps even storing details on a **Lightweight Directory Access Protocol** ( **LDAP** ) server. # Using a connection service file As the number of connection options grows, you may want to consider using a connection service file. The connection service file allows you to give a single name to a set of connection parameters. This can be accessed centrally, to avoid the need for individual users to know the host and port of the database, and it is more resistant to future change. You can set up a system-wide file as well as individual per-user files. The default file paths for these files are `/etc/pg_service.conf` and `~/.pg_service.conf` respectively. A system-wide connection file controls service names for all users from a single place, while a per-user file applies only to that particular user. Keep in mind that the per-user file overrides the system-wide file—if a service is defined in both the files, then the definition in the per-user file will prevail. # How to do it... First, create a file named `pg_service.conf` with the following content: **[dbservice1]** **host=postgres1** **port=5432** **dbname=postgres** You can then copy it to either `/etc/pg_service.conf` or another agreed central location. You can then set the `PGSYSCONFDIR` environment variable to that directory location. Alternatively, you can copy it to `~/.pg_service.conf`. If you want to use a different name, set `PGSERVICEFILE`. Either way, you can then specify a connection string like the following: **service=dbservice1 user=sriggs** The service can also be set using an environment variable named `PGSERVICE`. # How it works... This feature applies to libpq connections only, so it does not apply to JDBC. The connection service file can also be used to specify the user, though that would mean that the username would be shared. The `pg_service.conf` and `.pgpass` files can work together, or you can use just one of the two as you choose. Note that the `pg_service.conf` file is shared, so it is not a suitable place for passwords. The per-user connection service file is not shared, but in any case, it seems best to keep things separate and confine passwords to `.pgpass`. # Troubleshooting a failed connection This recipe is all about what you should do when things go wrong. Bear in mind that 90 percent of problems are just misunderstandings, and you'll quickly be on track again. # How to do it... Here we've made a checklist to be followed if a connection attempt fails: * Check whether the database name and the username are accurate. You may be requesting a service on one system when the database you require is on another system. Recheck your credentials; ensure that you haven't mixed things up and that you are not using the database name as the username, or vice versa. If you receive too many connections, then you may need to disconnect another session before you can connect, or wait for the administrator to re-enable the connections. * Check for explicit rejections. If you receive the pg_hba.conf rejects connection for host... error message, it means your connection attempt has been explicitly rejected by the database administrator for that server. You will not be able to connect from the current client system using those credentials. There is little point in attempting to contact the administrator, as you are violating an explicit security policy with what you are attempting to do. * Check for implicit rejections. If the error message you receive is no pg_hba.conf entry for..., it means there is no explicit rule that matches your credentials. This is likely an oversight on the part of the administrator and is common in very complex networks. Contact the administrator and request a ruling on whether your connection should be allowed (hopefully) or explicitly rejected in the future. * Check whether the connection works with psql. If you're trying to connect to PostgreSQL from anything other than the psql command-line utility, switch to that now. If you can make psql connect successfully but cannot make your main connection work correctly, then the problem may be in the local interface you are using. * PostgreSQL 9.3 and later versions ship the `pg_isready` utility, which checks the status of a database server, either local or remote, by establishing a minimal connection. Only the hostname and port are mandatory, which is great if you don't know the database name, username, or password. The following outcomes are possible: * The server is running and accepting connections. * The server is running but not accepting connections (because it is starting up, shutting down, or in recovery). * A connection attempt was made, but it failed. * No connection attempt was made because of a client problem (invalid parameters, out of memory, and so on). * Check whether the server is up. If a server is shut down, then you cannot connect. The typical problem here is simply mixing up the server to which you are connecting. You need to specify the hostname and port, so it's possible that you are mixing up those details. * Check whether the server is up and accepting new connections. A server that is shutting down will not accept new connections, apart from superusers. Also, a standby server may not have the `hot_standby` parameter enabled, preventing you from connecting. * Check whether the server is listening correctly, and check the port to which the server is actually listening. Confirm that the incoming request is arriving on the interface listed in the `listen_addresses` parameter. Check whether it is set to `*` for remote connections and `localhost` for local connections. * Check whether the database name and username exist. It's possible that the database or user no longer exists. * Check the connection request, that is, check whether the connection request was successful and was somehow dropped after the connection. You can confirm this by looking at the server log when the following parameters are enabled: **log_connections = on** **log_disconnections = on** * Check for other reasons for disconnection. If you are connecting to a standby server, it is possible that you have been disconnected because of Hot Standby conflicts. See Chapter 12, _Replication and Upgrades_ , for more information. # There's more... Client authentication and security are the rapidly changing areas over subsequent major PostgreSQL releases. You will also find differences between maintenance release levels. The PostgreSQL documents on this topic can be viewed at http://www.postgresql.org/docs/current/interactive/client-authentication.html. Always check which release level you are using before consulting the manual or asking for support. Many problems are caused simply by confusing the capabilities between release levels. # Exploring the Database In this chapter, we'll cover the following recipes: * What version is the server? * What is the server uptime? * Locating the database server files * Locating the database server's message log * Locating the database's system identifier * Listing databases on this database server * How many tables are there in a database? * How much disk space does a database use? * How much disk space does a table use? * Which are my biggest tables? * How many rows in a table? * Quickly estimating the number of rows in a table * Listing extensions in this database * Understanding object dependencies # Introduction To understand PostgreSQL, you need to see it in use. An empty database is like a ghost town without houses. For now, we will assume that you already have a database. There are over a thousand books on how to design your own database from nothing. So here we aim to help people who already have access to a PostgreSQL database, but are still learning to use the PostgreSQL database management system. The best way to start is by asking some simple questions to orient yourself and begin the process of understanding. Incidentally, these are also questions you'll need to answer if you ask someone else for help. # What version is the server? If you experience problems, then you'll need to double-check which version of the server you have. This will help you to report a fault or to consult the correct version of the manual. # How to do it... We will find out the version by directly querying the database server: 1. Connect to the database and issue the following command: **postgres # SELECT version();** 2. You'll get a response that looks something like this: **PostgreSQL 10.2 on x86_64-apple-darwin16.7.0, compiled by Apple LLVM version 9.0.0 (clang-900.0.39.2), 64-bit** That's probably too much information all at once! # How it works... The current PostgreSQL server version format is Major.Maintenance, from 10 onward. The first release was 10.0, and subsequent maintenance releases will be 10.1, 10.2, 10.3, and so on. Prior to release 10, PostgreSQL used a three-part numbering series, meaning that the feature set and compatibility related to the **Major.Minor** release level. What this means is that version 9.4 contains more additional features and compatibility changes when compared to version 9.3. There is also a separate version of the manual, so if something doesn't work exactly the way you think it should, you must consult the correct version of the manual. Maintenance software releases were identified by the full three-part numbering scheme. Version 9.4.0 was the initial release of 9.4, and version 9.4.1 was a later maintenance release. The release support policy for PostgreSQL is available at <http://www.postgresql.org/support/versioning/>. This article explains that each release will be supported for a period of five years. Since we release one major version per year, this means five major releases. All releases, up to and including 9.2, were de-supported in September 2017. So, by the time you're reading this book, only the PostgreSQL 9.3 and higher versions will be supported. The earlier versions are still robust, though many performance and enterprise features are missing from those releases. The later de-support dates are as follows: **Version** | **Last supported date** ---|--- PostgreSQL 9.3 | September 2018 PostgreSQL 9.4 | December 2019 PostgreSQL 9.5 | January 2021 PostgreSQL 9.6 | September 2021 PostgreSQL 10 | September 2022 # There's more... Some other ways of checking the version number are as follows: **bash # psql --version** **psql (PostgreSQL) 10.2** However, be wary that this shows the client software version number, which may differ from the server software version number. You should check the server version directly by using the following command: **bash # cat $PGDATA/PG_VERSION** Here, you must set `PGDATA` to the actual data directory. Refer to the _Locating the database server files_ recipe for more information. Notice that the preceding command does not show the maintenance release number. Why is the database version important? PostgreSQL has internal version numbers for the data file format, database catalog layout, and crash recovery format. Each of these is checked as the server runs to ensure that the data doesn't become corrupt. PostgreSQL doesn't change these internal formats for a single release; they only change across releases. From a user's perspective, each release differs in terms of the way the server behaves. If you know your application well, then it should be possible to assess the differences simply by reading the release notes for each version. In many cases, a retest of the application is the safest thing to do. # What is the server uptime? You may wonder, _How long has it been since the server started?_ As mentioned in the previous recipe, we will find this out by asking the database server. # How to do it... Issue the following SQL from any interface: **postgres=# SELECT date_trunc('second', current_timestamp - pg_postmaster_start_time()) as uptime;** You should get output as follows: **uptime** **--------------------------------------** **2 days 02:48:04** # How it works... Postgres stores the server start time, so we can access it directly, as follows: **postgres=# SELECT pg_postmaster_start_time(); pg_postmaster_start_time ---------------------------------------------- ** **2018-01-01 19:37:41.389134+00** Then, we can write a SQL query to get the uptime, like this: **postgres=# SELECT current_timestamp - pg_postmaster_start_time(); ?column? -------------------------------------------------------- 2 days 02:50:02.23939** Finally, we can apply some formatting: **postgres=# SELECT date_trunc('second',** **current_timestamp - pg_postmaster_start_time()) as uptime; uptime ---------------------------- 2 days 02:51:18** # See also This is simple stuff. Further monitoring and statistics are covered in Chapter 8, _Monitoring and Diagnosis_. # Locating the database server files Database server files are initially stored in a location referred to as the **data directory**. Additional data files may also be stored in tablespaces, if any exist. In this recipe, you will learn how to find the location of these directories on a given database server. # Getting ready You'll need to get operating system access to the database system, which is what we call the platform on which the database runs. # How to do it... On Debian or Ubuntu systems, the default `data` directory location is: `/var/lib/postgresql/R.r/main`. Here, `R.r` represents the major and minor release numbers of the database server software, respectively; for example, 9.6. The configuration files are located in `/etc/postgresql/R.r/main/`. Note that for release 10 onwards, it will just be 10, not 10.0. In both cases, `main` is just the name of a database server. Other names are also possible. For the sake of simplicity, we assume that you only have a single installation, although the point of including the release number and database server name as components of the directory path is to allow multiple database servers to coexist on the same host. The `pg_lsclusters` utility is specific to Debian/Ubuntu, and displays a list of all the available database servers, including information, such as the following, for each server: 1. Major release number. 2. Port. 3. Status (for example, online, down, and so on). 4. Data directory. 5. Log file. The `pg_lsclusters` utility is part of the `postgresql-common` Debian/Ubuntu package, which provides a structure under which multiple versions of PostgreSQL can be installed, and multiple clusters can be maintained, at one time. On Red Hat RHEL, CentOS, and Fedora, the default data directory location is `/var/lib/pgsql/data/`. This also contains the configuration files (`*.conf`) by default. Again, that is just the default location. You can create additional data directories using the `initdb` utility. On Windows, the default data directory location is: `C:\Program Files\PostgreSQL\R.r\data`. The `initdb` utility populates the given data directory with the initial content. The directory will be created for convenience if it is missing, but for safety, the utility will stop if the `data` directory is not empty. The `initdb` utility will read the `data` directory name from the `PGDATA` environment variable, unless the `-d` command-line option is used. # How it works... Even though the Debian/Ubuntu and Red Hat file layouts are different, they both follow the Linux **Filesystem Hierarchy Standard** ( **FHS** ), so neither layout is _wrong_. The Red Hat layout is simpler and easier to understand. The Debian/Ubuntu layout is more complex, but it has different and more adventurous goals. The Debian/Ubuntu layout is similar to the **Optimal Flexible Architecture** ( **OFA** ) of other database systems. As pointed out earlier, the goals are to provide a file layout that will allow you to have multiple PostgreSQL database servers on one system, and to allow many versions of the software to exist in the filesystem at once. Again, the layout for the Windows and OS X installers is different. Multiple database clusters are possible, but they are also more complex than on Debian/Ubuntu. I recommend that you follow the Debian/Ubuntu layout on whichever platform you are using. It doesn't really have a name, so I call it the **PostgreSQL Flexible Architecture** ( **PFA** ). Clearly, if you are using Debian or Ubuntu, then the Debian/Ubuntu layout is already being used. If you do this on other platforms, you'll need to lay things out yourself, but it does pay off in the long run. To implement PFA, you can set the following environment variables to name parts of the file layout: **export PGROOT=/var/lib/pgsql/** **export PGRELEASE=10** **export PGSERVERNAME=mamba** **export PGDATA=$PGROOT/$PGRELEASE/$PGSERVERNAME** In this example, `PGDATA` is `/var/lib/pgsql/10/mamba`. Finally, you must run `initdb` to actually initialize the `data` directory, as noted earlier, and custom administration scripts should be prepared to automate actions such as starting or stopping the database server when the system undergoes similar procedures. Note that server applications such as `initdb` can only work with one major PostgreSQL version. On distributions that allow several major versions, such as Debian or Ubuntu, these applications are placed in dedicated directories, which are not put in the default command path. This means that if you just type `initdb`, the system will not find the executable, and you will get an error message. This may look like a bug, but in fact it is the desired behavior. Instead of directly accessing `initdb`, you are supposed to use the `pg_createcluster` utility from `postgresql-common`, which will select the right `initdb` depending on the major version you specify. If you plan to run more than one database server on the same host, you must set the preceding variables differently for each server, as they mandate the name of the `data` directory. For instance, you can set them in the script that you use to start or stop the database server, which would be enough because `PGDATA` is mostly used only by the database server process. # There's more... Once you've located the data directory, you can look for the files that comprise the PostgreSQL database server. The layout is as follows: **Subdirectory** | **Purpose** ---|--- `base` | This is the main table storage. Beneath this directory, each database has its own directory, within which are the files for each database table or index. `global` | Here are the tables that are shared across all databases, including the list of databases. `pg_commit_ts` | Here we store transaction commit timestamp data (from 9.5 onwards). `pg_dynshmem` | This includes dynamic shared memory information (from 9.4 onwards). `pg_logical` | This includes the logical decoding status data. `pg_multixact` | This includes files used for shared row-level locks. `pg_notify` | This includes the `LISTEN`/`NOTIFY` status files. `pg_replslot` | This includes information about replication slots (from 9.4 onwards). `pg_serial` | This includes information on committed serializable transactions. `pg_snapshots` | This includes exported snapshot files. `pg_stat` | This includes permanent statistics data. `pg_stat_tmp` | This includes transient statistics data. `pg_subtrans` | This includes subtransaction status data. `pg_tblspc` | This includes symbolic links to tablespace directories. `pg_twophase` | This includes state files for prepared transactions. `pg_wal` | This includes the transaction log or **Write-Ahead Log** ( **WAL** ) (formerly `pg_xlog`). `pg_xact` | This includes the transaction status files (formerly `pg_clog`). None of the aforementioned directories contain user-modifiable files, nor should any of the files be manually deleted in order to save space, or for any other reason. _Don't touch it, because you'll break it, and you may not be able to fix it!_ It's not even sensible to copy files in these directories without carefully following the procedures described in Chapter 11, _Backup and Recovery_. Keep off the grass! We'll talk about tablespaces later in the book. We'll also discuss a performance enhancement that involves putting the transaction log on its own set of disk drives in Chapter 10, _Performance and Concurrency_. The only things you are allowed to touch are configuration files, which are all `*.conf` files, and server message log files. Server message log files may or may not be in the data directory. For more details on this, refer to the next recipe _Locating the database server's message log_. # Locating the database server's message log The database server's message log is a record of all messages recorded by the database server. This is the first place to look if you have server problems, and a good place to check regularly. This log will include messages that look something like the following: **2016-09-01 19:37:41 GMT [2507-1] LOG: database system was shut down at 2016-09-01 19:37:38 GMT** **2016-09-01 19:37:41 GMT [2506-1] LOG: database system is ready to accept connections** We'll explain some more about these logs once we've located the files. # Getting ready You'll need to get operating system access to the database system, which is what we call the platform on which the database runs. # How to do it... The server log can be in a few different places, so let's list all of them first, so that we can locate the log or decide where we want it to be placed: * The server log may be in a directory beneath the data directory. * It may be in a directory elsewhere on the filesystem. * It may be redirected to `syslog`. * There may be no server log at all. Then it's time to add a log soon. If not redirected to `syslog`, the server log consists of one or more files. You can change the names of these files, so it may not always be the same on every system. On Debian or Ubuntu systems, the default server log location is `/var/log/postgresql`. The current server log file is named `postgresql-R.r-main.log`, where `R.r` represents the major and minor release numbers of the server, for example, 9.6. From release 10 onwards, there will be just one number. The older log files are numbered as `postgresql-10-main.log.1`. The higher the final number, the older the file, since they are being rotated by the `logrotate` utility. On Red Hat, RHEL, CentOS, and Fedora, the default server log location is a subdirectory of the `data` directory, that is, `/var/lib/pgsql/data/pg_log`. On Windows systems, the messages are sent to the Windows Event Log by default. # How it works... The server log is just a file that records messages from the server. Each message has a severity level, the most typical of them being `LOG`, though there are others, as shown in the following table: **PostgreSQL severity** | **Meaning** | **Syslog severity** | **Windows Event Log** ---|---|---|--- `DEBUG 1` to `DEBUG 5` | This comprises the internal diagnostics | `DEBUG` | `INFORMATION` `INFO` | This is the command output for the user | `INFO` | `INFORMATION` `NOTICE` | This is helpful information | `NOTICE` | `INFORMATION` `WARNING` | This warns of likely problems | `NOTICE` | `WARNING` `ERROR` | This is the current command that is aborted | `WARNING` | `ERROR` `LOG` | This is useful for sysadmins | `INFO` | `INFORMATION` `FATAL` | This is the event that disconnects one session only | `ERR` | `ERROR` `PANIC` | This is the event that crashes the server | `CRIT` | `ERROR` Watch out for `FATAL` and `PANIC`. This shouldn't happen in most cases during normal server operation, apart from certain cases related to replication; so check out Chapter 12, _Replication and Upgrades_ , also. You can adjust the number of messages that appear in the log by changing the `log_min_messages` server parameter. You can also change the amount of information that is displayed for each event by changing the `log_error_verbosity` parameter. If the messages are sent to a standard log file, then each line in the log will have a prefix of useful information that can also be controlled by the system administrator, with a parameter named `log_line_prefix`. You can also alter the _what_ and the _how much_ that goes into the logs by changing other settings such as `log_statements`, `log_checkpoints`, `log_connections`/`log_disconnections`, `log_verbosity`, `log_lock_waits`, and so on. # There's more... The `log_destination` parameter controls where the log messages are stored. The valid values are `stderr`, `csvlog`, `syslog`, and `eventlog` (the latter only on Windows). The logging collector is a background process that writes to a log file everything that the PostgreSQL server outputs to `stderr`. This is probably the most reliable way to log messages in case of problems, since it depends on fewer services. Log rotation can be controlled with settings such as `log_rotation_age` and `log_rotation_size` if you are using the logging collector. Alternatively, it is possible to configure the `logrotate` utility to perform log rotation, which is the default on Debian and Ubuntu systems. In general, monitoring activities are covered in Chapter 8, _Monitoring and Diagnosis_ , and examining the message log is just one part of it. Refer to the _Producing a daily summary of log file errors_ recipe in Chapter 8, _Monitoring and Diagnosis_ , for more details. # Locating the database's system identifier Each database server has a system identifier assigned when the database is initialized (created). The server identifier remains the same if the server is backed up, cloned, and so on. Many actions on the server are keyed to the system identifier, and you may be asked to provide this information when you report a fault. In this recipe, you will learn how to display the system identifier. # Getting ready Connect as the postgres OS user, or another user with execute privileges on the server software. # How to do it... We just need to launch the following command: **pg_controldata <data-directory> | grep "system identifier"** **Database system identifier: 5558338346489861223** Note that the preceding syntax will not work on Debian or Ubuntu systems, for the same reasons explained for `initdb` in the _Locating the database server files_ recipe. However, in this case, there is no `postgresql-common` alternative, so if you must run `pg_controldata`, you need to specify the full path to the executable, as in this example: **/usr/lib/postgresql/10/bin/pg_controldata $PGDATA** Don't use `-D` in front of the data directory name. This is the only PostgreSQL server application where you don't need to do that. # How it works... The `pg_controldata` utility is a PostgreSQL server application that shows the content of a server's control file. The control file is located within the `data` directory of a server, and it is created at database initialization time. Some of the information within it is updated regularly, and some when certain major events occur. The full output of `pg_controldata` looks like the following (the bold values are those that may change over time as the server runs): **pg_control version number: 1002** **Catalog version number: 201707211** **Database system identifier: 6320137769675861859** **Database cluster state: in production** **pg_control last modified: Sun 31 Dec 2017 16:17:41 PM GMT** **Latest checkpoint location: 0/19000728** **Prior checkpoint location: 0/19000648** **Latest checkpoint's REDO location: 0/190006F0** **Latest checkpoint's REDO WAL file: 000000010000000000000019** **Latest checkpoint's TimeLineID: 1** **Latest checkpoint's PrevTimeLineID: 1** **Latest checkpoint's full_page_writes: on** **Latest checkpoint's NextXID: 0/703** **Latest checkpoint's NextOID: 24978** **Latest checkpoint's NextMultiXactId: 1** **Latest checkpoint's NextMultiOffset: 0** **Latest checkpoint's oldestXID: 616** **Latest checkpoint's oldestXID's DB: 1** **Latest checkpoint's oldestActiveXID: 703** **Latest checkpoint's oldestMultiXid: 1** **Latest checkpoint's oldestMulti's DB: 1** **Latest checkpoint's oldestCommitTsXid:0** **Latest checkpoint's newestCommitTsXid:0** **Time of latest checkpoint: Sun 31 Dec 2017 16:17:41 PM GMT** **Fake LSN counter for unlogged rels: 0/1** **Minimum recovery ending location: 0/0** **Min recovery ending loc's timeline: 0** **Backup start location: 0/0** **Backup end location: 0/0** **End-of-backup record required: no** **wal_level setting: replica** **wal_log_hints setting: off** **max_connections setting: 100** **max_worker_processes setting: 8** **max_prepared_xacts setting: 0** **max_locks_per_xact setting: 64** **track_commit_timestamp setting: off** **Maximum data alignment: 8** **Database block size: 8192** **Blocks per segment of large relation: 131072** **WAL block size: 8192** **Bytes per WAL segment: 16777216** **Maximum length of identifiers: 64** **Maximum columns in an index: 32** **Maximum size of a TOAST chunk: 1996** **Size of a large-object chunk: 2048** **Date/time type storage: 64-bit integers** **Float4 argument passing: by value** **Float8 argument passing: by value** **Data page checksum version: 0** **Mock authentication nonce a6b19bbbd477... (not shown in full** Never edit the PostgreSQL control file. If you do, the server probably won't start correctly, or you may mask other errors. And if you do that, people will be able to tell, so fess up as soon as possible! # Listing databases on this database server When we connect to PostgreSQL, we always connect to just one specific database on any database server. If there are many databases on a single server, it can get confusing, so sometimes you may just want to find out which databases are parts of the database server. This is also confusing because we can use the word database in two different, but related, contexts. Initially, we start off by thinking that PostgreSQL is a database in which we put data, referring to the whole _database_ _server_ by just the word _database_. In PostgreSQL, a database server (also known as, _cluster_ ) is potentially split into multiple, individual databases, so, as you get more used to working with PostgreSQL, you'll start to separate the two concepts. # How to do it... If you have access to `psql`, you can type the following command: **bash $ psql -l ** **List of databases ** **Name | Owner | Encoding | Collate | Ctype | Access privileges ** **-----------+--------+----------+-------------+-------------+------------------- ** **postgres | sriggs | UTF8 | en_GB.UTF-8 | en_GB.UTF-8 | ** **template0 | sriggs | UTF8 | en_GB.UTF-8 | en_GB.UTF-8 | =c/sriggs + ** **| | | | | sriggs=CTc/sriggs ** **template1 | sriggs | UTF8 | en_GB.UTF-8 | en_GB.UTF-8 | =c/sriggs + ** **| | | | | sriggs=CTc/sriggs ** **(3 rows)** You can also get the same information while running `psql` by simply typing `\l`. The information that we just looked at is stored in a PostgreSQL catalog table named `pg_database`. We can issue a SQL query directly against that table from any connection to get a simpler result, as follows: **postgres=# select datname from pg_database;** **datname** **-----------** **template1** **template0** **postgres** **(3 rows)** # How it works... PostgreSQL starts with three databases: `template0`, `template1`, and `postgres`. The main user database is `postgres`. You can create your own databases as well, like this: **CREATE DATABASE my_database;** You can do the same from the command line, using the following expression: **bash $ createdb my_database** After you've created your databases, make sure to secure them properly, as discussed in Chapter 6, _Security_. When you create another database, it actually takes a copy of an existing database. Once it is created, there is no further link between the two databases. The `template0` and `template1` databases are known as template databases. The `template1` database can be changed to allow you to create a localized template for any new databases that you create. The `template0` database exists so that, when you alter `template1`, you still have a pristine copy on which to fall back on. In other words, if you break `template1`, then you can drop it and recreate it from `template0`. You can drop the database named `postgres`. But don't, okay? Similarly, don't try to touch `template0`, because you won't be allowed to do anything with it, except use it as a template. On the other hand, the `template1` database exists to be modified, so feel free to change it. # There's more... The information that we just saw is stored in a PostgreSQL catalog table named `pg_database`. We can look at this directly to get some more information. In some ways, the output is less useful as well, as we need to look up some of the code in other tables: **postgres=# \x** **postgres=# select * from pg_database;** **-[ RECORD 1 ]-+------------------------------** **datname | template1** **datdba | 10** **encoding | 6** **datcollate | en_GB.UTF-8** **datctype | en_GB.UTF-8** **datistemplate | t** **datallowconn | t** **datconnlimit | -1** **datlastsysoid | 11620** **datfrozenxid | 644** **dattablespace | 1663** **datacl | {=c/sriggs,sriggs=CTc/sriggs}** **-[ RECORD 2 ]-+------------------------------** **datname | template0** **datdba | 10** **encoding | 6** **datcollate | en_GB.UTF-8** **datctype | en_GB.UTF-8** **datistemplate | t** **datallowconn | f** **datconnlimit | -1** **datlastsysoid | 11620** **datfrozenxid | 644** **dattablespace | 1663** **datacl | {=c/sriggs,sriggs=CTc/sriggs}** **-[ RECORD 3 ]-+------------------------------** **datname | postgres** **datdba | 10** **encoding | 6** **datcollate | en_GB.UTF-8** **datctype | en_GB.UTF-8** **datistemplate | f** **datallowconn | t** **datconnlimit | -1** **datlastsysoid | 11620** **datfrozenxid | 644** **dattablespace | 1663** **datacl |** First of all, look at the use of the `\x` command. It makes the output in `psql` appear as one column per line, rather than one row per line. This output raises many questions, I know. We've already discussed templates. The other interesting things are that we can turn connections on and off for a database, and we can set connection limits for them as well. Also, you can see that each database has a default tablespace. Therefore, data tables get created inside one specific database, and the data files for that table get placed in one tablespace. You can also see that each database has a collation sequence, which is the way various language features are defined. We'll cover more on that in the _Choosing good names for database objects_ recipe in Chapter 5, _Tables and Data_. # How many tables are there in a database? The number of tables in a relational database is a good measure of the complexity of a database, so it is a simple way to get to know any database. In this recipe, we will show you how to compute the number of tables. # How to do it... From any interface, type the following SQL command: **SELECT count(*) FROM information_schema.tables ** **WHERE table_schema NOT IN ('information_schema', ** **'pg_catalog');** You can also look at the list of tables directly, and judge whether the list is a small or large number. In `psql`, you can see your own tables by using the following command: **postgres@ebony:~/10.2/main$ psql -c "\d" ** **List of relations ** **Schema | Name | Type | Owner ** **--------+----------+-------+---------- ** **public | accounts | table | postgres ** **public | branches | table | postgres** In pgAdmin 4, you can see the tables in the tree view on the left-hand side, as shown in the following screenshot: # How it works... PostgreSQL stores information about the database in catalog tables. They describe every aspect of the way the database has been defined. There is a main set of catalog tables stored in a schema, called `pg_catalog`. There is a second set of catalog objects called the Information Schema, which is the SQL standard way of accessing information in a relational database. We want to exclude both of these schemas from our query. Otherwise, we'll get too much information. We excluded them in the preceding query using the `NOT IN` phrase in the `WHERE` clause. Note that this query shows only the number of tables in one of the databases on the PostgreSQL server. You can only see the tables in the database to which you are currently connected, so you'll need to run the same query on each database in turn. # There's more... As I said, the number of tables in a relational database is a good measure of the complexity. But the complexity of what? Well, a complex database may have been designed to be deliberately flexible in order to cover a variety of business situations, or, a complex business process may have a limited portion of its details covered in the database. So, a large number of tables might likely reveal a complex business process or just a complex piece of software. The highest number of distinct, major tables I've ever seen in a database is 20,000, not counting partitions, views, and work tables. That clearly rates as a very complex system: **Number of distinct tables (entities)** | **Complexity rating** ---|--- 20,000 | This is incredibly complex. You're either counting wrong or you have a big team to manage this. 2,000 | This is a complex business database. Usually, not many of these are seen. 200 | This is a typical modern business database. 20 | This is a simple business database. 2 | This is a database with a single, clear purpose, strictly designed for performance or some other goal. 0 | This tells you that you haven't loaded any data yet! Of course, you can't always easily tell which tables are entities, so we just need to count the tables. Some databases use a lot of partitions or similar tables, so the numbers can grow dramatically. I've seen databases with up to 200,000 tables (of any kind). That's not recommended, however, as the database catalog tables then begin to become awfully large. # How much disk space does a database use? For planning or space monitoring, we often need to know how big the database is. # How to do it... We can do this in the following ways: * Look at the size of the files that make up the database server * Run a SQL request to confirm the database size If you look at the size of the actual files, you'll need to make sure that you include the data directory and all subdirectories, as well as all other directories that contain tablespaces. This can be tricky, and it is also difficult to break out all the different pieces. The easiest way is to ask the database a simple query, like this: **SELECT pg_database_size(current_database());** However, this is limited to only the current database. If you want to know the size of all the databases together, then you'll need a query such as the following: **SELECT sum(pg_database_size(datname)) from pg_database;** # How it works... The database server knows which tables it has loaded. It also knows how to calculate the size of each table, so the `pg_database_size()` function just looks at the file sizes. # How much disk space does a table use? How big is a table? What is the total size of all the parts of a table? # How to do it... We can see the size of a table by using this command: **postgres=# select pg_relation_size('pgbench_accounts');** The output of this command is as follows: **pg_relation_size ** **------------------ ** **13582336 ** **(1 row)** We can also see the total size of a table, including indexes and other related spaces, as follows: **postgres=# select pg_total_relation_size('pgbench_accounts');** The output is as follows: **pg_total_relation_size ** **------------------------ ** **15425536 ** **(1 row)** We can also use a `psql` command, like this: **postgres=# \dt+ pgbench_accounts** **List of relations** **Schema | Name | Type | Owner | Size | Description** **--------+------------------+-------+--------+-------+-------------** **gianni | pgbench_accounts | table | gianni | 13 MB |** **(1 row)** # How it works... In PostgreSQL, a table is made up of many relations. The main relation is the data table. In addition, there are a variety of additional data files. Each index created on a table is also a relation. Long data values are placed in a secondary table named `TOAST`, so in most cases, each table also has a `TOAST` table and a `TOAST` index. Each relation consists of multiple data files. The main data files are broken into 1 GB pieces. The first file has no suffix; others have a numbered suffix (such as `.2`). There are also files marked `_vm` and `_fsm`, which represent the visibility map and free space map, respectively. They are used as part of maintenance operations. They stay fairly small, even for very large tables. # There's more... The preceding functions, which measure the size of a relation, output the number of bytes, which is normally too large to be immediately clear. You can apply the `pg_size_pretty()` function to format that number nicely, as shown in the following example: **SELECT pg_size_pretty(pg_relation_size('pgbench_accounts'));** This yields the following output: **pg_size_pretty** **----------------** **13 MB** **(1 row)** **TOAST** stands for **The Oversize Attribute Storage Technique**. As the name implies, this is a mechanism used to store long column values. PostgreSQL allows many data types to store values up to 1 GB in size. It transparently stores large data items in many smaller pieces, so the same data type can be used for data ranging from 1 byte to 1 GB. When appropriate, values are automatically compressed and decompressed before they are split and stored, so the actual limit will vary, depending on compressibility. You may also see files ending in `_init`; they are used by unlogged tables, and their indexes, for restoring them after a crash. Unlogged objects are called this way because they do not produce WAL. So they support faster writes, but in the event of a crash they must be truncated, that is, restored to an empty state. # Which are my biggest tables? We've looked at getting the size of a specific table, so now it's time to widen the problem to related areas. Rather than having an absolute value for a specific table, let's look at the relative sizes. # How to do it... The following basic query will tell us the 10 biggest tables: **SELECT table_name** **,pg_relation_size(table_schema || '.' || table_name) as size** **FROM information_schema.tables** **WHERE table_schema NOT IN ('information_schema', 'pg_catalog')** **ORDER BY size DESC** **LIMIT 10;** The tables are shown in descending order of size, with at the most 10 rows displayed. In this case, we look at all the tables in all the schemas, apart from the tables in `information_schema` or `pg_catalog`, like we did in the _How many tables are in the database?_ recipe. # How it works... PostgreSQL provides a dedicated function, `pg_relation_size`, to compute the actual disk space used by a specific table or index. We just need to provide the table name. In addition to the main data files, there are other files (called forks) that can be measured by specifying an optional second argument. These include the **Visibility Map** ( **VM** ), the **Free Space Map** ( **FSM** ), and the **Initialization Fork** for unlogged objects. # How many rows are there in a table? Counting is one of the easiest SQL statements, so it is also many people's first experience of a PostgreSQL query. # How to do it... From any interface, the SQL command used to count rows is as follows: **SELECT count(*) FROM table;** This will return a single integer value as the result. In `psql`, the command looks like the following: **postgres=# select count(*) from orders; count ** **-------** ** 345** **(1 row)** # How it works... PostgreSQL can choose between two techniques available to compute the SQL `count(*)` function. Both are available in all the currently supported versions. The first is called **sequential scan**. We access every data block in the table one after the other, reading the number of rows in each block. If the table is on the disk, it will cause a beneficial disk access pattern, and the statement will be fairly fast. The other technique is known as **index-only scan**. It requires an index on the table, and it covers a more general case than optimizing SQL queries with `count(*)`, so we will cover it in more detail in Chapter 10, _Performance and Concurrency_. Some people think that the `count` SQL statement is a good test of the performance of a DBMS. Some DBMS have specific tuning features for the `count` SQL statement, and Postgres optimizes this using index-only scans. The PostgreSQL project has talked about this many times, but few people thought we should try to optimize this. Yes, the `count` function is frequently used within applications, but without any `WHERE` clause it is not that useful. Therefore, the index-only scans feature has been implemented which applies to more real-world situations, as well as this recipe. We scan every block of the table because of a major feature of Postgres named **Multiversion Concurrency Control** ( **MVCC** ). MVCC allows us to run the `count` SQL statement at the same time that we are inserting, updating, or deleting data from the table. That's a very cool feature, and we went to a lot of trouble in Postgres to provide it for you. MVCC requires us to record information on each row of a table, stating when that change was made. If the changes were made after the SQL statement began to execute, then we just ignore those changes. This means that we need to carry out visibility checks on each row in the table to allow us to work out the results of the `count` SQL statement. The optimization provided by index-only scans is the ability to skip such checks on the table blocks that are already known to be visible to all current sessions. Rows in these blocks can be counted directly on the index, which is normally smaller than the table, and hence faster. If you think a little deeper about this, you'll see that the result of the count SQL statement is just the value at a moment in time. Depending on what happens to the table, that value could change a little or a lot while the `count` SQL statement is executing. So, once you've executed this, all you really know is that, at a particular point in the past, there were exactly _x_ rows in the table. # Quickly estimating the number of rows in a table We don't always need an accurate count of rows, especially on a large table that may take a long time to execute. Administrators often need to estimate how big a table is so that they can estimate how long other operations may take. # How to do it... We can get a quick estimate of the number of rows in a table using roughly the same calculation that the Postgres optimizer uses: **SELECT (CASE WHEN reltuples > 0 THEN ** **pg_relation_size(oid)*reltuples/(8192*relpages) ** **ELSE 0 ** **END)::bigint AS estimated_row_count ** **FROM pg_class ** **WHERE oid = 'mytable'::regclass;** This gives us the following output: **estimated_count** **---------------------** **293** **(1 row)** It returns a row count very quickly, no matter how large the table that we are examining is. # How it works... We saw the `pg_relation_size()` function earlier, so we know it brings back an accurate value for the current size of the table. When we vacuum a table in Postgres, we record two pieces of information in the `pg_class` catalog entry for the table. These two items are the number of data blocks in the table (`relpages`) and the number of rows in the table (`reltuples`). Some people think they can use the value of `reltuples` in `pg_class` as an estimate, but it could be severely out of date. You will also be fooled if you use information in another table named `pg_stat_user_tables`, which is discussed in more detail in Chapter 10, _Performance and Concurrency_. The Postgres optimizer uses the `relpages` and `reltuples` values to calculate the average rows per block, which is also known as the average tuple density. If we assume that the average tuple density remains constant over time, then we can calculate the number of rows using this formula: _Row estimate = number of data blocks * rows per block_. We include some code to handle cases where the `reltuples` or `relpages` fields are zero. The Postgres optimizer actually works a little harder than we do in that case, so our estimate isn't very good. The `WHERE oid = 'mytable'::regclass;` syntax introduces the concept of object identifier types. They just use a shorthand trick to convert the name of an object to the object identifier number for that object. The best way to understand this is to think of that syntax as meaning the same as a function named `relname2relid()`. # There's more... The good thing about the aforementioned recipe is that it returns a value in about the same time, no matter how big the table is. The bad thing about it is that `pg_relation_size()` requests a lock on the table, so if any other user has an `AccessExclusiveLock` lock on the table, then the table size estimate will wait for the lock to be released before returning a value. Err... so what is an `AccessExclusiveLock` lock? While performing a SQL maintenance action, such as changing the data type of a column, PostgreSQL will lock out all other actions on that table, including `pg_relation_size`, which takes a lock in the `AccessShareLock` mode. For me, a typical case is when I issue some form of SQL maintenance action, such as `ALTER TABLE`, and the statement takes much longer than I thought it would. At that point, I think, _Oh, was that table bigger than I thought? How long will I be waiting?_ Yes, it's better to calculate that beforehand, but hindsight doesn't get you out of the hole you are in right now. So, we need a way to calculate the size of a table without needing the lock. My solution is to look at the operating system files that Postgres uses to store data, and figure out how large they are. Now, this can get somewhat difficult. If the table is locked, PostgreSQL is probably doing something to the table, so trying to look at the files might well be fruitless or give wrong answers. The following are the steps we need to perform: 1. First, get some details on the table from `pg_class`: **SELECT reltablespace, relfilenode FROM pg_class** **WHERE oid = 'mytable'::regclass;** 2. Then, confirm the `databaseid` in which the table resides: **SELECT oid as databaseid FROM pg_database** **WHERE datname = current_database();** Together, `reltablespace`, `databaseid`, and `relfilenode` are the three things we need to locate the underlying data files within the `data` directory. If `reltablespace` is zero, then the files will be at the following location: **$PGDATADIR/base/{databaseid}/{relfilenode}*** The bigger the table, the more files you see. If `reltablespace` is not zero, then the files will be at the following location: **$PGDATADIR/pg_tblspc/{reltablespace}/** **{databaseid}/{relfilenode}*** Every file should be 1 GB in size, apart from the last file. The preceding discussion glossed over a few other points, as follows: * Postgres uses the terms data blocks and pages to refer to the same concept. Postgres also does that with the terms tuple and row. * A data block is 8,192 bytes in size, by default. You can change that if you recompile the server yourself, and create a new database. You may want to create SQL functions for the preceding calculations, so you won't need to retype the SQL code every now and then. # Function 1 – Estimating the number of rows The following function estimates the total number of rows using a mathematical procedure called **extrapolation**. In other words, we take the average number of bytes per row resulting from the last statistics collection, and we apply it to the current table size: **CREATE OR REPLACE FUNCTION estimated_row_count(text)** **RETURNS bigint** **LANGUAGE sql** **AS $$** **SELECT (CASE WHEN reltuples > 0 THEN ** **pg_relation_size($1)*reltuples/(8192*relpages)** **ELSE 0** **END)::bigint** **FROM pg_class** **WHERE oid = $1::regclass;** **$$;** # Function 2 – Computing the size of a table without locks Here is a function that does what `pg_relation_size` does, more or less, without taking any locks. Because of this, it is always fast, but it may give an incorrect result if the table is being heavily altered at the same time: **CREATE OR REPLACE FUNCTION pg_relation_size_nolock(tablename regclass)** **RETURNS BIGINT** **LANGUAGE plpgsql** **AS $$** **DECLARE** **classoutput RECORD;** **tsid INTEGER;** **rid INTEGER;** **dbid INTEGER;** **filepath TEXT;** **filename TEXT;** **datadir TEXT;** **i INTEGER := 0;** **tablesize BIGINT;** **BEGIN** **--** **-- Get data directory** **--** **EXECUTE 'SHOW data_directory' INTO datadir;** **--** **-- Get relfilenode and reltablespace** **--** **SELECT** **reltablespace as tsid** **,relfilenode as rid** **INTO classoutput** **FROM pg_class** **WHERE oid = tablename** **AND relkind = 'r';** **--** **-- Throw an error if we can't find the tablename specified** **--** **IF NOT FOUND THEN** **RAISE EXCEPTION 'tablename % not found', tablename;** **END IF;** **tsid := classoutput.tsid;** **rid := classoutput.rid;** **--** **-- Get the database object identifier (oid)** **--** **SELECT oid INTO dbid** **FROM pg_database** **WHERE datname = current_database();** **--** **-- Use some internals knowledge to set the filepath** **--** **IF tsid = 0 THEN** **filepath := datadir || '/base/' || dbid || '/' || rid;** **ELSE** **filepath := datadir || '/pg_tblspc/' || tsid || '/'** **|| dbid || '/' || rid;** **END IF;** **--** **-- Look for the first file. Report if missing** **--** **SELECT (pg_stat_file(filepath)).size** **INTO tablesize;** **--** **-- Sum the sizes of additional files, if any** **--** **WHILE FOUND LOOP** **i := i + 1;** **filename := filepath || '.' || i;** **--** **-- pg_stat_file returns ERROR if it cannot see file** **-- so we must trap the error and exit loop** **--** **BEGIN** **SELECT tablesize + (pg_stat_file(filename)).size** **INTO tablesize;** **EXCEPTION** **WHEN OTHERS THEN** **EXIT;** **END;** **END LOOP;** **RETURN tablesize;** **END;** **$$;** This function can also work on Windows with a few minor changes, which are left as an exercise for you. # Listing extensions in this database Every PostgreSQL database contains some objects that are automatically brought in when the database is created. Every user will find a `pg_database` system catalog that lists databases, as shown in the _Listing databases on this database server_ recipe. There is little point in checking whether these objects exist, because even superusers are not allowed to drop them. On the other hand, PostgreSQL comes with tens of collections of optional objects, called **modules** , or equivalently **extensions**. The database administrator can install or uninstall these objects, depending on the requirements. They are not automatically included in a newly created database, because they might not be required by every use case. Users will install only the extensions they actually need, when they need them; an extension can be installed while a database is up and running. In this recipe, we will explain how to list extensions that have been installed on the current database. This is important to get to know the database better, and also because certain extensions affect the behavior of the database. # Getting ready To get an idea of which extensions are available, you can browse the list of additional modules shipped together with PostgreSQL, which are almost all extensions, at https://www.postgresql.org/docs/current/static/contrib.html. # How to do it... In PostgreSQL, there is a catalog table recording the list of installed extensions, so this recipe is quite simple. Issue the following command: **cookbook= > SELECT * FROM pg_extension;** This results in the following output (note that the format is expanded, as if the `\x` metacommand has been previously issued): **-[ RECORD 1 ]--+--------** **extname | plpgsql** **extowner | 10** **extnamespace | 11** **extrelocatable | f** **extversion | 1.0** **extconfig |** **extcondition |** To get the same list with fewer technical details, you can use the metacommand `\dx`, like when listing databases. # How it works... A PostgreSQL extension is represented by a control file, `<extension name>.control`, located in the `SHAREDIR/extension` directory, plus one or more files containing the actual extension objects. The control file specifies the extension name, version, and other information that is useful for the extension infrastructure. Each time an extension is installed, uninstalled, or upgraded to a new version, the corresponding row in the `pg_extension` catalog table is inserted, deleted, or updated, respectively. # There's more... In this recipe, we only mentioned extensions distributed with PostgreSQL, and solely for the purpose of listing which ones are being used in the current database. The infrastructure for extensions will be described in greater detail in Chapter 3, _Configuration_. We will talk about the version number of an extension, and we will show you how to install, uninstall, and upgrade extensions, including those distributed independently of PostgreSQL. # Understanding object dependencies In most databases, there will be dependencies between objects in the database. Sometimes, we need to understand these dependencies to figure out how to perform certain actions. Let's look at this in detail. # Getting ready We'll use the following simple database to understand and investigate them. There are two tables, as follows: **CREATE TABLE orders (** **orderid integer PRIMARY KEY** **);** **CREATE TABLE orderlines (** **orderid integer** **,lineid smallint** **,PRIMARY KEY (orderid, lineid)** **);** Now, we add a link between them to enforce what is known as **Referential Integrity** , as follows: **ALTER TABLE orderlines ADD FOREIGN KEY (orderid)** **REFERENCES orders (orderid);** If we try to drop the referenced table, we get the following message: **DROP TABLE orders;** **ERROR: cannot drop table orders because other objects depend on it** **DETAIL: constraint orderlines_orderid_fkey on table orderlines depends on table orders** **HINT: Use DROP ... CASCADE to drop the dependent objects too.** Be very careful! If you follow the hint, you may accidentally remove all the objects that have any dependency on the `orders` table. You might think that this would be a great idea, but to me it seems lazy and foolish. It might work, but we need to ensure that it will work. Therefore, you need to know what dependencies are present on the `orders` table, and then review them. Then, you can decide whether it is okay to issue the `CASCADE` version of the command, or whether you should reconcile the situation manually. # How to do it... You can use the following command from `psql` to display full information about a table the constraints that are defined upon it, and the constraints that reference it: **\d+ orders** You can also get specific details of the constraints by using the following query: **SELECT * FROM pg_constraint** **WHERE confrelid = 'orders'::regclass;** Unfortunately, this is not the end of the story, so read the _There's more..._ section. # How it works... When we create a foreign key, we add a constraint to the catalog table known as `pg_constraint`. Therefore, the query shows us how to find all the constraints that depend upon the `orders` table. # There's more... With Postgres, there's always a little more when you look beneath the surface. In this case, there's a lot more, and it's important. The aforementioned queries only covered constraints between tables. We didn't discuss dependencies with other kinds of objects. Two important types of object that might have dependencies to tables are views and functions. Consider the following command: **DROP TABLE orders;** If you issue this, the dependency on any of the views will prevent the table from being dropped. Thus, you need to remove those views and then drop the table. The story with function dependencies is not as useful. Relationships between functions and tables are not recorded in the catalog, nor is the dependency information between functions and functions. This is partly due to the fact that most PostgreSQL procedural languages allow dynamic query execution, so you wouldn't be able to tell which tables or functions a function would access until it executes. That's only partly the reason, because most functions clearly reference other tables and functions, so it should be possible to identify and store those dependencies. However, right now, we don't do that. So, make a note that you need to record the dependency information for your functions manually, so that you'll know if and when it's okay to remove or alter a table or other objects that the functions depend on. # Configuration In this chapter, we will cover the following recipes: * Reading the fine manual * Planning a new database * Changing parameters in your programs * Finding the current configuration settings * Which parameters are at non-default settings? * Updating the parameter file * Setting parameters for particular groups of users * The basic server configuration checklist * Adding an external module to PostgreSQL * Using an installed module * Managing installed extensions # Introduction I get asked many questions about parameter settings in PostgreSQL. Everybody's busy, and most people want a 5-minute tour of how things work. That's exactly what a cookbook does, so we'll do our best. Some people believe that there are some magical parameter settings that will improve their performance, spending hours combing the pages of books to glean insights. Others feel comfortable because they have found a website somewhere that _explains everything_ , and they _know_ they have their database configured OK. For the most part, the settings are easy to understand. Finding the best setting can be difficult, and the optimal setting may change over time. This chapter is mostly about knowing how, when, and where to change parameter settings. # Reading the fine manual **Reading the fine manual** ( **RTFM** ) is often (rudely) used to mean _don't bother me, I'm busy_ ; or it is used as a stronger form of abuse. The strange thing is that asking you to read a manual is most often very good advice. Don't flame the advisors back; take the advice! The most important point to remember is that you should refer to a manual whose release version matches that of the server on which you are operating. The PostgreSQL manual is very well written and comprehensive in its coverage of specific topics. However, one of its main failings is that the documents aren't organized in a way that helps somebody who is trying to learn PostgreSQL. They are organized from the perspective of people checking specific technical points so that they can decide whether their difficulty is a user error or not. It sometimes answers _What?_ but seldom _Why?_ Or _How?_ I've helped write sections of the PostgreSQL documents, so I'm not embarrassed to steer you toward reading them. There are, nonetheless, many things to read here that are useful. # How to do it... The main documents for each PostgreSQL release are available at http://www.postgresql.org/docs/manuals/. The most frequently accessed parts of the documents are as follows: * SQL command reference, as well as client and server tools reference: http://www.postgresql.org/docs/current/interactive/reference.html * Configuration: http://www.postgresql.org/docs/current/interactive/runtime-config.html * Functions: http://www.postgresql.org/docs/current/interactive/functions.html You can also grab yourself a PDF version of the manual, which can allow easier searching in some cases. Don't print it! The documents are more than 2,000 pages of A4-sized sheets. # How it works... The PostgreSQL documents are written in SGML, which is similar to, but not the same as, XML. These files are then processed to generate HTML files, PDFs, and so on. This ensures that all the formats have exactly the same content. Then you can choose the format you prefer, and you can even compile it in other formats, such as EPUB, INFO, and so on. Moreover, the PostgreSQL manual is actually a subset of the PostgreSQL source code, so it evolves together with the software. It is written by the same people who make PostgreSQL. Even more reasons to read it! # There's more... More information is also available at http://wiki.postgresql.org. Many distributions offer packages that install static versions of the HTML documentation. For example, on Debian and Ubuntu, the docs for the most recent stable PostgreSQL version are named `postgresql-10-docs` (unsurprisingly). # Planning a new database Planning a new database can be a daunting task. It's easy to get overwhelmed by it, so here we present some planning ideas. It's also easy to charge headlong at the task, thinking that whatever you know is all you'll ever need to consider. # Getting ready You are ready. Don't wait to be told what to do. If you haven't been told what the requirements are, then write down what you think they are, clearly labeling them as _assumptions_ rather than _requirements_ ; you must not confuse the two things. Iterate until you get some agreement, and then build a prototype. # How to do it... Write a document that covers the following items: * Database design - plan your database design * Calculate the initial database sizing * Transaction analysis - How will we access the database? * Look at the most frequent access paths * What are the requirements for response times? * Hardware configuration * Initial performance thoughts - Will all of the data fit into the RAM? * Choose the operating system and filesystem types * How do we partition the disk? * Localization plan * Decide the server encoding, locale, and time zone * Access and security plan * Identify client systems and specify the required drivers * Create roles according to a plan for access control * Specify `pg_hba.conf` * Maintenance plan - Who will keep it working? How? * Availability plan - consider the availability requirements * `checkpoint_timeout` (for more details on this parameter, see the _Understanding and controlling crash recovery_ recipe in Chapter 11, _Backup and Recovery_ ) * Plan your backup mechanism, and test it * High-availability plan * Decide which form of replication you'll need, if any # How it works... One of the most important reasons for planning your database ahead of time is that retrofitting some things is difficult. This is especially true of server encoding and locale, which can cause much downtime and exertion if we need to change them later. Security is also much more difficult to set up after the system is live. # There's more... Planning always helps. You may know what you're doing, but others may not. Tell everybody what you're going to do before you do it, to avoid wasting time. If you're not sure yet, then build a prototype to help you decide. Approach the administration framework as if it were a development task. Make a list of things you don't know yet, and work through them one by one. This is deliberately a very short recipe. Everybody has their own way of doing things, and it's very important not to be too prescriptive about how to do things. If you already have a plan, great! If you don't, think about what you need to do, make a checklist, and then do it. # Changing parameters in your programs PostgreSQL allows you to set some parameter settings for each session or transaction. # How to do it... 1. You can change the value of a setting during your session, like this: **SET work_mem = '16MB';** 2. This value will then be used for every future transaction. You can also change it only for the duration of the current transaction: **SET LOCAL work_mem = '16MB';** 3. The setting will last until you issue this command: **RESET work_mem;** 4. Alternatively, you can issue the following command: **RESET ALL;** The `SET` and `RESET` commands are SQL commands that can be issued from any interface. They apply only to PostgreSQL server parameters, but this does not mean that they affect the entire server. In fact, the parameters you can change with `SET` and `RESET` apply only to the current session. Also, note that there may be other parameters, such as JDBC driver parameters, that cannot be set in this way. Refer to the _Connecting to the PostgreSQL server_ recipe in Chapter 1, _First Steps_ , for help with those parameters. # How it works... Suppose you change the value of a setting during your session, for example, by issuing this command: **SET work_mem = '16MB';** Then, the following will show up in the `pg_settings` catalog view: **postgres=# SELECT name, setting, reset_val, source** **FROM pg_settings WHERE source = 'session'; name | setting | reset_val | source ----------+---------+-----------+--------- work_mem | 16384 | 1024 | session** This will show until you issue this command: **RESET work_mem;** After issuing it, the setting returns to `reset_val` and the `source` returns to default: **name | setting | reset_val | source ---------+---------+-----------+--------- work_mem | 1024 | 1024 | default** # There's more... You can change the value of a setting during your transaction as well, like this: **SET LOCAL work_mem = '16MB';** This results in the following output: **WARNING: SET LOCAL can only be used in transaction blocks ** **SET** In order to understand what the warning means, we look that `setting` up in the `pg_settings` catalog view: **postgres=# SELECT name, setting, reset_val, source** **FROM pg_settings WHERE source = 'session'; ** **name | setting | reset_val | source ** **----------+---------+-----------+--------- ** **work_mem | 1024 | 1024 | session** Huh? What happened to your parameter setting? The `SET LOCAL` command takes effect only for the transaction in which it was executed, which was just the `SET LOCAL` command in our case. We need to execute it inside a transaction block to be able to see the setting take hold, as follows: **BEGIN;** **SET LOCAL work_mem = '16MB';** Here is what shows up in the `pg_settings` catalog view: **postgres=# SELECT name, setting, reset_val, source** **FROM pg_settings WHERE source = 'session';** **name | setting | reset_val | source** **----------+---------+-----------+---------** **work_mem | 16384 | 1024 | session** You should also note that the value of `source` is `session` rather than `transaction`, as you might have been expecting. # Finding the current configuration settings At some point, it will occur to you to ask, _What are the current configuration settings?_ Most settings can be changed in more than one way, and some ways do not affect all users or all sessions, so it is quite possible to get confused. # How to do it... Your first thought is probably to look in `postgresql.conf`, which is the configuration file, described in detail in the _Updating the parameter file_ recipe. That works, but only as long as there is only one parameter file. If there are two, then maybe you're reading the wrong file! How would you know? So, the cautious and accurate way is to not trust a text file, but to trust the server itself. Moreover, you learned in the previous recipe, _Changing parameters in your programs_ , that each parameter has a scope that determines when it can be set. Some parameters can be set through `postgresql.conf`, but others can be changed afterwards. So, the current values of configuration settings may have been subsequently changed. We can use the `SHOW` command like this: **postgres=# SHOW work_mem;** Its output is as follows: **work_mem ** **---------- ** **1MB ** **(1 row)** However, remember that it reports the current setting at the time it is run, and that can be changed in many places. Another way of finding the current settings is to access a PostgreSQL catalog view named `pg_settings`: **postgres=# \x Expanded display is on. postgres=# SELECT * FROM pg_settings WHERE name = 'work_mem'; [ RECORD 1 ] -------------------------------------------------------- name | work_mem setting | 1024 unit | kB category | Resource Usage / Memory short_desc | Sets the maximum memory to be used for query workspaces. extra_desc | This much memory can be used by each internal sort operation and hash table before switching to temporary disk files. context | user vartype | integer source | default min_val | 64 max_val | 2147483647 enumvals | boot_val | 1024 reset_val | 1024 sourcefile | sourceline |** Thus, you can use the `SHOW` command to retrieve the value for a setting, or you can access the full details via the catalog table. # There's more... The actual location of each configuration file can be asked directly to the PostgreSQL server, as shown in this example: **postgres=# SHOW config_file;** This returns the following output: **config_file** **------------------------------------------** **/etc/postgresql/10/main/postgresql.conf** **(1 row)** The other configuration files can be located by querying similar variables: `hba_file` and `ident_file`. # How it works... Each parameter setting is cached within each session, so that we can get fast access to the parameter settings. This allows us to access the parameter settings with ease. Remember that the values displayed are not necessarily settings for the server as a whole. Many of those parameters will be specific to the current session. That's different from what you experience with many other types of database software, and is also very useful. # Which parameters are at non-default settings? Often, we need to check which parameters have been changed, or whether our changes have taken effect correctly. In the previous two recipes, we have seen that parameters can be changed in several ways, and with different scopes. You learned how to inspect the value of one parameter or get the full list of parameters. In this recipe, we will show you how to use SQL capabilities to list only those parameters whose value in the current session differs from the system-wide default value. This list is valuable for several reasons. First, it includes only a few of the 200-plus available parameters, so it is more immediate. Also, it is difficult to remember all our past actions, especially in the middle of a long or complicated session. Version 9.4 introduces the `ALTER SYSTEM` syntax, which we will describe in the next recipe, _Updating the parameter file_. From the viewpoint of this recipe, the behavior of this syntax is quite different from all the other setting-related commands: you run it from within your session, and it changes the default value, but not the value in your session. # How to do it... We write an SQL query that lists all parameter values, excluding those whose current value is either the default or set from a configuration file: **postgres=# SELECT name, source, setting** **FROM pg_settings** **WHERE source != 'default'** **AND source != 'override'** **ORDER by 2, 1;** The output is as follows: **name | source | setting** **----------------------------+----------------------+-----------------** **application_name | client | psql** **client_encoding | client | UTF8** **DateStyle | configuration file | ISO, DMY** **default_text_search_config | configuration file | pg_catalog.english** **dynamic_shared_memory_type | configuration file | posix** **lc_messages | configuration file | en_GB.UTF-8** **lc_monetary | configuration file | en_GB.UTF-8** **lc_numeric | configuration file | en_GB.UTF-8** **lc_time | configuration file | en_GB.UTF-8** **log_timezone | configuration file | Europe/Rome** **max_connections | configuration file | 100** **port | configuration file | 5460** **shared_buffers | configuration file | 16384** **TimeZone | configuration file | Europe/Rome** **max_stack_depth | environment variable | 2048** # How it works... From `pg_settings`, you can see which parameters have non-default values, and what the source of the current value is. The `SHOW` command doesn't tell you whether a parameter is set at a non-default value. It just tells you the value, which isn't of much help if you're trying to understand what is set and why. If the source is a configuration file, then the `sourcefile` and `sourceline` columns are also set. These can be useful in understanding where the configuration came from. # There's more... The `setting` column of `pg_settings` shows the current value, but you can also look at the `boot_val` and `reset_val` parameters. The `boot_val` parameter shows the value assigned when the PostgreSQL database cluster was initialized (`initdb`), while `reset_val` shows the value that the parameter will return to if you issue the `RESET` command. The `max_stack_depth` parameter is an exception, because `pg_settings` says it is set by the environment variable, though it is actually set by `ulimit -s` on Linux and Unix systems. The `max_stack_depth` parameter just needs to be set directly on Windows. The timezone settings are also picked up from the OS environment, so you shouldn't need to set those directly. In older releases, `pg_settings` showed them as command-line settings. From version 9.1 onward, they are written to `postgresql.conf` when the `data` directory is initialized, so they show up as configuration files. # Updating the parameter file The parameter file is the main location for defining parameter values for the PostgreSQL server. All the parameters can be set in the parameter file, which is known as `postgresql.conf`. There are also two other parameter files: `pg_hba.conf` and `pg_ident.conf`. Both of these relate to connections and security, so we'll cover them in the appropriate chapters that follow. # Getting ready First, locate `postgresql.conf`, as described previously. # How to do it... Some of the parameters take effect only when the server is first started. A typical example might be `shared_buffers`, which defines the size of the shared memory cache. Many of the parameters can be changed while the server is still running. After changing the required parameters, we issue a `reload` command to the server, forcing PostgreSQL to reread the `postgresql.conf` file (and all other configuration files). There are a number of ways to do that, depending on your distribution and OS. The most common is to issue the following command, with the same OS user that runs the PostgreSQL server process: **pg_ctl reload** This assumes the default data directory; otherwise, you have to specify the correct data directory with the `-D` option. As previously noted, Debian and Ubuntu have a different multiversion architecture, so you should issue the following command instead: **pg_ctlcluster 10 main reload** On modern distributions, you can also use `systemd`, as follows: **sudo systemctl reload postgresql@10-main ** See the _Starting the database server manually_ recipe, in Chapter 4 _,_ _Server Control_ , for more details on how to manage PostgreSQL via `systemd`; the _Reloading the server configuration files_ recipe, also in Chapter 4, _Server Control_ , shows more ways to reload configuration files _._ Some other parameters require a restart of the server for changes to take effect; for instance, `max_connections`, `listen_addresses`, and so on. The syntax is very similar to a `reload` operation, as shown here: **pg_ctl restart** For Debian and Ubuntu, use this command: **pg_ctlcluster 10 main restart** With system, use this command: **sudo systemctl restart postgresql@10-main** Of course, a restart also has some impact on existing connections. See the _Restarting the server quickly_ recipe in Chapter 4, _Server Control_ , for further details. The `postgresql.conf` file is a normal text file that can be simply edited. Most of the parameters are listed in the file, so you can just search for them and then insert the desired value in the right place. # How it works... If you set the same parameter twice in different parts of the file, the last setting is what applies. This can cause lots of confusion if you add settings to the bottom of the file, so you are advised against doing it. The best practice is to version-control this by using git alongside any other code or config changes. # There's more... The `postgresql.conf` file also supports an `include` directive. This allows the `postgresql.conf` file to reference other files, which can then reference other files, and so on. That may help you organize your parameter settings better, if you don't make it too complicated. For more on reloading, see the _Reloading the server configuration files_ recipe in Chapter 4, _Server Control_. If you are working with PostgreSQL version 9.4 or later, you can change the values stored in the parameter files directly from your session, with syntax such as the following: **ALTER SYSTEM SET shared_buffers = '1GB';** This command will not actually edit `postgresql.conf`. Instead, it writes the new setting to another file named `postgresql.auto.conf`. The effect is equivalent, albeit in a safer way. The original configuration is never written, so it cannot be damaged in the event of a crash. If you mess up with too many `ALTER SYSTEM` commands, you can always delete `postgresql.auto.conf` manually, and reload the configuration or restart PostgreSQL, depending on what parameters you changed. PostgreSQL 10 now supports up to 7 TB of cache, if you have that much memory. # Setting parameters for particular groups of users PostgreSQL supports a variety of ways of defining parameter settings for various user groups. This is very convenient, especially to manage user groups that have different requirements. # How to do it... 1. For all users in the `saas` database, use the following commands: **ALTER DATABASE saas SET configuration_parameter = value1;** 2. For a user named `simon` connected to any database, use this: **ALTER ROLE simon SET configuration_parameter = value2;** 3. Alternatively, you can set a parameter for a user only when connected to a specific database, as follows: **ALTER ROLE simon IN DATABASE saas SET configuration_parameter = value3;** The user won't know that these have been executed specifically for them. These are default settings, and in most cases they can be overridden if the user requires non-default values. # How it works... You can set parameters for each of the following: * Database * User (which is named role by `PostgreSQL`) * Database/user combination Each of the parameter defaults is overridden by the one following it. In the preceding three SQL statements: * If user `hannu` connects to the `saas` database, then `value1` will apply * If user `simon` connects to a database other than `saas`, then `value2` will apply * If user `simon` connects to the `saas` database, then `value3` will apply PostgreSQL implements this in exactly the same way as if the user had manually issued the equivalent `SET` statements immediately after connecting. # The basic server configuration checklist PostgreSQL arrives configured for use on a shared system, though many people want to run dedicated database systems. The PostgreSQL project wishes to ensure that PostgreSQL will play nicely with other server software, and will not assume that it has access to the full server resources. If you, as the system administrator, know that there is no other important server software running on the system, then you can crank the values up much higher. # Getting ready Before we start, we need to know two sets of information: * We need to know the size of the physical RAM that will be dedicated to PostgreSQL * We need to know something about the types of applications for which we will use PostgreSQL # How to do it... If your database is larger than 32 MB, then you'll probably benefit from increasing `shared_buffers`. You can increase this to a much larger value, but remember that running out of memory induces many problems. For instance, PostgreSQL is able to store information to the disk when the available memory is too small, and it employs sophisticated algorithms to treat each case differently and to place each piece of data on the disk or in memory, depending on each use case. On the other hand, overstating the amount of available memory confuses such abilities and results in suboptimal behavior. For instance, if the memory is swapped to disk, then PostgreSQL will inefficiently treat all data as if it were the RAM. Another unfortunate circumstance is when the Linux **Out-Of-Memory** ( **OOM** ) killer terminates one of the various processes spawned by the PostgreSQL server. So, it's better to be conservative. It is a good practice to set a low value in your `postgresql.conf` and increment slowly, to ensure that you get the benefits from each change. If you increase `shared_buffers` and you're running on a non-Windows server, you will almost certainly need to increase the value of the `SHMMAX` OS parameter (and on some platforms, other parameters as well). On Linux, Mac OS, and FreeBSD, you will need to either edit the `/etc/sysctl.conf` file or use `sysctl -w` with the following values: * For Linux, use `kernel.shmmax=value` * For Mac OS, use `kern.sysv.shmmax=value` * For FreeBSD, use `kern.ipc.shmmax=value` # There's more... For more information, you can refer to http://www.postgresql.org/docs/9.6/static/kernel-resources.html#SYSVIPC. For example, on Linux, add the following line to `/etc/sysctl.conf`: **kernel.shmmax=value** Don't worry about setting `effective_cache_size`. It is much less important a parameter than you might think. There is no need for too much fuss selecting the value. If there is heavy write activity, you may want to set `wal_buffers` to a much higher value than the default. In fact, `wal_buffers` is automatically set from the value of `shared_buffers`, following a rule that fits most cases. However, it is always possible to specify an explicit value that overrides the computation for the very few cases where the rule is not good enough. If you're doing heavy write activity and/or large data loads, you may want to set `max_wal_size` and `min_wal_size` higher than the default to avoid wasting I/O in excessively frequent checkpoints. You may also wish to set `checkpoint_timeout` and `checkpoint_completion_target`. If your database has many large queries, you may wish to set `work_mem` to a value higher than the default. However, remember that such a limit applies to _each_ node separately in the query plan, so there is a real risk of over-allocating memory, with all the problems discussed earlier. Ensure that `autovacuum` is turned on, unless you have a very good reason to turn it off; most people don't. See later chapters for more information on `autovacuum`; in particular, see Chapter 9, _Regular Maintenance_. Leave the settings as they are for now. Don't fuss too much about getting the settings right. You can change most of them later, so you can take an iterative approach to improving things. And remember, don't touch the `fsync` parameter. It's keeping you safe. # Adding an external module to PostgreSQL Another strength of PostgreSQL is its extensibility. Extensibility was one of the original design goals, going back to the late 1980s. Now, in PostgreSQL 10, there are many additional modules that plug into the core PostgreSQL server. There are many kinds of additional module offerings, such as the following: * Additional functions * Additional data types * Additional operators * Additional index types Note that many tools and client interfaces work with PostgreSQL without any special installation. Here, we are discussing modules that extend and alter the behavior of the server beyond its normal range of SQL standard syntax, functions, and behavior. The procedure that makes a module usable is actually a two-step process. First, you install the module's files on your system so that they become available to the database server. Next, you connect to the database (or databases) where you want to use the module, and create the required objects. The first step is discussed in this recipe. For the second step, refer to the next recipe, _Using an installed module_. In this book, we will use the words _extension_ and _module_ as synonyms, like in the PostgreSQL documentation. Note, however, that the SQL commands that manage extensions, which we'll describe in the next recipe, are as follows: * `CREATE EXTENSION myext;` * `ALTER EXTENSION myext UPDATE;` In particular, commands such as `CREATE MODULE` won't work at all! # Getting ready First, you'll need to select an appropriate module to install. The journey toward a complete, automated package management system for PostgreSQL is not over yet, so you need to look in more than one place for the available modules, such as the following: * **Contrib** : The PostgreSQL core includes many functions. There is also an official section for add-in modules, known as contrib modules. They are always available for your database server, but are not automatically enabled in every database, because not all users might need them. In PostgreSQL version 10, we have 59 such modules. These are documented at http://www.postgresql.org/docs/10/static/contrib.html. * **PGXN** : This is the PostgreSQL Extension Network, a central distribution system dedicated to sharing PostgreSQL extensions. The website started in 2010 as a repository dedicated to the sharing of extension files. By 2017 there were more than 220 extensions from 239 different authors. You can learn more about it at http://pgxn.org/. * **Separate projects** : These are large external projects, such as PostGIS, offering extensive and complex PostgreSQL modules. For more information, take a look at http://www.postgis.org/. # How to do it... There are several ways to make additional modules available for your database server, as follows: * Using a software installer * Installing from PGXN * Installing from a manually downloaded package * Installing from source code Often, a particular module will be available in more than one way, and users are free to choose their favorite, exactly like PostgreSQL itself, which can be downloaded and installed through many different procedures. # Installing modules using a software installer Certain modules are available exactly like any other software packages that you may want to install in your server. All main Linux distributions provide packages for the most popular modules, such as PostGIS, SkyTools, procedural languages other than those distributed with the core, and so on. Modules can sometimes be added during installation if you're using a standalone installer application; for example, the OneClick installer, or tools such as `rpm`, `apt-get`, and `YaST` on Linux distributions. The same procedure can also be followed after the PostgreSQL installation, when the need for a certain module arrives. We will actually describe this case, which is very common. For example, let's say that you need to manage a collection of Debian package files and that one of your tasks is to be able to pick the latest version of one of them. You start by building a database that records all package files. Clearly, you need to store the version number of each package. However, Debian version numbers are much more complex than what we usually call "numbers". For instance, on my Debian laptop, I currently have version `10.3-1.pgdg90+1` of the PostgreSQL client package. Despite being complicated, that string follows a clearly defined specification, which includes many bits of information, including how to compare two versions to establish which of them is older. Since this recipe discusses extending PostgreSQL with custom data types and operators, you might have already guessed that I will now consider a custom data type for Debian version numbers that is capable of tasks such as understanding the Debian version number format, sorting version numbers, choosing the latest version number in a given group, and so on. It turns out that somebody else already did the work of creating the required PostgreSQL data type, endowed with all the useful accessories: comparison operators, input/output functions, support for indexes, and maximum/minimum aggregates. All of this has been packaged as a PostgreSQL extension, as well as a Debian package (not a big surprise), so it is just a matter of installing the `postgresql-10-debversion` package with a Debian tool such as `apt-get`, `aptitude`, or `synaptic`. On my laptop, that boils down to the following command: **apt-get install postgresql-10-debversion** This will download the required package and unpack all the files in the right locations, making them available to my PostgreSQL server. # Installing modules from PGXN The PostgreSQL Extension Network, PGXN for short, is a website (http://pgxn.org) launched in late 2010 with the purpose of providing a central distribution system for open source PostgreSQL extension libraries. Anybody can register and upload their own module, packaged as an extension archive. The website allows browsing available extensions and their versions, either via a search interface or from a directory of packages and usernames. The simple way is to use a command-line utility called `pgxnclient`. It can be easily installed in most systems; see the PGXN website for how to do so. Its purpose is to interact with PGXN and take care of administrative tasks, such as browsing available extensions, downloading the package, compiling the source code, installing files in the proper places, and removing installed package files. Alternatively, you can download the extension files from the website and place them in the right place by following the installation instructions. PGXN is different from official repositories because it serves another purpose. Official repositories usually contain only seasoned extensions, because they accept new software only after a certain amount of evaluation and testing. On the other hand, anybody can ask for a PGXN account and upload their own extensions, so there is no filter except requiring that the extension has an open source license and a few files that any extension must have. # Installing modules from a manually downloaded package You might have to install a module that is correctly packaged for your system, but is not available from the official package archives. For instance, it could be the case that the module has not been accepted in the official repository yet, or you may have repackaged a bespoke version of that module with some custom tweaks, which are so specific that they will never become official. Whatever the case, you will have to follow the installation procedure for standalone packages specific to your system. Here is an example with the Oracle compatibility module, described at http://postgres.cz/wiki/Oracle_functionality_(en)): 1. First, we get the package (say, for PostgreSQL 8.4 on a 64-bit architecture) from http://pgfoundry.org/frs/download.php/2414/orafce-3.0.1-1.pg84.rhel5.x86_64.rpm. 2. Then, we install the package in the standard way: **rpm -ivh orafce-3.0.1-1.pg84.rhel5.x86_64.rpm** If all the dependencies are met, we are done. I mentioned dependencies because that's one more potential problem when installing packages that are not officially part of the installed distribution; you can no longer assume that all software version numbers have been tested, all requirements are available, and there are no conflicts. If you get error messages that indicate problems in these areas, you may have to solve them yourself, by manually installing missing packages and/or uninstalling conflicting packages. # Installing modules from source code In many cases, useful modules may not have full packaging. In these cases, you may need to install the module manually. This isn't very hard, and it's a useful exercise that will help you understand what happens. Each module will have different installation requirements. There are generally two aspects of installing a module. They are as follows: * Building the libraries (only for modules that have libraries) * Installing the module files in the appropriate locations You need to follow the instructions for the specific module in order to build the libraries, if any are required. Installation will then be straightforward, and usually there will be a suitably prepared configuration file for the `make` utility, so that you just need to type the following command: **make install** Each file will be copied to the right directory. Remember that you normally need to be a system super user in order to install files on system directories. Once a library file is in the directory expected by the PostgreSQL server, it will be loaded automatically as soon as requested by a function. Modules such as `auto_explain` do not provide any additional user-defined functions, so they won't be auto-loaded; that needs to be done manually by a super user with a `LOAD` statement. # How it works... PostgreSQL can dynamically load libraries in the following ways: * Using the explicit `LOAD` command in a session * Using the `shared_preload_libraries` parameter in `postgresql.conf` at the server start * At the session start, using the `local_preload_libraries` parameter for a specific user, as set using `ALTER ROLE` PostgreSQL functions and objects can reference code in these libraries, allowing extensions to be bound tightly to the running server process. The tight binding makes this method suitable for use in even very high-performance applications, and there's no significant difference between additionally supplied features and native features. # Using an installed module In this recipe, we will explain how to enable an installed module so that it can be used in a particular database. The additional types, functions, and so on will exist only in those databases where we have carried out this step. Although most modules require this procedure, there are actually a couple of notable exceptions. For instance, the `auto_explain` module mentioned earlier, which is shipped together with PostgreSQL, does not create any function, type, or operator. To use it, you must load its object file using the `LOAD` command. From that moment, all statements longer than a configurable threshold will be logged together with their execution plan. In the rest of this recipe, we will cover all the other modules. They do not require a `LOAD` statement, because PostgreSQL can automatically load the relevant libraries when they are required. As mentioned in the previous recipe, _Adding an external module to PostgreSQL_ , specially packaged modules are called extensions in PostgreSQL. They can be managed with dedicated SQL commands. # Getting ready Suppose that you have chosen to install a certain module among those available for your system (see the previous recipe, _Adding an external module to PostgreSQL_ ); all you need to know is the extension name. # How to do it... Each extension has a unique name, so it is just a matter of issuing the following command: **CREATE EXTENSION myextname;** This will automatically create all the required objects inside the current database. For security reasons, you need to do so as a database super user. For instance, if you want to install the `dblink` extension, type this: **CREATE EXTENSION dblink;** # How it works... When you issue a `CREATE EXTENSION` command, the database server looks for a file named `EXTNAME.control` in the `SHAREDIR/extension` directory. That file tells PostgreSQL some properties of the extension, including a description, some installation information, and the default version number of the extension (which is unrelated to the PostgreSQL version number). Then, a creation script is executed in a single transaction; thus, if it fails, the database is unchanged. The database server also notes in a catalog table the extension name and all the objects that belong to it. # Managing installed extensions In the last two recipes, we showed you how to install external modules in PostgreSQL to augment its capabilities. In this recipe, we will show you some more capabilities offered by the extension infrastructure. # How to do it... 1. First, we list all the available extensions: **postgres=# \x on** **Expanded display is on.** **postgres=# SELECT *** **postgres-# FROM pg_available_extensions** **postgres-# ORDER BY name;** **-[ RECORD 1 ]-----+--------------------------------------------------** **name | adminpack** **default_version | 1.0** **installed_version |** **comment | administrative functions for PostgreSQL** **-[ RECORD 2 ]-----+--------------------------------------------------** **name | pg_stat statements** **default_version | 1.5** **installed_version |** **comment | track execution statistics of all SQL statements executed** **(...)** In particular, if the `dblink` extension is installed, then we see a record like this: **-[ RECORD 10 ]----+--------------------------------------------------** **name | dblink** **default_version | 1.0** **installed_version | 1.0** **comment | connect to other PostgreSQL databases from within a database** 2. Now, we can list all the objects in the `dblink` extension, as follows: **postgres=# \x off** **Expanded display is off.** **postgres=# \dx+ dblink** **Objects in extension "dblink"** **Object Description** **---------------------------------------------------------------------** **function dblink_build_sql_delete(text,int2vector,integer,text[])** **function dblink_build_sql_insert(text,int2vector,integer,text[],text[])** **function dblink_build_sql_update(text,int2vector,integer,text[],text[])** **function dblink_cancel_query(text)** **function dblink_close(text)** **function dblink_close(text,boolean)** **function dblink_close(text,text)** **(...)** 3. Objects created as parts of extensions are not special in any way, except that you can't drop them individually. This is done to protect you from mistakes: **postgres=# DROP FUNCTION dblink_close(text);** **ERROR: cannot drop function dblink_close(text) because extension dblink requires it** **HINT: You can drop extension dblink instead.** 4. Extensions might have dependencies, too. The `cube` and `earthdistance` contrib extensions are a good example, since the latter depends on the former: **postgres=# CREATE EXTENSION earthdistance;** **ERROR: required extension "cube" is not installed** **postgres=# CREATE EXTENSION cube;** **CREATE EXTENSION** **postgres=# CREATE EXTENSION earthdistance;** **CREATE EXTENSION** 5. As you can reasonably expect, dependencies are taken into account when dropping objects, just like for other objects: **postgres=# DROP EXTENSION cube;** **ERROR: cannot drop extension cube because other objects depend on it** **DETAIL: extension earthdistance depends on extension cube** **HINT: Use DROP ... CASCADE to drop the dependent objects too.** **postgres=# DROP EXTENSION cube CASCADE;** **NOTICE: drop cascades to extension earthdistance** **DROP EXTENSION** # How it works... The `pg_available_extensions` system view shows one row for each extension control file in the `SHAREDIR/extension` directory (see the _Using an installed module_ recipe). The `pg_extension` catalog table records only the extensions that have actually been created. The `psql` command-line utility provides the `\dx` meta-command to examine the extensions. It supports an optional plus sign (`+`) to control verbosity, and an optional pattern for the extension name to restrict its range. Consider the following command: **\dx+ db*** This will list all extensions whose names start with `db`, together with all their objects. The `CREATE EXTENSION` command creates all objects belonging to a given extension, and then records the dependency of each object on the extension in `pg_depend`. That's how PostgreSQL can ensure that you cannot drop one such object without dropping its extension. The extension control file admits an optional line, `requires`, that names one or more extensions on which the current one depends. The implementation of dependencies is still quite simple. For instance, there is no way to specify a dependency on a specific version number of other extensions, and there is no command that installs one extension and all its prerequisites. As a general PostgreSQL rule, the `CASCADE` keyword tells the `DROP` command to delete all objects that depend on `cube`, the `earthdistance` extension in this example. # There's more... Another system view, `pg_available_extension_versions`, shows all the versions available for each extension. It can be valuable when there are multiple versions of the same extension available at the same time; for example when making preparations for an extension upgrade. When a more recent version of an already installed extension becomes available to the database server, for instance, because of a distribution upgrade that installs updated package files, the super user can perform an upgrade by issuing the following command: **ALTER EXTENSION myext UPDATE TO '1.1';** This assumes that the author of the extension taught it how to perform the upgrade. Extensions interact nicely with logical backup and restore nicely, a topic that will be fully discussed in Chapter 11, _Backup and Recovery_. As an example, if your database contains the `cube` extension, then you will surely want a single line (`CREATE EXTENSION cube;`) in the dump file instead of lots of lines recreating each object individually, which is inefficient and also dangerous. The `CASCADE` option is accepted also by the `CREATE EXTENSION` syntax, with the meaning of "issue `CREATE EXTENSION` recursively to cover all dependencies." So, instead of creating an extension `cube` before creating the extension `earthdistance`, you could have issued the following command: **postgres=# CREATE EXTENSION earthdistance CASCADE;** **NOTICE: installing required extension "cube"** **CREATE EXTENSION** Remember that `CREATE EXTENSION ... CASCADE` will only work if all the extensions it tries to install have already been placed in the appropriate location. # Server Control In this chapter, we will cover the following recipes: * Starting the database server manually * Stopping the server safely and quickly * Stopping the server in an emergency * Reloading the server configuration files * Restarting the server quickly * Preventing new connections * Restricting users to only one session each * Pushing users off the system * Deciding on a design for multitenancy * Using multiple schemas * Giving users their own private database * Running multiple servers on one system * Setting up a connection pool * Accessing multiple servers using the same host and port # Introduction PostgreSQL consists of a set of server processes, the group leader of which is named the **postmaster**. Starting the server is the act of creating these processes, and stopping the server is the act of terminating those processes. Each postmaster listens for client connection requests on a defined port number. Multiple concurrently running postmasters cannot share that port number. The port number is often used to uniquely identify a particular postmaster and hence also the database server that it leads. When we start a database server, we refer to a data directory, which contains the heart and soul—or at least the data—of our database. Subsidiary tablespaces may contain some data outside the main `data` directory, so the `data` directory is just the main central location, and not the only place where data for that database server is held. Each running server has one `data` directory, and one `data` directory can have, at the most, one running server (or instance). To perform any action for a database server, we must know the `data` directory for that server. The basic actions we can perform on the database server are starting and stopping. We can also perform a restart, though that is just a stop followed by a start. In addition, we can reload the server, which means we can reread the server's configuration files. We should also mention a few other points. The default port number for PostgreSQL is `5432`. That has been registered with the **Internet Assigned Numbers Authority** ( **IANA** ), and so it should already be reserved for PostgreSQL's use in most places. Because each PostgreSQL server requires a distinct port number, the normal convention is to use subsequent numbers for any additional server; for example, `5433`, `5434`, and so on. Subsequent port numbers might not be as easily recognized by the network infrastructure, which might, in some cases, make life more difficult for you in large enterprises, especially in more security-conscious ones. Port number `6432` has been registered with IANA for PgBouncer, the connection pooler that we will describe in the _Setting up a connection pool_ recipe. This happened only recently, and many installations are using nonstandard port numbers such as `6543` only because they were deployed earlier. A database server is also sometimes referred to as a database cluster. I don't recommend this term for normal usage because it makes people think about multiple nodes, not one database server on one system. # Starting the database server manually Typically, the PostgreSQL server will start automatically when the system boots. You may have opted to stop and start the server manually, or you may need to start up or shut down for various operational reasons. # Getting ready First, you need to understand the difference between the service and the server. The word _server_ refers to the database server and its processes. The word _service_ refers to the operating system wrapper by which the server gets called. The server works in essentially the same way on every platform, whereas each operating system and distribution has its own concept of a service. Moreover, the way services are managed has changed recently: for instance, as of now (the beginning of 2018), most Linux distributions have adopted the `systemd` service manager. This means that you need to know which _distribution_ and _release_ you are using to find the correct variant of this recipe. With `systemd`, a PostgreSQL server process is represented by a **service unit** , which is managed via the `systemctl` command. The `systemd` command syntax is the same on all distributions, but the name of the service unit unfortunately is not, for example, it will have to be adjusted depending on your distribution. In other cases, you need to type the actual **data directory** path as part of the command line to start the server. More information on how to find out the data directory path is available in the _Locating the database server files_ recipe in Chapter 2, _Exploring the Database_. # How to do it... On each platform there is a specific command to start the server. If you are using a modern Linux distribution, you are probably using `systemd.` In this case, PostgreSQL can be started with the following command: **systemctl start SERVICEUNIT** This must be issued with OS superuser privileges, after replacing `SERVICEUNIT` with the appropriate `systemd` service unit name. The `systemctl` command must always be issued with operating system superuser privileges. Remember, throughout this book we will always prepend `systemctl` invocations with `sudo`. There are a couple of things to keep in mind: * This will work only if the user executing the command has been previously granted appropriate `sudo` privileges by the system administrator * If the command is executed from a superuser account, then the `sudo` keyword is unnecessary, although not harmful As mentioned previously, the service unit name depends on what distribution you are using. Precisely: * On Ubuntu and Debian there is a service unit called: **postgresql@RELEASE-CLUSTERNAME** * For each database server instance, there is another service unit called just `postgresql`, that can be used to manage all the database servers at once. So you can issue, for example: **sudo systemctl start postgresql** * To start all the available instances, and to start only the default version 10 instance: **sudo systemctl start postgresql@10-main** * Default Red Hat/Fedora packages call the service unit simply `postgresql`, so the syntax is as follows: **sudo systemctl start postgresql** * Red Hat/Fedora packages from the PostgreSQL Yum repository create a service unit called `postgresql--RELEASE`, so we can start version 10 as follows: **sudo systemctl start postgresql-10** As noted previously, `systemctl` is part of `systemd`, which is only available on Linux and is normally used by most of the recent distributions. The following commands can be used where `systemd` is not available: * On Debian and Ubuntu releases, you must invoke the PostgreSQL-specific utility `pg_ctlcluster` as follows: **pg_ctlcluster 10 main start** This command will also work when `systemd` is available; it will just redirect the start request to `systemctl` and print a message on the screen, so that the next time you will remember to use `systemctl` directly. * For Red Hat/Fedora, you can use this command: **service postgresql start ** * For Windows, the command is as follows: **net start postgres** * For Red Hat/Fedora, you can also use the following command: **pg_ctl -D $PGDATA start** where `PGDATA` is set to the data directory path. In fact, this command works on most distributions, including **macOS** , **Solaris** , and **FreeBSD** , although: * It is recommended to use, whenever possible, the distribution-specific syntax described previously. * You may have to specify the full path to the `pg_ctl` executable if it's not in your path already. This is normally the case with multi-version directory schemes such as Debian/Ubuntu, where distribution-specific scripts pick the appropriate executable for your version. # How it works... On Ubuntu/Debian, the `pg_ctlcluster` wrapper is a convenient utility that allows multiple servers to coexist more easily, which is especially good when you have servers with different versions. This capability is very useful, and is transposed on `systemd` as shown in the examples using `@` in the name of the service unit, where `@` denotes the usage of a service file template. Another interesting `systemd` feature is the capability to `enable`/`disable` a service unit to specify whether it will be started automatically on the next boot, with a syntax such as: **sudo systemctl enable postgresql@10-main** This can be very useful to set the appropriate behavior based on the purpose of each instance. A similar feature is implemented on Ubuntu and Debian by the `start.conf` file, located next to the other configuration files (that is, in the same directory). Apart from the informational comments, it contains only a single word, with the following meaning: * `auto`: The server will be started automatically on boot. This is the default when creating a new server. It is suitable for frequently used servers, such as those powering live services or being used for everyday development activities. * `manual`: The server will not be started automatically on boot, but can be started with `pg_ctlcluster`. This is suitable for custom servers that are seldom used. * `disabled`: The server is not supposed to be started. This setting is only a protection from starting the server accidentally. The `pg_ctlcluster` wrapper won't let you start it, but a skilled user can easily bypass the protection. If you need to reserve a port for a server not managed by `pg_ctlcluster`, for example, when compiling directly from the source code, then you can create a cluster with `start.conf` set to `disabled`, and then use its port. Any new servers will be allocated different ports. # Stopping the server safely and quickly There are several modes to stop the server, depending on the level of urgency. We'll do a comparison in view of the effects in each mode. # How to do it... We provide two variants: with and without `systemd`. This is similar to the previous recipe, _Starting the database server manually_ , which we'll refer to for further information. For example, what is the exact name of the `systemd` service unit for a given database server on a given GNU/Linux distribution? When using `systemd`, you can stop PostgreSQL using the _fast_ mode by issuing the following after having replaced `SERVICEUNIT` with the appropriate `systemd` service unit name: **sudo systemctl stop SERVICEUNIT** If `systemd` is not available, and you are using Debian or Ubuntu, the command is as in the following example, which applies to the default version 10 instance: **pg_ctlcluster 10 main stop -m fast** The fast mode is the default since PostgreSQL 9.5; the previous default was to use the `smart` mode, meaning _wait for all users to finish before we exit_. This can take a very long time, and all the while new connections are refused. On other Linux/Unix distributions, you can issue a database server `stop` command using the `fast` mode, as follows: **pg_ctl -D datadir -m fast stop** # How it works... When you do a `fast stop`, all users have their transactions aborted and all connections are disconnected. This is not very polite to users, but it still treats the server and its data with care, which is good. PostgreSQL is similar to other database systems in that it does do a shutdown checkpoint before it closes. This means that the startup that follows will be quick and clean. The more work the checkpoint has to do, the longer it will take to shut down. One difference between PostgreSQL and some other RDBMSes such as Oracle, DB2, or SQL Server is that the transaction rollback is very fast. On those other systems, if you shut down the server in a mode that rolls back transactions, it can cause the shutdown to take a while, possibly a very long time. This difference is for internal reasons, and isn't in any way unsafe. Debian and Ubuntu's `pg_ctlcluster` supports the `--force` option, which is rather nice because it first attempts a fast shutdown, and if that fails, it performs an immediate shutdown. After that, it kills the postmaster. # See also * The technology that provides immediate rollback for PostgreSQL is called **Multiversion Concurrency Control** ( **MVCC** ). More information on this is provided in the _Identifying and fixing bloated tables and indexes_ recipe in Chapter 9, _Regular Maintenance_. # Stopping the server in an emergency If nothing else is working, we may need to stop the server quickly, without caring about disconnecting the clients gently. _Break the glass in case of emergency!_ # How to do it... 1. The basic command to perform an emergency stop on the server is the following: **pg_ctl -D datadir stop -m immediate** 2. On Debian/Ubuntu, you can also use: **pg_ctlcluster 10 main stop -m immediate** As mentioned in the previous recipe, this is just a wrapper around `pg_ctl`. From this example, we can see that it can pass through the `-m immediate` option. In the previous recipe, we have seen examples where the `systemctl` command was used to stop a server safely; however, that command cannot be used to perform an emergency stop. # How it works... When you do an immediate stop, all users have their transactions aborted and all connections are disconnected. There is no clean shutdown, nor is there politeness of any kind. An immediate mode stop is similar to a database crash. Some cached files will need to be rebuilt, and the database itself needs to undergo crash recovery when it comes back up. Note that for DBAs with Oracle experience, the immediate mode is the same thing as a shutdown abort. The PostgreSQL immediate mode stop is _not_ the same thing as `shutdown immediate` on Oracle. # Reloading the server configuration files Some PostgreSQL configuration parameters can be changed only by reloading the entire configuration file(s). # How to do it... There are two variants of this recipe, depending on whether you are using `systemd`. This is similar to the previous recipes in this chapter, and especially the _Starting the database server manually_ recipe. More details are explained there, such as the exact names of `systemd` service units depending on which database server you want to reload, and which GNU/Linux distribution you are working on. With `systemd`, configuration files can be reloaded with the following syntax: **sudo systemctl reload SERVICEUNIT ** Here, `SERVICEUNIT` must be replaced with the exact name of the `systemd` service unit for the server(s) that you want to reload. Otherwise, on each platform there is a specific command to reload the server without using `systemd`. All of these are listed as follows: * On Ubuntu and Debian, you can issue: **pg_ctlcluster 10 main reload** * On older Red Hat/Fedora, the command is as follows: **service postgresql reload** * You can also use the following command: **pg_ctl -D /var/lib/pgsql/data reload** This also works on macOS, Solaris, and FreeBSD, replacing `/var/lib/pgsql/data` with your actual data directory if it's different. On all platforms, you can also reload the configuration files while still connected to PostgreSQL. If you are a superuser, this can be done from the following command line: **postgres=# select pg_reload_conf();** The output is rather short: **pg_reload_conf** **----------------** **t** This function is also often executed from an admin tool, such as **OmniDB**. If you do this, you should realize that it's possible to implement a new authentication rule that is violated by the current session. It won't force you to disconnect, but when you do disconnect, you may not be able to reconnect. Any error in a configuration file will be reported in the message log, so we recommend to look there immediately after reloading. You will quickly notice (and fix!) syntax errors in the parameter file, because they prevent any login even before reloading. Other errors, such as typos in parameter names, or wrong units, will only be reported in the log; moreover, only some non-syntax errors will prevent reloading the whole file, so it's best to always check the log. # How it works... To reload the configuration files, we send the `SIGHUP` signal to the postmaster, which then passes that to all connected backends. That's why some people call reloading the server _sigh-up-ing_. If you look at the `pg_settings` catalog table, you'll see that there is a column named `context`. Each setting has a time and a place where it can be changed. Some parameters can only be reset by a server reload, and so the value of `context` for those parameters will be a `sighup`. Here are a few of the parameters you'd want to change sometimes during server operation (there are others, however): **postgres=# SELECT name, setting, unit** **,(source = 'default') as is_default** **FROM pg_settings** **WHERE context = 'sighup'** **AND (name like '%delay' or name like '%timeout')** **AND setting != '0';** **name | setting | unit | is_default** **------------------------------+---------+------+------------** **authentication_timeout | 60 | s | t** **autovacuum_vacuum_cost_delay | 20 | ms | t** **bgwriter_delay | 10 | ms | f** **checkpoint_timeout | 32 | s | f** **deadlock_timeout | 1000 | ms | t** **max_standby_archive_delay | 30000 | ms | t** **max_standby_streaming_delay | 30000 | ms | t** **wal_receiver_timeout | 60000 | ms | t** **wal_sender_timeout | 60000 | ms | t** **wal_writer_delay | 200 | ms | t** **(9 rows)** # There's more... Since reloading the configuration file is achieved by sending the `SIGHUP` signal, we can reload the configuration file only for a single backend using the `kill` command. As you might expect, you may get some strange results from doing this, so don't try it at home. First, find the PID of the backend using `pg_stat_activity`. Then, from the OS prompt, issue the following: **kill -SIGHUP pid** Alternatively, we can do both at once, as shown in this command: **kill -SIGHUP \ ** **& & psql -t -c "select pid from pg_stat_activity limit 1";** This is only useful with a sensible `WHERE` clause. # Restarting the server quickly Some of the database server parameters require you to stop and start the server again fully. Doing this as quickly as possible can be very important in some cases. The best time to do this is usually a quiet time, with lots of planning, testing, and forethought. Sometimes, not everything goes according to plan. # How to do it... It's now become a habit for many recipes in this chapter to be presented in two forms, one with `systemd` and one without. This may look repetitive or boring, but it's unavoidable because the introduction of a new system does not automatically eliminate all existing alternatives, or migrate old installations to new ones. Like before, the reader can find further `systemd` details, including details on service unit names, in the previous recipe, _Starting the database server manually_ , of this chapter. A PostgreSQL server managed by `systemd` can be restarted in the _fast_ mode by issuing the following command: **sudo systemctl restart SERVICEUNIT** As before, change `SERVICEUNIT` to the appropriate service unit name, for example, `postgresql@10-main` for a PostgreSQL 10 cluster running in Debian or Ubuntu. If `systemd` is not available, then you can use the following syntax: **pg_ctlcluster 10 main restart -m fast** The basic command to restart the server is the following: **pg_ctl -D datadir restart -m fast** A `restart` is just a stop followed by a start, so it sounds very simple. In many cases, it will be simple, but there are times when you'll need to restart the server while it is fairly busy. That's when we need to start performing some tricks to make that restart happen faster. First, the stop performed needs to be a `fast stop`. If we do a default or `smart` stop, then the server will just wait for everyone to finish. If we do an immediate stop, then the server will crash, and we will need to crash-recover the data, which will be slower overall. The running database server has a cache full of data blocks, many of them dirty. PostgreSQL is similar to other database systems in that it does a shutdown checkpoint before it closes. This means that the startup that follows will be quick and clean. The more work the checkpoint has to do, the longer it will take to shut down. The actual shutdown will happen much faster if we issue a normal checkpoint first, as the shutdown checkpoint will have much less work to do. So, flush all the dirty shared buffers to disk with the following command, issued by a database superuser: **psql -c "CHECKPOINT"** The next consideration is that once we restart, the database cache will be empty again and will need to refresh itself. The larger the database cache, the longer it takes for the cache to get warm again, and 30 to 60 minutes is not uncommon before returning to full speed. So, what was a simple restart can actually have a large business impact if handled badly. # There's more... There is an extension called `pgfincore` that implements a set of functions to manage PostgreSQL data pages in the operating system's file cache. One possible use is to preload some tables so that PostgreSQL will load them faster when requested. The general idea is that you can provide more detailed information for the operating system cache, which can therefore behave more efficiently. The `pgfincore` extension is a stable project started in 2009. More details about it are available at http://pgfoundry.org/projects/pgfincore, including the source code. However, it should be noted that most distributions include a prebuilt `pgfincore` package, which makes installation easier. There is also a contrib module called `pg_prewarm`, introduced in PostgreSQL 9.4, which addresses a similar problem. While there is some overlapping with `pgfincore`, the feature sets are not the same; for instance, `pgfincore` can operate on files not in the shared buffer cache, and can also preload full relations with only a few system calls, taking into account the existing cache; on the other hand, `pg_prewarm` can operate on the PostgreSQL shared buffer cache, and it also works on Windows. # Preventing new connections In certain emergencies, you may need to lock down the server completely, or just prevent specific users from accessing the database. It's hard to foresee all the situations in which you might need to do this, so we will present a range of options. # How to do it... Connections can be prevented in a number of ways, as follows: * Pause and resume the session pool. See the _Setting up a connection pool_ recipe later in this chapter on controlling connection pools. * Stop the server! See the _Stopping the server safely and quickly_ and _Stopping the server in an emergency_ recipes, but this is not recommended. * Restrict the connections for a specific database to zero, by setting the connection limit to zero: **ALTER DATABASE foo_db CONNECTION LIMIT 0;** * This will limit normal users from connecting to that database, though it will still allow superuser connections. * Restrict the connections for a specific user to zero by setting the connection limit to zero (see the _Restricting users to only one session each_ recipe): **ALTER USER foo CONNECTION LIMIT 0;** * This will limit normal users from connecting to that database, but it will still allow connections if the user is a superuser, so luckily you cannot shut yourself out accidentally. * Change the **host-based authentication** ( **HBA** ) file to refuse all incoming connections, and then reload the server: * Create a new file named `pg_hba_lockdown.conf`, and add the following two lines to the file. This puts in place rules that will completely lock down the server, including superusers. You should have no doubt that this is a serious and drastic action: **# TYPE DATABASE USER ADDRESS METHOD ** **local all all reject ** **host all all 0.0.0.0/0 reject** If you still want superuser access, then try something like the following: **# TYPE DATABASE USER ADDRESS METHOD** **local all postgres peer** **local all all reject** **host all all 0.0.0.0/0 reject** This will prevent connections to the database by any user except the `postgres` operating system user ID, which connects locally to any database. Be careful not to confuse the second and third columns—the second column is the database and the third column is the username. It's worth keeping the header line just for that reason. The `peer` method should be replaced by other authentication methods if a more complex configuration is in use. * Copy the existing `pg_hba.conf` file to `pg_hba_access.conf` so that it can be replaced later, if required * Copy `pg_hba_lockdown.conf` to `pg_hba.conf` * Reload the server following the recipe earlier in this chapter # How it works... The `pg_hba.conf` file is where we specify the host-based authentication rules. We do not specify the authentications themselves, but just specify which authentication mechanisms will be used. This is the top-level set of rules for PostgreSQL authentication. The rules are specified in a file and applied by the postmaster process when connections are attempted. To prevent denial-of-service attacks, the HBA rules never involve database access, so we do not know whether a user is a superuser or not. As a result, you can lock out all users, but note that you can always re-enable access by editing the file and reloading. # Restricting users to only one session each If resources need to be closely controlled, you may wish to restrict users so that they can only connect to the server once, at most. The same technique can be used to prevent connections entirely for that user. # How to do it... We can restrict users to only one connection using the following command: **postgres=# ALTER ROLE fred CONNECTION LIMIT 1;** **ALTER ROLE** This will then cause any additional connections to receive the following error message: **FATAL: too many connections for role "fred".** You can eliminate this restriction by setting the value to `-1`. It's possible to set the limit to zero or any positive integer. You can set this to a number other than `max_connections`, though it is up to you to make sense of that if you do. Setting the value to zero will completely restrict normal connections. Note that even if you set the connection limit to zero for superusers, they will still be able to connect. # How it works... The connection limit is applied during the session connection. Raising this limit will never affect any connected users. Lowering the limit doesn't have any effect either, unless they try to disconnect and reconnect. So, if you lower the limit, you should immediately check to see whether there are more sessions connected than the new limit you just set. Otherwise, there may be some surprises in case there is a crash: **postgres= > SELECT rolconnlimit** **FROM pg_roles** **WHERE rolname = 'fred';** **rolconnlimit** **--------------** **1** **(1 row)** **postgres= > SELECT count(*)** **FROM pg_stat_activity** **WHERE usename = 'fred';** **count** **-------** **2** **(1 row)** If you have more connected sessions than the new limit, you can ask users politely to disconnect, or apply the next recipe, _Pushing users off the system_. Users can't raise or lower their own connection limit, just in case you are worried that they might be able to override this somehow. # Pushing users off the system Sometimes, we may need to remove groups of users from the database server for various operational reasons. Here's how to do it. # How to do it... You can terminate a user's session with the `pg_terminate_backend()` function included with PostgreSQL. That function takes the PID, or the process ID, of the user's session on the server. This process is known as the backend, and it is a different system process from the program that runs the client. To find the PID of a user, we can look at the `pg_stat_activity` view. We can use it in a query, like this: **SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE ...** There are a couple of things to note if you run this query. If the `WHERE` clause doesn't match any sessions, then you won't get any output from the query. Similarly, if it matches multiple rows, you will get a fairly useless result, that is, a list of Boolean `true` values. Unless you are careful enough to exclude your own session from the query, you will disconnect yourself! What's even funnier is that you'll disconnect yourself halfway through disconnecting the other users, as the query will run `pg_terminate_backend()` in the order in which sessions are returned from the outer query. Therefore, I suggest a safer and more useful query that gives a useful response in all cases, which is as follows: **postgres=# SELECT count(pg_terminate_backend(pid))** **FROM pg_stat_activity** **WHERE usename NOT IN** **(SELECT usename** **FROM pg_user** **WHERE usesuper);** **count** **-------** **1** This is assuming that superusers are performing administrative tasks. Other good filters might be the following: **WHERE application_name = 'myappname'** **WHERE wait_event_type IS NOT NULL AND wait_event_type != 'Activity'** **WHERE state = 'idle in transaction'** **WHERE state = 'idle'** # How it works... The `pg_terminate_backend()` function sends a signal directly to the operating system process for that session. It's possible that the session may have closed by the time `pg_terminate_backend()` is named. As PID numbers are assigned by the operating system, it could even happen that you try to terminate a given session (call it "session A"), but you actually terminate another session (call it "session B"). Here is how it could happen. Suppose you take note of the PID of session A and decide to disconnect it. Before you actually issue `pg_terminate_backend()`, session A disconnects, and right after, a new session B is given exactly the same PID. So, when you terminate that PID, you hit session B instead. On the one hand, you need to be careful. On the other hand, this case is really unlikely, and is only mentioned for completeness. For it to happen, _all_ the following events must happen as well: * One of the sessions you are trying to close must terminate independently in the very short interval between the moment `pg_stat_activity` is read and the moment `pg_terminate_backend()` is executed * Another session on the same database server must be started in the even shorter interval between the old session closing and the execution of `pg_terminate_backend()` * The new session must get exactly the same PID value as the old session, which is less than one chance in 32,000 on a 32-bit Linux machine Nonetheless, probability theory is tricky, even for experts. Therefore, it's better to be aware that there is a tiny risk, especially if you use the query many times per day over a long period of time, in which case the probability of getting caught at least once builds up. It's also possible that new sessions could start after we get the list of active sessions. There's no way to prevent this other than by following the _Preventing new connections_ recipe. Finally, remember that superusers can terminate any session, whilst a non-superuser can only terminate a session which belongs to the same user. # Deciding on a design for multitenancy There are many reasons why we might want to split groups of tables or applications: security, resource control, convenience, and so on. Whatever the reason, we often need to separate groups of tables (I avoid saying the word _database_ , just to avoid various kinds of confusion). This topic is frequently referred to as **multitenancy** , though it is not a fully accepted term as of yet. The purpose of this recipe is to discuss the options and lead to other, more detailed recipes. # How to do it... If you want to run multiple physical databases on one server, then you have four main options, which are as follows: * **Option 1** : Run multiple sets of tables in different schemas in one database of a PostgreSQL instance (covered in the _Using multiple schemas_ recipe) * **Option 2** : Run multiple databases in the same PostgreSQL instance (covered in the _Giving users their own private database_ recipe) * **Option 3** : Run multiple PostgreSQL instances on the same virtual/physical system (covered in the _Running multiple servers on one system_ recipe) * **Option 4** : Run separate PostgreSQL instances in separate virtual machines on the same physical server Which is best? Well, that's certainly a question many people ask, and something on which many views exist. The answer lies in looking at the specific requirements, which are as follows: * If our goal is the separation of physical resources, then _Option 3_ or _Option 4_ works best. Separate database servers can be easily assigned different disks, individual memory allocations can be assigned, and we can take the servers up or down without impacting the others. * If our goal is security, then _Option 2_ is sufficient. * If our goal is merely the separation of tables for administrative clarity, then _Option 1_ or _Option 2_ can be useful. _Option 2_ allows complete separation for security purposes. This does, however, prevent someone with privileges on both groups of tables from performing a join between those tables. So, if there is a possibility of future cross-analytics, it might be worth considering _Option 1_. However, it might also be argued that such analytics should be carried out on a separate data warehouse, not by co-locating production systems. _Option 3_ has a difficulty in many of the PostgreSQL distributions: the default installation uses a single location for the database, making it a little harder to configure that option. Ubuntu/Debian handles that aspect particularly well, making it more attractive in that environment. _Option 4_ can be applied using virtualization technology, but that is outside the scope of this book. # How it works... I've seen people who use PostgreSQL with thousands of databases, but it is my opinion that the majority of people use only one database, such as `postgres` (or at least, only a few databases). I've also seen people with a great many schemas. One thing you will find is that almost all admin GUI tools become significantly less useful if there are hundreds or thousands of items to display. In most cases, administration tools use a tree view, which doesn't cope gracefully with a large number of items. # Using multiple schemas We can separate groups of tables into their own _namespaces_ , referred to as _schemas_ by PostgreSQL. In many ways, they can be thought of as being similar to directories, though that is not a precise description. # Getting ready Make sure you've read the _Deciding on a design for multitenancy_ recipe so that you're certain that this is the route you wish to take. Other options exist, and they may be preferable in some cases. # How to do it... 1. Schemas can be easily created using the following commands: **CREATE SCHEMA finance; CREATE SCHEMA sales;** 2. We can then create objects directly within those schemas using _fully qualified_ names, like this: **CREATE TABLE finance.month_end_snapshot (.....)** The default schema in which an object is created is known as the `current_schema`. We can find out which is our current schema using the following query: **postgres=# select current_schema;** This returns an output like the following: **current_schema ** **---------------- ** **public ** **(1 row)** 3. When we access database objects, we use the user-settable `search_path` parameter to identify the schemas to search for. The `current_schema` is the first schema in the `search_path` parameter. There is no separate parameter for the `current_schema`. So, if we want to let only a specific user look at certain sets of tables, we can modify their `search_path` parameter. This parameter can be set for each user so that the value will be set when they connect. The SQL queries for this would be something like the following: **ALTER ROLE fiona SET search_path = 'finance';** **ALTER ROLE sally SET search_path = 'sales';** The public schema is not mentioned on `search_path`, so it will not be searched. All tables created by `fiona` will go into the `finance` schema by default, whereas all tables created by `sally` will go into the `sales` schema by default. 4. The users for `finance` and `sales` will be able to see that the other schema exists and change `search_path` to use it, but we will be able to `GRANT` or `REVOKE` privileges so that they can neither create objects nor read data in other people's schemas: **REVOKE ALL ON SCHEMA finance FROM public;** **GRANT ALL ON SCHEMA finance TO fiona;** **REVOKE ALL ON SCHEMA sales FROM public;** **GRANT ALL ON SCHEMA sales TO sally;** An alternate technique is to allow one user to create privileges on only one schema, but grant usage rights on all other schemas. We can set up that arrangement like this: **REVOKE ALL ON SCHEMA finance FROM public;** **GRANT USAGE ON SCHEMA finance TO fiona;** **GRANT CREATE ON SCHEMA finance TO fiona;** **REVOKE ALL ON SCHEMA sales FROM public;** **GRANT USAGE ON SCHEMA sales TO sally;** **GRANT CREATE ON SCHEMA sales TO sally; GRANT USAGE ON SCHEMA sales TO fiona; GRANT USAGE ON SCHEMA finance TO sally ** 5. Note that you need to grant the privileges for usage on the schema, as well as specific rights on the objects in the schema. So, you will also need to issue specific grants for objects, as shown here: **GRANT SELECT ON month_end_snapshot TO public;** You can also set default privileges so that they are picked up when objects are created, using the following command: **ALTER DEFAULT PRIVILEGES FOR USER fiona IN SCHEMA finance** **GRANT SELECT ON TABLES TO PUBLIC;** # How it works... Earlier, I said that schemas work like directories, or at least a little. The PostgreSQL concept of `search_path` is similar to the concept of a `PATH` environment variable. The PostgreSQL concept of the current schema is similar to the concept of the current working directory. There is no `cd` command to change the directory. The current working directory is changed by altering `search_path`. A few other differences exist; for example, PostgreSQL schemas are not arranged in a hierarchy like filesystem directories. Many people create a user of the same name as the schema to make this work in a way similar to other RDBMSes, such as Oracle. Both the `finance` and `sales` schemas exist within the same PostgreSQL database, and run on the same database server. They use a common buffer pool, and there are many global settings that tie the two schemas fairly close together. # Giving users their own private database Separating data and users is a key part of administration. There will always be a need to give users a private, secure, or simply risk-free area ( _sandpit_ ) to use the database. Here's how. # Getting ready Again, make sure you've read the _Deciding on a design for multitenancy_ recipe so that you're certain this is the route you wish to take. Other options exist, and they may be preferable in some cases. # How to do it... 1. We can create a database for a specific user with some ease. From the command line, as a superuser, these actions would be as follows: **postgres=# create user fred;** **CREATE ROLE** **postgres=# create database fred owner fred;** **CREATE DATABASE** 2. As the database owners, users have login privileges, so they can connect to any database by default. There is a command named `ALTER DEFAULT PRIVILEGES`, however, this does not currently apply to databases, tablespaces, or languages. The `ALTER DEFAULT PRIVILEGES` command also currently applies only to roles (that is, users) that already exist. So, we need to revoke the privilege to connect to our new database from everybody except the designated user. There isn't a `REVOKE ... FROM PUBLIC EXCEPT` command. Therefore, we need to revoke everything and then just re-grant everything we need, all in one transaction, such as in the following: **postgres=# BEGIN; ** **BEGIN ** **postgres=# REVOKE connect ON DATABASE fred FROM public; ** **REVOKE ** **postgres=# GRANT connect ON DATABASE fred TO fred; ** **GRANT ** **postgres=# COMMIT; ** **COMMIT ** **postgres=# create user bob; ** **CREATE ROLE** 3. Then, try to connect as `bob` to the `fred` database: **os $ psql -U bob fred** **psql: FATAL: permission denied for database "fred"** **DETAIL: User does not have CONNECT privilege.** This is exactly what we wanted. # How it works... If you didn't catch it before, PostgreSQL allows transactional DDL in most places, so either both of the `REVOKE` and `GRANT` commands in the preceding section work or neither works. This means that the `fred` user never loses the ability to connect to the database. Note that `CREATE DATABASE` cannot be performed as part of a transaction, though nothing serious happens as a result. # There's more... Superusers can still connect to the new database, and there is no way to prevent them from doing so. No other users can see the tables created in the new database, nor can they know the names of any of the objects. The new database can be seen to exist by other users, and they can also see the name of the user who owns the database. # See also * See Chapter 6, _Security_ , for more details on these issues # Running multiple servers on one system Running multiple PostgreSQL servers on one physical system is possible if it is convenient for your needs. # Getting ready Once again, make sure you've read the _Deciding on a design for multitenancy_ recipe so that you're certain this is the route you wish to take. Other options exist, and they may be preferable in some cases. # How to do it... Core PostgreSQL easily allows multiple servers to run on the same system, but there are a few wrinkles to be aware of. Some installer versions create a PostgreSQL data directory named `data`. It then gets a little difficult to have more than one `data` directory without using different directory structures and names. Debian/Ubuntu packagers chose a layout specifically designed to allow multiple servers, potentially running with different software release levels. You might remember this from the _Locating the database server files_ recipe in Chapter 2, _Exploring the Database_. Starting from `/var/lib/postgresql`, which is the home directory of the Postgres user, there is a subdirectory for each major version, for example, `10` or `9.3`, inside which the individual data directories are placed. When installing PostgreSQL server packages, a data directory is created with the default name of `main`. Configuration files are separately placed in `/etc/postgresql/<version>/<name>`, and log files are created in `/var/log/postgresql/postgresql-<version>-<name>.log`. Thus, not all files will be found in the `data` directory. As an example, let's create an additional `data` directory: 1. We start by running this command: **sudo -u postgres pg_createcluster 10 main2** 2. The new database server can then be started using the following command: **sudo -u postgres pg_ctlcluster 10 main2 start** This is sufficient to create and start an additional database cluster in version `10`, named `main2`. The data and configuration files are stored inside the `/var/lib/postgresql/10/main2/` and `/etc/postgresql/10/main2/` directories respectively, giving the new database the next unused port number, for example `5433` if this is the second PostgreSQL server on that machine. Local access to multiple PostgreSQL servers has been simplified as well. PostgreSQL client programs, such as `psql`, are wrapped by a special script that takes the cluster name as an additional parameter and automatically uses the corresponding port number. Hence, you don't really need the following command: **psql --port 5433 -h /var/run/postgresql ...** Instead, you can refer to the database server by name, as shown here: **psql --cluster 10/main2 ...** This has its advantages, especially if you wish (or need) to change the port in the future. I find this extremely convenient, and another reason is that it works with other utilities such as `pg_dump`, `pg_restore`, and so on. With Red Hat systems, you will need to run `initdb` directly, selecting your directories carefully: 1. First, initialize your `data` directory with something like the following: **sudo -u postgres initdb -D /var/lib/pgsql/datadir2** 2. Then, modify the `port` parameter in the `postgresql.conf` file and start using the following command: **sudo -u postgres pg_ctl -D /var/lib/pgsql/datadir2 start** This will create an additional database server at the default server version, with files stored in `/var/lib/pgsql/datadir2`. You can also set up the server with `chkconfig`, if your distribution supports it. # How it works... PostgreSQL servers are controlled using `pg_ctl`. Everything else is a wrapper of some kind around this utility. The only constraints on running multiple versions of PostgreSQL come from file locations and naming conventions, assuming (of course) that you have enough resources such as disk space, memory, and so on. Everything else is straightforward. Having said that, the Debian/Ubuntu design is currently the only design that makes it actually easy to run multiple servers. # Setting up a connection pool A connection pool is a term used for a collection of already connected sessions that can be used to reduce the overhead of connection and reconnection. There are various ways by which connection pools can be provided, depending on the software stack in use. Probably, the best option is to look at the server-side connection pool software because that works for all connection types, not just within a single software stack. Here, we're going to look at **PgBouncer** , which is designed as a very lightweight connection pool. The name comes from the idea that the pool can be paused and resumed to allow the server to be restarted, or _bounced_. # Getting ready First of all, decide where you're going to store the PgBouncer parameter files, log files, and PID files. PgBouncer can manage more than one database server's connections at the same time, though that probably isn't wise for simple architectures. If you keep PgBouncer files associated with the database server, then it should be easy to manage. # How to do it... Carry out the following steps to configure PgBouncer: 1. Create a `pgbouncer.ini` file, as follows: **;** **; pgbouncer configuration example** **;** **[databases]** **postgres = port=5432 dbname=postgres** **[pgbouncer]** **listen_addr = 127.0.0.1** **listen_port = 6432** **admin_users = postgres** **;stats_users = monitoring userid** **auth_type = any** **; put these files somewhere sensible:** **auth_file = users.txt** **logfile = pgbouncer.log** **pidfile = pgbouncer.pid** **server_reset_query = DISCARD ALL;** **; default values** **pool_mode = session** **default_pool_size = 20** **log_pooler_errors = 0** 2. Create a `users.txt` file. This must contain the minimum users mentioned in `admin_users` and `stats_users`. Its format is very simple: a collection of lines with a username and a password. Consider the following as an example: **"postgres" ""** 3. PgBouncer also supports MD5 authentication. To use that effectively, you need to copy the MD5 encrypted passwords from the database server into the `users.txt` file. 4. You may wish to create the `users.txt` file by directly copying the details from the server. This can be done by using the following `psql` script: **postgres= > \o users.txt ** **postgres= > \t ** **postgres= > SELECT '"'||rolname||'" "'||rolpassword||'"'** **postgres- > FROM pg_authid; ** **postgres= > \q** 5. Launch `pgbouncer`: **pgbouncer -d pgbouncer.ini** 6. Test the connection; it should respond to `reload`: **psql -p 6432 -h 127.0.0.1 -U postgres pgbouncer -c "reload"** 7. Finally, verify that PgBouncer's `max_client_conn` parameter does not exceed the `max_connections` parameter on PostgreSQL. # How it works... PgBouncer is a great piece of software. Its feature set is very carefully defined to ensure that it is simple, robust, and very fast. PgBouncer is not multithreaded, so it runs in a single process, and thus, on a single CPU. It is very efficient, but very large data transfers will take more time and reduce concurrency, so create those data dumps using a direct connection. PgBouncer provides connection pooling. If you set `pool_mode = transaction`, then PgBouncer will also provide connection concentration. This allows hundreds or even thousands of incoming connections to be managed, while only a few server connections are made. As new connections, transactions, or statements arrive, the pool will increase in size up to the user-defined maximum values. Those connections will stay around for at most the `server_idle_timeout` value before the pool releases them. PgBouncer also releases sessions every `server_lifetime`. This allows the server to free backends in rotation, to avoid issues with very long-lived session connections. The earlier query that creates `users.txt` only includes database users that have a password. All other users will have a null `rolpassword` field, so the whole string evaluates to `NULL`, and the line is omitted from the password file. This is intentional; users without a password represent a security risk, unless they are closely guarded. An example of this is the `postgres` system user connecting from the same machine, which bypasses PgBouncer, and is used only for maintenance by responsible and trusted people. It is possible to use an HBA file with the same syntax as `pg_hba.conf`. This allows for more flexibility enabling TLS encryption (which includes SSL) only for connections to remote servers, while using the more efficient peer authentication for local servers. # There's more... Instead of retrieving passwords from the `userlist.txt` file, PgBouncer can retrieve them directly from PostgreSQL, using the optional `auth_user` and `auth_query` parameters. If `auth_user` is set, PgBouncer will connect to the database using that user and run `auth_query` every time it needs to retrieve the password of some user trying to login. The default value of `auth_query` is as follows: **SELECT usename, passwd FROM pg_shadow WHERE usename=$1** This default is just a minimal functioning example, which illustrates the idea of `auth_query`; however, it requires giving PgBouncer superuser access to PostgreSQL. Hence it is good practice to use the more sophisticated approach of creating a `SECURITY DEFINER` function which can retrieve username and password, possibly making some checks on the username to allow only applicative connections. This is a good restriction because database administration connections should not go through a connection pooler. It's also possible to connect to PgBouncer itself to issue commands. This can be done interactively, as if you were entering `psql`, or it can be done using single commands or scripts. To shut down PgBouncer, we can just type `SHUTDOWN` or enter a single command, as follows: **psql -p 6432 pgbouncer -c "SHUTDOWN"** You can also use the `RELOAD` command to make PgBouncer reload (which means reread) the parameter files, like we did to test that everything is working. If you are using `pool_mode = transaction` or `pool_mode = statement`, then you can use the `PAUSE` command. This waits for the current transaction to complete before holding further work on that session. Thus, it allows you to perform DDL more easily or restart the server. PgBouncer also allows you to use the `SUSPEND` mode, which waits for all server-side buffers to flush. The `PAUSE` or `SUSPEND` modes should eventually be followed by `RESUME` when the work is done. In addition to the PgBouncer control commands, there are many varieties of `SHOW` commands, as listed here: `SHOW` command | Result set. ---|--- `SHOW STATS` | Traffic stats, total and average requests, query duration, bytes sent/received, and so on. See also `SHOW STATS_TOTALS` and `SHOW STATS_AVERAGES`. `SHOW SERVERS` | One row per connection to the database server. `SHOW CLIENTS` | One row per connection from the client. `SHOW POOLS` | One row per pool of users. `SHOW LISTS` | Gives a good summary of resource totals. `SHOW USERS` | Lists users in `users.txt`. `SHOW DATABASES` | Lists databases in `pgbouncer.ini`. `SHOW CONFIG` | Lists configuration parameters. `SHOW FDS` | Shows file descriptors. `SHOW SOCKETS` | Shows file sockets. `SHOW VERSION` | Shows the PgBouncer version. # Accessing multiple servers using the same host and port We will now show you one simple, yet important, application of the previous recipe, _Setting up a connection pool_. In that recipe, you saw how to reuse connections with PgBouncer, and thus reduced the cost of disconnecting and reconnecting. Here, we will demonstrate another way to use PgBouncer—one instance can connect to databases hosted by different database servers at the same time. The databases can be on separate hosts, and can even have different major versions of PostgreSQL! # Getting ready Suppose we have three database servers, each one hosting one database. All you need to know beforehand is the connection string for each database server. More complex arrangements are possible, but those are left to you as an exercise. Before you try this recipe, you should have already gone through the previous recipe. These two recipes have many steps in common, but we've kept them separate because they have clearly different goals. # How to do it... Each database is completely identified by its connection string. PgBouncer will read this information from its configuration file. The steps to be done are as follows: 1. All you need to do is to set up PgBouncer as you did in the previous recipe, replacing the `databases` section of `pgbouncer.ini` with the following: **[databases]** **myfirstdb = port=5432 host=localhost** **anotherdb = port=5437 host=localhost** **sparedb = port=5435 host=localhost** 2. Once you have started PgBouncer, you can connect to the first database: **$ psql -p 6432 -h 127.0.0.1 -U postgres myfirstdb** **psql (9.6.1)** **Type "help" for help.** **myfirstdb=# show port;** **port** **------** **5432** **(1 row)** **myfirstdb=# show server_version;** **server_version** **----------------** **10.1** **(1 row)** 3. Now you can connect to the `anotherdb` database as if it were on the same server: **myfirstdb=# \c anotherdb ** **psql (10.1, server 9.6.5) ** **You are now connected to database "anotherdb" as user "postgres".** 4. The server's greeting message suggests that we have landed on a different server, so we check the port and version: **anotherdb=# show port;** **port** **------** **5437** **(1 row)** **anotherdb=# show server_version;** **server_version** **----------------** **9.5.5** **(1 row)** # There's more... The _Listing databases on this database server_ recipe in Chapter 2, _Exploring the Database_ , shows you how to list the available databases on the current database server, using either the `\l` meta-command or a couple of equivalent variations. Unfortunately, that doesn't work when using PgBouncer, for the very good reason that the current database server cannot know the answer. We need to ask PgBouncer instead, and we do so by using the `SHOW` command when connected to the `pgbouncer` special administrative database: **myfirstdb=# \c pgbouncer ** **psql (10.1, server 1.8.1/bouncer) ** **You are now connected to database "pgbouncer" as user "postgres". ** **pgbouncer=# show databases; ** **name | host | port | database | force_user | pool_size | reserve_pool ** **-----------+-----------+------+-----------+------------+-----------+-------------- ** **anotherdb | localhost | 5437 | anotherdb | | 20 | 0 ** **myfirstdb | localhost | 5432 | myfirstdb | | 20 | 0 ** **pgbouncer | | 6432 | pgbouncer | pgbouncer | 2 | 0 ** **sparedb | localhost | 5435 | sparedb | | 20 | 0 ** **(4 rows) ** # Tables and Data This chapter covers a range of general recipes for your tables and for working with the data they contain. Many of the recipes contain general advice, though with specific PostgreSQL examples. Some system administrators I've met work only on the external aspects of the database server. What's actually in the database is someone else's problem. Look after your data, and your database will look after you. Keep your data clean, and your queries will run faster and cause fewer application errors. You'll also gain many friends in the business. Getting called in the middle of the night to fix data problems just isn't cool. In this chapter, we will cover the following recipes: * Choosing good names for database objects * Handling objects with quoted names * Enforcing the same name and definition for columns * Identifying and removing duplicates * Preventing duplicate rows * Finding a unique key for a set of data * Generating test data * Randomly sampling data * Loading data from a spreadsheet * Loading data from flat files # Choosing good names for database objects The easiest way to help other people understand a database is to ensure that all the objects have a meaningful name. What makes a name meaningful? # Getting ready Take some time to reflect on your database to make sure you have a clear view of its purpose and main use cases. This is because all the items in this recipe describe certain naming choices that you need to consider carefully in view of your specific circumstances. # How to do it... Here are the points you should consider when naming your database objects: 1. The name follows the existing standards and practices in place. Inventing new standards isn't helpful; enforcing existing standards is. 2. The name clearly describes the role or table contents. 3. For major tables, use short, powerful names. 4. Name lookup tables after the table to which they are linked, such as `account_status`. 5. For associative or linked tables, use all the names of the major tables to which they relate, such as `customer_account`. 6. Make sure that the name is clearly distinct from other similar names. 7. Use consistent abbreviations. 8. Use underscores. Casing is not preserved by default, so using CamelCase names, such as `customerAccount`, as used in Java will just leave them unreadable. See the _Handling objects with quoted names_ recipe. 9. Use consistent plurals, or don't use them at all. 10. Use suffixes to identify the content type or domain of an object. PostgreSQL already uses suffixes for automatically generated objects. 11. Think ahead. Don't pick names that refer to the current role or location of an object. So don't name a table `London` because it exists on a server in London. That server might get moved to Los Angeles. 12. Think ahead. Don't pick names that imply that an entity is the only one of its kind, such as a table named `TEST`, or a table named `BACKUP_DATA`. On the other hand, such information can be put in the database name, which is not normally used from within the database. 13. Avoid using acronyms in place of long table names. For example, `money_allocation_decision` is much better than `MAD`. This is especially important when PostgreSQL translates the names into lowercase, so the fact that it is an acronym may not be clear. 14. The table name is commonly used as the root for other objects that are created, so don't add the `table` suffix or similar ideas. # There's more... The standard names for indexes in PostgreSQL are as follows: **{tablename}_{columnname(s)}_{suffix}** Here, the suffix is one of the following: * `pkey`: This is used for a primary key constraint * `key`: This is used for a unique constraint * `excl`: This is used for an exclusion constraint * `idx`: This is used for any other kind of index The standard suffix for all sequences is `seq`. Tables can have multiple triggers fired on each event. Triggers are executed in alphabetical order, so trigger names should have some kind of action name to differentiate them and to allow the order to be specified. It might seem a good idea to put `INSERT`, `UPDATE`, or `DELETE` in the trigger name, but that can get confusing if you have triggers that work on both `UPDATE` and `DELETE`, and all of this may end up as a mess. The alphabetical order for trigger names always follows the `C` locale, regardless of your actual locale settings. If your trigger names use non-ASCII characters, then the actual ordering might not be what you expect. The following example shows how the characters `è` and `é` are ordered in the `C` locale. You can change the locale and/or the list of strings to explore how different locales affect ordering: `WITH a(x) AS (` ` VALUES ('è'),('é')` `) SELECT *` `FROM a` `ORDER BY x` `COLLATE "C";` A useful naming convention for triggers is as follows: **{tablename}_{actionname}_{after|before}_trig ** If you do find yourself with strange or irregular object names, it will be a good idea to use the `RENAME` subcommands to get things tidy again. Here is an example of this: **ALTER INDEX badly_named_index RENAME TO tablename_status_idx;** # Handling objects with quoted names PostgreSQL object names can contain spaces and mixed case characters if we enclose the table names in double quotes. This can cause some difficulties, so this recipe is designed to help you if you get stuck with this kind of problem. Case sensitivity issues can often be a problem for people more used to working with other database systems, such as MySQL, or for people who are facing the challenge of migrating code away from MySQL. # Getting ready First, let's create a table that uses a quoted name with mixed cases, such as the following: **CREATE TABLE "MyCust"** **AS** **SELECT * FROM cust;** # How to do it... If we try to access these tables without the proper case, we get this error: **postgres=# SELECT count(*) FROM mycust; ** **ERROR: relation "mycust" does not exist LINE 1: SELECT * FROM mycust;** So we write it in the correct case: **postgres=# SELECT count(*) FROM MyCust;** **ERROR: relation "mycust" does not exist** **LINE 1: SELECT * FROM mycust;** This still fails, and in fact gives the same error. If you want to access a table that was created with quoted names, then you must use quoted names, such as the following: **postgres=# SELECT count(*) FROM "MyCust";** The output is as follows: **count** **-------** **5** **(1 row)** The usage rule is that if you create your tables using quoted names, then you need to write your SQL using quoted names. Alternatively, if your SQL uses quoted names, then you will probably have to create the tables using quoted names as well. # How it works... PostgreSQL folds all names to lowercase when used within an SQL statement. Consider this command: **SELECT * FROM mycust;** This is exactly the same as the following command: **SELECT * FROM MYCUST;** It is also exactly the same as this command: **SELECT * FROM MyCust;** However, it is not the same thing as the following command: **SELECT * FROM "MyCust";** # There's more... If you are extracting values from a table that is being used to create object names, then you may need to use a handy function named `quote_ident()`. This function puts double quotes around a value if PostgreSQL requires that for an object name, as shown here: **postgres=# SELECT quote_ident('MyCust'); ** **quote_ident ** **------------- ** **"MyCust" ** **(1 row) ** **postgres=# SELECT quote_ident('mycust'); ** **quote_ident ** **------------- ** **mycust ** **(1 row)** The `quote_ident()` function may be especially useful if you are creating a table based on a variable name in a PL/pgSQL function, as follows: **EXECUTE 'CREATE TEMP TABLE ' || quote_ident(tablename) ||** **'(col1 INTEGER);'** # Enforcing the same name and definition for columns Sensibly designed databases have smooth, easy-to-understand definitions. This allows all users to understand the meaning of data in each table. It is an important way of removing data quality issues. # Getting ready If you want to run the queries in this recipe as a test, then use the following examples. Alternatively, you can just check for problems in your own database: **CREATE SCHEMA s1;** **CREATE SCHEMA s2; ** **CREATE TABLE s1.X** **( col1 integer** **,col2 TEXT); CREATE TABLE s2.X** **( col1 integer** **,col3 NUMERIC);** # How to do it... First, we will show you how to identify columns that are defined in different ways in different tables, using a query against the catalog. We use an `information_schema` query, as follows: **SELECT** **table_schema** **,table_name** **,column_name** **,data_type** **||coalesce(' ' || text(character_maximum_length), '')** **||coalesce(' ' || text(numeric_precision), '')** **||coalesce(',' || text(numeric_scale), '')** **as data_type** **FROM information_schema.columns** **WHERE column_name IN** **(SELECT** **column_name** **FROM** **(SELECT** **column_name** **,data_type** **,character_maximum_length** **,numeric_precision** **,numeric_scale** **FROM information_schema.columns** **WHERE table_schema NOT IN ('information_schema', 'pg_catalog')** **GROUP BY** **column_name** **,data_type** **,character_maximum_length** **,numeric_precision** **,numeric_scale** **) derived** **GROUP BY column_name** **HAVING count(*) > 1** **)** **AND table_schema NOT IN ('information_schema', 'pg_catalog')** **ORDER BY column_name** **;** The query gives an output as follows: **table_schema | table_name | column_name | data_type** **--------------+------------+-------------+---------------** **s2 | x | col1 | integer 32,0** **s1 | x | col1 | smallint 16,0** **(2 rows)** Comparing two given tables is more complex, as there are so many ways that the tables might be similar and yet a little different. The following query looks for all tables of the same name (and hence, in different schemas) that have different definitions: **WITH table_definition as** **( SELECT table_schema** **, table_name** **, string_agg( column_name || ' ' || data_type** **, ',' ORDER BY column_name** **) AS def** **FROM information_schema.columns** **WHERE table_schema NOT IN ( 'information_schema'** **, 'pg_catalog')** **GROUP BY table_schema** **, table_name** **)** **, unique_definition as** **( SELECT DISTINCT table_name** **, def** **FROM table_definition** **)** **, multiple_definition as** **( SELECT table_name** **FROM unique_definition** **GROUP BY table_name** **HAVING count( * ) > 1** **)** **SELECT table_schema** **, table_name** **, column_name** **, data_type** **FROM information_schema.columns** **WHERE table_name** **IN ( SELECT table_name** **FROM multiple_definition )** **ORDER BY table_name** **, table_schema** **, column_name** **;** Here is its output: **table_schema | table_name | column_name | data_type** **--------------+------------+-------------+-----------** **s1 | x | col1 | smallint** **s1 | x | col2 | text** **s2 | x | col1 | integer** **s2 | x | col3 | numeric** **(4 rows)** # How it works... The definitions of tables are held within PostgreSQL, and can be accessed using the Information Schema catalog views. There might be valid reasons why the definitions differ. We've excluded PostgreSQL's own internal tables because there are similar names between the two catalogs: PostgreSQL's implementation of the SQL Standard Information Schema and PostgreSQL's own internal `pg_catalog` schema. Those queries are fairly complex. In fact, there is even more complexity that we could add to those queries to compare all sorts of things such as default values or constraints. The basic idea can be extended in various directions from here. # There's more... We can compare the definitions of any two tables using the following function: **CREATE OR REPLACE FUNCTION diff_table_definition** **(t1_schemaname text** **,t1_tablename text** **,t2_schemaname text** **,t2_tablename text)** **RETURNS TABLE** **(t1_column_name text** **,t1_data_type text** **,t2_column_name text** **,t2_data_type text** **)** **LANGUAGE SQL** **as** **$$** **SELECT** **t1.column_name** **,t1.data_type** **,t2.column_name** **,t2.data_type** **FROM** **(SELECT column_name, data_type** **FROM information_schema.columns** **WHERE table_schema = $1** **AND table_name = $2** **) t1** **FULL OUTER JOIN** **(SELECT column_name, data_type** **FROM information_schema.columns** **WHERE table_schema = $3** **AND table_name = $4** **) t2** **ON t1.column_name = t2.column_name** **AND t1.data_type = t2.data_type** **WHERE t1.column_name IS NULL OR t2.column_name IS NULL** **;** **$$;** # Identifying and removing duplicates Relational databases work on the idea that items of data can be uniquely identified. However hard we try, there will always be bad data arriving from somewhere. This recipe shows you how to diagnose that and clean up the mess. # Getting ready Let's start by looking at our example table, `cust`. It has a duplicate value in `customerid`: **postgres=# SELECT * FROM cust;** **customerid | firstname | lastname | age** **------------+-----------+----------+-----** **1 | Philip | Marlowe | 38** **2 | Richard | Hannay | 42** **3 | Holly | Martins | 25** **4 | Harry | Palmer | 36** **4 | Mark | Hall | 47** **(5 rows)** Before you delete duplicate data, remember that sometimes it isn't the data that is wrong; it is your understanding of it. In those cases, it may be that you haven't properly normalized your database model, and that you need to include additional tables to account for the shape of the data. You might also find that duplicate rows are caused because of you deciding to exclude a column somewhere earlier in a data load process. Check twice, and delete once. # How to do it... First, identify the duplicates using a query such as the following: **CREATE UNLOGGED TABLE dup_cust AS** **SELECT *** **FROM cust** **WHERE customerid IN** **(SELECT customerid** **FROM cust** **GROUP BY customerid** **HAVING count(*) > 1);** We save the list of duplicates in a separate table because the query can be very slow if the table is big, so we don't want to run it more than once. An `UNLOGGED` table can be created with less I/O because it does not write WAL. It is better than a temporary table, because it doesn't disappear if you disconnect and then reconnect. The other side of the coin is that you lose its contents after a crash, but this is not too bad, because if you are using an unlogged table then you are telling PostgreSQL that you are able to recreate the contents of that table in the (unlikely) event of a crash. The results can be used to identify the bad data manually, and you can resolve the problem by carrying out the following steps: 1. Merge the two rows to give the best picture of the data, if required. This might use values from one row to update the row you decide to keep, as shown here: **UPDATE cust** **SET age = 47** **WHERE customerid = 4** **AND lastname = 'Palmer';** 2. Delete the remaining undesirable rows: **DELETE FROM cust** **WHERE customerid = 4** **AND lastname = 'Hall';** In some cases, the data rows might be completely identical, as in the `new_cust` table, which looks like the following: **postgres=# SELECT * FROM new_cust;** **customerid** **------------** **1** **2** **3** **4** **4** **(5 rows)** Unlike the preceding case, we can't tell the data apart at all, so we cannot remove duplicate rows without any manual process. SQL is a set-based language, so picking only one row out of a set is slightly harder than most people want it to be. In these circumstances, we should use a slightly different procedure to detect duplicates. We will use a hidden column named `ctid`. It denotes the physical location of the row you are observing; for example, duplicate rows will all have different `ctid` values. The steps are as follows: 1. First, we start a transaction: **BEGIN;** 2. Then, we lock the table in order to prevent any `INSERT`, `UPDATE,` or `DELETE` operations, which would alter the list of duplicates and/or change their `ctid` values: **LOCK TABLE new_cust IN SHARE ROW EXCLUSIVE MODE;** 3. Now we locate all duplicates, keeping track of the minimum `ctid` value so that we don't delete that value: **CREATE TEMPORARY TABLE dups_cust AS** **SELECT customerid, min(ctid) AS min_ctid** **FROM new_cust** **GROUP BY customerid** **HAVING count(*) > 1;** 4. Then we can delete each duplicate, with the exception of the duplicate with the minimum `ctid` value: **DELETE FROM new_cust** **USING dups_cust** **WHERE new_cust.customerid = dups_cust.customerid** **AND new_cust.ctid != dups_cust.min_ctid;** 5. We commit the transaction, which also releases the lock we previously took: **COMMIT;** 6. Finally, we clean up the table after the deletions: **VACUUM new_cust;** # How it works... The first query works by grouping together the rows on the unique column and counting rows. Anything with more than one row must be caused by duplicate values. If we're looking for duplicates of more than one column (or even all columns), then we have to use an SQL of the following form: **SELECT *** **FROM mytable** **WHERE (col1, col2, ... ,colN) IN** **(SELECT col1, col2, ... ,colN** **FROM mytable** **GROUP BY col1, col2, ... ,colN** **HAVING count(*) > 1);** Here, `col1`, `col2`, and so on until `colN` are the columns of the key. Note that this type of query may need to sort the complete table on all the key columns. That will require sort space equal to the size of the table, so you'd better think first before running that SQL on very large tables. You'll probably benefit from a large `work_mem` setting for this query, probably 128 MB or more. The `DELETE FROM ... USING` query that we showed only works with PostgreSQL because it uses the `ctid` value, which is the internal identifier of each row in the table. If you wanted to run that query against more than one column, as we did earlier in the chapter, you'd need to extend the queries in step _3_ , as follows: **SELECT customerid, customer_name, ..., min(ctid) AS min_ctid** **FROM ...** **GROUP BY customerid, customer_name, ...** **...;** Then, extend the query in step _4_ , like this: **DELETE FROM new_cust** **...** **WHERE new_cust.customerid = dups_cust.customerid** **AND new_cust.customer_name = dups_cust.customer_name** **AND ...** **AND new_cust.ctid != dups_cust.min_ctid;** The preceding query works by grouping together all the rows with similar values and then finding the row with the lowest `ctid` value. The lowest will mean closer to the start of the table, so duplicates will be removed from the far end of the table. When we run `VACUUM`, we may find that the table gets smaller, because we have removed rows from the far end. The `BEGIN` and `COMMIT` commands wrap the `LOCK` and `DELETE` commands into a single transaction, which is required. Otherwise, the lock will be released immediately after being taken. Another reason to use a single transaction is that we can always roll back if anything goes wrong, which is a good thing when we are removing data from a live table. # There's more... Locking the table against changes for long periods may not be possible while we remove duplicate rows. That creates some fairly hard problems with large tables. In that case, we need to do things slightly differently: 1. Identify the rows to be deleted, and save them in a side table. 2. Build an index on the main table to speed up access to rows (maybe using the `CONCURRENTLY` keyword, as explained in the _Maintaining indexes_ recipe in Chapter 9, _Regular Maintenance_ ). 3. Write a program that reads the rows from the side table in a loop, performing a series of smaller transactions. 4. Start a new transaction. 5. From the side table, read a set of rows that match. 6. Select those rows from the main table for updates, relying on the index to make those accesses happen quickly. 7. Delete the appropriate rows. 8. Commit, and then loop again. The aforementioned program can't be written as a `database` function, as we can't have multiple transactions in a function. We need multiple transactions to ensure that we hold locks on each row for the shortest possible duration. # Preventing duplicate rows Preventing duplicate rows is one of the most important aspects of data quality for any database. PostgreSQL offers some useful features in this area, extending beyond most relational databases. # Getting ready Identify the set of columns that you wish to make unique. Does this apply to all rows, or just a subset of rows? Let's start with our example table: **postgres=# SELECT * FROM newcust;** **customerid** **------------** **1** **2** **3** **4** **(4 rows)** # How to do it... To prevent duplicate rows, we need to create a unique index that the database server can use to enforce uniqueness of a particular set of columns. We can do this in the following three similar ways for basic data types: 1. Create a primary key constraint on the set of columns. We are allowed only one of these per table. The values of the data rows must not be `NULL`, as we force the columns to be `NOT NULL` if they aren't already: **ALTER TABLE newcust ADD PRIMARY KEY(customerid);** 2. This creates a new index named `newcust_pkey`. 3. Create a unique constraint on the set of columns. We can use these instead of/or with a primary key. There is no limit on the number of these per table. `NULL` values are allowed in the columns: **ALTER TABLE newcust ADD UNIQUE(customerid);** 4. This creates a new index named `newcust_customerid_key`. 5. Create a unique index on the set of columns: **CREATE UNIQUE INDEX ON newcust (customerid);** 6. This creates a new index named `newcust_customerid_idx`. All of these techniques exclude duplicates, just with slightly different syntaxes. All of them create an index, but only the first two create a formal _constraint_. Each of these techniques can be used when we have a primary key or unique constraint that uses multiple columns. The last method is important because it allows you to specify a `WHERE` clause on the index. This can be useful if you know that the column values are unique only in certain circumstances. The resulting index is then known as a partial index. Suppose our data looked like this: **postgres=# SELECT * FROM partial_unique;** This gives the following output: **customerid | status | close_date ** **-----------+--------+------------ ** **1 | OPEN | ** **2 | OPEN | ** **3 | OPEN | ** **3 | CLOSED | 2010-03-22 ** **(4 rows)** Then we can put a partial index on the table to enforce uniqueness of `customerid` only for `status = 'OPEN'`, like this: **CREATE UNIQUE INDEX ON partial_unique (customerid)** **WHERE status = 'OPEN';** If your uniqueness constraint needs to be enforced across more complex data types, then you may need to use a more advanced syntax. A few examples will help here. Let's start with the simplest example: create a table of boxes and put sample data in it. This may be the first time you're seeing PostgreSQL's data type syntax, so bear with me: **postgres=# CREATE TABLE boxes (name text, position box); ** **CREATE TABLE ** **postgres=# INSERT INTO boxes VALUES** **('First', box '((0,0), (1,1))'); ** **INSERT 0 1 ** **postgres=# INSERT INTO boxes VALUES** **('Second', box '((2,0), (2,1))'); ** **INSERT 0 1 ** **postgres=# SELECT * FROM boxes; ** **name | position ** **--------+------------- ** **First | (1,1),(0,0) ** **Second | (2,1),(2,0) ** **(2 rows)** We can see two boxes that neither touch nor overlap, based on their _x_ and _y_ coordinates. To enforce uniqueness here, we want to create a constraint that will throw out any attempt to add a position that overlaps with any existing box. The overlap operator for the box data type is defined to be `&&`, so we use the following syntax to add the constraint: **postgres=# ALTER TABLE boxes ADD EXCLUDE USING gist** **(position WITH &&);** **NOTICE: ALTER TABLE / ADD EXCLUDE will create implicit index** **"boxes_position_excl" for table "boxes"** **ALTER TABLE** This creates a new index named `boxes_position_excl`. We can use the same syntax even with the basic data types. So a fourth way of performing our first example would be as follows: **ALTER TABLE newcust ADD EXCLUDE (customerid WITH =);** This creates a new index named `newcust_customerid_excl`. # How it works... Uniqueness is always enforced by an index. Each index is defined with a data type operator. When a new row is inserted or the set of column values is updated, we use the operator to search for existing values that conflict with the new data. So, to enforce uniqueness, we need an index and a search operator defined on the data types of the columns. When we define normal `UNIQUE` constraints, we simply assume that we mean the equality operator (`=`) for the data type. The `EXCLUDE` syntax offers a richer syntax to allow us to express the same problem with different data types and operators. # There's more... Unique and exclusion constraints can be marked as deferrable, meaning that the user can choose to postpone the check to the end of the transaction, a nice way to relax constraints without reducing data integrity. However, as of PostgreSQL 10, there are a few limitations that you should be aware of; the restrictions are as follows: * You must define a constraint as `DEFERRABLE` when creating it, either in the `CREATE TABLE` statement or in the `ALTER TABLE` statement. You cannot change an existing constraint from `NOT DEFERRABLE` to `DEFERRABLE`, nor can you make it `INITIALLY DEFERRED` or `INITIALLY IMMEDIATE`. If you need to apply such a change on an existing constraint, you need to create a new constraint and then drop the old constraint. Optionally, you can rename the new constraint at the end. * You cannot mix deferrable unique constraints with foreign keys. You will get an error message if you try to add a foreign key that refers to a unique constraint that is deferrable. It's likely that these restrictions will be lifted in later releases. # Duplicate indexes Note that PostgreSQL allows you to have multiple indexes with exactly the same definition. This is useful in some contexts, but can also be annoying if you accidentally create multiple indexes, as each index has its own cost in terms of writes. You can also have constraints defined using each of the aforementioned different ways. Each of these ways enforces essentially the same constraint, so take care. # Uniqueness without indexes It's possible to have uniqueness in a set of columns without creating an index. That might be useful if all we want is to ensure uniqueness rather than allow index lookups. To do that, you can do either of the following: * Use a serial data type * Manually alter the default to be the `nextval()` function of a sequence Each of these will provide a unique value for use as a row's key. The uniqueness is not enforced, nor will there be a unique constraint defined. So there is still a possibility that someone might reset the sequence to an earlier value, which will eventually cause duplicate values. Consider also that this method provides the unique value as a default, which is not used when the user specifies an explicit value. An example of this is as follows: **CREATE TABLE t(id serial, descr text);** **INSERT INTO t(descr) VALUES ('First value');** **INSERT INTO t(id,descr) VALUES (1,'Cheating!');** Finally, you might also wish to have mostly unique data, such as using the `clock_timestamp()` function to provide ascending times to microsecond resolution. # Real-world example – IP address range allocation The problem is about assigning ranges of IP addresses, while at the same time ensuring that we don't allocate (or potentially allocate) the same addresses to different people or purposes. This is easy to do if we keep track of each individual IP address, and much harder to do if we want to deal solely with ranges of IP addresses. Initially, you may think of designing the database as follows: **CREATE TABLE iprange** **(iprange_start inet** **,iprange_stop inet** **,owner text);** **INSERT INTO iprange VALUES** **('192.168.0.1','192.168.0.16', 'Simon');** **INSERT INTO iprange VALUES** **('192.168.0.17','192.168.0.24', 'Gianni');** **INSERT INTO iprange VALUES** **('192.168.0.32','192.168.0.64', 'Gabriele');** However, you'll realize that there is no way to create a unique constraint that enforces the model constraint of avoiding overlapping ranges. You could create an after trigger that checks existing values, but it's going to be messy. PostgreSQL offers a better solution, based on _range types_. In fact, every data type that supports a `btree` operator class (that is, a way of ordering any two given values) can be used to create a range type. In our case, the SQL is as follows: **CREATE TYPE inetrange AS RANGE (SUBTYPE = inet);** This command creates a new data type that can represent ranges of `inet` values, that is, of IP addresses. Now we can use this new type when creating a table: **CREATE TABLE iprange2** **(iprange inetrange** **,owner text);** This new table can be populated as usual. We just have to group the extremes of each range into a single value, as follows: **INSERT INTO iprange2** **VALUES ('[192.168.0.1,192.168.0.16]', 'Simon');** **INSERT INTO iprange2** **VALUES ('[192.168.0.17,192.168.0.24]', 'Gianni');** **INSERT INTO iprange2** **VALUES ('[192.168.0.32,192.168.0.64]', 'Gabriele');** Now we can create a _unique exclusion constraint_ on the table, using the following syntax: **ALTER TABLE iprange2** **ADD EXCLUDE USING GIST (iprange WITH &&);** If we try to insert a range that overlaps with any of the existing ranges, then PostgreSQL will stop us: **INSERT INTO iprange2** **VALUES ('[192.168.0.10,192.168.0.20]', 'Somebody else');** **ERROR: conflicting key value violates exclusion constraint "iprange2_iprange_excl"** **DETAIL: Key (iprange)=([192.168.0.10,192.168.0.20]) conflicts with existing key (iprange)=([192.168.0.1,192.168.0.16]).** # Real-world example – range of time In many databases, there will be historical data tables with data that has a `START_DATE` and an `END_DATE` value, or something similar. As in the previous example, we can solve this example elegantly with a range type. Actually, this example is even shorter—we don't need to create the range type since the most common cases are already built-in, and precisely—integers, decimal values, dates, and timestamps with and without a time zone. # Real-world example – prefix ranges Another common problem involves assigning credit card numbers or telephone numbers. For example, with credit card numbers, we may need to perform additional checking for certain financial institutions, assuming that each institution is assigned a given range. In that case, we must check efficiently if a given credit card number belongs to a certain range. The prefix range data type has been specifically designed to address this class of problems. This is available as a PostgreSQL extension at http://github.com/dimitri/prefix. A warning—despite the similar name, prefix ranges cannot be implemented as range types. # Finding a unique key for a set of data Sometimes, it can be difficult to find a unique set of key columns that describe the data. # Getting ready Let's start with a small table, where the answer is fairly obvious: **postgres=# select * from ord;** We assume that the output is as follows: **orderid | customerid | amt ** **---------+------------+-------- ** **10677 | 2 | 5.50 ** **5019 | 3 | 277.44 ** **9748 | 3 | 77.17 ** **(3 rows)** # How to do it... First of all, there's no need to do this through a brute-force approach. Checking all the permutations of columns to see which is unique might take you a long time. Let's start by using PostgreSQL's own optimizer statistics. Run the following command on our table to get a fresh sample of statistics: **postgres=# analyze ord;** **ANALYZE** This runs quickly, so we don't have to wait too long. Now we can examine the relevant columns of the statistics: **postgres=# SELECT attname, n_distinct** **FROM pg_stats** **WHERE schemaname = 'public'** **AND tablename = 'ord'; ** **attname | n_distinct ** **------------+------------ ** **orderid | -1 ** **customerid | -0.666667 amt | -1** **(3 rows)** The preceding example was chosen because we have two potential answers. If the value of `n_distinct` is `-1`, then the column is thought to be unique within the sample of rows examined. We would then need to use our judgment to decide whether one or both of these columns are unique by chance, or as part of the design of the database that created them. It's possible that there is no single column that uniquely identifies the rows. Multiple column keys are fairly common. If none of the columns were unique, then we should start looking for unique keys that are combinations of the most unique columns. The following query shows a frequency distribution for the table such that a value occurs twice in one case, and another value occurs only once: **postgres=# SELECT num_of_values, count(*)** **FROM (SELECT customerid, count(*) AS num_of_values** **FROM ord** **GROUP BY customerid) s** **GROUP BY num_of_values** **ORDER BY count(*);** **num_of_values | count** **---------------+-------** **2 | 1** **1 | 1** **(2 rows)** We can change the query to include multiple columns, like this: **SELECT num_of_values, count(*)** **FROM (SELECT customerid, orderid, amt** **,count(*) AS num_of_values** **FROM ord** **GROUP BY customerid, orderid, amt** **) s** **GROUP BY num_of_values** **ORDER BY count(*);** This query will result in only one row once we find a set of columns that is unique. As we get closer to finding the key, we will see that the distribution gets tighter and tighter. So, the procedure is as follows: 1. Choose one column to start with. 2. Compute the corresponding frequency distribution. 3. If the outcome is multiple rows, then add one more column and repeat from step _2_. Otherwise, it means you have found a set of columns satisfying a uniqueness constraint. Now you must verify that the set of columns is minimal; for example, check whether it is possible to remove one or more columns without violating the unique constraint. This can be done using the frequency distribution as a test. Precisely, do the following: 1. Test each column by computing the frequency distribution on all the other columns. 2. If the frequency distribution has one row, then the column is not needed in the uniqueness constraint. Remove it from the set of columns and repeat from step _1_. Otherwise, you have found a minimal set of columns, which is also called a key for that table. # How it works... Finding a unique key is possible for a program, but in most cases, a human can do this much faster by looking at things such as column names, foreign keys, or business understanding to reduce the number of searches required by the brute-force approach. The `ANALYZE` command works by taking a sample of the table data, and then performing a statistical analysis of the results. The `n_distinct` value has two different meanings, depending on its sign: if positive, it is the estimate of the number of distinct values for the column; if negative, it is the estimate of the density of such distinct values, with the sign changed. For example, `n_distinct = -0.2` means that a table of one million rows is expected to have 200,000 distinct values, while `n_distinct = 5` means that we expect just five distinct values. # Generating test data DBAs frequently need to generate test data for a variety of reasons, whether it's for setting up a test database or just for generating a test case for an SQL performance issue. # How to do it... To create a table of test data, we need the following: * Some rows * Some columns * Some order The steps are as follows: 1. First, generate a lot of rows of data. We use something named a `set-returning` function. You can write your own, though PostgreSQL includes a couple of very useful ones. 2. You can generate a sequence of rows using a query like the following: **postgres=# SELECT * FROM generate_series(1,5); ** **generate_series ** **----------------- ** **1 ** **2 ** **3 ** **4 ** **5 ** **(5 rows)** 3. Alternatively, you can generate a list of dates, like this: **postgres=# SELECT date(t) ** **FROM generate_series(now(),** ** now() + '1 week', '1 day') AS f(t);** ** date ** **------------** ** 2018-04-24** ** 2018-04-25** ** 2018-04-26** ** 2018-04-27** ** 2018-04-28** ** 2018-04-29** ** 2018-04-30** ** 2018-05-01** **(8 rows)** 4. Then we want to generate a value for each column in the `test` table. We can break that down into a series of functions, using the following examples as a guide: * Either of these functions can be used to generate both rows and reasonable primary key values for them * For a random `integer` value, this is the function: **(random()*(2*10^9))::integer** 4. * For a random `bigint` value, the function is as follows: **(random()*(9*10^18))::bigint** 5. For random `numeric` data, the function is the following: **(random()*100.)::numeric(5,2)** * * For a random-length string, up to a maximum length, this is the function: **repeat('1',(random()*40)::integer)** * * For a random-length substring, the function is as follows: **substr('abcdefghijklmnopqrstuvwxyz',1, (random()*25)::integer)** * * Here is the function for a random string from a list of strings: **(ARRAY['one','two','three'])[0.5+random()*3]** 6. Finally, we can put both techniques together to generate our table: **postgres=# SELECT key** **,(random()*100.)::numeric(4,2)** **,repeat('1',(random()*25)::integer)** **FROM generate_series(1,10) AS f(key); ** **key | numeric | repeat ** **-----+---------+------------------------ ** **1 | 83.05 | 1111 ** **2 | 5.28 | 11111111111111 ** **3 | 41.85 | 1111111111111111111111 ** **4 | 41.70 | 11111111111111111 ** **5 | 53.31 | 1 ** **6 | 10.09 | 1111111111111111 ** **7 | 68.08 | 111 ** **8 | 19.42 | 1111111111111111 ** **9 | 87.03 | 11111111111111111111 ** **10 | 70.64 | 111111111111111 ** **(10 rows)** 7. Alternatively, we can use random ordering: **postgres=# SELECT key** **,(random()*100.)::numeric(4,2)** **,repeat('1',(random()*25)::integer)** **FROM generate_series(1,10) AS f(key)** **ORDER BY random() * 1.0; ** **key | numeric | repeat ** **-----+---------+------------------------- ** **4 | 86.09 | 1111 ** **10 | 28.30 | 11111111 ** **2 | 64.09 | 111111 ** **8 | 91.59 | 111111111111111 ** **5 | 64.05 | 11111111 ** **3 | 75.22 | 11111111111111111 ** **6 | 39.02 | 1111 ** **7 | 20.43 | 1111111 ** **1 | 42.91 | 11111111111111111111 ** **9 | 88.64 | 1111111111111111111111 ** **(10 rows)** # How it works... To set returning functions, literally return a set of rows. That allows them to be used in either the `FROM` clause, as if they were a table, or the `SELECT` clause. The `generate_series()` set of functions returns either dates or integers, depending on the data types of the input parameters you use. The `::` operator is used to cast between data types. The _random string from a list of strings_ example uses PostgreSQL arrays. You can create an array using the `ARRAY` constructor syntax, and then use an integer to reference one element in the array. In our case, we used a random subscript. # There's more... There are also some commercial tools used to generate application-specific test data for PostgreSQL. They are available at http://www.sqlmanager.net/products/postgresql/datagenerator and http://www.datanamic.com/datagenerator/index.html. The key features for any data generator are as follows: * The ability to generate data in the right format for custom data types * The ability to add data to multiple tables, while respecting foreign key constraints between tables * The ability to add data to non-uniform distributions The tools and tricks shown here are cool and clever, though there are some problems hiding here as well. Real data has so many strange things in it that it can be very hard to simulate. One of the most difficult things is generating data that follows realistic distributions. For example, if we had to generate data for people's heights, then we'd want to generate data to follow a normal distribution. If we were generating customer bank balances, we'd want to use a Zipf distribution, or for the number of reported insurance claims, perhaps a Poisson distribution (or perhaps not). Replicating the real quirks in data can take some time. Finally, note that casting a float into an integer rounds it to the nearest integer, so the distribution of integers is not uniform on each extreme. For instance, the probability of `(random()*10)::int` being 0 is just 5%, as is its probability of being 10, while each integer between 1 and 9 occurs with a probability of 10%. This is why we put 0.5 in the last example, which is simpler than using the `floor()` function. # See also * You can use existing data to generate test databases using sampling. That's the subject of our next recipe, _Randomly sampling data_. # Randomly sampling data DBAs may be asked to set up a test server and populate it with test data. Often, that server will be old hardware, possibly with smaller disk sizes. So, the subject of data sampling raises its head. The purpose of sampling is to reduce the size of the dataset and improve the speed of later analysis. Some statisticians are so used to the idea of sampling that they may not even question whether its use is valid or it can cause further complications. The SQL standard way to perform sampling is by adding the `TABLESAMPLE` clause to the `SELECT` statement. # How to do it... In this section, we will take a random sample of a given collection of data (for example, a given table). First, you should realize that there isn't a simple tool to slice off a sample of your database. It would be neat if there were, but there isn't. You'll need to read all of this to understand why: 1. We first consider using SQL to derive a sample. Random sampling is actually very simple because we can use the `TABLESAMPLE` clause. Consider the following example: **postgres=# SELECT count(*) FROM mybigtable; ** **count ** **------- ** **10000 ** **(1 row) ** **postgres=# SELECT count(*) FROM mybigtable** **TABLESAMPLE BERNOULLI(1); ** **count ** **------- ** **106 ** **(1 row) ** **postgres=# SELECT count(*) FROM mybigtable** **TABLESAMPLE BERNOULLI(1); ** **count ** **------- ** **99 ** **(1 row)** 2. Here the `TABLESAMPLE` clause applies to `mybigtable`, and tells `SELECT` to consider only a random sample, while the `BERNOULLI` keyword denotes the sampling method used, and the number 1 between parentheses represents the percentage of rows that we want to consider in the sample, that is, the 1%. Quite easy! 3. Now we need to get the sampled data out of the database, which is tricky for a few reasons. Firstly, there is no option to specify a `WHERE` clause for `pg_dump`. Secondly, if you create a view that contains the `WHERE` clause, `pg_dump` dumps only the view definition, not the view itself. 4. You can use `pg_dump` to dump all databases, apart from a set of tables, so you can produce a sampled dump like this: **pg_dump –-exclude-table=mybigtable > db.dmp ** **pg_dump –-table=mybigtable –-schema-only > mybigtable.schema ** **psql -c '\copy (SELECT * FROM mybigtable** **TABLESAMPLE BERNOULLI (1)) to mybigtable.dat'** 5. Then reload onto a separate database using the following commands: **psql -f db.dmp** **psql -f mybigtable.schema** **psql -c '\copy mybigtable from mybigtable.dat'** Overall, my advice is to use sampling with caution. In general, it is easier to apply it to a few very large tables only, in view of both the mathematical issues surrounding the sample design and the difficulty of extracting the data. # How it works... The extract mechanism shows off the capabilities of the PostgreSQL command-line tools, `psql` and `pg_dump`, as `pg_dump` allows you to include or exclude objects and dump the entire table (or only its schema), whereas `psql` allows you to dump out the result of an arbitrary query into a file. The `BERNOULLI` clause specifies the sampling method, that is, PostgreSQL takes the random sample by performing a full table scan, and then selecting each row with the required probability, here 1%. Another built-in sampling method is `SYSTEM`, which reads a random sample of table pages, and then includes all rows in these pages; this is generally faster, given that samples are normally quite smaller than the original, but the randomness of the selection is affected by how rows are physically arranged on disk, which makes it suitable for some applications only. Here is an example that shows what the problem is. Suppose you take a dictionary, rip out a few pages, and then select all the words in them; you will get a random sample composed by a few _clusters_ of consecutive words. This is good enough if you want to estimate the average length of a word, but not for analyzing the average number of words for each initial letter. The reason is that the initial letter of a word is strongly correlated with how the words are arranged in pages, while the length of a word is not. We haven't discussed how random the `TABLESAMPLE` clause is. This isn't the right place for such details; however, it is reasonably simple to extend PostgreSQL with extra functions or sampling methods, so if you prefer another mechanism, you can find an external random number generator, and create a new sampling method for the `TABLESAMPLE` clause. PostgreSQL includes two extra sampling methods, `tsm_system_rows` and `tsm_system_time,` as contrib extensions: they are excellent examples to start from. The `tsm_system_rows` method does not work with percentages; instead, the numeric argument is interpreted as the number of rows to be returned. Similarly, the `tsm_system_time` method will regard its argument as the number of milliseconds to spend retrieving the random sample. These two methods include the word `system` in their name because they use block-level sampling, like the built-in SYSTEM sampling method; hence, their randomness is affected by the same _clustering_ limitation as described previously. The sampling method shown earlier is a simple random sampling technique that has an **equal probability of selection** ( **EPS** ) design. EPS samples are considered useful because the variance of the sample attributes is similar to the variance of the original dataset. However, bear in mind that this is useful only if you are considering variances. Simple random sampling can make the eventual sample biased towards more frequently occurring data. For example, if you have a 1% sample of data on which some kinds of data occur only 0.001% of the time, you may end up with a dataset that doesn't have any of that outlying data. What you might wish to do is to pre-cluster your data and take different samples from each group to ensure that you have a sampled dataset that includes many more outlying attributes. A simple method might be to do the following: * Include 1% of all normal data * Include 25% of outlying data Note that if you do this, then it is no longer an EPS sample design. Undoubtedly, there are statisticians who will be in apoplexy after reading this. You're welcome to use the facilities of the SQL language to create a more accurate sample. Just make sure that you know what you're doing and/or check out some good statistical literature, websites, or textbooks. # Loading data from a spreadsheet Spreadsheets are the most obvious starting place for most data stores. Studies within a range of businesses consistently show that more than 50% of the smaller data stores are held in spreadsheets or small desktop databases. Loading data from these sources is a frequent and important task for many DBAs. # Getting ready Spreadsheets combine data, presentation, and programs all into one file. That's perfect for power users wanting to work quickly. Like other relational databases, PostgreSQL is mainly concerned with the lowest level of data, so extracting just the data from these spreadsheets can present some challenges. We can easily handle spreadsheet data if that spreadsheet's layout follows a very specific form, as follows: * Each spreadsheet column becomes one column in one table * Each row of the spreadsheet becomes one row in one table * Data is only in one worksheet of the spreadsheet * Optionally, the first row is a list of column descriptions/titles This is a very simple layout, and more often there will be other things in the spreadsheet, such as titles, comments, constants for use in formulas, summary lines, macros, images, and so on. If you're in this position, the best thing to do is to create a new worksheet within the spreadsheet in the pristine form described earlier, and then set up cross-worksheet references to bring in the data. An example of a cross-worksheet reference would be `=Sheet2.A1`. You'll need a separate worksheet for each set of data that will become one table on PostgreSQL. You can load multiple worksheets into one table, however. Some spreadsheet users will say that all of this is unnecessary, and is evidence of the problems of databases. The real spreadsheet gurus do actually advocate this type of layout—data in one worksheet and calculation and presentation in other worksheets. So it is actually best practice to design spreadsheets in this way; however, we must work with the world the way it is. # How to do it... Here, we will show you an example where data in a spreadsheet is loaded into a database: 1. If your spreadsheet data is neatly laid out in a single worksheet, as shown in the following screenshot, then you can go to File | Save As and then select CSV as the file type to be saved: 2. This will export the current worksheet to a file, like the following: **"Key","Value"** **1,"c"** **2,"d"** 3. We can then load it into an existing PostgreSQL table, using the following `psql` command: **postgres=# \COPY sample FROM sample.csv CSV HEADER ** **postgres=# SELECT * FROM sample; ** **key | value ** **-----+------- ** **1 | c ** **2 | d** 4. Alternatively, from the command line, this would be as follows: **psql -c '\COPY sample FROM sample.csv CSV HEADER'** 5. Note that the file can include a full file path if the data is in a different directory. The `psql \COPY` command transfers data from the client system where you run the command through to the database server, so the file is on the client. 6. If you are submitting SQL through another type of connection, then you should use the following SQL statement: **COPY sample FROM '/mydatafiledirectory/sample.csv' CSV HEADER;** Note that the preceding SQL statement runs on the database server and can only be executed by a super user. So you need to ensure that the server process is allowed to read that file, then transfer the data yourself to the server, and finally load the file. The `COPY` statement shown in the preceding SQL statement uses an absolute path to identify data files, which is required. The `COPY` (or `\COPY`) command does not create the table for you; that must be done beforehand. Note also that the `HEADER` option does nothing but ignore the first line of the input file, so the names of the columns from the `.csv` file don't need to match those of the `Postgres` table. If it hasn't occurred to you yet, this is also a problem. If you say `HEADER` and the file does not have a header line, then all it does is ignore the first data row. Unfortunately, there's no way for PostgreSQL to tell whether the first line of the file is truly a header or not. Be careful! There isn't a standard tool to load data directly from the spreadsheet to the database. It's fairly simple to write a spreadsheet macro to automate the aforementioned tasks, but that's not a topic for this book. # How it works... The `\COPY` command executes a `COPY` SQL statement, so the two methods described earlier are very similar. There's more to be said about `COPY`, so we'll cover that in the next recipe. # There's more... There are many data extract and loading tools available out there, some cheap and some expensive. Remember that the hardest part of loading data from any spreadsheet is separating the data from all the other things it contains. I've not yet seen a tool that can help with that. # Loading data from flat files Loading data into your database is one of the most important tasks. You need to do this accurately and quickly. Here's how. # Getting ready You'll need a copy of `pgloader`, which is commonly available in all main software distribution. At the time of writing, the current stable version is 3.4.1. The 3.x series is a major rewrite, with many additional features, and the 2.x series is now considered obsolete. # How to do it... PostgreSQL includes a command named `COPY` that provides the basic data load/unload mechanism. The `COPY` command doesn't do enough when loading data, so let's skip the basic command and go straight to `pgloader`. To load data, we need to understand our requirements, so let's break this down into a step-by-step process, as follows: 1. Identify the data files and where they are located. Make sure that `pgloader` is installed at the location of the files. 2. Identify the table into which you are loading, ensure that you have the permissions to load, and check the available space.Work out the file type (examples include fixed-size fields, delimited text, and CSV) and check the encoding. 3. Specify the mapping between columns in the file and columns on the table being loaded. Make sure you know which columns in the file are not needed—`pgloader` allows you to include only the columns you want. Identify any columns in the table for which you don't have data. Do you need them to have a default value on the table, or does `pgloader` need to generate values for those columns through functions or constants? 4. Specify any transformations that need to take place. The most common issue is date formats, though possibly there may be other issues. 5. Write the `pgloader` script. 6. `pgloader` will create a log file to record whether the load has succeeded or failed, and another file to store rejected rows. You need a directory with sufficient disk space if you expect them to be large. Their size is roughly proportional to the number of failing rows. 7. Finally, consider what settings you need for performance options. This is definitely last, as fiddling with things earlier can lead to confusion when you're still making the load work correctly. 8. You must use a script to execute `pgloader`. This is not a restriction; actually it is more like best practice, because it makes it much easier to iterate towards something that works. Loads never work the first time, except in the movies! Let's look at a typical example from pgloader's documentation—the `example.load` file: **LOAD CSV ** **FROM 'GeoLiteCity-Blocks.csv' WITH ENCODING iso-646-us ** **HAVING FIELDS ** **( ** **startIpNum, endIpNum, locId ** **) ** **INTO postgresql://user@localhost:54393/dbname?geolite.blocks ** **TARGET COLUMNS ** **( ** **iprange ip4r using (ip-range** **startIpNum endIpNum), ** **locId ** **) ** **WITH truncate, ** **skip header = 2, ** **fields optionally enclosed by '"', ** **fields escaped by backslash-quote, ** **fields terminated by '\t' ** **SET work_mem to '32 MB', maintenance_work_mem to '64 MB';** We can use the `load` script like this: **pgloader --summary summary.log example.load** # How it works... `pgloader` copes gracefully with errors. The `COPY` command loads all rows in a single transaction, so only a single error is enough to abort the load. `pgloader` breaks down an input file into reasonably sized chunks, and loads them piece by piece. If some rows in a chunk cause errors, then `pgloader` will split it iteratively until it loads all the good rows and skips all the bad rows, which are then saved in a separate "rejects" file for later inspection. This behavior is very convenient if you have large data files with a small percentage of bad rows; for instance, you can edit the rejects, fix them, and finally, load them with another `pgloader` run. Versions 2.x of `pgloader` were written in Python and connected to PostgreSQL through the standard Python client interface. Version 3.x is written in Common Lisp. Yes, `pgloader` is less efficient than loading data files using a `COPY` command, but running a `COPY` command has many more restrictions: the file has to be in the right place on the server, has to be in the right format, and must be unlikely to throw errors on loading. `pgloader` has additional overhead, but it also has the ability to load data using multiple parallel threads, so it can be faster to use as well. pgloader's ability to reformat the data via user-defined functions is often essential; straight `COPY` is just too simple. `pgloader` also allows loading from fixed-width files, which `COPY` does not. # There's more... If you need to reload the table completely from scratch, then specify the `-WITH TRUNCATE` clause in the `pgloader` script. There are also options to specify SQL to be executed before and after loading the data. For instance, you may have a script that creates the empty tables before, or you can add constraints after, or both. After loading, if we have load errors, then there will be some junk loaded into the PostgreSQL tables. It is not junk that you can see, or that gives any semantic errors, but think of it more like fragmentation. You should think about whether you need to add a `VACUUM` command after the data load, though this will make the load take possibly much longer. We need to be careful to avoid loading data twice. The only easy way of doing that is to make sure that there is at least one unique index defined on every table that you load. The load should then fail very quickly. String handling can often be difficult, because of the presence of formatting or non-printable characters. The default setting for PostgreSQL is to have a parameter named `standard_conforming_strings` set to `off`, which means that backslashes will be assumed to be escape characters. Put another way, by default, the `\n` string means line feed, which can cause data to appear truncated. You'll need to turn `standard_conforming_strings` to `on`, or you'll need to specify an escape character in the load-parameter file. If you are reloading data that has been unloaded from PostgreSQL, then you may want to use the `pg_restore` utility instead. The `pg_restore` utility has an option to reload data in parallel, `-j number_of_threads`, though this is only possible if the dump was produced using the custom `pg_dump` format. Refer to the recipes in Chapter 11, _Backup and Recovery_ , for more details. This can be useful for reloading dumps, though it lacks almost all of the other `pgloader` features discussed here. If you need to use rows from a read-only text file that does not have errors, then you may consider using the `file_fdw` contrib module. The short story is that it lets you create a _virtual_ table that will parse the text file every time it is scanned. This is different from filling a table once and for all, either with `COPY` or `pgloader`; therefore, it covers a different use case. For example, think about an external data source that is maintained by a third party and needs to be shared across different databases. # Security In this chapter, we will cover the following recipes: * The PostgreSQL superuser * Revoking user access to a table * Granting user access to a table * Granting user access to specific columns * Granting user access to specific rows * Creating a new user * Temporarily preventing a user from connecting * Removing a user without dropping their data * Checking whether all users have a secure password * Giving limited superuser powers to specific users * Auditing database access * Always knowing which user is logged in * Integrating with LDAP * Connecting using SSL * Using SSL certificates to authenticate * Mapping external usernames to database roles * Encrypting sensitive data # Introduction First set up access rules into the database server. PostgreSQL allows you to control access based upon the host that is trying to connect, using the `pg_hba.conf` file. You can specify SSL connections if needed, or skip that if the network is secure. You can specify the use of SCRAM authentication using 256 bit keys, as well as many other mechanisms. Next set up the role and privileges for accessing your data. Databases are mostly used to store data with several restrictions on how it can be used. Some records or tables can only be seen by certain users, and even for those tables that are visible to everyone, there can be restrictions on who can insert new data or change the existing data. All of this is managed by a privilege system, where users are granted different privileges for different tables or other database objects, such as schemas or functions. It is good practice not to grant these privileges directly to users, but to use an intermediate role to collect a set of privileges. Then, instead of granting all the same privileges to the actual user, this entire role is granted to users needing these privileges. For example, a clerk role may have rights to both insert data and update existing data in the `user_account` table, but may have rights to only insert data in the `transaction_history` table. Fine grained control over access can be managed using the **Row Level Security** ( **RLS** ) feature, which allows a defined Policy on selected tables. Another aspect of database security concerns the management of this access to the database; making sure that only the right people can access the database, and that one user can't see what other users are doing (unless you are an administrator or auditor); and deciding whether users can or cannot grant forward the roles granted to them. You should consider auditing the actions of administrators using `pgaudit`. # Typical user role The minimal production database setup contains at least two types of users, namely administrators and end users, where administrators can do everything (they are superusers), and end users can only do very little, usually just modify the data in only a few tables and read from a few more. It is not a good idea to let ordinary users create or change database object definitions, meaning that they should not have the `CREATE` privilege on any schema, including `PUBLIC`. There can be more roles for different types of end users, such as analysts, who can only select from a single table or view, or some maintenance script "users" who see no data at all and just have the ability to execute a few functions. Alternatively, there can also be a manager role, which can grant and revoke roles for other users but is not supposed to do anything else. # The PostgreSQL superuser In this recipe, you will learn how to grant right to a user to become a superuser. A PostgreSQL **superuser** is a user that can do anything in the database, regardless of what privileges it has been granted. Many cloud databases do not allow this level of privilege to be granted. It is normal to place strict controls on users of this type. # How to do it... 1. A user becomes a superuser when it is created with the `SUPERUSER` attribute set: **CREATE USER username SUPERUSER;** 2. A user can be deprived of its superuser status by removing the `SUPERUSER` attribute, using this command: **ALTER USER username NOSUPERUSER;** 3. A user can be restored to superuser status later, using the following command: **ALTER USER username SUPERUSER;** 4. When neither `SUPERUSER` nor `NOSUPERUSER` is given in the `CREATE USER` command, then the default is to create a user who is not a superuser. # How it works... Rights to some operations in PostgreSQL are not available by default and need to be granted specifically to users. They must be performed by a special user who has this special attribute set. The preceding commands set or reset this attribute for the user. # There's more... The PostgreSQL system comes set up with at least one superuser. Most commonly, this superuser is named `postgres`, but occasionally it adopts the same name as the system user who owns the database directory and with whose rights the PostgreSQL server runs. # Other superuser-like attributes In addition to `SUPERUSER`, there are two lesser attributes—`CREATEDB` and `CREATEUSER`—that give the user only some of the power reserved for superusers, namely creating new databases and users. See the _Giving limited superuser powers to specific users_ recipe for more information on this. # Attributes are never inherited Later, you will learn about granting one role to another user-role inheritance, and how privileges can be granted through these intermediate group roles. None of this applies to attributes—to perform superuser-only operations, you must be that user. # See also Also check out the _Always knowing which user is logged in_ recipe in this chapter. All of the following recipes assume a non-superuser unless it is explicitly mentioned that they apply to or need a superuser. # Revoking user access to a table This recipe answers the question, _How do I make sure that user X cannot access table Y?_ # Getting ready The current user must either be a superuser, the owner of the table, or a user with a `GRANT` option for the table. Also, bear in mind that you can't revoke rights from a user who is a superuser. # How to do it... To revoke all rights on the `table1` table from the `user2` user, you must run the following SQL command: **REVOKE ALL ON table1 FROM user2;** However, if `user2` has been granted another role that gives them some rights on `table1`, say `role3`, this command is not enough; you must also choose one of the following options: * Fix the user -that is, revoke `role3` from `user2` * Fix the role - that is, revoke privileges on `table1` from `role3` Both choices are imperfect because of their side-effects: The former will revoke all the privileges associated to `role3`, not just the privileges concerning `table1`; the latter will revoke the privileges on `table1` from all the other users that have been granted `role3`, not just from `user2`. It is normally better to avoid damaging other legitimate users, so we opt for the first solution. The following is a worked example. Using `psql`, display the list of roles that have been granted at least one privilege on `table1` by issuing `\z table1`. For instance, you can obtain the following output (an extra column about column privileges has been removed from the right-hand side because it was not relevant here): **Access privileges** **Schema | Name | Type | Access privileges | ...** **--------+--------+-------+---------------------------+ ...** **public | table1 | table | postgres=arwdDxt/postgres+| ...** **| | | role3=r/postgres +| ...** **| | | role5=a/postgres | ...** **(1 row)** Then we check whether `user2` is a member of any of those roles by typing `\du user2`: **List of roles** **Role name | Attributes | Member of** **-----------+------------+---------------** **user2 | | {role3, role4}** From the previous step, we notice that `role3` had been granted the `SELECT` privilege ( _r_ for _read_ ) by the `postgres` user, so we must revoke it, as follows: **REVOKE role3 FROM user2;** We must also inspect `role4`. Even if it doesn't have privileges on `table1`, in theory it could be a member of one of the three roles that have privileges on that table. We issue `\du role4` and get the following output: **List of roles** **Role name | Attributes | Member of** **-----------+--------------+-----------** **role4 | Cannot login | {role5}** Our suspicion was well founded: `user2` can get the `INSERT` privilege ( _a_ for _append_ ) on `table1`, first via `role4` and then via `role5`. So we must break this two-step chain as follows: **REVOKE role4 FROM user2;** This example may seem too unlikely to be true. We unexpectedly gain access to the table via a chain of two different role memberships, which was made possible by the fact that a non-login role, such as `role4`, was made a member of another non-login role, that is, `role5`. In most real-world cases, superusers will know very well whether such chains exist at all, so there will be no surprise; however, the goal of this recipe is to make sure that the user cannot access the table, meaning we cannot exclude less likely options. # How it works... The `\z` command, as well as its synonym, `\dp`, displays all privileges granted on tables, views, and sequences. If the `Access privileges` column is empty, it means _default privileges_ ; that is, all privileges are given to the owner (and the superusers, as always). The `\du` command shows attributes and roles that have been granted to roles. Both commands accept an optional name or pattern to restrict the display. # There's more... Here we'll cover some good practices on user and role management. # Database creation scripts For production systems, it is usually a good idea to always include `GRANT` and `REVOKE` statements in the database creation script so that you can be sure that only the right set of users has access to the table. If this is done manually, it is easy to forget. Also, in this way, we are sure that the same roles are used in development and testing environments so that there are no surprises at deployment time. The following is a sample extract from the database creation script: **CREATE TABLE table1(** **...** **);** **GRANT SELECT ON table1 TO webreaders;** **GRANT SELECT, INSERT, UPDATE, DELETE ON table1 TO editors;** **GRANT ALL ON table1 TO admins;** # Default search path It is always good practice to use a fully qualified name when revoking or granting rights; otherwise, you may be inadvertently working with the wrong table. To see the effective search path for the current database, run the following: **pguser=# show search_path ;** **search_path** **----------------** **"$user",public** **(1 row)** To see which table will be affected if you omit the schema name, run the following in psql: **pguser=# \d x** **Table "public.x"** **Column | Type | Modifiers** **--------+------+-----------** The `public.x` table name in the response contains the full name, including the schema. # Securing views It is a common technique to use a view to disclose only some parts of a secret table; however, a clever attacker can use access to the view to display the rest of the table using log messages. For instance, consider the following example: **CREATE VIEW for_the_public AS** **SELECT * FROM reserved_data WHERE importance < 10; ** **GRANT SELECT ON for_the_public TO PUBLIC;** A malicious user could define the following function: **CREATE FUNCTION f(text)** **RETURNS boolean** **COST 0.00000001** **LANGUAGE plpgsql AS $$** **BEGIN** **RAISE INFO '$1: %', $1;** **RETURN true;** **END;** **$$;** Then, they could use it to filter rows from the view: **SELECT * FROM for_the_public x WHERE f(x :: text);** The PostgreSQL optimizer will then internally rearrange the query, expanding the definition of the view and then combining the two filter conditions into a single `WHERE` clause. The trick here is that the function has been told to be very cheap using the `COST` keyword, so the optimizer will choose to evaluate that condition first. In other words, the function will access all the rows in the table, as you will realize when you see the corresponding `INFO` lines on the console if you run the code yourself. This security leak can be prevented using the `security_barrier` attribute: **ALTER VIEW for_the_public SET (security_barrier = on);** This means that the conditions that define the view will always be computed first, irrespective of cost considerations. The performance impact of this fix has been mitigated by introducing the `LEAKPROOF` attribute for functions. In short, a function that cannot leak information other than its output value can be marked as `LEAKPROOF` by a superuser so the planner will know that it's secure enough to compute the function before the other view conditions. # Granting user access to a table A user needs to have access to a table in order to perform any action on it. # Getting ready Make sure that you have the appropriate roles defined, and that privileges are revoked from the `PUBLIC` role. # How to do it... Grant access to the schema containing the table, as follows: **GRANT USAGE ON SCHEMA someschema TO somerole;** **GRANT SELECT, INSERT, UPDATE, DELETE ON someschema.sometable TO somerole;** **GRANT somerole TO someuser, otheruser;** # How it works... This sequence of commands first grants a role full access to all objects in that schema, then gives viewing (`SELECT`) and modifying (`INSERT`, `UPDATE`, and `DELETE`) rights on that table to the role, and finally grants membership in that role to two database users. # There's more... There is no requirement in PostgreSQL to have some privileges in order to have others. This means that you may well have _write-only_ tables, where you are allowed to insert but you can't select. This can be used to implement a mail-queue-like functionality, where several users post messages to one user, but they can't see what other users have posted. Alternatively, you could set up a situation where you can write a record, but you can't change or delete it. This is useful for auditing log type tables, where all changes are recorded, but cannot be tampered with. # Access to the schema We had to grant access to the schema in order to allow access to the table. This suggests that access to a given schema can be used as a fast and extreme way of preventing any access to any object in that schema. Otherwise, if you want to allow some access, you must use specific `GRANT` and `REVOKE` statements as needed. # Granting access to a table through a group role It is often desirable to give a group of users similar permissions to a group of database objects. To do this, you first assign all the permissions to a proxy role (also known as a permission group), and then assign the group to selected users, as follows: **CREATE GROUP webreaders;** **GRANT SELECT ON pages TO webreaders;** **GRANT INSERT ON viewlog TO webreaders;** **GRANT webreaders TO tim, bob;** Now both `tim` and `bob` have the `SELECT` privilege on the `pages` table and `INSERT` on the `viewlog` table. You can also add privileges to the group role after assigning it to users. Consider the following command: **GRANT INSERT, UPDATE, DELETE ON comments TO webreaders;** After running this command, both `bob` and `tim` have all of the aforementioned privileges on the `comments` table. This assumes that both the `bob` and `tim` roles were created with the `INHERIT` default setting. Otherwise, they do not automatically inherit the rights of roles but need to explicitly set their role to the granted user to make use of the privileges granted to that role. # Granting access to all objects in a schema Using this syntax, we can grant or revoke privileges on all objects of a certain kind in a specific schema: **GRANT SELECT ON ALL TABLES IN SCHEMA staging TO bob;** You still need to grant the privileges on the schema itself in a separate `GRANT` statement. # Granting user access to specific columns A user can be given access to only some table columns. # Getting ready We will continue the example in the previous recipe, so we assume that there is already a schema called `someschema` and a role called `somerole` with `USAGE` privileges on it. We create a new table on which we will grant column-level privileges: **CREATE TABLE someschema.sometable2(col1 int, col2 text);** # How to do it... We want to grant `somerole` the ability to view existing data and insert new data; we also want to give the ability to amend existing data, limited to column `col2` only. We use the following self-evident statements: **GRANT SELECT, INSERT ON someschema.sometable2 TO somerole;** **GRANT UPDATE (col2) ON someschema.sometable2 TO somerole;** Let us assume the identity of role `somerole` and test these privileges with the following commands: **SET ROLE TO somerole;** **INSERT INTO someschema.sometable2 VALUES (1, 'One');** **SELECT * FROM someschema.sometable2 WHERE col1 = 1;** As expected, we are able to insert a new row, and to view its contents. Let us now check our ability to update individual columns. We start with the second column, which we have authorized: **UPDATE someschema.sometable2 SET col2 = 'The number one';** This command returns the familiar output: **UPDATE 1** This means that we were able to successfully update that column in one row. Now we try to update the first column: **UPDATE someschema.sometable2 SET col1 = 2;** This time we get the following error message: **ERROR: permission denied for relation sometable2** This confirms that, as planned, we only authorized updates to the second column. # How it works... The `GRANT` command has been extended to allow specifying a list of columns, meaning that the privilege is granted on that list of columns, rather than on the whole table. # There's more... Consider a table `t` with columns `c1`, `c2`, and `c3`; there are two different ways of authorizing user `u` to perform the following query: **SELECT * FROM t;** The first is by granting a table-level privilege as follows: **GRANT SELECT ON TABLE t TO u;** The alternative way is by granting column-level privileges as follows: **GRANT SELECT (c1,c2,c3) ON TABLE t TO u;** Despite these two ways having overlapping effects, table-level privileges are distinct from column-level privileges, which is correct since the meaning of each is different. Granting privileges on a table means _to all columns present and future_ , while column-level privileges require the explicit indication of columns and, therefore, don't extend automatically to new columns. The way privileges work in PostgreSQL means that a given role will be allowed to perform a given action if it matches one of its privileges. This creates some ambiguity in overlapping areas. For example, consider the following command sequence: **GRANT SELECT ON someschema.sometable2 TO somerole;** **REVOKE SELECT (col1) ON someschema.sometable2 FROM** **somerole;** The outcome, somehow surprisingly, will be that `somerole` is allowed to view all the columns of that table, using the table-level privilege granted by the first command. The second command was ineffective because it tried to revoke a column-level privilege (`SELECT` on `col1`) that was never granted in the first place. # Granting user access to specific rows Recent PostgreSQL versions support granting users privileges on some rows only. # Getting ready This recipe uses **row-level security** ( **RLS** ), which is available only on PostgreSQL version 9.5 or later, so start by checking that you are not using an older version. As for the previous recipe, we assume that there is already a schema called `someschema` and a role called `somerole` with `USAGE` privileges on it. We create a new table to experiment with row-level privileges: **CREATE TABLE someschema.sometable3(col1 int, col2 text);** Row-level security must also be enabled on that table: **ALTER TABLE someschema.sometable3 ENABLE ROW LEVEL SECURITY;** # How to do it... First, we grant `somerole` the privilege to view the contents of the table, as we did in the previous recipe: **GRANT SELECT ON someschema.sometable3 TO somerole;** Let us assume that the contents of the table are as shown by the following command: **SELECT * FROM someschema.sometable3; ** **col1 | col2 ** **------+----------- ** **1 | One ** **-1 | Minus one ** **(2 rows)** In order to grant the ability to access some rows only, we create a policy specifying what is allowed and on which rows. For instance, this way we can enforce the condition that `somerole` is only allowed to select rows with positive values of `col1`: **CREATE POLICY example1 ON someschema.sometable3** **FOR SELECT** **TO somerole** **USING (col1 > 0);** The effect of this command is that the rows that do not satisfy the policy are silently skipped, as shown when `somerole` issues the following command: **SELECT * FROM someschema.sometable3; ** **col1 | col2 ** **------+----------- ** **1 | One ** **(1 row)** What if we want to introduce a policy on the `INSERT` clause? The preceding policy shows how the `USING` clause specifies which rows are affected. There is also a `WITH CHECK` clause that can be used to specify which inserts are accepted. More generally, the `USING` clause applies to pre-existing rows, while `WITH CHECK` applies to rows that are generated by the statement being analyzed. So the former works with `SELECT`, `UPDATE`, and `DELETE`, while the latter works with `INSERT` and `UPDATE`. Coming back to our example, we may want to allow only inserts where `col1` is positive: **CREATE POLICY example2 ON someschema.sometable3** **FOR INSERT** **TO somerole** **WITH CHECK (col1 > 0);** We must also remember to allow the `INSERT` commands on the table, as we did before with the `SELECT`: **GRANT INSERT ON someschema.sometable3 TO somerole;** **SELECT * FROM someschema.sometable3;** **col1 | col2** **------+-----------** **1 | One** **(1 row)** Now we are able to insert a new row, and to see it afterward: **INSERT INTO someschema.sometable3 VALUES (2, 'Two');** **SELECT * FROM someschema.sometable3;** **col1 | col2** **------+-----------** **1 | One** **2 | Two** **(2 rows)** # How it works... Row-level security policies are created and dropped on a given table using the `CREATE POLICY` syntax. The row-level security policy itself must also be enabled explicitly on the given table, because it is disabled by default. In the previous example, we needed to grant privileges on the table or on the columns, in addition to creating the row-level security policy. This is because row-level security is not one more privilege to be added to the other; rather, it works like an additional check. In this sense, it is convenient that it is off by default, so that we have to create policies only on the tables where our access logic depends on the row contents. # There's more... Row-level security can lead to very complex configurations for a variety of reasons. For instance: * An `UPDATE` policy can specify both the rows on which we act and what changes can be accepted * `UPDATE` and `DELETE` policies in some cases require visibility as granted by an appropriate `SELECT` policy * `UPDATE` policies are also applied to `INSERT ... ON CONFLICT DO UPDATE` We recommend reading the fine details at the following URL: https://www.postgresql.org/docs/current/static/ddl-rowsecurity.html # Creating a new user In this recipe, we will show you two ways of creating a new database user, one with a dedicated command-line utility, and one using SQL commands. # Getting ready To create new users, you must either be a superuser or have the `CREATEROLE` or `CREATEROLE` privilege. # How to do it... From the command line, you can run the `createuser` command: **pguser@hvost:~$ createuser bob** If you add the `--interactive` command-line option, you activate the interactive mode, which means you will be asked some questions, as follows: **pguser@hvost:~$ createuser --interactive alice** **Shall the new role be a superuser? (y/n) n** **Shall the new role be allowed to create databases? (y/n) y** **Shall the new role be allowed to create more new roles? (y/n) n** Without `--interactive`, the preceding questions get no as the default answer; you can change that with the `-s`, `-d`, and `-r` command-line options. In interactive mode, questions are asked only if they make sense. One example is when the user is a superuser; no other questions are asked because a superuser is not subject to privilege checks. Another example is when one of the preceding options is used to specify a non-default setting; the corresponding question will not be asked. # How it works... The `createuser` program is just a shallow wrapper around the executing SQL against the database cluster. It connects to the `postgres` database and then executes SQL commands for user creation. To create the same users through SQL, you can issue the following commands: **CREATE USER bob; ** **CREATE USER alice CREATEDB;** # There's more... You can check the attributes of a given user in `psql` as follows: **pguser=# \du alice** This gives the following output: **List of roles** **Role name | Attributes | Member of** **-----------+------------+-----------** **alice | Create DB | {}** The `CREATE USER` and `CREATE GROUP` commands are actually variations of `CREATE ROLE`. The `CREATE USER username;` statement is equivalent to `CREATE ROLE username LOGIN;`, and the `CREATE GROUP groupname;` statement is equivalent to `CREATE ROLE groupname NOLOGIN;`. # Temporarily preventing a user from connecting Sometimes, you need to temporarily revoke a user's connection rights without actually deleting the user or changing the user's password. This recipe presents the ways of doing this. # Getting ready To modify other users, you must either be a superuser or have the `CREATEROLE` privilege (in the latter case, only non-superuser roles can be altered). # How to do it... 1. To temporarily prevent the user from logging in, run this command: **pguser=# alter user bob nologin;** **ALTER ROLE** 2. To let the user connect again, run the following: **pguser=# alter user bob login;** **ALTER ROLE** # How it works... This sets a flag in the system catalog, telling PostgreSQL not to let the user log in. It does not kick out already connected users. # There's more... Here are some additional remarks. # Limiting the number of concurrent connections by a user The same result can be achieved by setting the connection limit for that user to `0`: **pguser=# alter user bob connection limit 0;** **ALTER ROLE** To allow `10` concurrent connections for the `bob` user, run this command: **pguser=# alter user bob connection limit 10;** **ALTER ROLE** To allow an unlimited number of connections for this user, run the following: **pguser=# alter user bob connection limit -1;** **ALTER ROLE** # Forcing NOLOGIN users to disconnect In order to make sure that all users whose login privilege has been revoked are disconnected right away, run the following SQL statement as a superuser: **SELECT pg_terminate_backend(pid)** **FROM pg_stat_activity a** **JOIN pg_roles r ON a.usename = r.rolname AND NOT rolcanlogin;** This disconnects all users who no longer are allowed to connect by terminating the backends opened by these users. # Removing a user without dropping their data When trying to drop a user who owns some tables or other database objects, you get the following error, and the user is not dropped: **testdb=# drop user bob; ** **ERROR: role "bob" cannot be dropped because some objects depend on it ** **DETAIL: owner of table bobstable ** **owner of sequence bobstable_id_seq** This recipe presents two solutions to this problem. # Getting ready To modify users, you must either be a superuser or have the `CREATEROLE` privilege. # How to do it... The easiest solution to this problem is to refrain from dropping the user and use the trick from a previous recipe to prevent the user from connecting: **pguser=# alter user bob nologin;** **ALTER ROLE** This has the added benefit of the original owner of the table being available later, if needed, for auditing or debugging purposes ( _Why is this table here? Who created it?_ ). Then you can assign the rights of the deleted user to a new user, using the following code: **pguser=# GRANT bob TO bobs_replacement;** **GRANT** # How it works... As noted previously, a user is implemented as a role with the login attribute set. This recipe works by removing that attribute from the user, which is then kept just as a role. If you really need to get rid of a user, you have to assign all ownership to another user. To do so, run the following query, which is a PostgreSQL extension to standard SQL: **REASSIGN OWNED BY bob TO bobs_replacement;** It does exactly what it says: it assigns ownership of all database objects currently owned by the `bob` role to the `bobs_replacement` role. However, you need to have privileges on both the old and the new roles to do that, and you need to do it in all databases where `bob` owns any objects, as the `REASSIGN OWNED` command works only on the current database. After this, you can delete the original user, `bob`. # Checking whether all users have a secure password PostgreSQL has no built-in facilities to make sure that you are using strong passwords. The best you can do is to make sure that all user passwords are encrypted, and that your `pg_hba.conf` file does not allow logins with a plain password. That is, always use the SCRAM-SHA-256 the login method for users, which is new in PostgreSQL 10. Any servers upgrading from earlier versions should upgrade from md5 to SCRAM-SHA-256 password encryption. For client applications connecting from trusted private networks, either real or virtual (VPN), you may use host-based access, provided you know that the machine on which the application is running is not used by some non-trusted individuals. For remote access over public networks, it may be a better idea to use SSL client certificates. # How to do it... To see which users don't yet have `SCRAM` encrypted passwords, use this query: **test2=# select usename,passwd from pg_shadow where passwd ** **not like 'SCRAM%' or passwd is null** ; **usename | passwd ** **----------+-------------- ** **tim | weakpassword ** **asterisk | md5chicken ** **(2 rows)** To enable `SCRAM-SHA-256` for encrypted passwords, use the following: **test2=# SET password_encryption = 'scram-sha-256'; ** **test2=# ALTER USER bob ENCRYPTED PASSWORD 'whatever'; ALTER USER** # How it works... The `password_encryption` parameter decides how the `ALTER USER` statement will encrypt the password. This should be set globally in the `postgresql.conf` file. Having the passwords encrypted in the database is just half of the equation. The bigger problem is making sure that users actually use passwords that are hard to guess that is, passwords such as password, secret, or test are out, and most common words are not good passwords either. If you don't trust your users to select strong passwords, you can write a wrapper application that checks the password strength and make them use that when changing passwords. A `contrib` module lets you do this for a limited set of cases (the password is sent from client to server in plain text). Visit <http://www.postgresql.org/docs/current/static/passwordcheck.html> for more information on this. # Giving limited superuser powers to specific users First, the superuser role has some privileges that can also be granted to non-superuser roles separately. To give the `bob` role the ability to create new databases, run this: **ALTER ROLE BOB WITH CREATEDB;** To give the `bob` role the ability to create new users, run the following: **ALTER ROLE BOB WITH CREATEROLE;** However, it is also possible to give ordinary users more fine-grained and controlled access to an action reserved for superusers using `security definer` functions. The same trick can also be used to pass partial privileges between different users. # Getting ready First, you must have access to the database as a superuser in order to delegate powers. Here, we assume the use of the default superuser named `postgres`. We will demonstrate two ways to make some superuser-only functionality available to a selected ordinary user. # How to do it... One thing that a superuser can do that ordinary user cannot tell PostgreSQL to copy table data from a file: **pguser@hvost:~$ psql -U postgres ** **test2 ** **... ** **test2=# create table lines(line text); ** **CREATE TABLE ** **test2=# copy lines from '/home/bob/names.txt'; ** **COPY 37 ** **test2=# SET ROLE to bob; ** **SET ** **test2= > copy lines from '/home/bob/names.txt'; ** **ERROR: must be superuser to COPY to or from a file ** **HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.** To let `bob` copy directly from the file, the superuser can write a special wrapper function for `bob`, as follows: **create or replace function copy_from(tablename text, filepath text)** **returns void** **security definer** **as** **$$** **declare** **begin** **execute 'copy ' || quote_ident(tablename)** **|| ' from ' || quote_literal(filepath) ;** **end;** **$$ language plpgsql;** It is usually a good idea to restrict the use of such a function to the intended user only: **revoke all on function copy_from( text, text) from public;** **grant execute on function copy_from( text, text) to bob;** You may also want to verify that `bob` imports files only from his home directory. Unfortunately, this solution is not completely secure against superuser privilege escalation by a malicious attacker. This is because the execution of the `COPY` command inside the function will also cause the execution, as the `postgres` user, of all side-effects, such as the execution of any `INSERT` trigger, computation of any `CHECK` constraint, computation of any functional index, and more. In other words, if the user wants to execute a given function as the superuser, it's enough to put that function inside any of the preceding functions. There are a few workarounds for this security hole, none of which are optimal. Require that the table has no triggers, `CHECK` constraints, and functional indexes. Instead of running `COPY` on the given table, create a new table with the same structure using the `CREATE newtable(LIKE oldtable)` syntax. Run the `COPY` against the new table, drop the old table, and give the new table the same name as the old table. # How it works... When a function defined with `security definer` is called, PostgreSQL changes the session's rights to those of the user who defined the function while that function is being executed. So, when `bob` executes the `copy_from(tablename, filepath)` function, `bob` is effectively promoted to superuser for the time the function is running. This behavior is similar to the `setuid` flag in Unix systems, where you can have a program that can be run by anybody (with execute access) as the owner of that program. It also carries similar risks. # There's more... There are other operations that are reserved for PostgreSQL superusers, such as setting certain parameters. # Writing a debugging_info function for developers Several of the parameters controlling logging are reserved for superusers. If you want to allow some of your developers to set logging on, you can write a function for them to do exactly that: **create or replace function debugging_info_on()** **returns void** **security definer** **as** **$$** **begin** **set client_min_messages to 'DEBUG1';** **set log_min_messages to 'DEBUG1';** **set log_error_verbosity to 'VERBOSE';** **set log_min_duration_statement to 0;** **end;** **$$ language plpgsql;** **revoke all on function debugging_info_on() from public;** **grant execute on function debugging_info_on() to bob;** You may also want to have a function go back to the default logging state by assigning `DEFAULT` to all the variables involved: **create or replace function debugging_info_reset()** **returns void** **security definer** **as** **$$** **begin** **set client_min_messages to DEFAULT;** **set log_min_messages to DEFAULT;** **set log_error_verbosity to DEFAULT;** **set log_min_duration_statement to DEFAULT;** **end;** **$$ language plpgsql;** There's no need for `GRANT` and `REVOKE` statements here, as setting them back to the default does not pose a security risk. Instead of `SET xxx to DEFAULT`, you can also use a shorter version of the same command, namely `RESET xxx`. Alternatively, you can simply end your session, as the parameters are valid only for the current session. # Auditing database access Auditing database access is a much bigger topic than you might expect because it can cover a whole range of requirements. # Getting ready First decide which of these you want and look at the appropriate subsection * What were the SQL statements executed? Auditing SQL * What were the tables accessed? Auditing table access * What were the data rows changed? Auditing data changes * What were the data rows viewed? Not described here, usually too much data Auditing just SQL produces the lowest volume of audit log information, especially if you choose to log only DDL. Higher levels accumulate more information very rapidly, so you may quickly decide not to do this in practice. Read each section to understand the benefits and trade-offs. # Auditing SQL There are two main ways to log SQL * Using the PostgreSQL `log_statement` parameter * Using the pgaudit extension's `pgaudit.log` parameter The `log_statement` parameter can be set to one of the following options: * ALL: logs all SQL statements executed at top-level * MOD: logs all SQL statements for `INSERT`, `UPDATE`, `DELETE`, and `TRUNCATE` * `ddl`: logs all SQL statements for DDL commands * NONE: no statements logged For example,to log all DDL commands, edit your `postgresql.conf` file to set the following **log_statement = 'ddl'** The `log_statement` SQL statements explicitly given in top-level commands. It is still possible to perform SQL without it being logged by this setting if you use any of the PL languages, either through DO statements or by calling a function that includes SQL statements. Was the change committed? It is possible to have some statements recorded in the log file but not visible in the database structure. Most DDL commands in PostgreSQL can be rolled back, so what is in the log is just a list of commands executed by PostgreSQL-not what was actually committed. The log file is not transactional, and it keeps commands that were rolled back. It is possible to display the transaction identifier on each log line by including `%x` in the `log_line_prefix` setting, though that has some difficulties in usage. Who made the changes? To be able to know which database user who made the DDL changes, you have to make sure that this information is logged as well. In order to do so, you may have to change the `log_line_prefix` parameter to include the `%u `format string. A recommended minimal `log_line_prefix` format string for auditing DDL is `%t %u %d`, which tells PostgreSQL to log the timestamp, database user, and database name at the start of every log line. The `pgaudit` extension provides two levels of audit logging: session and object levels. Session level has been designed to solve some of the problems of `log_statement`. `pgaudit` will log all access, even if it is not executed as a top-level statement and it will log all dynamic SQL. `pgaudit.log` can be set to include zero or more of the following settings: * `READ`: `SELECT` and `COPY` * `WRITE`: `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE` and `COPY` * `FUNCTION`: Function calls and DO blocks * `ROLE`: `GRANT`, `REVOKE`, `CREATE`/`ALTER`/`DROP ROLE` * `DDL`: All `DDL` not already included in the `ROLE` category * `MISC`: Miscelaneous – `DISCARD`, `FETCH`, `CHECKPOINT`, `VACUUM`, and so on For example, to log all DDL commands, edit your `postgresql.conf` file to set the following: **pgaudit.log = 'role, ddl'** You should set these parameters to reduce the overhead of logging: **pgaudit.log_catalog = off** **pgaudit.log_relation = off** **pgaudit.log_statement_once = on** The pgaudit extension was originally written by Simon Riggs and Abhijit Menon-Sen of 2ndQuadrant as part of the AXLE project for the EU. The next version was designed by Simon Riggs and David Steele to provide object level logging. The original version has been deprecated and is no longer available. The new version is fully supported and has been adopted by the US DoD as the tool of choice for PostgreSQL audit logging. `pgaudit` is available in binary form via `postgresql.org` repositories. # Auditing table access pgaudit can log each access to each table. So if an SQL table touches three tables then it can generate three log records, one for each table. This is important because otherwise, you might have to try and parse the SQL to find out which tables it touched, which would be difficult without access to the schema and the `search_path` settings. To make it easier to access the audit log per table, adjust these settings: **pgaudit.log_relation = on** **pgaudit.log_statement_once = off** If you want even finer grained auditing, pgaudit allows you to control which tables are audited. The user cannot tell which tables are logged and which are not, so it is possible for investigators to quietly enhance the level of logging once they are alerted to a suspect or a potential attack. First, set the role that will be used by the auditor: **pgaudit.role = 'investigator'** Then you can define logging through the privilege system, like the following command: **GRANT INSERT, UPDATE, DELETE on <vulnerable_table> TO investigator;** And remove it again when no longer required. Privileges may be set at individual column level to protect **Personally Identifiable Information** ( **PII** ). # Managing the audit log Both `log_statement` and `pgaudit` output audit log records to the server log. This is the most flexible approach since the log can be routed in various ways to ensure it is safe and separate from normal log entries. If you allow the log entries to go the normal server log you can find all occurrences of the `CREATE`, `ALTER`, and `DROP` commands in the log: **postgres@hvost:~$ egrep -i "create|alter|drop" \ ** **/var/log/postgresql/postgresql-9.6-main.log** If log rotation is in effect, you may need to use grep on older logs as well. If the available logs are too new, and you haven't saved the older logs in some other place, you are out of luck. The default settings in the `postgresql.conf` file for log rotation are as follows: **log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' ** **log_rotation_age = 1d ** **log_rotation_size = 10MB** Log rotation can also be implemented with third-party utilities. For instance, the default behavior on Debian and Ubuntu distributions is to use the `logrotate` utility to compress or delete old log files, according to the rules specified in the `/etc/logrotate.d/postgresql-common` file. To make sure you have the full history of DDL commands, you may want to set up a cron job that saves the DDL statements extracted from the main PostgreSQL log to a separate DDL audit log. You would still want to verify that the logs are not rotating too fast for this to catch all DDL statements. If you use syslog, then you can route audit messages using various OS utilities. Alternatively, you can use the pgaudit analyze extension to load data back into a special audit log databases. Various other options exist. # Auditing data changes This recipe provides different ways of collecting changes to data contained in the tables for auditing purposes. First, you must make the following decisions: * Do you need to audit all changes or only some? * What information about the changes do you need to collect? Only the fact that the data has changed? * When recording the new value of a field or tuple, do you also need to record the old value? * Is it enough to record which user made the change, or do you also need to record the IP address and other connection information? * How secure (tamper-proof) must the auditing information be? For example, does it need to be kept separately, away from the database being audited? Changes can be collected using triggers which collect new (and if needed, old) values from tuples, and save them to auditing table(s). Triggers can be added to whichever tables need to be tracked. The Audit-Trigger Extension provides a handy universal audit trigger so you do not need to write your own. It logs both old and new values of rows in any table, serialized as `hstore` data type values. The latest version of the trigger and its documentation are both available at <https://github.com/2ndQuadrant/audit-trigger>. The extension creates a schema called audit into which all the other components of the audit trigger code are placed, after which we can enable auditing on specific tables. As an example, we create standard pgbench tables by running the `pgbench` utility: **pgbench -i** Next, we connect to PostgreSQL as a superuser, and issue the following SQL to enable auditing on the `pgbench_account` table: **SELECT audit.audit_table('pgbench_accounts');** Now we perform some write activity to see how it is audited. The easiest choice is to run the `pgbench` utility again, this time to perform some transactions, as follows: **pgbench -t 1000** We expect the audit trigger to have logged the actions on `pgbench_accounts`, as we have enabled auditing on it. In order to verify this, we connect again with psql and issue the following SQL: **cookbook=# SELECT count(*) FROM audit.logged_actions; ** **count ** **------- ** **1000 ** **(1 row)** This confirms that we have indeed logged 1000 actions. Let us inspect what information is logged by reading one row of the `logged_actions` table. First, we enable expanded mode, as the query produces a large number of columns: **cookbook=# \x on** Then we issue the following command: **cookbook=# SELECT * FROM audit.logged_actions LIMIT 1; ** **-[ RECORD 1 ]-----+---------------------------------------------------------------------------------------------------------------------------------------------- ** **event_id | 1 ** **schema_name | public ** **table_name | pgbench_accounts ** **relid | 246511 ** **session_user_name | gianni ** **action_tstamp_tx | 2017-01-18 19:48:05.626299+01 ** **action_tstamp_stm | 2017-01-18 19:48:05.626446+01 ** **action_tstamp_clk | 2017-01-18 19:48:05.628488+01 ** **transaction_id | 182578 ** **application_name | pgbench ** **client_addr | ** **client_port | ** **client_query | UPDATE pgbench_accounts SET abalance = abalance + -758 WHERE aid = 86061; ** **action | U ** **row_data | "aid"= >"86061", "bid"=>"1", "filler"=>" ", "abalance"=>"0" ** **changed_fields | "abalance"= >"-758" ** **statement_only | f** # Always knowing which user is logged in In the preceding recipes, we just logged the value of the user variable in the current PostgreSQL session to log the current user role. This does not always mean that this particular user was the user that was actually authenticated at the start of the session. For example, a superuser can execute the `SET ROLE TO ...` command to set its current role to any other user or role in the system. As you might expect, non-superusers can assume only those roles that they own. It is possible to differentiate between the logged-in role and the assumed role using the `current_user `and `session_user session` variables: **postgres=# select current_user, session_user; ** **current_user | session_user ** **-------------+-------------- ** **postgres | postgres postgres=# set role to bob; SET ** **postgres= > select current_user, session_user; ** **current_user | session_user ** **-------------+-------------- ** **bob | postgres** Sometimes, it is desirable to let each user log in with their own username and just assume the role needed on a case-by-case basis. # Getting ready Prepare the required group roles for different tasks and access levels by granting the necessary privileges and options. # How to do it... The steps are as follows: 1. Create user roles with no privileges and with the NOINHERIT option: **postgres=# create user alice noinherit; CREATE ROLE ** **postgres=# create user bob noinherit; CREATE ROLE** 2. Then, create roles for each group of privileges that you need to assign: **postgres=# create group sales; CREATE ROLE ** **postgres=# create group marketing; CREATE ROLE ** **postgres=# grant postgres to marketing; GRANT ROLE** 3. Now grant each user the roles it may need: **postgres=# grant sales to alice; GRANT ROLE ** **postgres=# grant marketing to alice; GRANT ROLE ** **postgres=# grant sales to bob; GRANT ROLE** After you do this, the users `alice` and `bob` have no rights after login, but they can assume the sales role by executing `SET ROLE TO` sales, and `alice` can additionally assume the superuser role. # How it works... If a role or user is created with the `NOINHERIT` option, this user will not automatically get the rights that have been granted to the other roles that have been granted to itself. To claim these rights from a specific role, it has to set its role to one of those other roles. In some sense, this works a bit like the `s`u (set user) command in Unix and Linux systems. That is, you (may) have the right to become that user, but you do not automatically have the rights of the aforementioned user. This setup can be used to get better audit information, as it lets you know who the actual user was. If you just allow each user to log in as the role needed for a task, there is no good way to know later which of the users was really logged in as clerk1 when this $100,000 transfer was made. # There's more... The `SET ROLE` command works both ways; that is, you can both gain and lose privileges. A superuser can set its role to any user defined in the system. To get back to your original login role, just use `RESET ROLE`. # Not inheriting user attributes Not all rights come to users via `GRANT` commands. Some important rights are given via user attributes (`SUPERUSER`, `CREATEDB`, and `CREATEROL`E), and these are never inherited. If your user has been granted a superuser role and you want to use the superuser powers of this granted role, you have to use `SET ROLE To mysuperuserrole`; before anything that requires the superuser attribute to be set. In other words, the user attributes always behave as if the user had been a `NOINHERIT` user. # Integrating with LDAP This recipe shows you how to set up your PostgreSQL system so that it uses the **Lightweight Directory Access Protocol** ( **LDAP** ) for authentication. # Getting ready Ensure that the usernames in the database and your LDAP server match, as this method works for user authentication checks of users who are already defined in the database. # How to do it... In the PostgreSQL authentication file, `pg_hba.conf`, we define some address ranges to use LDAP as an authentication method, and we configure the LDAP server for this address range: **host all all 10.10.0.1/16 ldap \ ** **ldapserver=ldap.our.net ldapprefix="cn=" ldapsuffix=",** **dc=our,dc=net"** # How it works... This setup makes the PostgreSQL server check passwords from the configured LDAP server. User rights are not queried from the LDAP server but have to be defined inside the database using the `ALTER USER`, `GRANT`, and `REVOKE` commands. # There's more... We have shown how PostgreSQL can use an LDAP server for password authentication. It is also possible to use some more information from the LDAP server, as shown in the next two examples. # Setting up the client to use LDAP If you are using the `pg_service.conf` file to define your database access parameters, you may define some to be queried from the LDAP server by including a line similar to the following in your `pg_service.conf` file: **ldap://ldap.mycompany.com/dc=mycompany,dc=com?uniqueMember?one?(cn=mydb)** # Replacement for the User Name Map feature Although we cannot use the User Name Map feature with LDAP, we can achieve a similar effect on the LDAP side. Use `ldapsearchattribute` and the _search + bind_ mode to retrieve the PostgreSQL role name from the LDAP server. # See also * For server setup, including the search + bind mode, visit http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-LDAP * For client setup, visit <http://www.postgresql.org/docs/current/static/libpq-ldap.html> # Connecting using SSL Here, we will demonstrate how to enable PostgreSQL to use SSL for the protection of database connections by encrypting all of the data passed over that connection. Using SSL makes it much harder to sniff the database traffic, including usernames, passwords, and other sensitive data. Otherwise, everything that is passed unencrypted between a client and the database can be observed by someone listening to a network somewhere between them. An alternative to using SSL is running the connection over a **virtual private network** ( **VPN** ). Using SSL makes the data transfer on the encrypted connection a little slower, so you may not want to use it if you are sure that your network is safe. The performance impact can be quite large if you are creating lots of short connections, as setting up an SSL connection is quite CPU-heavy. In this case, you may want to run a local connection pooling solution, such as PgBouncer, to which the client connects without encryption, and then configure PgBouncer for server connections using SSL. Older versions of PgBouncer did not support SSL; the solution was to channel server connections through stunnel, as described in the PgBouncer FAQ at https://pgbouncer.github.io/faq.html. # Getting ready Get, or generate, an SSL server key and certificate pair for the server, and store these in the `data` directory of the current database instance as the `server.key` and `server.crt` files. On some platforms, this is unnecessary; the key and certificate pair may already be generated by the packager. For example, on Ubuntu, PostgreSQL is set up to support SSL connections by default. # How to do it... 1. Set `ssl = on` in `postgresql.conf` and restart the database # How it works... If `ssl = on` is set, then PostgreSQL listens to both plain and SSL connections on the same port (`5432` by default) and determines the type of connection from the first byte of a new connection. Then, it proceeds to set up an SSL connection if an incoming request asks for it. # There's more... You can leave the choice of whether or not to use SSL to the client, or you can force SSL usage from the server's side. To let the client choose, use a line of the following form in the `pg_hba.conf` file: **host database user IP-address/IP-mask auth-method** If you want to allow only SSL clients, use the `hostssl` keyword instead of `host`. The contents of `pg_hba.conf` can be seen using the view `pg_hba_file_rules`. The following fragment of `pg_hba.conf` enables both non-SSL and SSL connections from the `192.168.1.0/24` local subnet, but requires SSL from everybody accessing the database from other networks: **host all all 192.168.1.0/24 md5** **hostssl all all 0.0.0.0/0 md5** # Getting the SSL key and certificate For web servers, you must usually get your SSL certificate from a recognized **certificate authority** ( **CA** ), as most browsers complain if the certificate is not issued by a known CA. They warn the user of the most common security risks and require confirmation before connecting to a server with a certificate issued by an unknown CA. For your database server, it is usually sufficient to generate the certificate yourself, using OpenSSL. The following commands generate a self-signed certificate for your server: **openssl genrsa 2048 > server.key** **openssl req -new -x509 -key server.key -out server.crt** Read more on X.509 keys and certificates in OpenSSL's _HOWTO's_ pages at <https://github.com/openssl/openssl/tree/master/doc/HOWTO>. # Setting up a client to use SSL The behavior of the client application regarding SSL is controlled by an environment variable, `PGSSLMODE`. This can have the following values, as defined in the official PostgreSQL documentation: **SSL mode** | **Eavesdropping protection** | **MITM protection** | **Statement** ---|---|---|--- disabled | No | No | I don't care about security, and I don't want to pay the overhead of encryption. allow | Maybe | No | I don't care about security, but I will pay the overhead of encryption if the server insists on it. prefer | Maybe | No | I don't care about encryption, but I wish to pay the overhead of encryption if the server supports it. require | Yes | No | I want my data to be encrypted, and I accept the overhead. I trust that the network will ensure that I always connect to the server I want. verify-ca | Yes | Depends on the CA policy | I want my data encrypted, and I accept the overhead. I want to be sure that I connect to a server that I trust. verify-full | Yes | Yes | I want my data encrypted, and I accept the overhead. I want to be sure that I connect to a server I trust, and that the server is the one I specify. **MITM** in the preceding table means **man-in-the-middle** attack; that is, someone posing as your server-perhaps by manipulating DNS records or IP routing tables-but who actually just observes and forwards the traffic. For this to be possible with an SSL connection, this someone needs to have obtained a certificate that your client considers valid. # Checking server authenticity The last two SSL modes allow you to be reasonably sure that you are actually talking to your server by checking the SSL certificate presented by the server. In order to enable this useful security feature, the following files must be available on the client side. On Unix systems, they are located in the client home directory, in a subdirectory named `~/.postgresql`. On Windows, they are in `%APPDATA%\postgresql\`. **File** | **Contents** | **Effect** ---|---|--- `root.crt` | Certificates of one or more trusted CAs | PostgreSQL verifies that the server certificate is signed by a trusted CA `root.crl` | Certificates revoked by CAs | The server certificate must not be on this list Only the `root.crt` file is required for the client to authenticate the server certificate. It can contain multiple root certificates against which the server certificate is compared. # Using SSL certificates to authenticate This recipe shows you how to set up your PostgreSQL system so that it _requires_ clients to present a valid X.509 certificate before allowing them to connect. This can be used as an additional security layer to use double authentication, where the client must both have a valid certificate to set up the SSL connection and also know the database user's password. It can also be used as the sole authentication method, where the PostgreSQL server will first verify the client connection using the certificate presented by the client, and then retrieve the username from the same certificate. # Getting ready Get, or generate, a root certificate and a client certificate to be used by the connecting client. # How to do it... For testing purposes, or for just setting up a single trusted user, you can use a self-signed certificate: **openssl genrsa 2048 > client.key** **openssl req -new -x509 -key server.key -out client.crt** On the server, set up a line in `pg_hba.conf` file with the `hostssl` method and the `clientcert` option set to `1`: **hostssl all all 0.0.0.0/0 md5 clientcert=1** Put the client root certificate in the `root.crt` file in the server data directory `($PGDATA/root.crt`). This file may contain multiple trusted root certificates. If you are using a central certificate authority, you probably also have a certificate revocation list, which should be put in a `root.crl` file and regularly updated. On the **client** , put the client's private key and certificate in `~/.postgresql/postgresql.key` and `~/.postgresql/postgresql.crt`. Make sure that the private key file is not world-readable or group-readable by running the following command: **chmod 0600 ~/.postgresql/postgresql.key** On the Windows client, the corresponding files are `%APPDATA%\postgresql\postgresql.key` and `%APPDATA%\postgresql\postgresql.crt`. No permission check is done, as the location is considered secure. If the client certificate is not signed by the root CA but by an intermediate CA, then all the intermediate CA certificates up to the root certificate must be placed in the `postgresql.crt` file as well. # How it works... If the `clientcert=1` option is set for a `hostssl` row in `pg_hba.conf`, then PostgreSQL accepts only connection requests accompanied by a valid certificate. The validity of the certificate is checked against certificates present in the `root.crt` file in the server data directory. If there is a `root.crl` file, then the presented certificate is looked for in this file and, if found, is rejected. After the client certificate is validated and the SSL connection is established, the server proceeds to validate the actual connecting user using whatever authentication method is specified in the corresponding `hostssl` line. In the following example, clients from a special address can connect as any user when using an SSL certificate, and they must specify a `SCRAM-SHA-256` password for non-SSL connections. Clients from all the other addresses must present a certificate and use `md5` password authentication: **host all all 10.10.10.10/32 md5** **hostssl all all 10.10.10.10/32 trust clientcert=1** **hostssl all all all scram-sha-256 clientcert=1** # There's more... In this section, we provide some additional content, describing an important optimization for an SSL-only database server, plus two extensions of the basic SSL configuration. # Avoiding duplicate SSL connection attempts In the _Setting up a client to use SSL_ section of the previous recipe, _Connecting using SSL_ , we saw how the client's SSL behavior is affected by environment variables. Depending on how the `SSLMODE` environment variable is set on the client (either via compile-time settings, the `PGSSLMODE` environment variable, or the `sslmode` connection parameter), the client may attempt to connect without SSL first, and then attempt an SSL connection only after the server rejects the non-SSL connection. This duplicates a connection attempt every time a client accesses an SSL-only server. To make sure that the client tries to establish an SSL connection on the first attempt, `SSLMODE` must be set to `prefer` or higher. # Using multiple client certificates You may sometimes need different certificates to connect to different PostgreSQL servers. The location of the certificate and key files in `postgresql.crt` and `postgresql.key` in the table from the _Checking server authenticity_ section is just the default, and can be overridden by specifying alternative file paths using the `sslcert` and `sslkey` connection parameters or the `PGSSLCERT` and `PGSSLKEY` environment variables. # Using the client certificate to select the database user It is possible to use the client certificate for two purposes at once: proving that the connecting client is a valid one, and selecting the database user to be used for the connection. For this, you set the authentication method to `cert` in the `hostssl` line: **hostssl all all 0.0.0.0/0 cert** As you can see, the `clientcert=1` option used with `hostssl` to require client certificates is no longer required, being implied by the `cert` method itself. When using the `cert` authentication method, a valid client certificate is required, and the `cn` (short for, common name) attribute of the certificate will be compared to the requested database username. The login will be allowed only if they match. It is possible to use a User Name Map to map the common names in the certificates to database usernames by specifying the `map` option: **hostssl all all 0.0.0.0/0 cert map=x509cnmap** Here, `x509cnmap` is the name that we have arbitrarily chosen for our mapping. More details on User Name Maps are provided in the next recipe, _Mapping external usernames to database roles_. # See also To understand more about SSL in general, and the _OpenSSL library_ used by PostgreSQL in particular, visit http://www.openssl.org, or get a good book about SSL. To get started with the generation of simple SSL keys and certificates, see https://github.com/openssl/openssl/blob/master/doc/HOWTO/certificates.txt. There is also a nice presentation named _Encrypted PostgreSQL_ explaining these issues at PGCon 2009. The slides are available at http://www.pgcon.org/2009/schedule/events/120.en.html. # Mapping external usernames to database roles In some cases, the authentication username is different from the PostgreSQL username. For instance, this can happen when using an external system for authentication, such as certificate authentication, as described in the previous recipe, or any other external or single sign-on system authentication method from <http://www.postgresql.org/docs/current/static/auth-methods.html> (GSSAPI, SSPI, Kerberos, Radius, or PAM). Or you may just need to enable an externally authenticated user to connect as multiple database users. In such cases, you can specify rules to map the external username to the appropriate database role. # Getting ready Prepare a list of usernames from the external authentication system and decide which database users they are allowed to connect as-that is, which external users map to which database users. # How to do it... Create a `pg_ident.conf` file in the usual place (`PGDATA`), with lines in the following format: **map-name system-username database-username** Here, `map-name` is the value of the `map` option from the corresponding line in `pg_hba.conf`, `system-username` is the username that the external system authenticated the connection as, and `database-username` is the database user this system user is allowed to connect as. The same system user may be allowed to connect as multiple database users, so this is not a 1:1 mapping, but rather a list of allowed database users for each system user. If `system-username` starts with a slash (`/`), then the rest of it is treated as a regular expression rather than a directly matching string, and it is possible to use the `\1` string in `database-username` to refer to the part captured by the parentheses in the regular expression. For example, consider the following lines: **salesmap /^(.*)@sales\.comp\.com$ \1** **salesmap /^(.*)@sales\.comp\.com$ sales** **salesmap manager@sales.comp.com auditor** These will allow any user authenticated with a `@sales.comp.com` e-mail address to connect both as a database user equal to the name before the `@` sign in their e-mail address, and as the `sales` user. They will additionally allow `manager@sales.comp.com` to connect as the auditor user. Then edit the `pg_hba.conf` line to specify the `map=salesmap` option # How it works... After authenticating the connection using an external authentication system, PostgreSQL will usually proceed to check that the externally authenticated username matches the database username that the user wishes to connect as, and rejects the connection if these two do not match. If there is a `map=` parameter specified for the current line in `pg_hba.conf`, then the system will scan the map line by line, and will let the client proceed with connecting if a match is found. # There's more... By default, the map file is called `pg_ident.conf` (because it was first used for the `ident` authentication method). Nowadays, it is possible to change the name of this file via the `ident_file` configuration parameter in `postgresql.conf`. It can also be located outside the `PGDATA` directory by setting `ident_file` to a full path. A relative path can also be used, but since it is relative to where the `postgres` process is started, this is usually not a good idea. # Encrypting sensitive data This recipe shows you how to encrypt data using the `pgcrypto` contrib package. # Getting ready Make sure you (and/or your database server) are in a country where encryption is not illegal-it still is in some countries. In order to create and manage PGP keys, you also need the well-known `GnuPG` command-line utility, which is available on practically all distributions. `pgcrypto` is part of the contrib collection. Starting from version 10, on Debian and Ubuntu is part of the main `postgresql-10` server package, while in previous versions there was a separate package, for example, `postgresql-contrib-9.6`. Install it on the database in which you want to use it, following the _Adding an external module to PostgreSQL_ recipe from Chapter 3, _Configuration_. You also need to have PGP keys set up: **pguser@laptop:~$ gpg --gen-key** Answer some questions here (the defaults are OK, unless you are an expert), select the key type as `DSA and Elgamal`, and enter an empty password. Now, export the keys: **pguser@laptop:~$ gpg -a --export "PostgreSQL User (test key for PG Cookbook) <pguser@somewhere.net>" > public.key ** **pguser@laptop:~$ gpg -a --export-secret-keys "PostgreSQL User (test key for** **PG Cookbook) <pguser@somewhere.net>" > secret.key** Make sure only you and the `postgres` database user have access to the secret key: **pguser@laptop:~$ sudo chgrp postgres secret.key ** **pguser@laptop:~$ chmod 440 secret.key ** **pguser@laptop:~$ ls -l *.key ** **-rw-r--r-- 1 pguser pguser 1718 2016-03-26 13:53 public.key ** **-r--r----- 1 pguser postgres 1818 2016-03-26 13:54 secret.key** Last, but not least, make a copy of the public and the secret key; if you lose them, you'll lose the ability to encrypt/decrypt. # How to do it... To ensure that the secret keys are never visible in database logs, write a wrapper function to get the keys from the file. You need to do it in an untrusted embedded language, such as PL/PythonU, as only untrusted languages can access the filesystem. You need to be a PostgreSQL superuser in order to create functions in untrusted languages. It's not difficult to write a PostgreSQL function that reads a text file. For convenience, here is an example that requires PL/PythonU: **create or replace function get_my_public_key() returns text as $$** **return open('/home/pguser/public.key').read()** **$$** **language plpythonu;** **revoke all on function get_my_public_key() from public;** **create or replace function get_my_secret_key() returns text as $$** **return open('/home/pguser/secret.key').read()** **$$** **language plpythonu;** **revoke all on function get_my_secret_key() from public;** This can also be fully implemented in PL/pgSQL using the built-in PostgreSQL system function, `pg_read_file` (filename), and you don't have to bother with PL/PythonU at all. However, to use this function, you must place the files in the `data` directory as required by that function for additional security, so the database superuser is not allowed to access the rest of the filesystem directly. If you don't want other database users to be able to see the keys, you also need to write wrapper functions for encryption and decryption, and then give access to these wrapper functions to end users. The `encryption` function can be like this: **create or replace function encrypt_using_my_public_key(** **cleartext text,** **ciphertext out bytea** **)** **AS $$** **DECLARE** **pubkey_bin bytea;** **BEGIN** **-- text version of public key needs to be passed through function dearmor() to get to raw key** **pubkey_bin := dearmor(get_my_public_key());** **ciphertext := pgp_pub_encrypt(cleartext, pubkey_bin);** **END;** **$$ language plpgsql security definer;** **revoke all on function encrypt_using_my_public_key(text) from public;** **grant execute on function encrypt_using_my_public_key(text) to bob;** The `decryption` function can be as follows: **create or replace function decrypt_using_my_secret_key(** **ciphertext bytea,** **cleartext out text** **)** **AS $$** **DECLARE** **secret_key_bin bytea;** **BEGIN** **-- text version of secret key needs to be passed through function dearmor() to get to raw binary key** **secret_key_bin := dearmor(get_my_secret_key());** **cleartext := pgp_pub_decrypt(ciphertext, secret_key_bin);** **END;** **$$ language plpgsql security definer;** **revoke all on function decrypt_using_my_secret_key(bytea) from public;** **grant execute on function decrypt_using_my_secret_key(bytea) to bob;** Finally, we test the encryption: **test2=# select encrypt_using_my_public_key('X marks the spot!');** This function returns a `bytea` (that is, raw binary) result that looks something like the following: **encrypt_using_my_public_key | ** **\301\301N\003\223o\215\2125\203\252;\020\007\376-z\233\211H...** To see that it actually works, you must go both ways: **test2=# select decrypt_using_my_secret_key(encrypt_using_my_public_key('X marks the spot!')); ** **decrypt_using_my_secret_key ** **----------------------------- ** **X marks the spot! ** **(1 row)** Yes, we got back our initial string! # How it works... What we have done here is the following: * Hidden the keys from non-superuser database users * Provided wrappers for authorized users to use encryption and decryption functionalities To ensure that your sensitive data is not stolen while in transit between the client and the database server, make sure you connect to PostgreSQL either using an SSL-encrypted connection or from localhost. You also have to trust your server administrators and all the other users with superuser privileges to be sure that your encrypted data is safe. And, of course, you must trust the safety of the entire environment; PostgreSQL can decrypt the data, so any other user or software that has access to the same files can do the same. # There's more... A higher level of security is possible, with more complex procedures and architecture, as shown in the next sections. We also mention a limited `pgcrypto` version that does not use OpenSSL. # For really sensitive data For some data, you wouldn't want to risk keeping the decryption password on the same machine as the encrypted data. In those cases, you can use **public-key cryptography** , also known as **asymmetric cryptography** , and carry out only the encryption part on the database server. This also means that you only have the encryption key on the database host, and not the key needed for decryption. Alternatively, you can deploy a separate, extra-secure encryption server in your server infrastructure that provides just the encrypting and decrypting functionality as a remote call. This solution is secure because, in asymmetric cryptography, the private (that is, decryption) key cannot be derived from the corresponding public (that is, encryption) key, hence the names `public` and `private`, which denote the appropriate dissemination policies. If you wish to prove the identity of the author of a file, the correct method is to use a digital signature, which is an entirely different application of cryptography. Note that this is not currently supported by `pgcrypto`, so you must implement your own methods as C functions or in a procedural language capable of using cryptographic libraries. # For really, really, really sensitive data! For even more sensitive data, you may never want the data to leave the client computer unencrypted. Therefore, you need to encrypt the data before sending it to the database. In that case, PostgreSQL receives already encrypted data, and never sees the unencrypted version. This also means that the only useful indexes you can have are for use in `WHERE encrypted_column = encrypted_data` and for ensuring uniqueness. Even these forms can be used only if the encryption algorithm always produces the same ciphertext (output) for the same plaintext (input), which is true only for weaker encryption algorithms. For example, it would be easy to determine the age or sex of a person if the same value is always encrypted into the same ciphertext. To avoid this vulnerability, strong encryption algorithms are able to produce a different ciphertext for the same value. The versions of `pgcrypto` are usually compiled to use the _OpenSSL library_ (http://www.openssl.org). If, for some reason, you don't have OpenSSL, or just don't want to use it, it is possible to compile `pgcrypto` without it, with a smaller number of supported encryption algorithms and a slightly reduced performance. # See also * The page on `pgcrypto` in the PostgreSQL online documentation is available at http://www.postgresql.org/docs/current/static/pgcrypto.html * The OpenSSL web page can be accessed at http://www.openssl.org/ * The _GNU Privacy Handbook_ can be read at http://www.gnupg.org/gph/en/manual.html # Database Administration In this chapter, we will cover the following recipes: * Writing a script that either succeeds entirely or fails entirely * Writing a psql script that exits on the first error * Using psql variables * Placing query output into psql variables * Writing a conditional psql script * Investigating a psql error * Performing actions on many tables * Adding/removing columns on a table * Changing the data type of a column * Changing the definition of a data type * Adding/removing schemas * Moving objects between schemas * Adding/removing tablespaces * Moving objects between tablespaces * Accessing objects in other PostgreSQL databases * Accessing objects in other foreign databases * Updatable views * Using materialized views # Introduction In Chapter 5, _Tables and Data_ , we looked at the contents of tables and various complexities. Now we'll turn our attention to larger administration tasks that we need to perform from time to time, such as creating things, moving things around, storing things neatly, and removing them when they're no longer required. The most sensible way to perform major administrative tasks is to write a script to do what you think is required. If you're unsure, you can always run the script on a system test server, and then run it again on the production server once you're happy. Manically typing commands against production database servers isn't wise. Worse, using an admin tool can lead to serious issues if that tool doesn't show you the SQL you're about to execute. If you haven't dropped your first live table yet, don't worry; you will. Perhaps you might want to read Chapter 11, _Backup and Recovery_ , first, eh? Back it up using scripts. Scripts are great because you can automate common tasks, and there's no need to sit there with a mouse, working your way through a hundred changes. If you're drawn to the discussion about the command line versus GUI, then my thoughts and reasons are completely orthogonal to that. I want to encourage you to avoid errors and save time by repetitive and automatic execution of small administration programs or scripts. If it were safe or easy to do the equivalent of mouse movements in a script, then that would be an option; but it's definitely not. The only viable way to write a repeatable script is by writing text SQL commands. Which scripting tool to use is a more interesting debate. We consider `psql` here because if you've got PostgreSQL, then you've certainly got it, without needing to install additional software. So we're on solid ground to provide examples that way. On to the recipes! First, we'll start by looking at some scripting techniques that are valuable in PostgreSQL. This will make you more accurate and repeatable and free up time for other cool things. # Writing a script that either succeeds entirely or fails entirely Database administration often involves applying a coordinated set of changes to the database. One of PostgreSQL's great strengths is the transaction system, wherein almost all actions can be executed inside a transaction. This allows us to build a script with many actions that will either all succeed or all fail. This means that if any of these actions fail, then all the other actions in the script are rolled back and never become visible to any other user, which can be critically important on a production system. This property is referred to as _atomicity_ in the sense that the script is intended as a single unit that cannot be split, and this is the meaning of the _A_ in the _ACID_ properties of database transactions. Transactions definitely apply to **Data Definition Language** ( **DDL** ), which refers to the set of SQL commands used to define, modify, and delete database objects. The term DDL goes back many years, but it persists because that subset is a useful short name for the commands that most administrators need to execute: `CREATE`, `ALTER`, `DROP`, and so on. Although most commands in PostgreSQL are transactional, there are a few that cannot be. The most common example is of commands that use sequences. They cannot be transactional because when a new sequence number is allocated, the effect of having _consumed_ that number must become visible immediately, without waiting for that transaction to be committed. Otherwise, the same number will be given to another transaction, which is contrary to what sequences are supposed to do. # How to do it... The basic way to ensure that we get all commands successful or none at all is to literally wrap our script into a transaction, as follows: **BEGIN;** **command 1;** **command 2;** **command 3;** **COMMIT;** Writing a transaction control command involves editing the script, which you may not want to do or even have access to do. There are, however, other ways as well. From `psql`, you can do this by simply using the `-1` or `--single-transaction` command-line options, as follows: **bash $ psql -1 -f myscript.sql ** **bash $ psql --single-transaction -f myscript.sql** The `-1` option is short, but I recommend using `--single-transaction`, as it's much clearer which option is being selected. # How it works... The entire script will fail if, at any point, one of the commands gives an error (or higher) message. Almost all of the SQL used to define objects (DDL) allows a way to avoid throwing errors. More precisely, commands that begin with the `DROP` keyword have an `IF EXISTS` option. This allows you to execute the `DROP` keyword, whether or not the object already exists. Thus, by the end of the command, that object will not exist: **DROP VIEW IF EXISTS cust_view;** Similarly, most commands that begin with the `CREATE` keyword have the optional `OR REPLACE` suffix. This allows the `CREATE` statement to overwrite the definition if one already exists, or add the new object if it didn't exist yet, like this: **CREATE OR REPLACE VIEW cust_view AS** **SELECT * FROM cust;** In the cases where both the `DROP IF EXISTS` and `CREATE OR REPLACE` options exist, you might think that `CREATE OR REPLACE` is usually sufficient. However, if you change the output definition of a function or a view, then using `OR REPLACE` is not sufficient. In that case, you must use `DROP` and recreate it, as shown in the following example: **postgres=# CREATE OR REPLACE VIEW cust_view AS** **SELECT col as title1 FROM cust; ** **CREATE VIEW ** **postgres=# CREATE OR REPLACE VIEW cust_view** **AS SELECT col as title2 FROM cust; ** **ERROR: cannot change name of view column "title1" to "title2"** Note also that `CREATE INDEX` does not have an `OR REPLACE` option. If you run it twice, you'll get two indexes on your table, unless you specifically name the index. There is a `DROP INDEX IF EXISTS` option, but it may take a long time to drop and recreate an index. An index exists just for the purpose of optimization, and it does not change the actual result of any query, so this different behavior is actually very convenient. This is also reflected in the fact that the SQL standard doesn't mention indexes at all, even though they exist in practically all database systems, because they do not affect the logical layer. PostgreSQL does not support nested transaction control commands, which can lead to unexpected behavior. For instance, consider the following code, written in a _nested transaction_ style: **postgres=# BEGIN; ** **BEGIN ** **postgres=# CREATE TABLE a(x int); ** **CREATE TABLE ** **postgres=# BEGIN; ** **WARNING: there is already a transaction in progress ** **BEGIN ** **postgres=# CREATE TABLE b(x int); ** **CREATE TABLE ** **postgres=# COMMIT; ** **COMMIT ** **postgres=# ROLLBACK; ** **NOTICE: there is no transaction in progress ** **ROLLBACK** A hypothetical author of such code probably meant to create table `a` first, and then create table `b`. Then, they changed their mind and rolled back both the _inner_ transaction and the _outer_ transaction. However, what PostgreSQL does is discard the second `BEGIN` statement so that the `COMMIT` statement is matched with the first `BEGIN` statement and the _inner_ transaction becomes a top-level transaction. Hence, right after the `COMMIT` statement, we are outside a transaction block, so the next statement is assigned its own transaction. When `ROLLBACK` is issued as the next statement, PostgreSQL notices that the transaction is actually empty. The danger in this particular example is that the user inadvertently committed a transaction, thus waving the right to roll it back, although we should say that a careful user would have noticed the warning and paused to think before going ahead. From this example, you learn a valuable lesson: if you have used transaction control commands in your script, then wrapping them again in a higher-level script or command can cause problems of the worst kind, such as committing stuff that you wanted to roll back. This is important enough to deserve a boxed warning. PostgreSQL accepts nested transactional control commands, but does not act on them. After the first commit, the commands will be assumed to be transactions in their own right and will persist should the script fail. Be careful! # There's more... The following commands cannot be included in a script that uses transactions in the way we just described: * `CREATE DATABASE`/`DROP DATABASE` * `CREATE TABLESPACE`/`DROP TABLESPACE` * `CREATE INDEX CONCURRENTLY` * `VACUUM` * `REINDEX DATABASE`/`REINDEX SYSTEM` * `CLUSTER` None of these actions need to be run manually on a regular basis within complex programs, so this shouldn't be a problem for you. Note also that these commands do not substantially alter the _logical_ content of a database; that is, they don't create new user tables or alter any rows, so there's less need to use them inside complex transactions. While PostgreSQL does not support nested transaction commands, it supports the notion of `SAVEPOINT`, which can be used to achieve the same behavior. Suppose we wanted to implement the following pseudocode: **(begin transaction T1)** **(statement 1)** **(begin transaction T2)** **(statement 2)** **(commit transaction T2)** **(statement 3)** **(commit transaction t1)** The effect we seek has the following properties: * If `statements 1` and `3` succeed, and `statement 2` fails, then `statements 1` and `3` will be committed * If all three statements succeed, then they will all be committed * Otherwise, no statement will be committed These properties also hold with the following PostgreSQL commands: **BEGIN; ** **– (statement 1) ** **SAVEPOINT T2; ** **– (statement 2) ** **RELEASE SAVEPOINT T2; /* we assume that statement 2 does not fail */ ** **– (statement 3) ** **COMMIT;** This form, as noted in the code, applies only if `statement 2` does not fail. If it fails, we must replace `RELEASE SAVEPOINT` with `ROLLBACK TO SAVEPOINT`, or we will get an error. This is a slight difference with top-level transaction commands; a `COMMIT` statement is silently converted in a `ROLLBACK` when the transaction is in a failed state. # Writing a psql script that exits on the first error The default mode for the `psql` script tool is to continue processing when it finds an error. This sounds dumb, but it exists for historical compatibility only. There are some easy and mostly permanent ways to avoid this, so let's look at them. # Getting ready Let's start with a simple script, with a command we know will fail: **$ $EDITOR test.sql ** **mistake1; ** **mistake2; ** **mistake3;** Execute the following script using `psql` to see what the results look like: **$ psql -f test.sql ** **psql:test.sql:1: ERROR: syntax error at or near "mistake1" ** **LINE 1: mistake1; ** **^ ** **psql:test.sql:2: ERROR: syntax error at or near "mistake2" ** **LINE 1: mistake2; ** **^ ** **psql:test.sql:3: ERROR: syntax error at or near "mistake3" ** **LINE 1: mistake3; ** **^** # How to do it... 1. To exit the script on the first error, we can write the following command: **$ psql -f test.sql -v ON_ERROR_STOP=on ** **psql:test.sql:1: ERROR: syntax error at or near "mistake1" ** **LINE 1: mistake1; ** **^** 2. Alternatively, we can edit the `test.sql` file with the initial line shown here: **$ $EDITOR test.sql ** **\set ON_ERROR_STOP on ** **mistake1; ** **mistake2; ** **mistake3;** 3. Note that the following command will _not_ work because we have missed the crucial `ON` value: **$ psql -f test.sql -v ON_ERROR_STOP** # How it works... The `ON_ERROR_STOP` variable is a `psql` special variable that controls the behavior of `psql` as it executes in script mode. When this variable is set, a SQL error will generate an OS return code 3, whereas other OS-related errors will return code 1. # There's more... You can place some `psql` commands in a profile that will get executed when you run `psql`. Adding `ON_ERROR_STOP` to your profile will ensure that this setting is applied to all `psql` sessions: **$ $EDITOR ~/.psqlrc ** **\set ON_ERROR_STOP** You can forcibly override this, and request `psql` to execute without a profile using `-X`. This is probably the safest thing to do for batch execution of scripts, so they always work in the same way, irrespective of the local settings. `ON_ERROR_STOP` is one of some special variables that affect the way psql behaves. The full list is available at the following URL: <https://www.postgresql.org/docs/10/static/app-psql.html#APP-PSQL-VARIABLES> # Using psql variables In the previous recipe, we have seen how to use the `ON_ERROR_STOP` variable. Here we show how to work with any variable, including user-defined ones. # Getting ready As an example, we create a script that does some work on a given table. We will keep it simple, because we just want to show how variables work. For instance, we might want to add a text column to a table, and then set it to a given value. So we write the following lines into a file called `vartest.sql` : **ALTER TABLE mytable ADD COLUMN mycol text;** **UPDATE mytable SET mycol = 'myval';** The script can be run as follows: **psql -f vartest.sql** # How to do it... We change `vartest.sql` as follows: **\set tabname mytable** **\set colname mycol** **\set colval 'myval'** **ALTER TABLE :tabname ADD COLUMN :colname text;** **UPDATE :tabname SET :colname = :'colval';** # How it works... What do these changes mean? We have defined three variables, setting them respectively to the table name, column name and column value. Then we have replaced the mentions of those specific values with the name of the variable preceded by a colon, which in psql means "replace with the value of this variable". In the case of colval, we have also surrounded the variable name by single quotes, meaning "treat the value as a string". If we want `vartest.sql` to add a different column, we just have to make one change to the top of the script, where all variables are conveniently set. Then the new column name will be used. # There's more... This was just one way to define variables. Another is to indicate them in the command line, when running the script: **psql -v tabname=mytab2 -f vartest.sql** Variables can also be set interactively. The following line will prompt the user, and then set the variable to whatever is typed before hitting _Enter_ : **\prompt 'Insert the table name: ' tabname** In the next recipe, we will see how to set variables using an SQL query. # Placing query output into psql variables It is also possible to store some values produced by a query into variables, for instance to reuse them later in other queries. In this recipe we demonstrate this approach with a concrete example. # Getting ready In recipe _Controlling_ _automatic database maintenance_ of Chapter 9, _Regular_ _Maintenance_ , we describe `VACUUM`, showing that it runs regularly on each table based on the number of rows that might need vacuuming ("dead rows"). VACUUM will run if that number exceeds a given threshold, which by default is just above 20% of the row count. In this recipe we create a script that picks the table with the largest number of dead rows, and runs VACUUM on it. # How to do it... The script is as follows: **SELECT schemaname** **, relname** **, n_dead_tup** **, n_live_tup** **FROM pg_stat_user_tables** **ORDER BY n_dead_tup DESC** **LIMIT 1** **\gset** **\qecho Running VACUUM on table :"relname" in schema :"schemaname"** **\qecho Rows before: :n_dead_tup dead, :n_live_tup live** **VACUUM ANALYZE :schemaname.:relname;** **\qecho Waiting 1 second...** **SELECT pg_sleep(1);** **SELECT n_dead_tup AS n_dead_tup_now** **, n_live_tup AS n_live_tup_now** **FROM pg_stat_user_tables** **WHERE schemaname = :'schemaname'** **AND relname = :'relname'** **\gset** **\qecho Rows after: :n_dead_tup_now dead, :n_live_tup_now live** # How it works... You might have noticed that the first query is not ended by a semicolon, as usual. This is because we end it with `\gset` instead, which means "run the query, and assign each returned value to a variable having the same name of the output column". This command expects the query to return exactly one row, as you might expect too, and if not it does not set any variable. The script waits one second before reading the updated number of dead and live rows. The reason for the wait is that such statistics are updated after the end of the transaction that makes the changes, which sends a signal to the statistics collector which then does the update. # There's more... See the next recipe on how to improve the script with iterations so that it vacuums more than one table. # Writing a conditional psql script psql supports conditional meta-commands `\if`, `\elif`, `\else` and `\endif` . In this recipe we demonstrate some of them. # Getting ready We want to improve the `vartest.sql` script so that it runs VACUUM only if there actually are dead rows in that table. # How to do it... We add conditional commands to `vartest.sql` resulting in the following script: **SELECT schemaname** **, relname** **, n_dead_tup** **, n_live_tup** **, n_dead_tup > 0 AS needs_vacuum** **FROM pg_stat_user_tables** **ORDER BY n_dead_tup DESC** **LIMIT 1** **\gset** **\if :needs_vacuum** **\qecho Running VACUUM on table :"relname" in schema :"schemaname"** **\qecho Rows before: :n_dead_tup dead, :n_live_tup live** **VACUUM ANALYZE :schemaname.:relname;** **\qecho Waiting 1 second...** **SELECT pg_sleep(1);** **SELECT n_dead_tup AS n_dead_tup_now** **, n_live_tup AS n_live_tup_now** **FROM pg_stat_user_tables** **WHERE schemaname = :'schemaname' AND relname = :'relname'** **\gset** **\qecho Rows after: :n_dead_tup_now dead, :n_live_tup_now live** **\else** **\qecho Skipping VACUUM on table :"relname" in schema :"schemaname"** **\endif** # How it works... We have added an extra column `needs_vacuum` to the first query, resulting in one more variable that we can use to make the VACUUM part conditional. # There's more... Conditional statements are usually part of flow control statements, which include also iterations. While iterating is not directly supported by psql, a similar effect can be achieved in other ways. For instance: * A script, called for instance file.sql, can be iterated by adding some lines at the end, as in the following fragment: **SELECT /* add a termination condition as appropriate */ AS do_loop** **\gset** **\if do_loop** **\ir file.sql** **\endif** * Instead of iterating, you can follow the approach described later in this chapter in the recipe _Performing actions on many tables_. # Investigating a psql error Error messages can sometimes be cryptic, and you may be left wondering _why did this error happen at all?_ For this purpose, `psql` recognizes two variables, `VERBOSITY` and `CONTEXT`; valid values are `terse`, `default`, or `verbose` for the former, and `never`, `errors`, or `always` for the latter. A more verbose error message will hopefully specify extra detail, and the context information will be included. Here is an example to show the difference: **postgres=# \set VERBOSITY terse ** **postgres=# \set CONTEXT never ** **postgres=# select * from missingtable; ** **ERROR: relation "missingtable" does not exist at character 15** This is quite a simple error, so we don't actually need the extra detail, but it is nevertheless useful for illustrating the extra detail you get when raising verbosity and enabling context information: **postgres=# \set VERBOSITY verbose ** **postgres=# \set CONTEXT errors ** **postgres=# select * from missingtable; ** **ERROR: 42P01: relation "missingtable" does not exist ** **LINE 1: select * from missingtable; ** **^ ** **LOCATION: parserOpenTable, parse_relation.c:1159** Now you get the SQL error code `42P01`, which you can look up in the PostgreSQL manual, and even a reference to the file and the line in the PostgreSQL source code where this error is raised, so you can investigate it (the beauty of open source!). However, there is a problem with having to enable verbosity in advance: you need to do it before running the command. If all errors were reproducible, this would not be a huge inconvenience. But in certain cases you may hit a transient error, such as a _serialization failure_ , which is difficult to detect itself; and it could sometimes happen that you struggle to reproduce the error, let alone analyze it. The `\errverbose` metacommand in `psql` was introduced precisely to avoid these problems. # Getting ready In fact, there isn't much to do, as the point of the `\errverbose` meta-command is precisely to capture information on the error without requiring any prior activity. # How to do it... 1. Suppose you hit an error as in the following query, and `verbose` reporting was not enabled: **postgres=# create table wrongname();** **ERROR: relation "wrongname" already exists** 2. The extra detail that is not displayed is nevertheless remembered by `psql`, so you can view it as follows: **postgres=# \errverbose** **ERROR: 42P07: relation "wrongname" already exists** **LOCATION: heap_create_with_catalog, heap.c:1067** # There's more... * The list of PostgreSQL error codes is available in the manual at the following URL https://www.postgresql.org/docs/current/static/errcodes-appendix.html * The PostgreSQL source code can be downloaded or inspected from this URL https://git.postgresql.org/ # Performing actions on many tables As a database administrator, you will often need to apply multiple commands as part of the same overall task. That task could be one of the following: * Many different actions on multiple tables * The same action on multiple tables * The same action on multiple tables in parallel * Different actions-one on each table-in parallel The first is a general case where you need to make a set of coordinated changes. The solution is _write a script_ , as we've already discussed. We can also call this static scripting because you write the script manually and then execute it. The second type of task can be achieved very simply with dynamic scripts, where we write a script that writes another script. This technique is the main topic of this recipe. Performing actions in parallel sounds really cool, and it would be useful if it were easy. In some ways it is, but trying to run multiple tasks concurrently and trap and understand all the errors is much harder. And if you're thinking it won't matter if you don't check for errors, think again. If you run tasks in parallel, then you cannot run them inside the same transaction; so you definitely need error checking. Don't worry! Running in parallel is usually not as bad as it may seem after reading the previous paragraph, and we'll explain it after a few basic examples. # Getting ready Let's just create a basic schema to run some examples: **postgres=# create schema test; ** **CREATE SCHEMA ** **postgres=# create table test.a (col1 INTEGER); ** **CREATE TABLE ** **postgres=# create table test.b (col1 INTEGER); ** **CREATE TABLE ** **postgres=# create table test.c (col1 INTEGER); ** **CREATE TABLE** # How to do it... Our task is to run an SQL statement using this form, with `X` as the table name, against each of our three test tables: **ALTER TABLE X ADD COLUMN last_update_timestamp TIMESTAMP WITH TIME ZONE;** The steps are as follows: 1. Our starting point is a script that lists the tables that we want to perform tasks against—something like the following: **postgres=# SELECT relname ** **FROM pg_class c ** **JOIN pg_namespace n ** **ON c.relnamespace = n.oid ** **WHERE n.nspname = 'test';** 2. This displays the list of tables that we will act upon (so that you can check it): **relname ** **--------- ** **a ** **b ** **c ** **(3 rows)** 3. We then use the preceding SQL to generate the text for a SQL script, substituting the schema name and table name in the SQL text. We then output to a script file named `multi.sql`, as follows: **postgres=# \t on ** **postgres=# \o multi.sql ** **postgres=# SELECT 'ALTER TABLE '|| n.nspname ** **|| '.' || c.relname || ** **' ADD COLUMN last_update_timestamp TIMESTAMP WITH TIME ZONE;' ** **FROM pg_class c ** **JOIN pg_namespace n ** **ON c.relnamespace = n.oid ** **WHERE n.nspname = 'test'; ** **\o** 4. Once we've generated the script, we can check whether all of it looks correct: **postgres=# \! cat multi.sql ** **ALTER TABLE test.a ADD COLUMN last_update_timestamp TIMESTAMP WITH TIME ZONE; ** **ALTER TABLE test.b ADD COLUMN last_update_timestamp TIMESTAMP WITH TIME ZONE; ** **ALTER TABLE test.c ADD COLUMN last_update_timestamp TIMESTAMP WITH TIME ZONE;** 5. Finally, we run the script and watch the results (success!): **postgres=# \i multi.sql ** **ALTER TABLE ** **ALTER TABLE ** **ALTER TABLE** # How it works... Overall, this is just an example of dynamic scripting, and it has been used by DBAs for many decades, even before PostgreSQL was born. This method can go wrong in various ways, especially if you generate SQL text with syntax errors. Just fix that and carry on. The `\t` command means _tuples only_ , so keeping `\t` to `on` will ensure that there are no headers, command tags, or row counts following the results. The `\o FILENAME` command redirects the output to a file until the subsequent `\o` command reverts to no redirection. The `\!` command runs operating system commands, so `\! cat` will show the file contents on *nix systems. The `\i` command redirects the input from a file, or in simpler terms, executes the named file. Running the script in this way may ignore earlier recipes, so I still recommend following those earlier guidelines. The `\ir` command does the same as `\i`; the difference is that `\ir` is relative to the directory where the current script is, while `\i` is relative to the _current_ directory. This directory is the one where the psql command line was started, and is changed by the `\cd` command. Dynamic scripting can also be called a "quick and dirty" approach. The previous scripts didn't filter out views and other objects in the test schema, so you'll need to add that yourself, or not, as required. There is another way of doing this as well: **DO $$ ** **DECLARE t record; ** **BEGIN ** **FOR t IN SELECT c.*, n.nspname ** **FROM pg_class c JOIN pg_namespace n ** **ON c.relnamespace = n.oid ** **WHERE n.nspname = 'test' /* ; not needed */ ** **LOOP ** **EXECUTE 'ALTER TABLE '|| quote_ident(t.nspname) || ** **'.' || quote_ident(t.relname) || ** **' ADD COLUMN last_update_timestamp ' || ** **'TIMESTAMP WITH TIME ZONE'; ** **END LOOP; ** **END $$;** I don't prefer using this method because it executes the SQL directly and doesn't allow you to keep the script afterwards. The preceding syntax with `DO` is called an **anonymous code block** because it's like a function without a name. # There's more... Earlier, I said I'll explain how to run multiple tasks in parallel. Some practical approaches to this are possible, with a bit of discussion. Making tasks run in parallel can be thought of as subdividing the main task so that we run x2, x4, x8, and other subscripts, rather than one large script. First, you should note that error checking gets worse when you spawn more parallel tasks, whereas performance improves most for the first few subdivisions. Also, we're often constrained by CPU, RAM, or I/O resources for intensive tasks. This means that splitting a main task into two to four parallel subtasks isn't practical without some kind of tool to help us manage them. There are two approaches here, depending on the two types of tasks: * A task consists of many smaller tasks, all roughly of the same size * A task consists of many smaller tasks, and the execution times vary according to the size and complexity of the database object If we have lots of smaller tasks, then we can simply run our scripts multiple times using a simple round-robin split of tasks so that each subscript runs a part of all subtasks. Here is how to do it: each row in `pg_class` has a hidden column called `oid`, whose value is a 32-bit number allocated from an internal counter on table creation. Therefore, about half of the tables will have even values of `oid`, and we can achieve an even split by adding the following clauses: * **Script 1** : Add `WHERE c.oid % 2 = 0` * **Script 2** : Add `WHERE c.oid % 2 = 1` The task we were performing as an example was to add a column to many tables. In the previous example, we were adding the column with no specified default; so the new column will have a `NULL` value, and as a result, it will run very quickly with `ALTER TABLE`, even on large tables. If we change the `ALTER TABLE` statement so as to specify a default, then PostgreSQL will need to rewrite the entire table. So the runtime will vary according to the table size (approximately, and also according to the number and type of indexes). Now that our subtasks vary in runtime according to size, we need to be more careful when splitting the subtasks so that we can end up with multiple scripts that will run for about the same time. If we already know that we have just a few big tables, it's easy to split those manually into their own scripts. If the database has many large tables, then we can sort SQL statements by table size and then distribute them using round-robin distribution into multiple subscripts that will have approximately the same runtime. The following SQL script, which should be saved in a `make-script.sql` file, is an example of this technique: **\t on ** **\o script-:i.sql ** **SELECT sql FROM ( ** **SELECT 'ALTER TABLE '|| n.nspname || '.' || c.relname || ** **' ADD COLUMN last_update_timestamp TIMESTAMP WITH TIME ZONE DEFAULT now();' as sql ** **,row_number() OVER (ORDER BY pg_relation_size(c.oid)) ** **FROM pg_class c ** **JOIN pg_namespace n ** **ON c.relnamespace = n.oid ** **WHERE n.nspname = 'test' ** **ORDER BY 2 DESC) as s ** **WHERE row_number % 2 = :i; ** **\o** Then, we generate the two scripts, as follows: **$ psql -v i=0 -f make-script.sql ** **$ psql -v i=1 -f make-script.sql** Finally, we execute the two jobs in parallel, like this: **$ psql -f script-0.sql & ** **$ psql -f script-1.sql &** Note how we used `psql` parameters—via the `-v` command line option—to select different rows using the same script. Also, note how we used the `row_number()` window function to sort the data by size. Then, we split the data into pieces using the following line: **WHERE row_number % N = i;** Here, `N` is the total number of scripts we're producing, and `i` ranges between 0 and `N` minus 1 (we are using modular arithmetic to distribute the subtasks). # Adding/removing columns on a table As designs change, we may want to add or remove columns from our data tables. These are common operations in development, though they need more careful planning on a running production database server, as they take full locks and may run for long periods. # How to do it... You can add a new column to a table using this command: **ALTER TABLE mytable ADD COLUMN last_update_timestamp TIMESTAMP WITHOUT TIME ZONE;** You can drop the same column using the following command: **ALTER TABLE mytable DROP COLUMN last_update_timestamp;** You can combine multiple operations when using `ALTER TABLE`, which then applies the changes in a sequence. This allows you to do a useful trick, which is to add a column unconditionally, using `IF EXISTS`, as follows: **ALTER TABLE mytable DROP COLUMN IF EXISTS last_update_timestamp,** **ADD COLUMN last_update_timestamp TIMESTAMP WITHOUT TIME ZONE;** Note that this will have almost the same effect as the following command: **UPDATE mytable SET last_update_timestamp = NULL;** However, `ALTER TABLE` runs much faster. That's very cool if you want to perform an update, but not much fun if you want to keep the data in the existing column. # How it works... The `ALTER TABLE` statement, which is used to add or drop a column, takes a full table lock (at the `AccessExclusiveLock` lock level) so that it can prevent all other actions on the table. So we want it to be as fast as possible. The `DROP COLUMN` command doesn't actually remove the column from each row of the table; it just marks the column as dropped. This makes `DROP COLUMN` a very fast operation. The `ADD COLUMN` command is also very fast if we are adding a nullable column with a null default value. If we use a `NOT NULL` constraint or specify an explicit default value, then we'll need to rewrite every row of the table, which can be quite slow. The `ALTER TABLE` command allows us to execute many column operations at once, as shown in the main recipe. The `ALTER TABLE` command is optimized so that we are able to include all column operations in a single pass of the table, greatly improving the speed for complex sets of changes: **ALTER TABLE mytable ADD COLUMN last_update_userid INTEGER DEFAULT 0,** **ADD COLUMN last_update_comment TEXT;** If we rewrite the table, then the dropped columns are removed. If not, they may stay there for some time. Subsequent `INSERT` and `UPDATE` operations will insert a null value for the dropped column (s). Updates will reduce the size of the stored rows if they were not null already. So, in theory, you just have to wait, and the database will eventually reclaim the space. In practice, this works only if all the rows in the table are updated within a given period of time. Many tables contain historical data, so space may not be reclaimed at all without additional actions. The PostgreSQL manual recommends changing the data type of a column to the same type- which forces rewriting of every row as a technique to reclaim the space taken by the dropped columns. I don't recommend this because it will completely lock the table for a long period, at least on larger databases. My recommendation is not to drop the column at all, if you can avoid it, when you're in production. Just keep track of the changes you would make if you get time, if ever. If you're looking at alternatives, then `VACUUM` will not rewrite the table, though a `VACUUM FULL` or a `CLUSTER` statement will. Be careful in those cases as well, because they also hold a full table lock. # There's more... Indexes that depend on a dropped column are automatically dropped as well. All other objects that depend on the column(s), such as foreign keys from other tables, will cause the `ALTER TABLE` statement to be rejected. You can override this and drop everything in sight using the `CASCADE` option, as follows: **ALTER TABLE x DROP COLUMN last_update_timestamp CASCADE;** Adding a column with a non-null default value can be done with `ALTER TABLE... ADD COLUMN... DEFAULT...`, as shown above, which however holds an AccessExclusive lock for the whole duration of the command, which is not short as 100% of the rows must be rewritten. The script introduced in the recipe " _Using psql variables"_ in this chapter is an example of how to do the same without holding an AccessExclusive lock for a long time. This lighter solution has only another tiny difference: it doesn't use a single transaction, which would be pointless since it would hold the lock until the end. If any row is inserted by another session between the `ALTER TABLE` and the `UPDATE,` and that row has a `NULL` value for the new column, then that value will be updated together with all the rows that existed before the `ALTER TABLE`, which is OK in most cases, but not in all, depending on the data model of the application. A proper solution would involve using two sessions, to ensure that no such writes can happen in between, with a procedure that can be sketched as follows: 1. Open two sessions, and note their PIDs 2. In session 1, BEGIN a transaction, then take an ACCESS EXCLUSIVE lock on the table, which will be granted 3. Immediately after, but in session 2, BEGIN a transaction, then take a SHARE lock on the table, which will hang waiting for session 1 4. In a third session, display the ordered wait queue for locks on session 1 as follows: **SELECT *** **FROM pg_stat_activity** **WHERE pg_blocking_pids(pid) @ > array[pid1]** **ORDER BY state_change;** (here `pid1` is the PID of session 1) and check that PID2 is the second one in the list; if not, it means that step _3_ was not fast enough, so `ROLLBACK` both sessions and repeat from step _1._ 5. In session 1, perform `ALTER TABLE` and then `COMMIT` 6. In session 2 (which will be unblocked by the previous step, and will therefore acquire the SHARE lock straight away), perform the `UPDATE` and then the `COMMIT` # Changing the data type of a column Thankfully, changing column data types is not an everyday task, but when we need to do it, we must know all the details so that we can perform the conversion on a production system without any errors. # Getting ready Let's start with a simple example of a table, as follows: **postgres=# select * from birthday;** This gives the following output: **name | dob ** **-------+-------- ** **simon | 690926 ** **(1 row)** The preceding table was created using this command: **CREATE TABLE birthday ( name TEXT** **, dob INTEGER);** # How to do it... Let's say we want to change the `dob` column to another data type. Let's try with a simple example first, as follows: **postgres=# ALTER TABLE birthday ** **postgres-# ALTER COLUMN dob SET DATA TYPE text; ** **ALTER TABLE** This works fine. Let's just change that back to the `integer` type so that we can try something more complex, such as a `date` data type: **postgres=# ALTER TABLE birthday ** **postgres-# ALTER COLUMN dob SET DATA TYPE integer; ** **ERROR: column "dob" cannot be cast to type integer** Oh! What went wrong? Let's try using an explicit conversion with the `USING` clause, as follows: **postgres=# ALTER TABLE birthday ** **ALTER COLUMN dob SET DATA TYPE integer USING dob::integer; ** **ALTER TABLE** This works as expected. Now let's try moving to a `date` type: **postgres=# ALTER TABLE birthday ** **ALTER COLUMN dob SET DATA TYPE date ** **USING date(to_date(dob::text, 'YYMMDD') - ** **(CASE WHEN dob/10000 BETWEEN 16 AND 69 THEN interval '100 years' ** **ELSE interval '0' END));** Now it gives what we were hoping to see: **postgres=# select * from birthday; ** **name | dob ** **-------+------------ ** **simon | 26/09/1969 ** **(1 row)** With PostgreSQL, you can also set or drop default expressions, irrespective of whether or not the `NOT NULL` constraints are applied: **ALTER TABLE foo ALTER COLUMN col DROP DEFAULT; ** **ALTER TABLE foo ALTER COLUMN col SET DEFAULT 'expression'; ** **ALTER TABLE foo ALTER COLUMN col SET NOT NULL; ** **ALTER TABLE foo ALTER COLUMN col DROP NOT NULL;** # How it works... Moving from the `integer` to the `date` type uses a complex `USING` expression. Let's break that down step by step so that we can see why, as follows: **postgres=# ALTER TABLE birthday ** **ALTER COLUMN dob SET DATA TYPE date ** **USING date(to_date(dob::text, 'YYMMDD') - ** **(CASE WHEN dob/10000 BETWEEN 16 AND 69 ** **THEN interval '100 years' ** **ELSE interval '0' END));** First, we can't move directly from `integer` to `date`. We need to convert it to `text` and then to `date`. The `dob::text` statement means _cast to text_. Once we have `text`, we use the `to_date()` function to move to a `date` type. This is not enough; our starting data was `690926`, which we presume is a date in the `YYMMDD` format. When PostgreSQL converts this data to a date, it assumes that the two-digit year, 69, is in the current century because it chooses the year nearest to 2020. So it outputs 2069 rather than 1969. This is why a case statement is added to reduce any year between 16 and 69 to be a date in the previous century by explicitly subtracting an interval of 100 years. We do not need to take away one century for years after 69 because they are already placed in the 20th century. It is very strongly recommended that you test this conversion by performing a `SELECT` first. Converting data types, especially to/from dates, always causes some problems, so don't try to do this quickly. Always take a backup of the data first. # There's more... The `USING` clause can also be used to handle complex expressions involving other columns. This could be used for data transformations, which might be useful for DBAs in some circumstances, such as migrating to a new database design on a production database server. Let's put everything together in a full, working example. We will start with this table that has to be transformed: **postgres=# select * from cust; ** **customerid | firstname | lastname | age ** **------------+-----------+----------+----- ** **1 | Philip | Marlowe | 38 ** **2 | Richard | Hannay | 42 ** **3 | Holly | Martins | 25 ** **4 | Harry | Palmer | 36 ** **(4 rows)** We want to transform it into a table design like the following: **postgres=# select * from cust; ** **customerid | custname | age ** **------------+----------------+----- ** **1 | Philip Marlowe | 38 ** **2 | Richard Hannay | 42 ** **3 | Holly Martins | 25 ** **4 | Harry Palmer | 36 ** **(4 rows)** We can decide to do it using these simple steps: **ALTER TABLE cust ADD COLUMN custname text NOT NULL DEFAULT ''; ** **UPDATE cust SET custname = firstname || ' ' || lastname; ** **ALTER TABLE cust DROP COLUMN firstname; ** **ALTER TABLE cust DROP COLUMN lastname;** We can also use the SQL commands directly or make them use a tool such as **OmniDB**. Following those steps may cause problems, as the changes aren't within a transaction, meaning that other users can see the changes when they are only half finished. Hence, it would be better to do this in a single transaction, using `BEGIN` and `COMMIT`. Also, those four changes require us to make two passes over the table. However, we can perform the entire transformation in one pass using multiple clauses on the `ALTER TABLE` command. So instead, we do the following: **BEGIN; ** **ALTER TABLE cust ** **ALTER COLUMN firstname SET DATA TYPE text ** **USING firstname || ' ' || lastname, ** **ALTER COLUMN firstname SET NOT NULL, ** **ALTER COLUMN firstname SET DEFAULT '', DROP COLUMN lastname; ** **ALTER TABLE cust RENAME firstname TO custname; ** **COMMIT;** This is a great example of why I personally prefer using scripts to make such changes to large production databases rather than directly making the changes using a GUI. Some type changes can be performed without actually rewriting rows, for example, if you are casting data from `varchar` to `text`, or from `NUMERIC(10,2)` to `NUMERIC(18,2)`, or simply to `NUMERIC`. Moreover, foreign key constraints will recognize type changes of this kind on the source table, and will therefore skip the constraint check whenever it is safe. # Changing the definition of a data type PostgreSQL comes with several data types, but users can create custom types to most faithfully represent any value. Data type management is mostly, but not exclusively, a developer's job, and data type design goes beyond the scope of this book. This is a quick recipe that covers only the simpler problem of the need to apply a specific change to an existing data type. # Getting ready Enumerative data types are defined like this: **CREATE TYPE satellites_urani AS ENUM ('titania','oberon');** The other popular case is composite data types, which are created as follows: **CREATE TYPE node AS (** **node_name text, ** **connstr text, ** **standbys text[]);** # How to do it... If you made a mistake in the spelling of some enumerative values, and you realize it too late, you can fix it like in the following example: **ALTER TYPE satellites_urani RENAME VALUE 'titania' TO 'Titania'; ALTER TYPE satellites_urani RENAME VALUE 'oberon' TO 'Oberon';** This is very useful if the application expects—and uses—the right names. A more complicate case is when you are upgrading your database to a new version, say because you want to consider some facts that were not available during the initial design, and you need extra values for the enumerative type that we defined in the preceding code. You want to put the new values in a certain position to preserve the correct ordering. For that, you can use an `ALTER TYPE` syntax, as follows: **ALTER TYPE satellites_urani ADD VALUE 'Ariel' BEFORE 'Titania'; ALTER TYPE satellites_urani ADD VALUE 'Umbriel' AFTER 'Ariel';** Composite data types can be changed with similar commands. Attributes can be renamed like in this example: **ALTER TYPE node ** **RENAME ATTRIBUTE slaves TO standbys;** And new attributes can be added as follows: **ALTER TYPE node ** **DROP ATTRIBUTE standbys, ** **ADD ATTRIBUTE async_standbys text[], ** **ADD ATTRIBUTE sync_standbys text[];** This form supports a list of changes, perhaps because composite types are more complex than a list of enumerative values, and can therefore, require complicated modifications. # How it works... Each time you create a table, a composite type is automatically created with the same attribute names, types, and positions. Each `ALTER TABLE` command that changes table column definitions will silently issue a corresponding `ALTER TYPE` statement to keep the type in agreement with _its_ table definition. # There's more... When an attribute is removed from a composite data type, the corresponding values will instantly disappear from all the values of that same type stored in any database table. What actually happens is that these values are still inside the tables, but they have become invisible because their attribute is now marked as deleted, and the space they occupy will be reclaimed only when the contents of the composite type are parsed again. This can be forced with a query like the following: **UPDATE mytable SET mynode = mynode :: text :: node;** Here, `mytable` is a table that has a `mynode` column of the `node` type. This query converts the values to the `text` type, displaying only current attribute values, and then back to `node`. You may have noticed that this behavior is very similar to the example of the dropped column in the previous recipe. # Adding/removing schemas Separating groups of objects is a good way of improving administration efficiency. You need to know how to create new schemas and remove schemas that are no longer required. # How to do it... To add a new schema, issue this command: **CREATE SCHEMA sharedschema;** If you want that schema to be owned by a particular user, then you can add the following option: **CREATE SCHEMA sharedschema AUTHORIZATION scarlett;** If you want to create a new schema that has the same name as an existing user, so that the user becomes the owner, then try this: **CREATE SCHEMA AUTHORIZATION scarlett;** In many database systems, the schema name is the same as that of the owning user. PostgreSQL allows schemas owned by one user to have objects owned by another user within them. This can be especially confusing when you have a schema of the same name as that of the owning user. To avoid this, you should have two types of schema: schemas that are named the same as the owning user should be limited to only objects owned by that user. Other general schemas can have shared ownership. To remove a schema named `str`, we can issue the following command: **DROP SCHEMA str;** If you want to ensure that the schema exists in all cases, you can issue the following command: **CREATE SCHEMA IF NOT EXISTS str;** This command has been added to version 9.3. Clearly, you need to be careful because the outcome of the command depends on the previous state of the database. As an example, try issuing the following: **CREATE TABLE str.tb (x int);** This can generate an error if the `str` schema contained that table before `CREATE SCHEMA IF NOT EXISTS` was run. Otherwise, there's no namespace error. Irrespective of your PostgreSQL version, there isn't a `CREATE OR REPLACE SCHEMA` command, so when you want to create a schema, regardless of whether or not it already exists, you can do the following: **DROP SCHEMA IF EXISTS newschema; ** **CREATE SCHEMA newschema;** The `DROP SCHEMA` command won't work unless the schema is empty or unless you use the nuclear option: **DROP SCHEMA IF EXISTS newschema CASCADE;** The nuclear option kills all known germs and all your database objects ( _even the good objects_ ). # There's more... In the SQL standard, you can also create a schema and the objects it contains in one SQL statement. PostgreSQL accepts this syntax if you need it: **CREATE SCHEMA foo ** **CREATE TABLE account (id INTEGER NOT NULL PRIMARY KEY ,balance NUMERIC(50,2)) CREATE VIEW accountsample AS SELECT * FROM account WHERE random() < 0.1;** Mostly, I find this limiting. This syntax exists to allow us to create two or more objects at the same time. That can be achieved more easily using PostgreSQL's ability to allow transactional DDL, which was discussed in the _Writing a script that either succeeds entirely or fails entirely_ recipe. # Using schema-level privileges Privileges can be granted for objects in a schema using the `GRANT` command, as follows: **GRANT SELECT ON ALL TABLES IN SCHEMA sharedschema TO PUBLIC;** However, this will only affect tables that already exist. Tables created in the future will inherit privileges defined by the `ALTER DEFAULT PRIVILEGES` command, as follows: **ALTER DEFAULT PRIVILEGES IN SCHEMA sharedschema GRANT SELECT ON TABLES TO PUBLIC;** # Moving objects between schemas Once you've created schemas for administration purposes, you'll want to move existing objects to keep things tidy. # How to do it... To move one table from its current schema to a new schema, use the following: **ALTER TABLE cust SET SCHEMA anotherschema;** If you want to move all objects, you can consider renaming the schema itself, using the following query: **ALTER SCHEMA existingschema RENAME TO anotherschema;** This only works if another schema with that name does not exist. Otherwise, you'll need to run `ALTER TABLE` for each table you want to move. You can use the earlier recipe _Performing actions on many tables_ to achieve that. Views, sequences, functions, aggregates, and domains can also be moved by `ALTER` commands with `SET SCHEMA` options. # How it works... When you move tables to a new schema, all the indexes, triggers, and rules defined on those tables will also be moved to the new schema. If you've used a `SERIAL` data type and an implicit sequence has been created, then that also moves to the new schema. Schemas are purely an administrative concept and they do not affect the location of the table's data files. Tablespaces don't work this way, as we will see in later recipes. Databases, users/roles, languages, and conversions don't exist in a schema. Schemas exist in a particular database. Schemas don't exist within schemas; they are not arranged in a tree or hierarchy. More details can be found in the _Using multiple schemas_ recipe in Chapter 4, _Server Control_. # There's more... Casts don't exist in a schema, though the data types and functions they reference do exist. These things are not typically something we want to move around anyway. This is just a note if you're wondering how things work. # Adding/removing tablespaces Tablespaces allow us to store PostgreSQL data across different devices. We might want to do that for performance or administrative ease, or our database might just have run out of disk space. # Getting ready Before we can create a useful tablespace, we need the underlying devices in a production-ready form. Think carefully about the speed, volume, and robustness of the disks you are about to use. Make sure that they are configured correctly. Those decisions will affect your life for the next few months and years! Disk performance is a subtle issue that most people think can be decided in a few seconds. We recommend reading Chapter 10, _Performance and Concurrency_ , from this book, as well as additional books on the same topic. Once you've done all of that, then you can create a directory for your tablespace. The directory must be: * Empty * Owned by the PostgreSQL owning user ID * Specified with an absolute pathname On Linux and Unix systems, you shouldn't use a mount point directly. Create a subdirectory and use that instead. That simplifies ownership and avoids some filesystem-specific issues, such as getting `lost+found` directories. The directory also needs to follow sensible naming conventions so that we can clearly identify which tablespace goes with which server. Do not be tempted to use something simple, such as `data`, because it will make later administration more difficult. Be especially careful that test or development servers do not and cannot get confused with production systems. # How to do it... Once you've created your directory, adding the tablespace is simple: **CREATE TABLESPACE new_tablespace LOCATION '/usr/local/pgsql/new_tablespace';** The command to remove the tablespace is also simple and is as follows: **DROP TABLESPACE new_tablespace;** Every tablespace has a location assigned to it, with the exception of the `pg_global` and `pg_default` default tablespaces, for shared system catalogs and all other objects, respectively. They don't have a location because they live in a subdirectory of the `data` directory. A tablespace can be dropped only when it is empty, so how do you know when a tablespace is empty? Tablespaces can contain both permanent and temporary objects. Permanent data objects are tables, indexes, and TOAST objects. We don't need to worry too much about TOAST objects because they are created and always live in the same tablespace as their main table, and you cannot manipulate their privileges or ownership. Indexes can exist in separate tablespaces as a performance option, though that requires explicit specification in the `CREATE INDEX` statement. The default is to create indexes in the same tablespace as the table to which they belong. Temporary objects may also exist in a tablespace. These exist when users have explicitly created temporary tables or there may be implicitly created data files when large queries overflow their `work_mem` settings. These files are created according to the setting of the `temp_tablespaces` parameter. That might cause an issue because you can't tell for certain what the setting of `temp_tablespaces` is for each user. Users can change their setting of `temp_tablespaces` from the default value specified in the `postgresql.conf` file to something else. We can identify the tablespace of each user object using the following query: **SELECT spcname** ** ,relname** ** ,CASE WHEN relpersistence = 't' THEN 'temp '** ** WHEN relpersistence = 'u' THEN 'unlogged '** ** ELSE '' END ||** ** CASE** ** WHEN relkind = 'r' THEN 'table'** ** WHEN relkind = 'p' THEN 'partitioned table'** ** WHEN relkind = 'f' THEN 'foreign table'** ** WHEN relkind = 't' THEN 'TOAST table'** ** WHEN relkind = 'v' THEN 'view'** ** WHEN relkind = 'm' THEN 'materialized view'** ** WHEN relkind = 'S' THEN 'sequence'** ** WHEN relkind = 'c' THEN 'type'** ** ELSE 'index' END as objtype** **FROM pg_class c join pg_tablespace ts** **ON (CASE WHEN c.reltablespace = 0 THEN** ** (SELECT dattablespace FROM pg_database** ** WHERE datname = current_database())** ** ELSE c.reltablespace END) = ts.oid** **WHERE relname NOT LIKE 'pg_toast%'** **AND relnamespace NOT IN** ** (SELECT oid FROM pg_namespace** ** WHERE nspname IN ('pg_catalog', 'information_schema'))** **;** This displays an output like the following: **spcname | relname | objtype ** **------------------+-----------+------------ ** **new_tablespace | x | table ** **new_tablespace | y | table ** **new_tablespace | z | temp table ** **new_tablespace | y_val_idx | index** You may also want to look at the `spcowner`, `relowner`, `relacl`, and `spcacl` columns to determine who owns what and what they're allowed to do. The `relacl` and `spcacl` columns refer to the **access control list** ( **ACL** ) that details the privileges available on those objects. The `spcowner` and `relowner` columns record the owners of the tablespace and tables/indexes, respectively. # How it works... A tablespace is just a directory where we store PostgreSQL data files. We use symbolic links from the `data` directory to the tablespace. We exclude TOAST tables because they are always in the same tablespace as their parent tables, but remember that TOAST tables are always in a separate schema. You can exclude TOAST tables using the `relkind` column, but that would still include the indexes on the TOAST tables. TOAST tables and TOAST indexes both start with `pg_toast`, so we can exclude those easily from our queries. The preceding query needs to be complex because `pg_class` entry for an object will show `reltablespace = 0` when an object is created in the database's default tablespace. So if you directly join `pg_class` and `pg_tablespace`, you end up losing rows. Note that we can see that a temporary object exists, and we can see the tablespace in which it is created, even though we cannot refer to a temporary object in another user's session. # There's more... Some more notes on best practices follow. A tablespace can contain objects from multiple databases, so it's possible to be in a position where there are no objects visible in the current database. The tablespace just refuses to go away, giving the following error: **ERROR: tablespace "old_tablespace" is not empty** You are strongly advised to make a separate tablespace for each database to avoid confusion. This can be especially confusing if you have the same schema names and table names in the separate databases. How to avoid this? If you just created a new tablespace directory, you might want to create subdirectories within that for each database that needs space, and then change the subdirectories to tablespaces instead. You may also wish to consider giving each tablespace a specific owner, using the following query: **ALTER TABLESPACE new_tablespace OWNER TO eliza;** This may help smooth administration. You may also wish to set default tablespaces for a user so that tables are automatically created there by issuing the following query: **ALTER USER eliza SET default_tablespace = 'new_tablespace';** # Putting pg_wal on a separate device You may seek advice about placing the `pg_wal` directory on a separate device for performance reasons. This sounds very similar to tablespaces, though there is no explicit command to do this once you have a running database, and files in `pg_wal` are frequently written. So you must perform the steps outlined in the following example: 1. Stop the database server: **[postgres@myhost ~]$ pg_ctl stop** 2. Move `pg_wal` to a location supported by a different disk device: **[postgres@myhost ~]$ mv $PGDATA/pg_wal /mnt/newdisk/** 3. Create a symbolic link from the old location to the new location: **[postgres@myhost ~]$ ln -s /mnt/newdisk/pg_wal $PGDATA/pg_wal** 4. Restart the database server: **[postgres@myhost ~]$ pg_ctl start** 5. Verify that everything is working by committing any transaction (preferably, a transaction that does not damage the existing workload): **[postgres@myhost ~]$ psql -c 'CREATE TABLE pg_wal (x int)'** # Tablespace-level tuning As each tablespace has different I/O characteristics, we may wish to alter the planner cost parameters for each tablespace. These can be set with the following command: **ALTER TABLESPACE new_tablespace SET (seq_page_cost = 0.05, random_page_cost = 0.1);** In this example, settings are roughly appropriate for an SSD drive, and it assumes that the drive is 40 times faster than an HDD for random reads, and 20 times faster for sequential reads. The values given need more discussion than we have time for here. # Moving objects between tablespaces Moving data between tablespaces may sometimes be required. # Getting ready First, create your tablespaces. Once the old and new tablespaces exist, we can issue the commands to move them. # How to do it... Tablespaces can contain both permanent and temporary objects. Permanent data objects are tables, indexes, and TOAST objects. We don't need to worry too much about TOAST objects because they are created in and always live in the same tablespace as their main table. So, if you alter the tablespace of a table, its TOAST objects will also move: **ALTER TABLE mytable SET TABLESPACE new_tablespace;** Indexes can exist in separate tablespaces, and moving a table leaves the indexes where they are. Don't forget to run `ALTER INDEX` commands as well, one for each index, as follows: **ALTER INDEX mytable_val_idx SET TABLESPACE new_tablespace;** Temporary objects cannot be explicitly moved to a new tablespace, so we take that to mean you want to _ensure they are created somewhere else in the future_. To do that you need to do the following: 1. Edit the `temp_tablespaces` parameter, as shown in the _Updating the parameter file_ recipe in Chapter 3, _Configuration._ 2. Reload the server to allow new configuration settings to take effect. There is no single command to do this that will work for all users. # How it works... If you want to move a table and its indexes all in one pass, you can issue all the commands in a single transaction, as follows: **BEGIN; ** **ALTER TABLE mytable SET TABLESPACE new_tablespace; ** **ALTER INDEX mytable_val1_idx SET TABLESPACE new_tablespace; ** **ALTER INDEX mytable_val2_idx SET TABLESPACE new_tablespace; ** **COMMIT;** Moving tablespaces means bulk copying of data. Copying happens sequentially, block by block. That works well, but there's no way to avoid the fact that the bigger the table, the longer it will take. Performance will be optimized if archiving or streaming replication is not active, as no WAL will be written in that case. You should be aware that the table is fully locked (the AccessExclusiveLock lock) while the copy is taking place, so this can cause an effective outage for your application. Be very careful! If you want to ensure that objects are created in the right place next time you create them, then you can use this query: **SET default_tablespace = 'new_tablespace';** You can run this automatically for all users that connect to a database using the following query: **ALTER DATABASE mydb SET default_tablespace = 'new_tablespace';** Take care that you do not run the following command by mistake, however: **ALTER DATABASE mydb SET TABLESPACE new_tablespace;** This literally moves all objects that do not have an explicitly defined tablespace into `new_tablespace`. For a large database, this will take a very long time, and your database will be completely locked while it runs; not cool, if you do it by accident! # There's more... If you just discovered that indexes don't get moved when you move a table, then you may want to check whether any indexes are in tablespaces different from their parent tables. Run the following to check: **SELECT i.relname as index_name** **, tsi.spcname as index_tbsp** **, t.relname as table_name** **, tst.spcname as table_tbsp** **FROM ( pg_class t /* tables */** **JOIN pg_tablespace tst** **ON t.reltablespace = tst.oid** **OR ( t.reltablespace = 0** **AND tst.spcname = 'pg_default' )** **)** **JOIN pg_index pgi** **ON pgi.indrelid = t.oid** **JOIN ( pg_class i /* indexes */** **JOIN pg_tablespace tsi** **ON i.reltablespace = tsi.oid** **OR ( i.reltablespace = 0** **AND tsi.spcname = 'pg_default' )** **)** **ON pgi.indexrelid = i.oid** **WHERE i.relname NOT LIKE 'pg_toast%'** **AND i.reltablespace != t.reltablespace** **;** If we have one table with an index in a separate tablespace, we might see this as a `psql` definition: **postgres=# \d y ** **Table "public.y" ** **Column | Type | Modifiers ** **--------+------+----------- ** **val | text | ** **Indexes: ** **"y_val_idx" btree (val), tablespace "new_tablespace" ** **Tablespace: "new_tablespace2"** Running the previously presented query gives the following results: **relname | spcname | relname | spcname ** **-----------+------------------+---------+--------------- ** **y_val_idx | new_tablespace | y | new_tablespace2 ** **(1 row)** # Accessing objects in other PostgreSQL databases Sometimes, you may want to access data in other PostgreSQL databases. The reasons may be as follows: * You have more than one database server, and you need to extract data (such as reference) from one server and load it into the other. * You want to access data that is in a different database on the same database server, which was split for administrative purposes. * You want to perform some changes that you do not wish to rollback in the event of an error or transaction abort. These are known as **function side-effects** or **autonomous transactions**. You might also be considering this because you are exploring the scale out, sharding, or load balancing approaches. If so, read the last part of this recipe, the _See also_ section, and then skip to Chapter 12, _Replication and Upgrades_. PostgreSQL includes two separate mechanisms for accessing external PostgreSQL databases: dblink and the PostgreSQL Foreign Data Wrapper. The latter is more efficient and implements a part of the SQL standard, but does not fully replace dblink, therefore we provide two variants of this recipe. # Getting ready First of all, let's make a distinction to prevent confusion: * The **Foreign Data Wrapper** infrastructure, a mechanism to manage the definition of remote connections, servers, and users, is available in all supported PostgreSQL versions * The **PostgreSQL Foreign Data Wrapper** is a specific contrib extension that uses the Foreign Data Wrapper infrastructure to connect to remote PostgreSQL servers. In particular, the Foreign Data Wrapper infrastructure will be used to manage definitions in both cases, that is, when using the PostgreSQL Foreign Data Wrapper and when using the `dblink` module. Foreign Data Wrapper extensions for other database systems will be discussed in the next recipe, _Accessing objects in other foreign databases_. # How to do it... We will first describe the variant that uses `dblink`, which applies to all supported PostgreSQL versions: 1. First, we need to install the `dblink` contrib module. The general procedure is explained in the _Adding an external module to PostgreSQL_ recipe of Chapter 3, _Configuration_. 2. Then, we create some access definitions. The preferred way is to use the following commands, which are SQL standard (SQL/MED): **postgres=# CREATE FOREIGN DATA WRAPPER postgresql** ** VALIDATOR postgresql_fdw_validator; ** **CREATE FOREIGN DATA WRAPPER ** **postgres=# CREATE SERVER otherdb** ** FOREIGN DATA WRAPPER postgresql** ** OPTIONS (host 'foo', dbname 'otherdb', port '5432'); ** **CREATE SERVER ** **postgres=# CREATE USER MAPPING FOR PUBLIC ** **SERVER otherdb; ** **CREATE USER MAPPING** 3. You must create `FOREIGN DATA WRAPPER` only once, though you need one `SERVER` for each PostgreSQL destination database to which you may wish to connect. This is just the connection definition, not the connection itself. 4. Creating a public user mapping with no options seems strange, though it will mean that we use the `libpq` default behavior. It will also mean that we will connect the remote database using the value of `PGUSER`, or if it is not set, use the operating system user. Clearly, if we want to use different credentials, then we must specify them with suitable options, either while creating the mapping or afterwards (`ALTER USER MAPPING`). The `VALIDATOR` clause specifies a function whose purpose is to validate the parameters. That function is a part of the Foreign Data Wrapper and should have been provided by the author, so you need to create it only if you are developing a new type of Foreign Data Wrapper yourself. 5. Now connect using an unnamed connection, as follows: **SELECT dblink_connect('otherdb');** 6. This produces the following output: **dblink_connect** **----------------** **OK** **(1 row)** 7. We limit ourselves to unnamed connections for simplicity. It is also possible to create a named connection, that is, a connection that is assigned a string so that it can be referred to directly later. This is obviously useful if we want to manage several connections, but it comes at the price of actually having to manage their life cycle (connection and disconnection). 8. Suppose you want to execute the following command: **postgres=# INSERT INTO audit_log VALUES (current_user, now());** 9. To do so, run it on the unnamed remote connection like this: **postgres=# SELECT dblink_exec('INSERT INTO audit_log VALUES' ||** **' (current_user, now())', true);** 10. This will give the following output: **dblink_exec ** **------------- ** **INSERT 0 1 ** **(1 row)** 11. Notice that the remote command returns the command tag and number of rows processed as the return value of the function. The second option means "fail on error". If you look closely, there's also a subtle error-when the `INSERT` command is executed locally, we use this server's value of `current_user`. But when we execute remotely, we use the remote server's value of `current_user`, which might differ, depending on the user mapping defined previously. 12. Similarly, suppose you want to execute the following query on the unnamed remote connection: **SELECT generate_series(1,3)** 13. We start by typing this: **SELECT *** **FROM dblink('SELECT generate_series(1,3)')** 14. This will result in the following error: **ERROR: a column definition list is required for functions returning ** **"record" ** **LINE 2: FROM dblink('SELECT generate_series(1,3)'); ** **^** 15. This error message is telling us that we need to specify the list of output columns and output types that we expect from the `dblink()` function, because PostgreSQL is unable to determine them automatically at parsing time (that is, without running the query). 16. We can add the missing information by providing an alias in the `FROM` clause, as in the following example: **SELECT *** **FROM dblink('SELECT generate_series(1,3)')** **AS link(col1 integer);** 17. This will succeed, and result in the following output: **col1** **------** **1** **2** **3** **(3 rows)** 18. To disconnect from the unnamed connection, you can issue the following: **SELECT dblink_disconnect();** 19. You get the following output: **dblink_connect** **----------------** **OK** **(1 row)** Now we will describe the second variant of this recipe, which uses the PostgreSQL Foreign Data Wrapper instead of `dblink`. 1. The first step is to install the `postgres_fdw` contrib module, which is as simple as this: **postgres=# CREATE EXTENSION postgres_fdw;** 2. The result is as follows: **CREATE EXTENSION** 3. This extension automatically creates the corresponding Foreign Data Wrapper, as you can check with psql's `\dew` meta-command: **postgres=# \dew** **List of foreign-data wrappers** **Name | Owner | Handler | Validator** **--------------+--------+----------------------+------------------------** **postgres_fdw | gianni | postgres_fdw_handler | postgres_fdw_validator** **(1 row)** 4. We can now define a server: **postgres=# CREATE SERVER otherdb** **FOREIGN DATA WRAPPER postgres_fdw** **OPTIONS (host 'foo', dbname 'otherdb', port '5432');** 5. This produces the following output: **CREATE SERVER** 6. Then, we can define the user mapping: **postgres=# CREATE USER MAPPING FOR PUBLIC SERVER otherdb;** 7. The output is as follows: **CREATE USER MAPPING** As an example, we will access a portion of a remote table containing (integer, text) pairs: **postgres=# CREATE FOREIGN TABLE ft (** **num int ,** **word text )** **SERVER otherdb** **OPTIONS (** **schema_name 'public' ,** **table_name 't' );** The result is quite laconic: **CREATE FOREIGN TABLE** This table can now be operated almost like any other table. We check whether it is empty: **postgres=# select * from ft;** This is the output: **num | word** **-----+------** **(0 rows)** 8. We can insert rows as follows: **postgres=# insert into ft(num,word) values** **(1,'One'), (2,'Two'),(3,'Three');** 9. This query produces the following output: **INSERT 0 3** 10. Then, we can verify that the aforementioned rows have been inserted: **postgres=# select * from ft;** 11. This is confirmed by the output: **num | word** **-----+-------** **1 | One** **2 | Two** **3 | Three** **(3 rows)** Note that you don't have to manage connections or format text strings to assemble your queries. Most of the complexity is handled automatically by the Foreign Data Wrapper. # How it works... The `dblink` module establishes a persistent connection with the other database. The `dblink` functions track the details of that connection, so you don't need to worry about doing so yourself. You should be aware that this is an external resource, and so the generic programming problem of _resource leaks_ becomes possible. If you forget about your connection and forget to disconnect it, you may experience problems later. The remote connections will be terminated should your session disconnect. Note that the remote connection persists even across transaction failures and other errors, so there is no need to reconnect. The `postgres_fdw` extension can manage connections transparently and efficiently, so if your use case does not involve commands other than `SELECT`, `INSERT`, `UPDATE`, and `DELETE` then you should definitely go for it. The `dblink()` module executes the remote query and will assemble the result set in the memory before the local reply begins to be sent. This means that very large queries might fail due to lack of memory, and everybody else will notice that. This isn't a problem; `dblink` is simply not designed to handle bulk data flows. Look at the _Loading data from flat files_ recipe in Chapter 5, _Tables and Data_ , if that's what you want to do. Running slightly larger queries can be achieved using cursors. They allow us to bring the answer set back in smaller chunks. Conceptually, we need to open the cursor, loop while fetching rows until we are done, and then close the cursor. An example query for that is as follows: **postgres=# SELECT dblink_open('example', ** **'SELECT generate_series(1,3)', true); ** **dblink_open ** **------------- ** **OK ** **(1 row) ** **postgres=# SELECT * ** **FROM dblink_fetch('example', 10, true) ** **AS link (col1 integer); ** **col1 ** **------ ** **1 ** **2 ** **3 ** **(3 rows)** Notice that we didn't need to define the cursor when we opened it, though we do need to define the results from the cursor when we fetch from it, just as we did with a normal query. For instance, to fetch 10 rows at a time, we can do this: **postgres=# SELECT * ** **FROM dblink_fetch('example', 10, true) AS link (col1 integer); ** **col1 ** **------ ** **(0 rows) ** **postgres=# SELECT dblink_close('example'); ** **dblink_close ** **-------------- ** **OK** **(1 row)** The `dblink` module also allows you to use more than one connection. Using just one connection is generally not good for modular programming. For more complex situations, it's good practice to assume that the connection you want is not the same as the connection that another part of the program might need. The `dblink` module allows named connections, so you don't need to hope that the default connection is still the right connection. There is also a function named `dblink_get_connections()` that will allow you to see which connections you have active. # There's more... Remote data sources look as if they can be treated as tables, and in fact, they are represented as such by Foreign Data Wrappers. Unfortunately, in practice, this doesn't work in all the ways you might hope and expect. However, by writing your queries and code in the standard way, you give the database usable context information about what you are trying to achieve; future PostgreSQL versions might achieve better optimization on the same SQL code. This is a general advantage over custom solutions, which are usually opaque to the server and thus cannot be optimized further. Ideally, we would like to use foreign tables interchangeably with local tables, with minimum possible performance penalty and maintenance cost, so it is important to know what already works and what is still on the wish list. First, here's the good news: foreign tables can have statistics collected, just like ordinary tables, and they can be used as models to create local tables: **CREATE TABLE my_local_copy (LIKE my_foreign_table);** This is not supported by `dblink`, because it works on statements instead of managing tables. In general, there is no federated query optimizer. If we join a local table and a remote table with `dblink`, then data from the remote database is simply pulled through, even if it would have been quicker to send the data and then pull back matching rows. On the other hand, `postgres_fdw` can share information with the query planner, allowing some optimization, and more improvements are likely to come in following years, now that the infrastructure has been built. As of version 10, `postgres_fdw` transparently pushes `WHERE` clauses to the remote server. Suppose you issue this: **SELECT * FROM ft WHERE num = 2;** Then, only the matching rows will be fetched, using any remote index if available. This is a massive advantage in working with selective queries on large tables. The `dblink` module cannot automatically send a local `WHERE` clause to the remote database, so a query like the following would perform poorly: **SELECT * FROM dblink('otherdb', 'SELECT * FROM bigtable') AS link ( ... ) WHERE filtercolumn > 100;** We will need to explicitly add the `WHERE` clause to the remote query at the application level, like the following: **SELECT * FROM dblink('otherdb', 'SELECT * FROM bigtable' || ** **' WHERE filtercolumn > 100') AS link ( ... );** This means that, in general, setting up views of remote data this way isn't very helpful, as it encourages users to think that the table location doesn't matter, whereas, from a performance perspective, it definitely does. This isn't really any different from other federated or remote access database products. The version of `postgres_fdw` shipped with PostgreSQL 10 can delegate even more activities to the remote node. This includes—performing sorts or joins; computing aggregates carrying out entire `UPDATE` or `DELETE` statements, and evaluating operators or functions provided by suitable extensions. There are also a few performance considerations that you may wish to consider. The first is that when the remote query executes, the current session waits for it to complete. You can also execute queries without waiting for them to return, using the following functions: * `dblink_send_query()` * `dblink_is_busy()` * `dblink_get_result()` If you are concerned about the overhead of connection time, then you may want to consider using a session pool. This will reserve a number of database connections, which will allow you to reduce apparent connection time. For more information, look at the _Setting up a connection pool recipe_ in Chapter 4, _Server Control_. # There's more... Another-and sometimes easier-way of accessing other databases is with a tool named **PL/Proxy** , available as a PostgreSQL extension. PL/Proxy allows you to create a local database function that is a proxy for a remote database function. PL/Proxy works only for functions, and some people regard this as a restriction, in a way similar to `postgres_fdw`, which operates only on rows in tables. That is why these solutions complement `dblink`, rather than replacing it. Creating a local proxy function is simple: **CREATE FUNCTION my_task(VOID) RETURNS SETOF text AS $$ CONNECT 'dbname=myremoteserver'; SELECT my_task(); $$ LANGUAGE plproxy;** You need a local function, but you don't need to call a remote function; you can use SQL statements directly. The following example shows a parameterized function: **CREATE FUNCTION get_cust_email(p_username text) RETURNS SETOF text AS $$ CONNECT 'dbname=myremoteserver'; SELECT email FROM users WHERE username = p_username; $$ LANGUAGE plproxy;** PL/Proxy is specifically designed to allow more complex architecture for sharding and load balancing. The `RUN ON` command allows us to dynamically specify the remote database on which we will run the SQL statement. So the preceding example becomes as follows: **CREATE FUNCTION get_cust_email(p_username text) RETURNS SETOF text AS $$ CLUSTER 'mycluster'; RUN ON hashtext(p_username); SELECT email FROM users WHERE username = p_username; $$ LANGUAGE plproxy;** You'll likely need to read Chapter 12, _Replication and Upgrades_ , before you begin designing application architecture using these concepts. # Accessing objects in other foreign databases In the previous recipe, you saw how to use objects from a different PostgreSQL database, either with `dblink` or by using the Foreign Data Wrapper infrastructure. Here we will explore another variant of the latter-using Foreign Data Wrappers to access databases other than PostgreSQL. There are many Foreign Data Wrappers for other database systems, all of which are maintained as extensions independently from the PostgreSQL project. PGXN, the PostgreSQL Extension Network mentioned in Chapter 3, _Configuration_ , is a good place where you can see which extensions are available. Just note this so that you don't get confused: while you can find Foreign Data Wrappers to access several database systems, there are also other wrappers for different types of data sources, such as text files, web services, and so on.There is even `postgres_fdw`, a backport of the contrib module which we covered in the previous recipe, for users of older PostgreSQL versions that did not have it yet. When evaluating external extensions, I advise you to carefully examine the `README` file in each extension before making stable choices, as the code maturity varies a lot. Some extensions are still development experiments, while others are production-ready extensions, such as `oracle_fdw`. # Getting ready For this example, we will use the Oracle Foreign Data Wrapper, `oracle_fdw`, whose version is 2.0.0. You must have obtained and installed the required Oracle software as specified in the `oracle_fdw` documentation at <https://github.com/laurenz/oracle_fdw/blob/ORACLE_FDW_2_0_0/README.oracle_fdw#L497>. The `oracle_fdw` wrapper is available in the PostgreSQL Extension Network, so you can follow the straightforward installation procedure described in the _Installing modules from PGXN_ section of the _Adding an external module to PostgreSQL_ recipe in Chapter 3, _Configuration_. Obviously, you must have access to an Oracle database server. # How to do it... Here, we provide stepwise instructions on how to connect to an Oracle server using `oracle_fdw`: 1. First, we ensure that the extension is loaded: **CREATE EXTENSION IF NOT EXISTS oracle_fdw;** 2. Then, we configure the server and the user mapping: **CREATE SERVER myserv ** **FOREIGN DATA WRAPPER oracle_fdw ** **OPTIONS (dbserver '//myhost/MYDB'); ** **CREATE USER MAPPING FOR myuser ** **SERVER myserv;** 3. Then, we create a PostgreSQL foreign table with the same column names as the source table in Oracle, and with compatible column types: **CREATE FOREIGN TABLE mytab(id bigint, descr text) ** **SERVER myserv ** **OPTIONS (user 'scott', password 'tiger');** 4. Now, we can try to write to the table: **INSERT INTO mytab VALUES (-1, 'Minus One');** 5. Finally, we are able to read the values that we have inserted: **SELECT * FROM mytab WHERE id = -1;** This should result in the following output: **id | descr ** **----+----------- ** **-1 | Minus One ** **(1 row)** # How it works... Our query has a `WHERE` condition that filters the rows we select from the foreign table. As in the `postgres_fdw` example from the previous recipe, Foreign Data Wrappers do the clever thing: the `WHERE` condition is pushed to the remote server, and only the matching rows are retrieved. This is good in two ways: firstly, we delegate some work to another system, and secondly, we reduce the overall network traffic by not transferring unnecessary data. We also notice that the `WHERE` condition is expressed in the PostgreSQL syntax; the Foreign Data Wrapper is able to translate it into whatever form required by the remote system. # There's more... PostgreSQL provides the infrastructure for collecting statistics on foreign tables, so the planner will be able to consider such information, provided that the feature is implemented in the specific Foreign Data Wrapper you are using. For example, statistics are supported by `oracle_fdw`. The latest improvements for foreign tables include trigger support, `IMPORT FOREIGN SCHEMA`, and several improvements to the query planner. Particularly useful for database administrators is the `IMPORT FOREIGN SCHEMA` syntax, which can be used to create, with a single statement, foreign tables for all tables and views in a given remote schema. Among the query planner improvements, we wish to mention **Join Pushdown**. In a nutshell: a query that joins some foreign tables that belong to the same server is able to have the join performed transparently on the remote server. To avoid security issues, this can only happen if these tables are all accessed with the same role. Another interesting extension is Multicorn (http://multicorn.org). It helps Python programmers create Foreign Data Wrappers by providing a dedicated interface. Multicorn reduces the creation of a basic Foreign Data Wrapper to the implementation of one Python method. Additional features, such as write access, are available through further optional methods. # Updatable views PostgreSQL supports the SQL standard `CREATE VIEW` command, which supports automatic `UPDATE`, `INSERT`, and `DELETE` commands, provided they are simple enough. Note that certain types of updates are forbidden just because it is either impossible or impractical to derive a corresponding list of modifications on the constituent tables. We'll discuss those issues here. # Getting ready First, you need to consider that only simple views can be made to receive insertions, updates, and deletions easily. The SQL standard differentiates between views that are _simple` updatable`_ and more complex views that cannot be expected to be updatable. So, before we proceed, we need to understand what a simple updatable view is and what it is not. Let's start from the `cust` table: **postgres=# SELECT * FROM cust; ** **customerid | firstname | lastname | age ** **------------+-----------+----------+----- ** **1 | Philip | Marlowe | 38 ** **2 | Richard | Hannay | 42 ** **3 | Holly | Martins | 25 ** **4 | Harry | Palmer | 36 ** **4 | Mark | Hall | 47 ** **(5 rows)** We create a very simple view on top of it, like the following: **CREATE VIEW cust_view AS SELECT customerid ** **,firstname ** **,lastname ** **,age ** **FROM cust;** Each row in our view corresponds to one row in a single-source table, and each column is referred to directly without any further processing, except possibly for a column rename. Thus, we expect to be able to make `INSERT`, `UPDATE`, and `DELETE` commands pass through our view into the base table, which is what happens in PostgreSQL. The following examples are three views where `INSERT`, `UPDATE`, and `DELETE` commands cannot be made to flow to the base table easily, for the reasons just described: **CREATE VIEW cust_avg AS SELECT avg(age) ** **FROM cust; ** **CREATE VIEW cust_above_avg_age AS SELECT customerid ** **,substr(firstname, 1, 20) as fname ** **,substr(lastname, 1, 20) as lname ** **,age - ** **(SELECT avg(age)::integer ** **FROM cust) as years_above_avg ** **FROM cust ** **WHERE age >** ** (SELECT avg(age) ** **FROM cust); ** **CREATE VIEW potential_spammers AS** **SELECT customerid, spam_score(firstname,lastname)** **FROM cust** **ORDER BY spam_score(firstname,lastname) DESC** **LIMIT 100;** The first view just shows a single row with the average of a numeric column. Changing an average directly doesn't make much sense. For instance, if we want to raise the average age by 1, should we increase all numbers by 1, resulting in an update of each row which is unusual? Or we should change some rows only, by a larger amount? A user who really wants to do this can update the cust table directly. The second view shows a column called `years_above_avg`, which is the difference between the age of that customer and the average. Changing that column would be more complex than it seems at first glance: just consider that increasing the age by 10 would not result in increasing the `years_above_avg` by 10, because also the average will be affected. The third view displays a computed column which can definitely not be updated directly - we can't change the value int the `spam_score` column without changing the algorithm implemented by the `spam_score()` function. Now we can proceed to the steps to allow any or all of insertions, updates, or deletions to flow from views to base tables, having clarified whether this makes sense conceptually. # How to do it... There is nothing to do for simple views—PostgreSQL will propagate modifications to the underlying table automatically. Conversely, if the view is not simple enough, but you still have a clear idea of how you would like to propagate changes to the underlying table(s), then you can allow updatable views by telling PostgreSQL how to actually perform DML statements. (DML stands for Data Manipulation Language, which in PostgreSQL means `INSERT`, `UPDATE`, `DELETE` or `TRUNCATE`). PostgreSQL supports two mechanisms to achieve updatable views, namely rewrite rules and `INSTEAD OF` triggers. The latter provide a mechanism to implement updatable views by creating trigger functions that execute arbitrary code every time a data-modification command is executed on the view. The `INSTEAD OF` triggers are part of the SQL standard, and other database systems support them. Conversely, query rewrite rules are specific to PostgreSQL and cannot be found anywhere else in this exact form. There is no clearly preferable method. On one hand, rules can be more efficient than triggers, but on the other hand, they can be more difficult to understand than triggers and could result in inefficient execution if the code is badly written (although the latter is not an exclusive property of rules, unfortunately). To explain this point concretely, we will now provide an example using rules, and then we will re-implement the same example with triggers. We start with a table of mountains and of their height in meters: **CREATE TABLE mountains_m** **( name text primary key** **, meters int not null** **);** Then we create a view that adds a computed column expressing the height in feet, and that displays the data in descending height order: **CREATE VIEW mountains AS** **SELECT *, ROUND(meters / 0.3048) AS feet** **FROM mountains_m** **ORDER BY meters DESC;** DML automatically flows to the base table when inserting only columns that are not computed: **INSERT INTO mountains(name, meters)** **VALUES ('Everest', 8848);** **TABLE mountains;** **name | meters | feet** **-------+--------+-------** **Everest| 8848 | 29029** **(1 row)** However, when we try to insert data with the height specified in feet we get the following error: **INSERT INTO mountains(name, feet)** **VALUES ('K2', 28251);** **ERROR: cannot insert into column "feet" of view "mountains"** **DETAIL: View columns that are not columns of their base relation are not updatable.** So we create a rule that replaces the update with another query that works all the time: **CREATE RULE mountains_ins_rule AS** **ON INSERT TO mountains DO INSTEAD** **INSERT INTO mountains_m** **VALUES (NEW.name, COALESCE (NEW.meters, NEW.feet * 0.3048));** Now we can insert in both `meters` and `feet`: **INSERT INTO mountains(name, feet)** **VALUES ('K 2', 28251);** **INSERT INTO mountains(name, meters)** **VALUES ('Kangchenjunga', 8586);** **TABLE mountains;** **name | meters | feet** **--------------+--------+----** **Everest | 8848 | 29029** **K 2 | 8611 | 28251** **Kangchenjunga | 8586 | 28169** **(3 rows)** Updates are also propagated automatically, but only to non-computed columns: **UPDATE mountains SET name = 'K2' WHERE name = 'K 2';** **TABLE mountains;** **name | meters | feet** **--------------+--------+-------** **Everest | 8848 | 29029** **K2 | 8611 | 28251** **Kangchenjunga | 8586 | 28169** **(3 rows)** **UPDATE mountains SET feet = 29064 WHERE name = 'K2';** **ERROR: cannot update column "feet" of view "mountains"** **DETAIL: View columns that are not columns of their base relation are not updatable.** If we add another rule replacing updates with a query that covers all cases, then the last update will succeed and produce the desired effect: **CREATE RULE mountains_upd_rule AS** **ON UPDATE TO mountains DO INSTEAD** **UPDATE mountains_m** **SET name = NEW.name, meters =** **CASE** **WHEN NEW.meters != OLD.meters** **THEN NEW.meters** **WHEN NEW.feet != OLD.feet** **THEN NEW.feet * 0.3048** **ELSE OLD.meters** **END** **WHERE name = OLD.name;** **UPDATE mountains SET feet = 29064 WHERE name = 'K2';** **TABLE mountains;** **name | meters | feet** **--------------+--------+-------** **K2 | 8859 | 29065** **Everest | 8848 | 29029** **Kangchenjunga | 8586 | 28169** **(3 rows)** The query used in this rule also covers the simpler case of a non-computed column: **UPDATE mountains SET meters = 8611 WHERE name = 'K2';** **TABLE mountains;** **name | meters | feet** **--------------+--------+-------** **Everest | 8848 | 29029** **K2 | 8611 | 28251** **Kangchenjunga | 8586 | 28169** **(3 rows)** The same effect can be achieved by adding the following trigger, which replaces the two rules above: **CREATE FUNCTION mountains_tf()** **RETURNS TRIGGER** **LANGUAGE plpgsql** **AS $$** **BEGIN** **IF TG_OP = 'INSERT' THEN** **INSERT INTO mountains_m VALUES (NEW.name,** **CASE** **WHEN NEW.meters IS NULL** **THEN NEW.feet * 0.3048** **ELSE NEW.meters** **END );** **ELSIF TG_OP = 'UPDATE' THEN** **UPDATE mountains_m** **SET name = NEW.name, meters =** **CASE** **WHEN NEW.meters != OLD.meters** **THEN NEW.meters** **WHEN NEW.feet != OLD.feet** **THEN NEW.feet * 0.3048** **ELSE OLD.meters** **END** **WHERE name = OLD.name;** **END IF;** **RETURN NEW;** **END;** **$$;** **CREATE TRIGGER mountains_tg** **INSTEAD OF INSERT OR UPDATE ON mountains** **FOR EACH ROW** **EXECUTE PROCEDURE mountains_tf();** # How it works... In the rule-based example, we use the `COALESCE` function, which returns the first argument, if not null, or the second one otherwise. When the original `INSERT` statement does not specify a value in meters, then it uses the value in feet divided by `0.3048`. The second rule sets the value in meters to different expressions—if the value in meters was updated we use the new one; if the value in feet was updated, we use the new value in feet divided by `0.3048`, and otherwise we use the old value in meters (that is, we don't change it). The logic implemented in the trigger function is similar to the one above: note that we use the `TG_OP` automatic variable to handle `INSERT` and `UPDATE` separately. We've just scratched the surface of what you can achieve with rules, though personally I find them too complex for widespread use. You can do a lot of things with rules; you just need to be sure that everything you do makes sense and has a practical purpose. There are some other important points that I should mention about rules before you dive in and start using them everywhere. Rules are applied by PostgreSQL after the SQL has been received by the server and parsed for syntax errors, but before the planner tries to optimize the SQL statement. In the rules in the preceding recipe, we referenced the values of the old or the new row, just as we do within trigger functions, using the old and new keywords. Similarly, there are only new values in an `INSERT` command and only old values in a `DELETE` command. One of the major downsides of using rules is that we cannot bulk load data into the table using the `COPY` command. Also, we cannot transform a stream of inserts into a single `COPY` command, nor can we do a `COPY` operation against the view. Bulk loading requires direct access to the table. Suppose we have a view like the following: **CREATE VIEW cust_minor AS SELECT customerid ** **,firstname ** **,lastname ** **,age ** **FROM cust ** **WHERE age < 18;** Then, we have some more difficulties. If we wish to update this view, then you might read the manual and understand that we can use a conditional rule by adding a `WHERE` clause to match the `WHERE` clause in the view, as follows: **CREATE RULE cust_minor_update AS ** **ON update TO cust_minor ** **WHERE new.age < 18 ** **DO INSTEAD ** **UPDATE cust SET firstname = new.firstname** **,lastname = new.lastname** **,age = new.age ** **WHERE** **customerid = old.customerid;** This fails, however, as you can see if you try to update `cust_minor`. The fix is to add two rules, one as an unconditional rule that does nothing (literally) and needs to exist for internal reasons, and the other to do the work we want: **CREATE RULE cust_minor_update_dummy AS ON update TO cust_minor ** **DO INSTEAD NOTHING; ** **CREATE RULE cust_minor_update_conditional AS ** **ON update TO cust_minor ** **WHERE new.age < 18 ** **DO INSTEAD ** **UPDATE cust SET firstname = new.firstname ** **,lastname = new.lastname ** **,age = new.age ** **WHERE customerid = old.customerid;** # There's more... There is yet another question posed by updatable views. As an example, we shall use the `cust_minor` view we just defined, which does not allow performing insertions or updates such that the affected rows fall out of the view itself. For instance, consider this query: **UPDATE cust_minor SET age = 19 WHERE customerid = 123;** The preceding query will not affect any row because of the `WHERE age < 18` conditions in the rule definition. The `CREATE VIEW` statement has a `WITH CHECK OPTION` clause; if specified, any update which excludes any row from the view will fail. If a view includes some updatable columns together with other non-updatable columns (for example expressions, literals, and so on), then updates are allowed if they only change the updatable columns. Finally, it should be noted that some, or perhaps many, DBAs have found rules to be a serious annoyance. Here's one more reason for that: let's try running our main example in a different way, mixing rules with triggers. We'd like to make that view updatable so that it behaves like the following view: **CREATE VIEW cust_view AS SELECT customerid ** **,firstname ** **,lastname ** **,age ** **FROM cust;** Before version 9.3, we couldn't create triggers on views, so let's try to create a table instead, as follows: **CREATE TABLE cust_view AS SELECT * FROM cust WHERE false;** We emulate the view by first creating a `SELECT` rule on the dummy table, and then try to create triggers on the table for the `INSERT`, `UPDATE`, and `DELETE` actions. The rule works only if it is named `_RETURN` and the table is completely empty: **postgres # CREATE RULE "_RETURN" AS ON SELECT TO cust_view DO INSTEAD SELECT * FROM cust; ** **CREATE RULE ** **postgres # CREATE TRIGGER cust_view_modify_after_trig AFTER INSERT OR UPDATE OR DELETE ON cust_view FOR EACH ROW ** **EXECUTE PROCEDURE cust_view_modify_trig_proc(); ** **ERROR: "cust_view" is not a table** Huh? So what is it if it's not a table? **postgres # DROP TABLE cust_view; ** **ERROR: "cust_view" is not a table HINT: Use DROP VIEW to remove a view ** **postgres # DROP VIEW cust_view; ** **DROP VIEW** Wow! That works! Yes, we created a table and then added a rule to it. This turned the table into a view. Now we realize that we can't put triggers on a view and we can't put a `SELECT` rule on a table without it becoming a view. Since triggers are not fired by `SELECT`, this route won't work at all. It is probably best to accept that if you want to load data into a table, then you have to refer to the table directly, rather than use a view. # Using materialized views Every time we select rows from a view, we actually select from the result of the underlying query. If that query is slow and we need to use it more than once, then it makes sense to run the query once, save its output as a table, and then select the rows from the latter. This procedure has been available for a long time, and version 9.3 saw the addition of the dedicated syntax, `CREATE MATERIALIZED VIEW`, which we will describe in this recipe. # Getting ready Let's create two randomly populated tables, of which one is large: **CREATE TABLE dish ** **( dish_id SERIAL PRIMARY KEY ** **, dish_description text ** **); ** **CREATE TABLE eater ** **( eater_id SERIAL ** **, eating_date date ** **, dish_id int REFERENCES dish (dish_id) ** **); ** **INSERT INTO dish (dish_description) ** **VALUES ('Lentils'), ('Mango'), ('Plantain'), ('Rice'), ('Tea'); ** **INSERT INTO eater(eating_date, dish_id) ** **SELECT floor(abs(sin(n)) * 365) :: int + date '2014-01-01' ** **, ceil(abs(sin(n :: float * n))*5) :: int ** **FROM generate_series(1,500000) AS rand(n);** Notice that the data is not truly random. It is generated by a deterministic procedure, so you get exactly the same result if you copy the preceding code. # How to do it... Let's create the following view: **CREATE VIEW v_dish AS ** **SELECT dish_description, count(*) ** **FROM dish JOIN eater USING (dish_id) ** **GROUP BY dish_description ** **ORDER BY 1;** Then, we'll query it: **SELECT * FROM v_dish;** We obtain the following output: **dish_description | count ** **------------------+-------- ** **Lentils | 64236 ** **Mango | 66512 ** **Plantain | 74058 ** **Rice | 90222 ** **Tea | 204972 ** **(5 rows)** With a very similar syntax, we create a materialized view with the same underlying query: **CREATE MATERIALIZED VIEW m_dish AS ** **SELECT dish_description, count(*) ** **FROM dish JOIN eater USING (dish_id) ** **GROUP BY dish_description ** **ORDER BY 1;** The corresponding query yields the same output as before: **SELECT * FROM m_dish;** The materialized version is much faster than the non-materialized version. On my laptop, their execution times are 0.2 ms versus 300 ms. # How it works... Creating a non-materialized view is exactly the same as creating an empty table with a `SELECT` rule, as we discovered from the previous recipe. No data is extracted until the view is actually used. When creating a materialized view, the default is to run the query immediately and then store its results, like we do for table content. In short, creating a materialized view is slow, but using it is fast. This is the opposite of standard views, which are created instantly and recomputed at every use. # There's more... The output of a materialized view is physically stored like a regular table, and the analogy doesn't stop here. In both cases, it is possible to create indexes to speed up queries. A materialized view will not automatically change when its constituent tables change. For that to happen, you must issue the following: **REFRESH MATERIALIZED VIEW m_dish;** This replaces all the contents of the view with newly computed ones. It is possible to quickly create an empty materialized view and populate it later. Just add `WITH NO DATA` at the end of the `CREATE MATERIALIZED VIEW` statement. Obviously, the view cannot be used before being populated, which you can do with `REFRESH MATERIALIZED VIEW`, as you just saw. A materialized view cannot be read while it is being refreshed. For that, you need to use the `CONCURRENTLY` clause at the expense of a somewhat slower refresh. As you can understand from these paragraphs, currently there is only a partial advantage in using materialized views, compared to previous solutions such as this: **CREATE UNLOGGED TABLE m_dish AS SELECT * FROM v_dish;** However, when using a declarative language, such as SQL, the same syntax may automatically result in a more efficient algorithm in case of future improvements of PostgreSQL. For instance, one day PostgreSQL will be able to perform a faster refresh by simply replacing those rows that changed, instead of recomputing the entire content. # Monitoring and Diagnosis In this chapter, you will find recipes for some common monitoring and diagnosis actions you will want to do inside your database. They are meant to answer specific questions that you often face when using PostgreSQL. Databases are not isolated entities. They live on computer hardware using CPUs, RAM, and disk subsystems. Users access databases using networks. Depending on the setup, databases themselves may need network resources to function in any of the following ways: performing some authentication checks when users log in, using disks that are mounted over the network (not generally recommended), or making remote function calls to other databases. This means that _monitoring only the database is not enough_. As a minimum, one should also monitor everything directly involved in using the database. This means knowing the following: * Is the database host available? Does it accept connections? * How much of the network bandwidth is in use? Have there been network interruptions and dropped connections? * Is there enough RAM available for the most common tasks? How much of it is left? * Is there enough disk space available? When will you run out of disk space? * Is the disk subsystem keeping up? How much more load can it take? * Can the CPU keep up with the load? How many spare idle cycles do the CPUs have? * Are other network services the database access depends on (if any) available? For example, if you use Kerberos for authentication, you need to monitor it as well. * How many context switches are happening when the database is running? * For most of these things, you are interested in the history; that is, how have things evolved? Was everything mostly the same yesterday or last week? * When did the disk usage start changing rapidly? * For any larger installation, you probably have something already in place to monitor the health of your hosts and network. The two aspects of monitoring are collecting historical data to see how things have evolved, and getting alerts when things go seriously wrong. Tools based on a **Round Robin Database Tool** ( **RRDtool** ) such as **Munin** , or time series databases such as Graphite's **Carbon** , and **Prometheus** , are quite popular for collecting the historical information on all aspects of the servers and presenting this information in an easy-to-follow graphical form, for which Grafana is a popular tool. Seeing several statistics on the same timescale can really help when trying to figure out why the system is behaving the way it is. Another aspect of monitoring is getting alerts when something goes really wrong and needs (immediate) attention. For alerting, one of the most widely used tools is **Icinga** (a fork of **Nagios** ), an established solution. The aforementioned trending tools can integrate with it. `check_postgres` is a rather popular Icinga plugin for monitoring many standard aspects of a PostgreSQL database server. Icinga is a stable and mature solution, based on the long-standing approach where each plugin decides whether a given measurement is cause of alarm, more complex to manage and maintain. A more recent tool is the aforementioned **Prometheus** , based on a design that separates data collection from the centralized alerting logic. Should you need a solution for both the alerting and trending aspects of a monitoring tool, you might also want to look into **Zabbix**. Furthermore, if you require integration with a system based on **Simple Network Management Protocol** ( **SNMP** ), the `pgsnmpd` project offers some basic support. However, as it is not actively maintained, we recommend switching to one of the other monitoring approaches if at all possible. In this chapter, we will cover the following recipes: * Providing PostgreSQL information to monitoring tools * Real-time viewing using pgAdmin or OmniDB * Checking whether a user is connected * Checking whether a computer is connected * Repeatedly executing a query in psql * Checking which queries are running * Checking which queries are active or blocked * Knowing who is blocking a query * Killing a specific session * Detecting an in-doubt prepared transaction * Knowing whether anybody is using a specific table * Knowing when a table was last used * Usage of disk space by temporary data * Understanding why queries slow down * Investigating and reporting a bug * Producing a daily summary of log file errors * Analyzing the real-time performance of your queries # Providing PostgreSQL information to monitoring tools It's best to use historical monitoring information when all of it is available from the same place and on the same timescale. Most monitoring systems are designed for generic purposes, while allowing application and system developers to integrate their specific checks with the monitoring infrastructure. This is possible through a plugin architecture. Adding new kinds of data inputs to them means installing a plugin. Sometimes, you may need to write or develop this plugin, but writing a plugin for something such as Cacti is easy. You just have to write a script that outputs monitored values in simple text format. In most common scenarios, the monitoring system is centralized and data is collected directly (and remotely) by the system itself or through some distributed components that are responsible for sending the observed metrics back to the main node. As far as PostgreSQL is concerned, some useful things to include in graphs are the number of connections, disk usage, number of queries, number of WAL files, most numbers from `pg_stat_user_tables` and `pg_stat_user_indexes`, and so on. One _Swiss Army knife_ script, which can be used from both Cacti and Nagios/Icinga, is `check_postgres`. It is available at http://bucardo.org/wiki/Check_postgres. It has ready-made reporting actions for a large array of things worth monitoring in PostgreSQL. For Munin, there are some PostgreSQL plugins available at the Munin plugin repository at https://github.com/munin-monitoring/contrib/tree/master/plugins/postgresql. The following screenshot shows a Munin graph about PostgreSQL buffer cache hits for a specific database, where cache hits (the blue line) dominate reads from the disk (the green line): # Finding more information about generic monitoring tools Setting up the tools themselves is a larger topic, and it is beyond the scope of this book. In fact, each of these tools has more than one book written about them. The basic setup information and the tools themselves can be found at the following URLs: * RRDtool: <http://www.mrtg.org/rrdtool/> * Cacti: <http://www.cacti.net/> * Icinga: http://www.icinga.org * Munin: <http://munin-monitoring.org/> * Nagios: http://www.nagios.org/ * Zabbix: http://www.zabbix.org/ # Real-time viewing using pgAdmin or OmniDB You can also use a GUI tool such as pgAdmin or OmniDB, which we discussed first in Chapter 1, _First Steps_ to get a quick view of what is going on in the database. # Getting ready If you use pgAdmin, for better control you need to install the `adminpack` extension in the destination database by issuing this command: **CREATE EXTENSION adminpack;** This extension is a part of the additionally supplied modules of PostgreSQL (aka contrib). It provides several administration functions that pgAdmin (and other tools) can use in order to manage, control, and monitor a Postgres server from a remote location. # How to do it... (with pgAdmin) The following section illustrates the pgAdmin tool. Once you have installed `adminpack`, connect to the database server; this will open a window similar to that shown in the following screenshot, reporting a general view plus information on connections, locks, and running transactions: # How to do it... (with OmniDB) Here's another section that illustrates the OmniDB tool: After starting OmniDB and opening a database, a tab called Monitoring is automatically displayed, as in the following screenshot: The Monitoring tab shows a series of charts and diagrams about sessions, locks, activity, database size, and table size. The display can be customized by adding/removing charts from a list of predefined templates, or by creating a bespoke chart, by modifying the data script and/or the chart script. The easiest way to add a new type of chart is to take an existing one, understanding first what information it displays, and then using it as a starting point for making a different one. # Checking whether a user is connected Here, we will show you how to learn whether a certain database user is currently connected to the database. # Getting ready If you are logged in as a superuser you will have full access to monitoring information. # How to do it... Issue the following query to see whether the `bob` user is connected: **SELECT datname FROM pg_stat_activity WHERE usename = 'bob';** If this query returns any rows, then it means `bob` is connected to the database. The returned value is the name of the database to which the user is connected. # How it works... PostgreSQL's `pg_stat_activity` system view keeps track of all running PostgreSQL backends. This includes information such as the query that is being currently executed, or the last query that was executed by each backend; who is connected; when the connection, the transaction, and/or the query were started; and so on. # There's more... Please spend a few minutes reading the PostgreSQL documentation, which contains more detailed information about `pg_stat_activity`, available at http://www.postgresql.org/docs/current/static/monitoring-stats.html#PG-STAT-ACTIVITY-VIEW. You can find answers to many administration-related questions by analyzing the `pg_stat_activity` view. One common example is outlined in the next recipe. # Checking whether a computer is connected Often, several different processes may connect as the same database user. In that case, you may actually want to know whether there is a connection from a specific computer. # How to do it... You can get this information from the `pg_stat_activity` view, as it includes the connected clients' IP address, port, and hostname (where applicable). The port is only needed if you have more than one connection from the same client computer and you need to do further digging to see which process there connects to which database. Run the following command: **SELECT datname, usename, client_addr, client_port, ** **application_name FROM pg_stat_activity;** The `client_addr` and `client_port` parameters help you look up the exact computer and even the process on that computer that has connected to the specific database. You can also retrieve the hostname of the remote computer through the `client_hostname` option (this requires `log_hostname` to be set to `on`). # There's more... I would always recommend including `application_name` in your reports. This field has become widely recognized and honored by third-party application developers (I advise you to do the same with your own applications). For information on how to set the application name for your connections, refer to _Database Connection Control Functions_ in the PostgreSQL documentation at http://www.postgresql.org/docs/current/static/libpq-connect.html. # Repeatedly executing a query in psql Sometimes we want to execute a query more than once, repeated at regular intervals; in this recipe we see an interesting `psql` command that does exactly that. # How to do it... The `\watch` meta-command allows psql users to automatically (and continuously) re-execute a query. This behavior is similar to the `watch` utility of some Linux and Unix environments. In the following example, we run a simple query on `pg_stat_activity` and ask psql to repeat it every 5 seconds. You can exit at any time by pressing _Ctrl_ \+ _C_ : **gabriele= > SELECT count(*) FROM pg_stat_activity; ** **count ** **------- ** **1 ** **(1 row) ** ** gabriele= > \watch 5 ** **Watch every 5s Tue Aug 27 21:47:24 2013 ** ** count ** **------- ** **1 ** **(1 row) ** **< snip>** # There's more... For further information about the psql utility, refer to the PostgreSQL documentation at http://www.postgresql.org/docs/current/static/app-psql.html. # Checking which queries are running Here we will show you how to check which query is currently running. # Getting ready You have to make sure that you are logged in as a superuser or as the same database user you want to check. Also, ensure that the parameter `track_activities = on` is set (which it normally should be, being the default setting). If not, check the _Updating the parameter file_ recipe in Chapter 3, _Configuration_. # How to do it... To see which connected users are running at this moment, just run the following: **SELECT datname, usename, state, query ** **FROM pg_stat_activity;** On systems with a lot of users, you may notice that the majority of backends have `state` set to `idle`. This denotes that no query is actually running, and PostgreSQL is waiting for new commands from the user. The `query` field shows the statement that was last executed by that particular backend. If, on the other hand, you are interested in active queries only, limit your selection to those records that have `state` set to `active`: **SELECT datname, usename, state, query ** **FROM pg_stat_activity WHERE state = 'active';** # How it works... When `track_activities = on` is set, PostgreSQL collects data about all running queries. Users with sufficient rights can then view this data using the `pg_stat_activity` system view. The `pg_stat_activity` view uses a system function named `pg_stat_get_activity (procpid int)`. You can use this function directly to watch for the activity of a specific backend by supplying the process ID as an argument. Giving `NULL` as an argument returns information for all backends. # There's more... Sometimes, you don't care about getting all queries that are currently running. You may be only interested in seeing some of these, or you may not like to connect to the database just to see what is running. # Catching queries that only run for a few milliseconds As most queries on modern **online transaction processing** ( **OLTP** ) systems take only a few milliseconds to run, it is often hard to catch the active ones when simply probing the `pg_stat_activity` table. Most likely, you will be able to see only the last executed query for those backends that have `state` different from `active`. In some cases, this can be enough. In general, if you need to perform a deeper analysis, I strongly recommend installing and configuring the `pg_stat_statements` module, which is described in the _Analyzing the real-time performance of your queries_ recipe in this chapter. Another option is to run a post analysis of log files using pgBadger. Depending on the workload of your system, you may want to limit the production of highly granular log files (that is, log all queries) to a short period of time. For further information on pgBadger, refer to the _Producing a daily summary of log file errors_ recipe of this chapter. # Watching the longest queries Another thing of interest that you may want to look for is long-running queries. To get a list of running queries ordered by how long they have been executing, use the following: **SELECT ** **current_timestamp - query_start AS runtime, ** **datname, usename, query ** **FROM pg_stat_activity ** **WHERE state = 'active' ** **ORDER BY 1 DESC;** This will return currently running queries, with the longest running queries in the front. On busy systems, you may want to limit the set of queries returned to only the first few queries (add `LIMIT 10` at the end) or only the queries that have been running over a certain period of time. For example, to get a list of queries that have been running for more than a minute, use this query: **SELECT ** **current_timestamp - query_start AS runtime, ** **datname, usename, query ** **FROM pg_stat_activity ** **WHERE state = 'active' ** **AND current_timestamp - query_start > '1 min' ** **ORDER BY 1 DESC;** # Watching queries from ps If you want, you can also make queries being run show up in process titles by setting the following in the `postgresql.conf` file: update_process_title = on Although the `ps` and `top` output are not the best places for watching database queries, they may make sense in some circumstances. # See also * The page in PostgreSQL's online documentation that covers the appropriate settings is available at http://www.postgresql.org/docs/current/static/runtime-config-statistics.html # Checking which queries are active or blocked Here, we will show you how to know whether a query is actually running or waiting for another query. # Getting ready If you are logged in as superuser you will have full access to monitoring information. # How to do it... 1. You can run the following query: **SELECT datname ** **, usename ** **, wait_event_type ** **, wait_event ** **, query ** **FROM pg_stat_activity WHERE wait_event_type IS NOT NULL** **AND wait_event_type NOT IN ('Activity', 'Client');** 2. The output will look like the following: **-[ RECORD 1 ]---+-----------------** **datname | postgres** **usename | gianni** **wait_event_type | Lock** **wait_event | relation** **query | select * from t;** # How it works... The `pg_stat_activity` system view includes the `wait_event_type` and `wait_event` columns, which are set respectively to the kind of wait and to the kind of object that is blocked. The preceding query uses the `wait_event` field to filter out only those queries that are waiting. # There's more... Further explanation about the preceding queries is appropriate here. # No need for the = true part As the `waiting` column is already Boolean, you can safely omit the `= true` part from the query and simply write the following: **SELECT datname, usename, query ** **FROM pg_stat_activity ** **WHERE waiting;** # Do we catch all queries waiting on locks? PostgreSQL provides a version of the `pg_stat_activity` view capable of capturing many kinds of waits; however, in older versions `pg_stat_activity` could only detect waits on locks such as those placed on SQL objects, via the `pg_stat_activity.waiting` field. Although this is the main cause of waiting when using pure SQL, it is possible to write a query in any of PostgreSQL's embedded languages that can wait on other system resources, such as waiting for an HTTP response, for a file write to get completed, or just waiting on a timer. As an example, you can make your backend sleep for a certain number of seconds using `pg_sleep(seconds)`. While you are monitoring `pg_stat_activity`, open a new terminal session with `psql` and run the following statement in it: **db=# SELECT pg_sleep(10); ** **< it "stops" for 10 seconds here> ** **pg_sleep ** **---------- ** **(1 row) ** It will show up as _not waiting_ in the `pg_stat_activity` view, even though the query is, in fact, blocked in the timer. # Knowing who is blocking a query Once you have found out that a query is blocked, you need to know who or what is blocking them. # Getting ready If you are logged in as a superuser you will have full access to monitoring information. # How to do it... 1. You can write the following query: **SELECT datname ** **, usename ** **, wait_event_type ** **, wait_event ** **, pg_blocking_pids(pid) AS blocked_by ** **, query ** **FROM pg_stat_activity WHERE wait_event_type IS NOT NULL** **AND wait_event_type NOT IN ('Activity', 'Client');** 2. You will get an output like the following: **-[ RECORD 1 ]---+-----------------** **datname | postgres** **usename | gianni** **wait_event_type | Lock** **wait_event | relation** **blocked_by | {18142}** **query | select * from t;** This is in fact the query described in the previous recipe, with the addition of the column called `blocked_by`. Recall that the PID is the unique identifier assigned by the operating system to each session; for more details, see Chapter 4, _Server Control_. Here the PID is used by the `pg_blocking_pids(pid)` system function to identify blocking sessions. Parallel queries allow powerful queries using multiple cores, but also increase the number of ways in which one query can be blocked by another; think how complicated it can be to extract dependencies and display them neatly if there are multiple PIDs for a single session. # How it works... The query is relatively simple: we just introduced the `pg_blocking_pids()` function, which returns an array composed by the PIDs of all the sessions that are blocking the session with the given PID. # Killing a specific session Sometimes, the only way to let the system continue as a whole is by _surgically_ terminating some offending database sessions. Yes, you read it right: surgically. You might indeed be tempted to _reboot_ the server, but you should think of that as a last resort in a business continuity scenario. In this recipe, you will learn how to intervene, from gracefully canceling a query to brutally killing the actual process from the command line. # How to do it... You can either run this function as a superuser or with the same user as that of the offending backend (look for the `usename` field in the `pg_stat_activity` view). Once you have figured out the backend you need to kill, use the function named `pg_terminate_backend(pid)` to kill it. # How it works... When a backend executes the `pg_terminate_backend(pid)` function, it sends a signal, `SIGTERM`, to the backend as an argument after verifying that the process identified by the argument `pid` is actually a PostgreSQL backend. The backend receiving this signal stops whatever it is doing, and terminates it in a controlled way. The client using that backend loses the connection to the database. Depending on how the client application is written, it may silently reconnect, or it may show an error to the user. # There's more... Killing the session may not always be what you really want, so consider other options as well. It might also be a good idea to look at the _Server Signaling Functions_ section in the PostgreSQL documentation at http://www.postgresql.org/docs/current/static/functions-admin.html#FUNCTIONS-ADMIN-SIGNAL. # Try to cancel the query first First, you may want to try `pg_cancel_backend(pid)`, a milder version of `pg_terminate_backend(pid)`. The difference between these two is that `pg_cancel_backend()` just cancels the current query, whereas `pg_terminate_backend()` really kills the backend (therefore, this can be used for `idle` or `idle in transaction` backends). # What if the backend won't terminate? If `pg_terminate_backend(pid)` fails to kill the backend and you really need to reset the database state to make it continue processing requests, then you have yet another option: sending `SIGKILL` to the offending backend. This can be done only from the command line as the `root` or the `postgres` system user, and on the same host the database is running on, by executing the following code: **kill -9 <backend_pid>** This command kills that backend immediately, without giving it a chance to clean up. Consequently, the postmaster is forced to kill all the other backends as well and restart the whole cluster. Therefore, it actually does not matter which of the PostgreSQL backends you kill. You must be extremely careful if you have set the `synchronous_commit` parameter to `off`. You may end up losing some supposedly committed transactions if you use `kill -9` on a backend. Thus, `kill -9` is the last resort, but only if nothing else helps, and not on a regular basis. # Using statement_timeout to clean up queries that take too long to run Often, you know that you don't have any use for queries running longer than a given time. Maybe your web frontend just refuses to wait for more than 10 seconds for a query to complete and returns a default answer to users if it takes longer, abandoning the query. In such a case, it might be a good idea to set `statement_timeout = 10 sec`, either in `postgresql.conf` or as a per-user or per-database setting. Once you do so, queries running too long won't consume precious resources and make others' queries fail. The queries terminated by a statement timeout show up in the log, as follows: **hannu=# SET statement_timeout TO '3 s'; ** **SET ** **hannu=# SELECT pg_sleep(10); ** **ERROR: canceling statement due to statement timeout** For the older versions of PostgreSQL, they show up as a more confusing message: `query canceled due to user request`. # Killing idle in transaction queries Sometimes, people start a transaction, run some queries, and then just leave, without ending the transaction. This can leave some system resources in a state where some housekeeping processes can't be run. They may even have done something more serious, such as locking a table, thereby causing immediate _denial of service_ for other users who need that table. You can use the following query to kill all backends that have an open transaction but have been doing nothing for the last 10 minutes: **SELECT pg_terminate_backend(pid) ** **FROM pg_stat_activity ** **WHERE state = 'idle in transaction' ** **AND current_timestamp - query_start > '10 min';** You can even schedule this to run every minute while you are trying to find the specific frontend application that ignores open transactions, or when you have a lazy administration that leaves a psql connection open, or when a flaky network drops clients without the server noticing it. # Killing the backend from the command line Another possibility to terminate a backend is by using a Unix/Linux command named `kill N`. This command orders the `SIGTERM` signal to process `N` on the system where it is running. You have to be either the `root` user or the user running the database backends (usually `postgres`) to be able to send signals to processes. You can cancel a backend (and simulate the `pg_cancel_backend(pid)` function) by sending a `SIGINT` signal: **kill -SIGINT <backend_pid>** For more detailed information and the exact syntax, type `man kill` from your favorite shell environment. # Detecting an in-doubt prepared transaction While using **two-phase commit** ( **2PC** ), you may end up in a situation where you have something locked but cannot find a backend that holds the locks. This recipe describes how to detect such a case. # How to do it... 1. You need to look up the `pg_locks` table for those entries with an empty `pid` value. Run this query: **SELECT t.schemaname || '.' || t.relname AS tablename, ** **l.pid, l.granted ** **FROM pg_locks l JOIN pg_stat_user_tables t ** **ON l.relation = t.relid;** 2. The output will be something similar to the following: **tablename | pid | granted** **-----------+-------+--------- ** **db.x | | t ** **db.x | 27289 | f ** **(2 rows)** The preceding example shows a lock on the `db.x` table, which has no process associated with it. If you need to remove a particular prepared transaction, you can refer to the _Removing old prepared transactions_ recipe in Chapter 9, _Regular Maintenance_. # Knowing whether anybody is using a specific table This recipe helps you when you are in doubt whether some obscure table is used any more or it is left over from the past and just takes up space. # Getting ready Make sure that you are a superuser, or at least have full rights to the table in question. # How to do it... 1. To see whether a table is currently in active use (that is, whether anyone is using it while you are watching it), run the following query on the database you plan to inspect: **CREATE TEMPORARY TABLE tmp_stat_user_tables AS ** **SELECT * FROM pg_stat_user_tables;** 2. Then wait a little, and see what has changed: **SELECT * FROM pg_stat_user_tables n** **JOIN tmp_stat_user_tables t** **ON n.relid=t.relid** **AND (n.seq_scan,n.idx_scan,n.n_tup_ins,n.n_tup_upd,n.n_tup_del)** ** <> (t.seq_scan,t.idx_scan,t.n_tup_ins,t.n_tup_upd,t.n_tup_del);** # How it works... The `pg_stat_user_tables` view shows the current statistics for table usage. To see whether a table is used, you check for changes in its usage counts. The previous query selects all the tables where any of the usage counts for `SELECT` or data manipulation have changed. # There's more... You can use one of the following approaches to detect usage changes. # The quick-and-dirty way If you are sure that you have no use for the cumulative statistics gathered by PostgreSQL, you can just reset all table statistics by executing the following command: **SELECT pg_stat_reset();** This sets all statistics to zero, and you can detect table use by just looking for tables where any usage count is not zero. Of course, you can make a backup copy of the statistics table first, as follows: **CREATE TABLE backup_stat_user_tables AS ** **SELECT current_timestamp AS snaptime, ** *** ** **FROM pg_stat_user_tables;** # Collecting daily usage statistics It is often useful to have historical usage statistics for tables when trying to solve performance problems or understand usage patterns. For this purpose, you can collect usage data in a regular manner, daily or even more often, using either a cron or a PostgreSQL-specific scheduler such as `pg_agent`. Advanced users can take advantage of background workers to schedule such an activity. For more information on background worker processes, go to http://www.postgresql.org/docs/current/static/bgworker.html. The following query adds a snapshot of current usage statistics with a timestamp to the table created earlier: **INSERT INTO backup_stat_user_tables ** **SELECT current_timestamp AS snaptime, ** *** ** **FROM pg_stat_user_tables;** # Knowing when a table was last used Once you know that a table is not currently used, the next question is _When was it last used?_ # Getting ready Using a user with appropriate privileges. # How to do it... PostgreSQL does not have any built-in _last used_ information about tables, so you have to use other means to figure it out. If you have set up a cron job to collect usage statistics, as described in the previous chapter, then it is relatively easy to find out the last date of change using a SQL query. Other than this, there are basically two possibilities, neither of which gives you absolutely reliable answers. You can either look at the actual timestamps of the files in which the data is stored, or you can use the `xmin` and `xmax` system columns to find out the latest transaction ID that changed the table data. In this recipe, we cover the first case and focus on the date information in the table's files. The following PL/pgSQL function looks for the table's data files to get the value of their last access and modification times: **CREATE OR REPLACE FUNCTION table_file_access_info( ** **IN schemaname text, IN tablename text, ** **OUT last_access timestamp with time zone, ** **OUT last_change timestamp with time zone ** **) LANGUAGE plpgsql AS $func$ ** **DECLARE ** **tabledir text; ** **filenode text; ** **BEGIN ** **SELECT regexp_replace( ** **current_setting('data_directory') || '/' || pg_relation_filepath(c.oid), ** **pg_relation_filenode(c.oid) || '$', ''), ** **pg_relation_filenode(c.oid) ** **INTO tabledir, filenode ** **FROM pg_class c ** **JOIN pg_namespace ns ** **ON c.relnamespace = ns.oid ** **AND c.relname = tablename ** **AND ns.nspname = schemaname; ** **RAISE NOTICE 'tabledir: % - filenode: %', tabledir, filenode; ** **-- find latest access and modification times over all segments ** **SELECT max((pg_stat_file(tabledir || filename)).access), ** **max((pg_stat_file(tabledir || filename)).modification) ** **INTO last_access, last_change ** **FROM pg_ls_dir(tabledir) AS filename ** **-- only use files matching <basefilename>[.segmentnumber] ** **WHERE filename ~ ('^' || filenode || '([.]?[0-9]+)?$'); ** **END; ** **$func$;** # How it works... The `table_file_access_info(schemaname, tablename)` function returns the last access and modification times for a given table using the filesystem as a source of information. The last query uses this data to get the latest time any of these files were modified or read by PostgreSQL. Beware that this is not a very reliable way to get information about the latest use of any table, but it gives you a rough upper-limit estimate about when it was last modified or read (for example, consider the autovacuum process accessing a table). You can definitely improve and personalize the preceding function. I advise you to look at the PostgreSQL documentation and read about two built-in functions, `pg_ls_dir(dirname text)` and `pg_stat_file(filename text)`. Another good source of information is the _Database File Layout_ page in the PostgreSQL documentation at http://www.postgresql.org/docs/current/static/storage-file-layout.html. # There's more... Recently, there have been discussions about adding last-used data to the information about tables that PostgreSQL keeps, so it is quite possible that answering the question _when did anybody last use this table?_ will be much easier in the next version of PostgreSQL. # Usage of disk space by temporary data In addition to ordinary persistent tables, you can also create temporary tables. Also, PostgreSQL may use temporary files for query processing if it can't fit all the necessary data into the memory. So, how do you find out how much data is used by temporary tables and files? You can do this using any untrusted embedded language, or directly on the database host. # Getting ready You have to use an untrusted language, because trusted languages run in a sandbox, which prohibits them from directly accessing the host filesystem. # How to do it... Perform the following steps: 1. First, check whether your database defines special tablespaces for temporary files, as follows: **SELECT current_setting('temp_tablespaces');** 2. As explained later on in this recipe, if the setting is empty, it means PostgreSQL is not using temporary tablespaces, and temporary objects will be located in the default tablespace for each database. 3. On the other hand, if `temp_tablespaces` has one or more tablespaces, then your task is easy because all temporary files, both those used for temporary tables and those used for query processing, are inside the directories of these tablespaces. The following query (which uses `WITH` queries and string and array functions) demonstrates how to check the space used by temporary tablespaces: **WITH temporary_tablespaces AS (SELECT** **unnest(string_to_array(** **current_setting('temp_tablespaces'), ',')** **) AS temp_tablespace** **)** **SELECT tt.temp_tablespace,** **pg_tablespace_location(t.oid) AS location,** **pg_tablespace_size(t.oid) AS size** **FROM temporary_tablespaces tt** **JOIN pg_tablespace t ON t.spcname = tt.temp_tablespace** **ORDER BY 1;** The output shows very limited use of temporary space (I ran the preceding query while I had two open transactions that had just created small, temporary tables using random data through `generate_series()`): **temp_tablespace | location | size** **-----------------+--------------+---------** **pgtemp1 | /srv/pgtemp1 | 3633152** **pgtemp2 | /srv/pgtemp2 | 376832** **(2 rows)** Even though you can obtain similar results using different queries, or just by checking the disk usage from the filesystem through `du` (once you know the location of tablespaces), I would like to focus on two functions here: * `pg_tablespace_location(oid)`: This provides the location of the tablespace with the given `oid` * `pg_tablespace_size(oid)` or `pg_tablespace_size(name)`: This allows us to check the size used by a named tablespace directly within PostgreSQL Because the amount of temporary disk space used can vary a lot in an active system, you may want to repeat the query several times to get a better picture of how the disk usage changes (with psql, use `\watch`, as explained in the _Checking whether a user is connected_ recipe). Further information on these functions can be found at http://www.postgresql.org/docs/current/static/functions-admin.html. On the other hand, if the `temp_tablespaces` setting is empty, then the temporary tables are stored in the same directory as ordinary tables, and the temporary files used for query processing are stored in the `pgsql_tmp` directory inside the main database directory. Look up the cluster's `home` directory using this query: **SELECT current_setting('data_directory') || '/base/pgsql_tmp'** The size of this directory gives the total size of current temporary files for query processing. The total size of temporary files used by a database can be found in the `pg_stat_database` system view, and specifically in the two fields `temp_files` and `temp_bytes`. The following query returns the cumulative number of temporary files and the space used by every database since the last reset (`stats_reset`): **SELECT datname, temp_files, temp_bytes, stats_reset ** **FROM pg_stat_database;** The `pg_stat_database` view holds very important statistics. I recommend that you look at the official documentation at http://www.postgresql.org/docs/current/static/monitoring-stats.html#PG-STAT-DATABASE-VIEW for detailed information and to get further ideas on how to improve your monitoring skills. # How it works... Because all temporary tables and other temporary on-disk data are stored in files, you can use PostgreSQL's internal tables to find the locations of these files, and then determine the total size of these files. # There's more... While the preceding information about temporary tables is correct, it is not the entire story. # Finding out whether a temporary file is in use any more Because temporary files are not as carefully preserved as ordinary tables (this is actually one of the benefits of temporary tables, as less bookkeeping makes them faster), it may sometimes happen that a system crash leaves a few temporary files, which can (in the worst cases) take up a significant amount of disk space. As a rule, you can clean up such files by shutting down the PostgreSQL server and then deleting all files from the `pgsql_tmp` directory. # Logging temporary file usage If you set `log_temp_files = 0` or a larger value, then the creation of all temporary files that are larger than this value in kilobytes is logged to the standard PostgreSQL log. If, while monitoring the log and the `pg_stat_database` view, you notice an increase in temporary file activity, you should consider increasing `work_mem`, either globally or (preferably) on a query/session basis. # Understanding why queries slow down In production environments with large databases and high concurrent access, it might happen that queries that used to run in tens of milliseconds suddenly take several seconds. Likewise, a summary query for a report that used to run in a few seconds might take half an hour to complete. Here are some ways to find out what is slowing them down. # Getting ready Any questions of the type _Why is this different today from what it was last week_? are much easier to answer if you have some kind of historical data collection setup. Tools such as Cacti or Munin (for monitoring general server characteristics such as CPU and RAM usage, disk I/O, network traffic, and load average) are very useful to see what has changed recently, and to try to correlate these changes with the observed performance of some database operations. Also, collecting historical statistics data from `pg_stat_*` tables, whether daily, hourly, or even every five minutes if you have enough disk space, is also very useful for detecting possible causes of sudden changes or a gradual degradation in performance. If you are gathering both of these, then that's even better. If you have none, then the question is actually: _Why is this query slow?_ But don't despair! There are a few things you can do to try to restore performance. # How to do it... First, analyze your database using this code: **db_01=# analyse;** **ANALYZE** **Time: 6231.313 ms** **db_01=#** This is the first thing to try, as it is usually cheap and is meant to be done quite often anyway. If this restores the query's performance or at least improves the current performance considerably, then it means that autovacuum is not doing its task well, and the next thing to do is to find out why. You must ensure that the performance improvement is not due to caching of the pages required by the requested query. Make sure that you repeat your query several times before classifying it as slow. Looking at `pg_stat_statements` (which is covered later in this chapter) can help you analyze the impact of a particular query in terms of caching, by inspecting two fields: `shared_blks_hit` and `shared_blks_read`. # How it works... The `ANALYZE` command updates statistics about data size and data distribution in all tables. If a table size has changed significantly without its statistics being updated, then PostgreSQL's statistics-based optimizer may choose a bad plan. Manually running the `ANALYZE` command updates the statistics for all tables. # There's more... There are a few other common problems. # Do the queries return significantly more data than they did earlier? If you've initially tested your queries on almost empty tables, it is entirely possible that you are querying much more data than you need. As an example, if you select all users' items and then show the first 10 items, this query runs very fast when the user has 10 or even 50 items, but not so well when they have 50,000. Ensure that you don't ask for more data than you need. Use the `LIMIT` clause to return less data to your application (and to give the optimizer at least a chance to select a plan that processes less data when selecting: it may also have a lower startup cost). In some cases, you can evaluate the use of cursors for your applications. # Do the queries also run slowly when they are run alone? If you can, then try to run the same slow query when the database has no (or very few) other queries running concurrently. If it runs well in this situation, then it may be that the database host is just overloaded (CPU, memory, or disk I/O) or other applications are interfering with Postgres on the same server. Consequently, a plan that works well under a light load is not so good any more. It may even be that this is not a very good query plan with which to begin, and you were fooled by modern computers being really fast: **db=# select count(*) from t; ** **count ** **--------- ** **1000000 ** **(1 row) ** **Time: 329.743 ms** As you can see, scanning 1 million rows takes just 0.3 seconds on a laptop that is a few years old if these rows are already cached. However, if you have a few such queries running in parallel, and also other queries competing for memory, this query is likely to slow down an order of magnitude or two. See Chapter 10, _Performance and Concurrency_ , for general advice on performance tuning. # Is the second run of the same query also slow? This test is related to the previous test, and it checks whether the slowdown is caused by some of the necessary data not fitting into the memory or being pushed out of the memory by other queries. If the second run of the query is fast, then you probably lack enough memory. Again, see Chapter 10, _Performance and Concurrency_ , for details about this. # Table and index bloat Table bloat is something that can develop over time if some maintenance processes can't be run properly. In other words, due to the way **Multiversion Concurrency Control** ( **MVCC** ) works, your table will contain a lot of older versions of rows, if these versions can't be removed in a timely manner. There are several ways this can develop, but all involve lots of updates or deletes and inserts, while autovacuum is prevented from doing its job of getting rid of old tuples. It is possible that, even after the old versions are deleted, the table stays at its newly acquired and large size, thanks to visible rows being located at the end of the table and preventing PostgreSQL from shrinking the file. There have been cases where a one-row table has grown to several gigabytes in size. If you suspect that some tables may contain bloat, then run the following query: **SELECT pg_relation_size(relid) AS tablesize,schemaname,relname,n_live_tup** **FROM pg_stat_user_tables** **WHERE relname = <tablename>;** Then, see whether the relation of `tablesize` to `n_live_tup` makes sense. For example, if the table size is tens of megabytes, and there are only a small number of rows, then you have bloat, and proper `VACUUM` strategies are necessary (as explained in Chapter 9, _Regular Maintenance_ ). It is important to check that the statistics are up-to-date. You might indeed need to run `ANALYSE` on the table and run the query again. # See also * The _Collecting daily usage statistics_ section shows one way to collect info on table changes * Chapter 9, _Regular Maintenance_ * Chapter 10, _Performance and Concurrency_ * The _How many rows in a table?_ recipe in Chapter 2, _Exploring the Database_ , for an introduction to MVCC * The `auto_explain` contrib module at http://www.postgresql.org/docs/current/static/auto-explain.html # Investigating and reporting a bug When you find out that PostgreSQL is not doing what it should, then it's time to investigate. # Getting ready It is a good idea to make a full copy of your PostgreSQL installation before you start investigating. This will help you restart several times and be sure that you are actually investigating the results of the bug, and not chasing your own tail by looking at changes introduced by your last investigation and debugging attempt. Do not forget to include your tablespaces too in the full copy. # How to do it... Try to make a minimal repeatable test scenario that exhibits this bug. Sometimes, the bug disappears while doing this, but mostly it is needed to make the process easy. It is almost impossible to fix a bug that you can't observe and repeat at will. If it is about query processing, then you can usually provide a minimal dump file (the result of running `pg_dump`) of your database together with a SQL script that exhibits the error. If you have corrupt data, then you may want to make a subset of the corrupted data files available for people who have the knowledge and time to look at it. Sometimes, you can find such people on the PostgreSQL hackers' list, and sometimes you have to hire someone or even fix it yourself. The more preparatory work you do yourself and the better you formulate your questions, the higher the chance you have of finding help quickly. If you suspect a data corruption bug and feel adventurous, then you can read about data formats at http://www.postgresql.org/docs/current/static/storage.html, and investigate your data tables using the `pageinspect` package from contrib. When reporting a bug, always include at least the PostgreSQL version you are using and the operating system on which you are using it. More detailed information on this process is available at the PostgreSQL Wiki. By following the official recommendations at http://wiki.postgresql.org/wiki/Guide_to_reporting_problems and http://wiki.postgresql.org/wiki/SlowQueryQuestions, you will have a higher chance of getting your questions answered. # How it works... If everything works really well, then it goes like the following: * A user submits a well-researched bug report to the PostgreSQL hackers' list. * Some discussions follow on the list, and the user may be asked to provide some additional information. * Somebody finds out what is wrong and proposes a fix. * The fix is discussed on the hackers' list. * The bug is fixed. There is a patch for the current version, and the fix is sure to be included in the next version. * Sometimes, the fix is backported to older versions. Unfortunately, any step may go wrong due to various reasons, such as nobody feeling that this is their area of expertise, the right people not having time and hoping for someone else to deal with it, and these other people not reading the list at the right moment. If this happens, follow up your question in a day or two to try to understand why there was no reaction. # Producing a daily summary of log file errors PostgreSQL can generate gigabytes of logs per day. Lots of data is good if you want to investigate some specific event, but it is not what you will use for daily monitoring of database health. In this recipe, we'll see how to perform a post analysis of our log files and get reports (and insights) about what has happened in a given period of time. A different approach is to perform real-time analysis of queries through the `pg_stat_statements` extension, which will be covered in the next recipe. # Getting ready Make sure that your PostgreSQL is set up to rotate log files, for example, daily. I personally prefer to integrate PostgreSQL with `rsyslog` and `logrotate` for log management on Linux or Unix systems, but you can use any method that is allowed by PostgreSQL (CSV or standard error, for example). A typical default setup will divert log messages to `stderr`, and you can set up log rotation directly in PostgreSQL through the `log_rotation_age` configuration option. Once you have your logs ready, it is time to feed them to a PostgreSQL log-processing program. Here, we describe how to do so using pgBadger, a multi-platform application written in Perl that has recently become more popular than its famous predecessor, **pgFouine**. Some of the cool features of pgBadger include—multi-file processing, parallel processing, auto-detection of the input format, on-the-fly decompression, as well as very light HTML reports with Javascript-generated charts (that have zooming capabilities), as shown here: Report of time-consuming queries with pgBadger For most Linux systems, you should be able to use your default package manager to install pgBadger. Otherwise, you can simply download its sources. Configure your PostgreSQL server to produce log files in a format that `pgBadger` understands. Everything is thoroughly described in the online documentation for pgBadger at http://dalibo.github.io/pgbadger/. Suppose you are using `syslog` and you want to exclude queries that take less than a second to be executed. You can have a logging configuration of your PostgreSQL server similar to this: **log_destination = syslog** **syslog_facility = LOCAL0** **syslog_ident = 'postgres'** **log_line_prefix = 'user=%u,db=%d,client=%h '** **log_temp_files = 0** **log_statement = ddl** **log_min_duration_statement = 1000** **log_min_messages = info** **log_checkpoints = on** **log_lock_waits = on** The documentation for pgBadger is a great source of information regarding PostgreSQL configuration in terms of logging. You are advised to read that together with the _Error Reporting and Logging_ section of the Postgres documentation available at http://www.postgresql.org/docs/current/static/runtime-config-logging.html. # How to do it... Set up a cron job to run regularly (for example once every hour, day, or week) and let pgBadger analyze one or more log files. Here, you can find a very simple example that can be used to prepare daily reports every hour. For the sake of simplicity, the script has been purged of any error check. Production usage requires the addition of some basic shell controls: **#!/bin/bash ** **outdir=/var/www/reports ** **begin=$(date +'%Y-%m-%d %H:00:00' -d '-1 day') ** **end=$(date +'%Y-%m-%d %H:00:00') ** **outfile="$outdir/daily-$(date +'%H').html" ** ** pgbadger -q -b "$begin" -e "$end" -o "$outfile" \ ** **/var/log/postgres.log.1 /var/log/postgres.log** The preceding script informs `pgbadger` to analyze the current log file `(/var/log/postgresql.log`) and the previously rotated file (`/var/log/postgres.log.1`), to limit the reporting activity to the last 24 hours (see how the `date` command was used to generate timestamps), and then write the output to the `$outfile` HTML file. Once again, this is just a very simple use case for pgBadger. I strongly advise you to look at the documentation and investigate all the options and possibilities that pgBadger offers. I want to end this recipe with a practical idea that you can explore with your system administrators. You might have noticed that the output directory has been set as a common default `DocumentRoot` for Apache servers (`/var/www`). A very practical way to use pgBadger is to integrate it with a web server. Production environments may benefit from SSL encryption, basic authentication, and the `mod_dir` module, which allows you to make your reports automatically available through the internet (or your intranet). # How it works... The pgBadger tool condenses and ranks error messages for easy viewing, and produces a nicely formatted report in HTML. From that report, you can find out the most frequent errors. As a rule, it is good practice not to tolerate errors in database logs if you can avoid them. Once the errors start showing up in the log and report, you should find their cause and fix them. While it is tempting to leave the errors there and consider them as just a small nuisance because _they do no harm_ , simple errors are often an indication of other problems in the application. These problems, if not found and understood, may lead to all kinds of larger problems, such as security breaches or eventual data corruption at the logical level. # There's more... If you have only a small number of errors in your log files, then it may be sufficient to run each log file through grep to find errors: **user@dbhost: $ egrep "FATAL|ERROR" /var/log/postgres.log** # Analyzing the real-time performance of your queries The `pg_stat_statements` extension adds the capability to track execution statistics of queries that are run in a database, including the number of calls, total execution time, total number of returned rows, and internal information on memory and I/O access. It is evident how this approach opens up new opportunities in PostgreSQL performance analysis, by allowing DBAs to get insights directly from the database through SQL and in real time. # Getting ready The `pg_stat_statements` module is available as a contrib module of PostgreSQL. The extension must be installed as a superuser in the desired databases. It also requires administrators to add the library in the `postgresql.conf` file, as follows: **shared_preload_libraries = 'pg_stat_statements'** This change requires restarting the PostgreSQL server. Finally, in order to use it, the extension must be installed in the desired database through the usual `CREATE EXTENSION` command (run as a superuser): **gabriele=# CREATE EXTENSION pg_stat_statements; ** **CREATE EXTENSION** # How to do it... Connect to a database where you have installed the `pg_stat_statements` extension, preferably as a superuser. You can start by retrieving a list of the most frequent queries: **SELECT query FROM pg_stat_statements ORDER BY calls DESC;** Alternatively, you can retrieve the queries with the highest average execution time: **SELECT query, total_time/calls AS avg, calls ** **FROM pg_stat_statements ORDER BY 2 DESC;** These are just examples. I strongly recommend that you look at the PostgreSQL documentation at http://www.postgresql.org/docs/current/static/pgstatstatements.html for more detailed information on the structure of the `pg_stat_statements` view. # How it works... Since the `pg_stat_statements` shared library has been loaded by the PostgreSQL server, Postgres starts collecting statistics for every database in the instance. The extension simply installs the `pg_stat_statements` view and the `pg_stat_statements_reset()` function in the current database, allowing the DBA to inspect the available statistics. By default, read access to the `pg_stat_statements` view is granted to every user who can access the database (even though standard users are allowed to see only the SQL statements of their queries). The `pg_stat_statements_reset()` function can be used to discard the statistics collected by the server up to that moment, and set all the counters to `0`. It requires a superuser in order to be run. # There's more... A very important `pg_stat_statements` feature is the normalization of queries that can be planned (`SELECT`, `INSERT`, `DELETE`, and `UPDATE`). You might have indeed noticed some `?` characters in the `query` field returned by the queries outlined in the previous section. The normalization process intercepts constants in SQL statements run by users and replaces them with a placeholder (identified by a question mark). Consider the following queries: **SELECT * FROM bands WHERE name = 'AC/DC'; ** **SELECT * FROM bands WHERE name = 'Lynyrd Skynyrd';** After the normalization process, these two queries appear as one in `pg_stat_statements`: **gabriele=# SELECT query, calls FROM pg_stat_statements;** **query | calls** **---------------------------------------+-------** **SELECT * FROM bands WHERE name = ?; | 2** ** &mldr; <snip> &mldr;** This is the expected behavior, isn't it? The extension comes with a few configuration options, such as the maximum number of queries to be tracked. # Regular Maintenance PostgreSQL prefers regular maintenance, so please read the recipe that discusses maintenance planning (the one in this chapter). We recognize that you're here for a reason and are looking for a quick solution to your needs. You're probably thinking— _Fix me first, and I'll plan later_. So off we go! PostgreSQL provides a utility command named `VACUUM`, which is a jokey name for a garbage collector that sweeps up all the bad things and fixes them - or at least, most of them. That's the single most important thing you need to remember to do—I say single, because closely connected to that is the `ANALYZE` command, which collects optimizer statistics. It's possible to run `VACUUM` and `ANALYZE` as a single joint command, `VACUUM ANALYZE`, and those actions are automatically executed for you when appropriate by `autovacuum`, a special background process that runs as part of the PostgreSQL server. `VACUUM` performs a range of cleanup activities, some of them too complex to describe without a whole sideline into their internals. `VACUUM` has been heavily optimized over a 20-year period to take the minimum required lock levels on tables and execute in the most efficient manner possible, skipping all the unnecessary work and using L2 cache CPU optimizations when work is required. Many experienced PostgreSQL DBAs will prefer to execute their own `VACUUM` commands, though `autovacuum` now provides a fine degree of control, which—if enabled and controlled—can save much of your time. Using both manual and automatic vacuuming gives you control and a safety net. In this chapter, we will cover the following recipes: * Controlling automatic database maintenance * Avoiding auto-freezing and page corruptions * Removing issues that cause bloat * Removing old prepared transactions * Actions for heavy users of temporary tables * Identifying and fixing bloated tables and indexes * Monitoring and tuning vacuum * Maintaining indexes * Adding a constraint without checking existing rows * Finding unused indexes * Carefully removing unwanted indexes * Planning maintenance # Controlling automatic database maintenance Autovacuum is enabled by default in PostgreSQL, and mostly does a great job of maintaining your PostgreSQL database. We say mostly because it doesn't know everything you do about the database, such as the best time to perform maintenance actions. # Getting ready Exercising control requires some thinking about what you actually want: * What are the best times of day to do things? When are system resources more available? * Which days are quiet, and which are not? * Which tables are critical to the application, and which are not? # How to do it... The first thing to do is make sure that `autovacuum` is switched `on`, which is the default. Check that you have the following parameters enabled in your `postgresql.conf` file: **autovacuum = on** **track_counts = on** PostgreSQL controls `autovacuum` with more than 40 individually tunable parameters. That provides a wide range of options, though it can be a little daunting. The following are the relevant parameters that can be set in `postgresql.conf` to tune the `VACUUM` command: **vacuum_cost_page_dirty** **vacuum_cost_page_hit** **vacuum_cost_page_miss** **vacuum_cost_delay** **vacuum_cost_limit** **vacuum_freeze_min_age** **vacuum_freeze_table_age** **vacuum_multixact_freeze_min_age** **vacuum_multixact_freeze_table_age** There are also parameters that apply specifically to the `autovacuum` process: **autovacuum** **autovacuum_work_mem** **autovacuum_max_workers** **autovacuum_naptime** **autovacuum_vacuum_scale_factor** **autovacuum_vacuum_threshold** **autovacuum_analyze_scale_factor** **autovacuum_analyze_threshold** **autovacuum_vacuum_cost_delay** **autovacuum_vacuum_cost_limit** **autovacuum_freeze_max_age** **autovacuum_multixact_freeze_max_age** **log_autovacuum_min_duration** The preceding parameters apply to all tables at once. Individual tables can be controlled by storage parameters, which are set using the following command: **ALTER TABLE mytable SET (storage_parameter = value);** The storage parameters that relate to maintenance are as follows: **autovacuum_enabled** **autovacuum_vacuum_cost_delay** **autovacuum_vacuum_cost_limit** **autovacuum_vacuum_scale_factor** **autovacuum_vacuum_threshold** **autovacuum_freeze_min_age** **autovacuum_freeze_max_age** **autovacuum_freeze_table_age** **autovacuum_multixact_freeze_min_age** **autovacuum_multixact_freeze_max_age** **autovacuum_multixact_freeze_table_age** **autovacuum_analyze_scale_factor** **autovacuum_analyze_threshold** **log_autovacuum_min_duration** The `toast` tables can be controlled with the following parameters: **toast.autovacuum_enabled** **toast.autovacuum_vacuum_cost_delay** **toast.autovacuum_vacuum_cost_limit** **toast.autovacuum_vacuum_scale_factor** **toast.autovacuum_vacuum_threshold** **toast.autovacuum_freeze_min_age** **toast.autovacuum_freeze_max_age** **toast.autovacuum_freeze_table_age** **toast.autovacuum_multixact_freeze_min_age** **toast.autovacuum_multixact_freeze_max_age** **toast.autovacuum_multixact_freeze_table_age** **toast.log_autovacuum_min_duration** # How it works... If `autovacuum` is set, then it will wake up every `autovacuum_naptime` seconds, and decide whether to run `VACUUM`, `ANALYZE`, or both (don't modify that). There will never be more than `autovacuum_max_workers` maintenance processes running at any time. As these autovacuum workers perform I/O, they accumulate cost points until they hit the `autovacuum_vacuum_cost_limit` value, after which they sleep for an `autovacuum_vacuum_cost_delay` period of time. This is designed to throttle the resource utilization of autovacuum to prevent it from using all of the available disk performance, which it should never do. So increasing `autovacuum_vacuum_cost_delay` will slow down each `VACUUM` to reduce the impact on user activity. Autovacuum will run `ANALYZE` when there have been at least `autovacuum_analyze_threshold` changes and a fraction of the table defined by `autovacuum_analyze_scale_factor` has been inserted, updated, or deleted. Autovacuum will run `VACUUM` when there have been at least `autovacuum_vacuum_threshold` changes, and a fraction of the table defined by `autovacuum_vacuum_scale_factor` has been updated or deleted. The `autovacuum_*` parameters only change vacuums and analyze operations executed by autovacuum. User initiated `VACUUM` and `ANALYZE` commands are affected by `vacuum_vacuum_cost_delay` and other `vacuum_*` parameters. If you set `log_autovacuum_min_duration`, then any autovacuum process that runs for longer than this value will be logged to the server log, like the following: **2010-04-29 01:33:55 BST (13130) LOG: automatic vacuum of table "postgres.public.pgbench_accounts": index scans: 1** **pages: 0 removed, 3279 remain** **tuples: 100000 removed, 100000 remain** **system usage: CPU 0.19s/0.36u sec elapsed 19.01 sec** **2010-04-29 01:33:59 BST (13130) LOG: automatic analyze of table "postgres.public.pgbench_accounts"** **system usage: CPU 0.06s/0.18u sec elapsed 3.66 sec** Most of the preceding global parameters can also be set at the table level. For example, if you think that you don't want a table to be autovacuumed, then you can set this: **ALTER TABLE big_table SET (autovacuum_enabled = off);** It's also possible to set parameters for toast tables. A `toast` table is the location where oversize column values get placed, which the documents refer to as _supplementary storage tables_. If there are no oversize values, then the `toast` table will occupy little space. Tables with very wide values often have large `toast` tables. **TOAST** (short for **the oversize attribute storage technique** ) is optimized for `UPDATE`. If you have a heavily updated table, the `toast` table is untouched, so it may make sense to turn off autovacuuming of the `toast` table, as follows: **ALTER TABLE pgbench_accounts ** **SET ( toast.autovacuum_enabled = off);** This will turn `off` autovacuuming of the `toast` table. Note that autovacuuming of the `toast` table is performed completely separately from the main table, even though you can't ask for an explicit include or exclude of the `toast` table yourself when running `VACUUM`. Use the following query to display the `reloptions` for tables and their `toast` tables: **postgres=# ** **SELECT n.nspname ** **, c.relname ** **, array_to_string( ** **c.reloptions || ** **ARRAY( ** **SELECT 'toast.' || x ** **FROM unnest(tc.reloptions) AS x ** **), ', ') ** **AS relopts ** **FROM pg_class c ** **LEFT JOIN pg_class tc ON c.reltoastrelid = tc.oid ** **JOIN pg_namespace n ON c.relnamespace = n.oid ** **WHERE c.relkind = 'r' ** **AND nspname NOT IN ('pg_catalog', 'information_schema');** This query gives the following output: **nspname | relname | relopts** **---------+------------------+------------------------------** **public | pgbench_accounts | fillfactor=100,** **autovacuum_enabled=on,** **autovacuum_vacuum_cost_delay=20** **public | pgbench_tellers | fillfactor=100** **public | pgbench_branches | fillfactor=100** **public | pgbench_history |** **public | text_archive | toast.autovacuum_enabled=off** `VACUUM` allows insertions, updates, and deletions while it runs, but it prevents actions such as `ALTER TABLE` and `CREATE INDEX`. That's not a problem since you should be using `CREATE INDEX CONCURRENTLY`. Autovacuum can detect if a user has requested a conflicting lock on the table while it runs, and it will cancel itself if it is getting in the user's way. `VACUUM` doesn't cancel itself since we expect the DBA would not want it to be canceled. Note that `VACUUM` does not shrink a table when it runs, unless there is a large run of space at the end of a table, and nobody is accessing the table when we try to shrink it. To shrink a table properly, you'll need `VACUUM FULL`, but it locks up the whole table for a long time, and should be avoided if possible. The `VACUUM FULL` command will literally rewrite every row of the table and completely rebuild all indexes. This process is faster than it used to be, though it still takes a long time for larger tables. # There's more... The `postgresql.conf` file also allows `include` directives, which look like the following: **include 'autovacuum.conf'** These specify another file that will be read at that point, just as if those parameters had been included in the main file. This can be used to maintain multiple sets of files for the autovacuum configuration. Let's say we have a website that is busy mainly during the daytime, with some occasional night-time use. We decide to have two profiles: one for daytime, when we want less aggressive autovacuuming, and another at night, where we can allow more aggressive vacuuming: 1. We add the following lines to `postgresql.conf`: **autovacuum = on** **autovacuum_max_workers = 3** **include 'autovacuum.conf'** 2. We remove all other `autovacuum` parameters 3. We then create a file named `autovacuum.conf.day`, containing the following parameters: **autovacuum_analyze_scale_factor = 0.1** **autovacuum_analyze_threshold = 50** **autovacuum_vacuum_cost_delay = 30** **autovacuum_vacuum_cost_limit = -1 autovacuum_vacuum_scale_factor = 0.2** **autovacuum_vacuum_threshold = 50** 4. Then, we create another file, named `autovacuum.conf.night`, which contains the following parameters: **autovacuum_analyze_scale_factor = 0.05** **autovacuum_analyze_threshold = 50** **autovacuum_vacuum_cost_delay = 10** **autovacuum_vacuum_cost_limit = -1** **autovacuum_vacuum_scale_factor = 0.1** **autovacuum_vacuum_threshold = 50** 5. To swap profiles, we simply do this: **$ ln -sf autovacuum.conf.night autovacuum.conf ** **$ pg_ctl reload** The latter is the command to reload the server configuration, and it must be customized depending on your platform. This then allows us to switch profiles twice per day without needing to edit the configuration files. You can also tell easily which is the active profile simply by looking at the full details of the linked file (using `ls -l`). The exact details of the schedule are up to you. Night and day was just an example, which is unlikely to suit everybody. # See also * The `autovacuum_freeze_max_age` parameter is explained in the next recipe, _Avoiding auto-freezing and page corruptions_ , as are the more complex table-level parameters # Avoiding auto-freezing and page corruptions There are some aspects of `VACUUM` whose reason to exist is complex to explain, and occasionally they have negative behavior. Let's look more deeply at those, and find some solutions. # How to do it... PostgreSQL uses internal transaction identifiers that are 4 bytes long, so we only have 232 transaction IDs (about four billion). PostgreSQL starts again from the beginning when that wraps around, allocating new identifiers in a circular manner. The reason we do this is that moving to an 8-byte identifier has various other negative effects and costs that we would rather not pay, so we keep the 4-byte transaction identifier, which means we need to do regular sweeps to replace old transaction identifiers with a special value that is not interpreted in a circular way, and is called **Frozen Transaction ID** ; that's why this procedure is known as _freezing_. There are two routes that a row can take in PostgreSQL—a row version dies and needs to be removed by `VACUUM`, or a row version gets old enough and needs to be frozen, which is also performed by the `VACUUM` process. Why do we care? Suppose that we load a table with 100 million rows, and everything is fine. When those rows have been there long enough to begin being frozen, the next `VACUUM` operation on that table will rewrite all of them to freeze their transaction identifiers. Put another way, `autovacuum` will wake up and start using lots of I/O to perform the freezing. The most obvious way to forestall the problem is to explicitly vacuum a table after a major load. Of course, that doesn't remove the problem entirely, and you might not have time for that. The knee-jerk reaction for many people is to turn off `autovacuum`, because it keeps waking up at the most inconvenient times. My way is described in the _Controlling automatic database maintenance_ recipe. Freezing takes place when a transaction identifier on a row becomes more than `vacuum_freeze_min_age` transactions older than the current next value. Normal `VACUUM` operations will perform a small amount of freezing as you go, and in most cases, you won't notice that at all. As explained in the earlier example, large transactions leave many rows with the same transaction identifiers, so those might cause problems at the freezing time. The `VACUUM` command is normally optimized to only look at the chunks of a table that require cleaning, both for normal vacuum and freezing operations. If you fiddle with those parameters to try to forestall heavy `VACUUM` operations, then you'll notice that the `autovacuum_freeze_max_age` parameter controls when the table will be scanned by a forced `VACUUM` command. To put that another way, you can't turn off the need to freeze rows, but you can get to choose when this happens. My advice is to control autovacuum as described in the previous recipe, or perform explicit `VACUUM` operations at a time of your choosing. The `VACUUM` command is also an efficient way to confirm the absence of page corruptions, so it is worth scanning the whole database, block-by-block, from time to time. To do this, you can run the following command on each of your databases: **VACUUM (DISABLE_PAGE_SKIPPING);** You can do this table by table, as well. There's nothing special about whole database `VACUUM` operations anymore; in earlier versions of PostgreSQL this was important, so you may read in random places on the web that this is a good idea. If you've never had a corrupt block, then you may only need to scan every two to three months. If you start to get corrupt blocks, then you may want to increase the scan rate to confirm everything is OK. Corrupt blocks are usually hardware induced, though they show up as database errors. It's possible but rare that the corruption was from a PostgreSQL bug instead. There's no easy way to fix page corruptions at present. There are, however, ways to investigate and extract data from corrupt blocks, for example, using the `pageinspect` contrib utility that Simon wrote. You can also detect them automatically by creating the whole cluster using the following: **initdb --data-checksums ** This command initializes the data directory and enables data block checksums. This means that, every time something changes in a block, PostgreSQL will compute the new checksum, and then store in that same block the resulting block checksums, so that a simple programme can detect it. # Removing issues that cause bloat Bloat can be caused by long running queries or long running write transactions that execute alongside write-heavy workloads. Resolving that is mostly down to understanding the workloads running on the server. # Getting ready Look at the age of the oldest snapshots that are running, like this: **postgres=# SELECT now() -** **CASE** **WHEN backend_xid IS NOT NULL** **THEN xact_start** **ELSE query_start END** **AS age** **, pid** **, backend_xid AS xid** **, backend_xmin AS xmin** **, state** **FROM pg_stat_activity** **WHERE backend_type = 'client backend'** **ORDER BY 1 DESC;** **age | pid | xid | xmin | state** **----------------+-------+----------+----------+------------------** **00:00:25.791098 | 27624 | | 10671262 | active** **00:00:08.018103 | 27591 | | | idle in transaction** **00:00:00.002444 | 27630 | 10703641 | 10703639 | active** **00:00:00.001506 | 27631 | 10703642 | 10703640 | active** **00:00:00.000324 | 27632 | 10703643 | 10703641 | active** **00:00:00 | 27379 | | 10703641 | active** The preceding example shows an update workload of three sessions alongside one session that is waiting in _idle in transaction_ state, plus two other sessions that are only reading data. # How to do it... If you have sessions stuck in idle in transaction state, then you may want to consider setting the `idle_in_transaction_session_timeout` parameter, so that transactions in that mode will be canceled. The default for that is zero, meaning there will be no cancellation. If not, try running shorter transactions or shorter queries. If that is not an option, then consider setting `old_snapshot_threshold`. This parameter sets a time delay after which dead rows are at risk of being removed. If a query attempts to read data that has been removed then we cancel the query. All queries executing in less time than the `old_snapshot_threshold` parameter will be safe. This is a very similar concept to the way _Hot Standby_ works (see Chapter 12, _Replication and Upgrades_ ). # How it works... `VACUUM` cannot remove dead rows until they are invisible to all users. The earliest data visible to a session is defined by its oldest snapshot's `xmin` value, or if that is not set then by the backend's `xid` value if that is set. # There's more... A session which is not running any query is in the _idle_ state if outside of a transaction, or in the _idle in transaction_ state if it is inside a transaction, that is, between a `BEGIN` and the corresponding `COMMIT`. Recall recipe _Writing a script that either succeeds entirely_ _or fails entirely_ in Chapter 7, _Database Administration_ , for how `BEGIN` and `COMMIT` can be used to wrap several commands into one transaction. The reason to distinguish between these two states is that locks are released at the end of a transaction. Hence an _idle in transaction_ session is not currently doing anything, but it might be preventing other queries, including VACUUM, from accessing some tables. # Removing old prepared transactions You may have been routed here from other recipes, so you might not even know what prepared transactions are, let alone what an old prepared transaction looks like. The good news is that prepared transactions don't just happen; they happen in certain situations. If you don't know what I'm talking about, it's OK! You won't need to, and better still, you probably don't have any prepared transactions either. Prepared transactions are part of the two-phase commit feature, also known as **2PC**. A transaction commits in two stages rather than one, allowing multiple databases to have synchronized commits. Its typical use is to combine multiple so-called resource managers using the **XA** protocol, usually provided by a **Transaction Manager** ( **TM** ), as used by the **Java Transaction API** ( **JTA** ) and others. If none of this meant anything to you, then you probably don't have any prepared transactions. # Getting ready First, check the setting of `max_prepared_transactions`: **SHOW max_prepared_transactions;** If your setting is more than zero, then check whether you have any prepared transactions. As an example, you may find something like the following: **postgres=# SELECT * FROM pg_prepared_xacts; ** **-[ RECORD 1 ]------------------------------ ** **transaction | 459812 ** **gid | prep1 ** **prepared | 2017-04-11 13:21:51.912374+01 owner | postgres ** **database | postgres** Here, the `gid` (global identifier) will usually have been automatically generated. # How to do it... Removing a prepared transaction is also referred to as _resolving in-doubt transactions_. The transaction is literally stuck between committing and aborting. The database or transaction manager may have crashed, leaving the transaction midway through the two-phase commit process. If you have a connection pool of 100 active connections and something crashes, you'll probably find 1 to 20 transactions stuck in the prepared state, depending on how long your average transaction is. To resolve the transaction, we need to decide whether we want that change or not. The best way is to check what happened externally to PostgreSQL. That should help you decide. If you need further help, look at the _There's more..._ section. If you wish to commit the changes, then use this command: **COMMIT PREPARED 'prep1';** If you want to rollback the changes, then use the following command: **ROLLBACK PREPARED 'prep1';** # How it works... Prepared transactions are persistent across crashes, so you can't just do a fast restart to get rid of them. They have both an internal transaction identifier and an external global identifier. Either of these can be used to locate locked resources and decide how to resolve the transactions. # There's more... If you're not sure what the prepared transaction actually did, you can go and look, though that is time-consuming. The `pg_locks` view shows locks that are held by prepared transactions. You can get a full report of what is being locked by using the following query: **postgres=# SELECT l.locktype, x.database, l.relation, l.page, l.tuple,l.classid, l.objid, l.objsubid, l.mode, x.transaction, x.gid, x.prepared, x.owner FROM pg_locks l JOIN pg_prepared_xacts x ON l.virtualtransaction = '-1/' || x.transaction::text;** The documents mention that you can join `pg_locks` to `pg_prepared_xacts`, but they don't mention that if you join directly on the transaction ID, all it tells you is that there is a transaction lock, unless there are some row-level locks. The table locks are listed as being held by a virtual transaction. A simpler query is the following: **postgres=# SELECT DISTINCT x.database, l.relation FROM pg_locks l JOIN pg_prepared_xacts x ON l.virtualtransaction = '-1/' || x.transaction::text WHERE l.locktype != 'transactionid'; database | relation** **---------+----------** **postgres | 16390** **postgres | 16401** **(2 rows)** This tells you which relations in which databases have been touched by the remaining prepared transactions. We can't tell the names because we'd need to connect to those databases to check. Finally, we can inspect which rows have been changed by the transaction. We will use `xmin`, which is a hidden column in each table. For more details on that, refer to the _Identifying and fixing bloated tables and indexes_ recipe in this chapter. You can then fully scan each of those tables, looking for changes like the following: **SELECT * FROM table WHERE xmax = 121083; ** This query will show you all the rows in that table that will be deleted or updated by transaction `121083`, taken from the transaction column of `pg_prepared_xacts`. Not all rows touched by the transaction can be displayed, however. Newly inserted rows and new versions of updated rows will not be accessible in this way, for the very good reason that they must be invisible before the transaction is committed. As you might expect, the PostgreSQL developers did their homework properly. Say that you have some prepared transactions and you change `max_prepared_transactions` to zero, which requires a restart to come into effect. No prepared transaction will sneak into your database unnoticed. When starting, PostgreSQL will try to recover every prepared transaction, and refuse to start unless `max_prepared_transactions` is large enough. # Actions for heavy users of temporary tables If you are a heavy user of temporary tables in your applications, then there are some additional actions that you may need to perform. # How to do it... There are four main things to check, which are as follows: 1. Make sure you run `VACUUM` on system tables, or enable `autovacuum` to do this for you. 2. Monitor running queries to see how many temporary files are active and how large they are. 3. Tune the memory parameters. Think about increasing the `temp_buffers` parameter, but be careful not to over-allocate memory by doing so. 4. Separate the temp table's I/O. In a query-intensive system, you may find that reads/writes to temporary files exceed reads/writes on permanent data tables and indexes. In this case, you should create new tablespace(s) on separate disks, and ensure that the `temp_tablespaces` parameter is configured to use the additional tablespace(s). # How it works... When we create a temporary table, we insert entries into the `pg_class`, `pg_type`, and `pg_attribute` catalog tables. These catalog tables and their indexes begin to grow and bloat—an issue covered in later recipes. To control that growth, you can either vacuum those tables manually, or let `autovacuum` do its work. You cannot run `ALTER TABLE` against system tables, so it is not possible to set specific `autovacuum` settings for any of these tables. If you vacuum the system catalog tables manually, make sure you get all of the system tables. You can get the full list of tables to vacuum and a list of their indexes using the following query: **postgres=# SELECT relname, pg_relation_size(oid) FROM pg_class** **WHERE relkind in ('i','r') AND relnamespace = 'pg_catalog'::regnamespace** **ORDER BY 2 DESC;** This results in the following output: **relname | pg_relation_size** **---------------------------------+------------------** **pg_proc | 450560** **pg_depend | 344064** **pg_attribute | 286720** **pg_depend_depender_index | 204800** **pg_depend_reference_index | 204800** **pg_proc_proname_args_nsp_index | 180224** **pg_description | 172032** **pg_attribute_relid_attnam_index | 114688** **pg_operator | 106496** **pg_statistic | 106496** **pg_description_o_c_o_index | 98304** **pg_attribute_relid_attnum_index | 81920** **pg_proc_oid_index | 73728** **pg_rewrite | 73728** **pg_class | 57344** **pg_type | 57344** **pg_class_relname_nsp_index | 40960** **...(partial listing)** The preceding values are for a newly created database. These tables can get very large if not properly maintained, with values of 11 GB for one index being witnessed in one unlucky installation. # Identifying and fixing bloated tables and indexes PostgreSQL implements **Multiversion Concurrency Control** ( **MVCC** ), which allows users to read data at the same time as writers make changes. This is an important feature for concurrency in database applications, as it can allow the following: * Better performance because of fewer locks * Greatly reduced deadlocking * Simplified application design and management MVCC is a core part of PostgreSQL and cannot be turned off; nor would you really want it to be. The internals of MVCC have some implications for the DBA that need to be understood: each row represents a row version, and therefore it has two system columns, `xmin` and `xmax`, indicating the identifiers of the two transactions when the version was created and deleted, respectively. The value of `xmax` is `NULL` if that version has not been deleted yet. The general idea is that, instead of actually removing row versions, we alter their visibility by changing their `xmin` and/or `xmax` values. Precisely, when a row is inserted, its `xmin` value is set to the number of the creating transaction, while `xmax` is emptied; when a row is deleted, `xmax` is set to the number of the deleting transaction, without actually removing the row. An `UPDATE` operation is treated exactly like a `DELETE` followed by an `INSERT`; the deleted row represents the older version, and the row inserted is the newer version. Finally, when rolling back a transaction, all of its changes are made invisible by marking that transaction ID as aborted. In this way, we get faster `DELETE`, `UPDATE`, and `ROLLBACK` statements, but the price of these benefits is that the `SQL UPDATE` command can cause tables and indexes to grow in size, because they leave behind dead row versions. The `DELETE` and aborted `INSERT` statements take up space, which must be reclaimed by garbage collection. `VACUUM` is the mechanism by which we reclaim space, though there is another internal feature named **Heap-Only Tuples** ( **HOT** ), which does much of this work for us automatically. Knowing this, many people become worried by, and spend much time trying to rid themselves of, dead row versions. Many users will be familiar with tools used to perform tasks, such as defragmentation, shrinking, reorganization, and table optimization. These tasks are necessary, but you should not be unduly worried by the need for vacuuming in PostgreSQL. Many users execute `VACUUM` far too frequently, while at the same time complaining about the cost of doing so. This recipe is all about understanding when you need to run `VACUUM` by estimating the amount of bloat in tables and indexes. # How to do it... The best way to understand things is to look at things the same way that `autovacuum` does, using a view created with the following query: **CREATE OR REPLACE VIEW av_needed AS** **SELECT N.nspname, C.relname** **, pg_stat_get_tuples_inserted(C.oid) AS n_tup_ins** **, pg_stat_get_tuples_updated(C.oid) AS n_tup_upd** **, pg_stat_get_tuples_deleted(C.oid) AS n_tup_del** **, CASE WHEN pg_stat_get_tuples_updated(C.oid) > 0 ** **THEN pg_stat_get_tuples_hot_updated(C.oid)::real** **/ pg_stat_get_tuples_updated(C.oid)** **END** **AS HOT_update_ratio** **, pg_stat_get_live_tuples(C.oid) AS n_live_tup** **, pg_stat_get_dead_tuples(C.oid) AS n_dead_tup** **, C.reltuples AS reltuples** **, round( current_setting('autovacuum_vacuum_threshold')::integer** **+ current_setting('autovacuum_vacuum_scale_factor')::numeric** *** C.reltuples)** **AS av_threshold** **, date_trunc('minute',** **greatest(pg_stat_get_last_vacuum_time(C.oid),** **pg_stat_get_last_autovacuum_time(C.oid)))** **AS last_vacuum** **, date_trunc('minute',** **greatest(pg_stat_get_last_analyze_time(C.oid),** **pg_stat_get_last_analyze_time(C.oid)))** **AS last_analyze** **, pg_stat_get_dead_tuples(C.oid) > ** **round( current_setting('autovacuum_vacuum_threshold')::integer** **+ current_setting('autovacuum_vacuum_scale_factor')::numeric** *** C.reltuples)** **AS av_needed** **, CASE WHEN reltuples > 0 ** **THEN round(100.0 * pg_stat_get_dead_tuples(C.oid) / reltuples)** **ELSE 0 END** **AS pct_dead** **FROM pg_class C** **LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)** **WHERE C.relkind IN ('r', 't', 'm') ** **AND N.nspname NOT IN ('pg_catalog', 'information_schema')** **AND N.nspname NOT LIKE 'pg_toast%'** **ORDER BY av_needed DESC, n_dead_tup DESC;** We can then use this to look at individual tables, as follows: **postgres=# \x** **postgres=# SELECT * FROM av_needed WHERE nspname = 'public' AND relname = 'pgbench_accounts';** Thus, we get this output: **-[ RECORD 1 ]----+------------------------** **nspname | public** **relname | pgbench_accounts** **n_tup_ins | 100001** **n_tup_upd | 117201** **n_tup_del | 1** **hot_update_ratio | 0.123454578032611** **n_live_tup | 100000** **n_dead_tup | 0** **reltuples | 100000** **av_threshold | 20050** **last_vacuum | 2010-04-29 01:33:00+01** **last_analyze | 2010-04-28 15:21:00+01** **av_needed | f** **pct_dead | 0** # How it works... We can compare the number of dead row versions, shown as `n_dead_tup` against the required threshold, `av_threshold`. The preceding query doesn't take into account table-specific autovacuum thresholds. It could do so if you really need it, but the main purpose of the query is to give us information to understand what is happening, and then set the parameters accordingly—not the other way around. Notice that the table query shows insertions, updates, and deletions, so you can understand your workload better. There is also something named the `hot_update_ratio`. This shows the fraction of updates that take advantage of the HOT feature, which allows a table to self-vacuum as the table changes. If that ratio is high, then you may avoid `VACUUM` activities altogether or at least for long periods. If the ratio is low, then you will need to execute `VACUUM` commands or autovacuums more frequently. Note that the ratio never reaches 1.0, so if you have it above 0.95, then that is very good and you need not think about it further. HOT updates take place when the `UPDATE` statement does not change any of the column values that are indexed by any index, and there is enough free space in the disk page where the updated row is located. If you change even one column that is indexed by just one index, then it will be a non-HOT update, and there will be a performance hit. So careful selection of indexes can improve update performance and reduce the need for maintenance. Also, if HOT updates do occur, though not often enough for your liking, you might want to try to decrease the `fillfactor` storage parameter for the table to make more space for them. Remember that this will be important only on your most active tables. Seldom touched tables don't need much tuning. To recap, non-HOT updates cause indexes to bloat. The following query is useful in investigating the index size and how it changes over time. It runs fairly quickly, and can be used to monitor whether your indexes are changing in size over time: **SELECT** **nspname,relname,** **round(100 * pg_relation_size(indexrelid) /** **pg_relation_size(indrelid)) / 100** **AS index_ratio,** **pg_size_pretty(pg_relation_size(indexrelid))** **AS index_size,** **pg_size_pretty(pg_relation_size(indrelid))** **AS table_size** **FROM pg_index I** **LEFT JOIN pg_class C ON (C.oid = I.indexrelid)** **LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)** **WHERE** **nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND** **C.relkind='i' AND** **pg_relation_size(indrelid) > 0;** Another route is to use the `pgstattuple` contrib module which provides very detailed statistics. You can scan tables using `pgstattuple()`, as follows: **test= > SELECT * FROM pgstattuple('pg_catalog.pg_proc');** The output will look like the following: **-[ RECORD 1 ]------+-------** **table_len | 458752** **tuple_count | 1470** **tuple_len | 438896** **tuple_percent | 95.67** **dead_tuple_count | 11** **dead_tuple_len | 3157** **dead_tuple_percent | 0.69** **free_space | 8932** **free_percent | 1.95** The downside of `pgstattuple` is that it derives exact statistics by scanning the whole table and literally counting everything. If you have time to scan the table, you may as well vacuum the whole table anyway. So a better idea is to use `pgstattuple_approx()`, which is much, much faster, and yet is still fairly accurate. It works by accessing the table's visibility map first and then only scanning the pages that need `VACUUM,` so I recommend you use it in all cases for checking tables (there is no equivalent for indexes): **postgres=# select * from pgstattuple_approx('pgbench_accounts');** **-[ RECORD 1 ]--------+-----------------** **table_len | 268591104** **scanned_percent | 0** **approx_tuple_count | 1001738** **approx_tuple_len | 137442656** **approx_tuple_percent | 51.1717082037088** **dead_tuple_count | 0** **dead_tuple_len | 0** **dead_tuple_percent | 0** **approx_free_space | 131148448** **approx_free_percent | 48.8282917962912** You can also scan indexes using `pgstatindex()`, as follows: **postgres= > SELECT * FROM pgstatindex('pg_cast_oid_index');** **-[ RECORD 1 ]------+------** **version | 2** **tree_level | 0** **index_size | 8192** **root_block_no | 1** **internal_pages | 0** **leaf_pages | 1** **empty_pages | 0** **deleted_pages | 0** **avg_leaf_density | 50.27** **leaf_fragmentation | 0** # There's more... You may want this as a Nagios plugin. Look at `check_postgres_bloat`, which is a part of the `check_postgres` plugins. It provides some flexible options to assess bloat. Unfortunately, it's not that well documented, but if you've read this, it should make sense. You'll need to play with it to get the thresholding correct anyway, so that shouldn't be a problem. Note also that the only way to know for certain the exact bloat of a table or index is to scan the whole relation. Anything else is just an estimate, and might lead to you running maintenance either too early or too late. # Monitoring and tuning vacuum If you're currently waiting for a long running vacuum (or autovacuum) to finish, go straight to the _How to do it..._ section. If you've just had a long running vacuum then you may want to think about setting a few parameters. # Getting ready `autovacuum_max_workers` should always be set to more than 2. Setting it too high may not be very useful, so be careful. Setting `vacuum_cost_delay` too high is counterproductive. `VACUUM` is your friend, not your enemy, so delaying it until it doesn't happen at all just makes things worse. `maintenance_work_mem` should be set to anything up to 1 GB, according to how much memory you can allocate to this task at this time. Let's watch what happens when we run a large `VACUUM.` First, locate which process is running the `VACUUM` by using the `pg_stat_activity` view to identify the specific `pid`. # How to do it... Repeatedly execute this query to see the progress of the `VACUUM` command: **postgres=# SELECT * FROM pg_stat_progress_vacuum WHERE pid = 34399;** # How it works... `VACUUM` works in three phases. The first main phase is _scanning heap_. The `heap_blks_scanned` columns will increase from `0` up to the value of `heap_blks_total`: **Pid | 34399** **datid | 12515** **datname | postgres** **relid | 16422** **phase | scanning heap** **heap_blks_total | 32787** **heap_blks_scanned | 25207** **heap_blks_vacuumed | 0** **index_vacuum_count | 0** **max_dead_tuples | 9541017** **num_dead_tuples | 537600** The number of blocks vacuumed is shown as `heap_blks_vacuumed` and the resulting rows to be removed are shown as `num_dead_tuples`. After this we switch to the second phase where we start vacuuming indexes: **Pid | 34399** **datid | 12515** **datname | postgres** **relid | 16422** **phase | vacuuming indexes** **heap_blks_total | 32787** **heap_blks_scanned | 32787** **heap_blks_vacuumed | 0** **index_vacuum_count | 0** **max_dead_tuples | 9541017** **num_dead_tuples | 999966** Though while this phase is happening the progress data doesn't change until it has vacuumed all of the indexes. This phase can take a long time; more indexes increase the time required. Once indexes are vacuumed, we move onto the third phase where we return to the _vacuuming heap_ : **Pid | 34399** **datid | 12515** **datname | postgres** **relid | 16422** **phase | vacuuming heap** **heap_blks_total | 32787** **heap_blks_scanned | 32787** **heap_blks_vacuumed | 25051** **index_vacuum_count | 1** **max_dead_tuples | 9541017** **num_dead_tuples | 999966** The value of `max_dead_tuples` is defined by the setting of `maintenance_work_mem`: PostgreSQL makes space for the largest meaningful number of entries allowed by that setting. If the `num_dead_tuples` is higher than `max_dead_tuples` then we repeat phases two and three until complete, so it's a good idea to set `maintenance_work_mem` high enough to avoid that. `VACUUM` moves through various other fairly short phases. If there are many empty blocks at the end of the table `VACUUM` will attempt to get an `AccessExclusiveLock` on the table, and once acquired, it will truncate the end of the table—showing a phase of truncating heap. Truncation does not occur every time, because PostgreSQL will attempt it only if the gain is significant and if there's no conflicting lock; if it does it can often last a long time. All phases of `VACUUM` will be slowed down by `vacuum_cost_delay`, but there's nothing you can do there to speed it up. If you need to change the settings to speed up a running process then autovacuum will pick up any new default settings when you reload the `postgresql.conf` file. # There's more... `VACUUM` doesn't run in parallel on a single table. If you want to run multiple VACUUMs at once you can do it like this, for example, running four vacuums at once to scan all databases: **$ vacuumdb --jobs=4 --all** If you run multiple VACUUMs at once you'll use more memory and I/O, so be careful. The exact calculation is complex, especially if you have tables with custom `VACUUM` settings, but the general idea is that I/O can be slowed down by raising `vacuum_cost_delay` or lowering `vacuum_cost_limit`. # Maintaining indexes Indexes can become a problem in many database applications that involve a high proportion of `INSERT`/`DELETE` commands. Just as tables can become bloated, so can indexes. In the previous recipe, you saw that non-HOT updates can cause bloated indexes. Non-primary-key indexes are also prone to some bloat from normal `INSERT` commands, as is common in most relational databases. Autovacuum does not detect bloated indexes, nor does it do anything to rebuild indexes. So we need to look at other ways to maintain indexes. # Getting ready PostgreSQL supports commands that will rebuild indexes for you. The client utility, `reindexdb`, allows you to execute the `REINDEX` command in a convenient way from the operating system: **$ reindexdb** This executes the SQL `REINDEX` command on every table in the default database. If you want to reindex all databases, then use the following: **$ reindexdb -a** That's what the manual says anyway. My experience is that most indexes don't need rebuilding, and even if they do, `REINDEX` puts a full-table lock (`AccessExclusiveLock`) on the table while it runs. That locks your database for possibly hours, and I advise that you think about not doing that. Try these steps instead: 1. First, let's create a test table with two indexes—a primary key and an additional index as follows: **DROP TABLE IF EXISTS test; CREATE TABLE test** **(id INTEGER PRIMARY KEY** **,category TEXT** **, value TEXT);** **CREATE INDEX ON test (category);** 2. Now let's look at the internal identifier of the tables, `oid`, and the current file number (`relfilenodes`), as follows: **SELECT oid, relname, relfilenode** **FROM pg_class** **WHERE oid in (SELECT indexrelid** **FROM pg_index** **WHERE indrelid = 'test'::regclass);** **oid | relname | relfilenode** **-------+-------------------+-------------** **16639 | test_pkey | 16639** **16641 | test_category_idx | 16641** **(2 rows)** # How to do it... PostgreSQL supports a command known as `CREATE INDEX CONCURRENTLY`, which builds an index without taking a full table lock. PostgreSQL also supports the ability to have two indexes, with different names, that have exactly the same definition. So, the trick is to build another index identical to the one you wish to rebuild, drop the old index, and then rename the new index to the same name as the old index. Et voilà, fresh index, and no locking! Let's see that in slow motion: **CREATE INDEX CONCURRENTLY new_index** **ON test (category);** **BEGIN;** **DROP INDEX test_category_idx;** **ALTER INDEX new_index RENAME TO test_category_idx;** **COMMIT;** When we check our internal identifiers again, we get the following: **SELECT oid, relname, relfilenode** **FROM pg_class** **WHERE oid in (SELECT indexrelid** **FROM pg_index** **WHERE indrelid = 'test'::regclass);** **oid | relname | relfilenode** **-------+-------------------+-------------** **16639 | test_pkey | 16639** **16642 | test_category_idx | 16642** **(2 rows)** So we can see that `test_category_idx` is now a completely new index. That seems pretty good, and it works on primary keys too, but in a slightly complex way—you need to create a new index using `UNIQUE` and `CONCURRENTLY`, and then issue this to make it a primary key: **ALTER TABLE ... ADD PRIMARY KEY USING INDEX ...** This is not optimal yet, because a primary key could be the target of one or more foreign keys. In that case, we need to drop and recreate the foreign keys, which unfortunately has no `CONCURRENTLY` variant. The next recipe, _Adding a constraint without checking existing rows_ , is a recommended reading. # How it works... The `CREATE INDEX CONCURRENTLY` statement allows `INSERT`, `UPDATE`, and `DELETE` commands while the index is being created. It cannot be executed inside another transaction, and only one index per table can be created concurrently at any time. Swapping the indexes is easy and doesn't use any trickery. # There's more... If you are fairly new to database systems, you might think rebuilding indexes for performance is something that only PostgreSQL needs to do. Other DBMSs require this as well, they just maybe don't say so. Indexes are designed for performance, and in all databases, deleting index entries causes contention and loss of performance. PostgreSQL does not remove index entries for a row when that row is deleted, so an index can be filled with dead entries. PostgreSQL does attempt to remove dead entries when a block becomes full, but that doesn't stop a small numbers of dead entries from accumulating in many data blocks. No `REINDEX CONCURRENTLY` command has been added yet to PostgreSQL. # Adding a constraint without checking existing rows A table constraint is a guarantee that must be satisfied by all the rows in the table. Therefore, adding a constraint to a table is a two-phase procedure—first, the constraint is created, and then all the existing rows are checked. Both happen in the same transaction, and the table cannot be accessed in the meantime. The constraint becomes visible after the check, yielding perfect consistency, which is usually the desired behavior—at the expense of availability, which is not that great. This recipe demonstrates another case—how to enforce a constraint on future transactions _only_ , without checking existing rows. This may be desirable in some specific cases, such as the following two: * Enabling the constraint on newer rows of a large table that cannot remain unavailable for a long time * Enforcing the constraint on newer rows, while keeping older rows that are known to violate the constraint The constraint is marked as `NOT VALID` to make it clear that it does not exclude violations, unlike ordinary constraints. As seen following, it is possible to validate the constraint at a later time, for example, when allowed by the workload or business continuity requirements. All existing rows will be checked, and then the `NOT VALID` mark will be removed from the constraint. Conversely, in the other example, the constraint will never be validated, and its only purpose will be to prevent further violations by rejecting incompatible transactions. # Getting ready We'll start this recipe by creating two tables with a few test rows: **postgres=# CREATE TABLE ft(fk int PRIMARY KEY, fs text);** **CREATE TABLE** **postgres=# CREATE TABLE pt(pk int, ps text);** **CREATE TABLE** **postgres=# INSERT INTO ft(fk,fs) VALUES (1,'one'), (2,'two');** **INSERT 0 2** **postgres=# INSERT INTO pt(pk,ps) VALUES (1,'I'), (2,'II'), (3,'III');** **INSERT 0 3** # How to do it... We have inserted inconsistent data on purpose so that any attempt to check existing rows will be revealed by an error message. If we attempt to create an ordinary foreign key, we get an error, since the number `3` does not appear in the `ft` table: **postgres=# ALTER TABLE pt ADD CONSTRAINT pc FOREIGN KEY (pk) REFERENCES ft(fk);** **ERROR: insert or update on table "pt" violates foreign key constraint** **pc"** **DETAIL: Key (pk)=(3) is not present in table "ft".** However, the same constraint can be successfully created as `NOT VALID`: **postgres=# ALTER TABLE pt ADD CONSTRAINT pc FOREIGN KEY (pk) REFERENCES ft(fk) NOT VALID;** **ALTER TABLE** Note that the invalid state of the foreign key is mentioned by `psql`. **postgres=# \d pt** **Table "public.pt"** **Column | Type | Modifiers** **--------+---------+-----------** **pk | integer |** **ps | text |** **Foreign-key constraints:** **"pc" FOREIGN KEY (pk) REFERENCES ft(fk) NOT VALID** The violation is detected when we try to transform the `NOT VALID` constraint into a valid one: **postgres=# ALTER TABLE pt VALIDATE CONSTRAINT pc;** **ERROR: insert or update on table "pt" violates foreign key constraint** **pc"** **DETAIL: Key (pk)=(3) is not present in table "ft".** Validation becomes possible after removing the inconsistency, and the foreign key is upgraded to an ordinary one: **postgres=# DELETE FROM pt WHERE pk = 3;** **DELETE 1** **postgres=# ALTER TABLE pt VALIDATE CONSTRAINT pc;** **ALTER TABLE** **postgres=# \d pt** **Table "public.pt"** **Column | Type | Modifiers** **--------+---------+-----------** **pk | integer |** **ps | text |** **Foreign-key constraints:** **"pc" FOREIGN KEY (pk) REFERENCES ft(fk)** # How it works... `ALTER TABLE ... ADD CONSTRAINT.. NOT VALID` uses the `ShareRowExclusiveLock` that blocks writes and `VACUUM`, yet allows reads on the table to continue. The command `ALTER TABLE ... VALIDATE CONSTRAINT` executes using a `ShareUpdateExclusiveLock` that allows both reads and writes on the table yet blocks `DDL` and `VACUUM` while it scans the table. PostgreSQL takes SQL locks according to the ISO standard, that is, locks are taken during the transaction and then released at its end. This means that algorithms like this one, where there is a short activity requiring stronger locks, followed by a longer activity that needs only lighter locks, cannot be implemented as a single command. # Finding unused indexes Selecting the correct set of indexes for a workload is known to be a hard problem. It usually involves trial and error by developers and DBAs to get a good mix of indexes. Tools for identifying slow queries exist, and many `SELECT` statements can be improved by the addition of an index. What many people forget is to check whether the mix of indexes remains valuable over time, which is something for the DBA to investigate and optimize. # How to do it... PostgreSQL keeps track of each access against an index. We can view that information and use it to see whether an index is unused, as follows: **postgres=# SELECT schemaname, relname, indexrelname, idx_scan FROM pg_stat_user_indexes ORDER BY idx_scan;** **schemaname | indexrelname | idx_scan** **------------+--------------------------+----------** **public | pgbench_accounts_bid_idx | 0** **public | pgbench_branches_pkey | 14575** **public | pgbench_tellers_pkey | 15350** **public | pgbench_accounts_pkey | 114400** **(4 rows)** As we can see in the preceding code, there is one index that is totally unused, alongside others that have some usage. You now need to decide whether unused means you should remove the index. That is a more complex question, and we first need to explain how it works. # How it works... The PostgreSQL statistics accumulate various pieces of useful information. These statistics can be reset to zero using an administrator function. Also, as the data accumulates over time, we usually find that objects that have been there for longer periods of time have higher apparent usage. So if we see a low number for `idx_scan`, then it might be that the index was newly created (as was the case in my preceding demonstration), or that the index is only used by a part of the application that runs only at certain times of a day, week, month, and so on. Another important consideration is that the index may be a unique constraint index that exists specifically to safeguard against duplicate `INSERT` commands. An `INSERT` operation does not show up as an `idx_scan`, even if the index was actually used while checking the uniqueness of the newly inserted values, whereas an `UPDATE` or `DELETE` might show up, because they have to locate the row first. So a table that only has `INSERT` commands against it will appear to have unused indexes. Also, some indexes that show usage might be showing usage that was historical, and there is no further usage. Or it might be the case that some queries use an index where they could just as easily and almost as cheaply use an alternative index. Those things are for you to explore and understand before you take action. A very common approach is to regularly monitor such numbers in order to gain knowledge by examining their evolution over time on both the master database and on any replicated hot standby nodes. In the end, you may decide from this that you want to remove an index. If only there was a way to try removing an index and then put it back again quickly, in case you cause problems! Rebuilding an index might take hours on a big table, so these decisions can be a little scary. No worries! Just follow the next recipe, _Carefully removing unwanted indexes_. # Carefully removing unwanted indexes Carefully removing? You mean press _Enter_ gently after typing `DROP INDEX`? Err, no! The thinking is that it takes a long time to build an index, and a short time to drop it. What we want is a way of removing an index such that if we discover that removing it was a mistake, we can put the index back again quickly. # Getting ready The following query will list all invalid indexes, if any: **SELECT ir.relname AS indexname** **, it.relname AS tablename** **, n.nspname AS schemaname** **FROM pg_index i** **JOIN pg_class ir ON ir.oid = i.indexrelid** **JOIN pg_class it ON it.oid = i.indrelid** **JOIN pg_namespace n ON n.oid = it.relnamespace** **WHERE NOT i.indisvalid;** Take note of these indexes, so that later you can tell whether a given index is invalid because we marked it as invalid during this recipe, in which case it can safely be marked as valid, or because it was already invalid for other reasons. # How to do it... We will describe a procedure that allows us to deactivate an index without actually dropping it, so that we can appreciate what its contribution was and possibly reactivate it: 1. First, create the following function: **CREATE OR REPLACE FUNCTION trial_drop_index(iname TEXT) RETURNS VOID** **LANGUAGE SQL AS $$ UPDATE pg_index** **SET indisvalid = false** **WHERE indexrelid = $1::regclass;** **$$;** 2. Then, run it to do a trial of dropping the index. 3. If you experience performance issues after dropping the index, then use this function to `undrop` the index: **CREATE OR REPLACE FUNCTION trial_undrop_index(iname TEXT) RETURNS VOID ** **LANGUAGE SQL AS $$ UPDATE pg_index ** **SET indisvalid = true ** **WHERE indexrelid = $1::regclass; ** **$$;** Be careful to avoid undropping any index that was detected by the query in the _Getting Ready_ section; if it wasn't marked as invalid when applying this recipe, then it may be unusable because it really is not valid. # How it works... This recipe also uses some inside knowledge. When we create an index using `CREATE INDEX CONCURRENTLY`, it is a two-stage process. The first phase builds the index and then marks it invalid. `INSERT`, `UPDATE`, and `DELETE` statements now begin maintaining the index, but we perform a further pass over the table to see if we missed anything, before declaring the index valid. User queries don't use the index until it says that it is valid. Once the index is built and the valid flag is set, then if we set the flag to invalid, the index will still be maintained. It's just that it will not be used by queries. This allows us to turn the index off quickly, though with the option to turn it on again if we realize that we actually do need the index after all. This makes it practical to test whether dropping the index will alter the performance of any of your most important queries. # Planning maintenance In these busy times, many people believe, _if it ain't broken, don't fix it_. I believe that too, but it isn't an excuse for not taking action to maintain your database servers and be sure that nothing will break. Database maintenance is about making your database run smoothly. Monitoring systems are not a substitute for good planning. They alert you to unplanned situations that need attention. The more unplanned things you respond to, the greater the chance that you will need to respond to multiple emergencies at once. And when that happens, something will break. Ultimately, that is your fault. If you wish to take your responsibilities seriously, you should plan ahead. # How to do it... This recipe is about planning, so we'll provide discussion points rather than portions of code. We'll cover the main points that should be addressed, and also provide a list of points as food for thought, around which the actual implementation should be built: * **Let's break a rule** : If you don't have a backup, take one now. I mean now, go on, off you go! Then, let's talk some more about planning maintenance. If you already do, well done! It's hard to keep your job as a DBA if you lose data because of missing backups, especially today, when everybody's grandmother knows to keep her photos backed up. * **First, plan your time** : Decide a regular date on which to perform certain actions. Don't allow yourself to be a puppet of your monitoring system, running up and down every time the lights change. If you keep getting dragged off on other assignments, then you must understand that you need to get a good handle on the database maintenance to make sure that it doesn't bite you. * **Don't be scared** : It's easy to worry about what you don't know, and either overreact or underreact. Your database probably doesn't need to be inspected daily, but never is definitely a bad practice. # How it works... Build a regular cycle of activity around the following tasks: * **Capacity planning** : Observe long-term trends in system performance and keep track of the growth of database volumes. Plan to schedule any new data feeds and new projects that increase the rates of change. This is best done monthly so that you monitor what has happened and what will happen. * **Backups, recovery testing, and emergency planning** : Organize regular reviews of written plans and test scripts. Check the tape rotation, confirm that you still have the password to the off-site backups, and so on. Some sysadmins run a test recovery every night so that they always know that a successful recovery is possible. * **Vacuum and index maintenance** : To reduce bloat, as well as collecting optimizer statistics through `ANALYZE`. Also, regularly check index usage and drop unused indexes Consider `VACUUM` again, with the need to manage the less frequent **freezing** process. This is listed as a separate task so that you don't ignore this and let it bite you later! * **Server log file analysis** : How many times has the server restarted? Are you sure you know about each incident? * **Security and intrusion detection** : Has your database already been hacked? What did they do? * **Understanding usage patterns** : If you don't know much about what your database is used for, then I'll wager it is not very well tuned or maintained. * **Long-term performance analysis** : It's a common occurrence for me to get asked to come and tune a system that is slow. Often what happens is that a database server gets slower over a very long period. Nobody ever noticed any particular day when it got slow—it just got slower over time. Keeping records of response times over time can help confirm whether everything is as good now as it was months or years earlier. This activity is where you might reconsider current index choices. Many of these activities are mentioned in this chapter or throughout the rest of the cookbook. Some are not because they aren't so much technical tasks, but more about planning and understanding of your environment. You might also find time to consider the following: * **Data quality** : Are the contents of the database accurate and meaningful? Could the data be enhanced? * **Business intelligence** : Is the data being used for everything that can bring value to the organization? # Performance and Concurrency In this chapter, we will cover the following recipes: * Finding slow SQL statements * Collecting regular statistics from pg_stat* views * Finding out what makes SQL slow * Reducing the number of rows returned * Simplifying complex SQL queries * Speeding up queries without rewriting them * Discovering why a query is not using an index * Forcing a query to use an index * Using parallel query * Using Optimistic locking * Reporting performance problems # Introduction Performance and concurrency are two problems that are often tightly coupled -- when concurrency problems are encountered, performance usually degrades, in some cases a lot. If you take care of concurrency problems, you will achieve better performance. In this chapter, we will show you how to find slow queries and also how to find queries that make other queries slow. Performance tuning, unfortunately, is still not an exact science, so you may also encounter a performance problem not covered by any of the given methods. We will also show you how to get help in the final recipe, _Reporting performance problems_ , in case none of the other recipes covered here work. # Finding slow SQL statements There are two main kinds of slowness that can manifest themselves in a database. The first kind is a single query that can be too slow to be really usable, such as a customer information query in a CRM running for minutes, a password check query running in tens of seconds, or a daily data aggregation query running for more than a day. These can be found by logging queries that take over a certain amount of time, either at the client end or in the database. The second kind is a query that is run frequently (say a few thousand times a second) and used to run in single-digit milliseconds, but is now running in several tens or even hundreds of milliseconds, thus slowing down the system. This kind of slowness is much harder to find. Here, we will show you several ways to find the statements that are either slow or cause the database as a whole to slow down (although they are not slow by themselves). # Getting ready Connect to the database as the user whose statements you want to investigate, or as a superuser to investigate all users' queries. Check that you have the `pg_stat_statements` extension installed: **postgres=# \x** **postgres=# \dx pg_stat_statements** List of installed extensions: **-[ RECORD 1 ]----------------------------------------------------------** **Name | pg_stat_statements** **Version | 1.4** **Schema | public** **Description | track execution statistics of all SQL statements executed** If not, then issue the following command: **postgres=# CREATE EXTENSION pg_stat_statements; postgres=# ALTER SYSTEM** **SET shared_preload_libraries = 'pg_stat_statements';** Then restart the server, or refer to the Using an installed module and Managing installed extensions recipes from Chapter 3, Configuration, for more details. # How to do it... Run this query to look at the top 10 highest workloads on your server side: **postgres=# SELECT calls, total_time, query FROM pg_stat_statements** **ORDER BY total_time DESC LIMIT 10;** The output is ordered by `total_time`, so it doesn't matter whether it was a single query or thousands of smaller queries. There are many additional columns useful in tracking down further information about particular entries: **postgres=# \d pg_stat_statements** **View "public.pg_stat_statements"** **Column | Type | Modifiers** **---------------------+------------------+-----------** **userid | oid |** **dbid | oid |** **queryid | bigint |** **query | text |** **calls | bigint |** **total_time | double precision |** **min_time | double precision |** **max_time | double precision |** **mean_time | double precision |** **stddev_time | double precision |** **rows | bigint |** **shared_blks_hit | bigint |** **shared_blks_read | bigint |** **shared_blks_dirtied | bigint |** **shared_blks_written | bigint |** **local_blks_hit | bigint |** **local_blks_read | bigint |** **local_blks_dirtied | bigint |** **local_blks_written | bigint |** **temp_blks_read | bigint |** **temp_blks_written | bigint |** **blk_read_time | double precision |** **blk_write_time | double precision |** # How it works... `pg_stat_statements` collects data on all running queries by accumulating data in memory, producing minimal overheads. Similar SQL statements are normalized so that the constants and parameters used for execution are removed. This allows you to see all similar SQL statements in one line of the report, rather than seeing thousands of lines, which would be fairly useless. While useful, it can sometimes mean that it's hard to work out which parameter values are actually causing the problem. # There's more... Another way to find slow queries is to set up PostgreSQL to log them all. So if you decide to monitor a query taking over 10 seconds, then set up logging queries over 10 seconds by executing the following: **postgres=# ALTER SYSTEM** **SET log_min_duration_statement = 10000;** Remember that the duration is in milliseconds. After doing this, reload PostgreSQL. All queries that are slow enough to exceed the threshold will be logged. The PostgreSQL log files are usually located together with other log files; for example, on Debian/Ubuntu Linux, they are in the `/var/log/postgresql/` directory. You can also log every query, though that can often swamp the log files and cause performance problems itself and so is hardly ever recommend. Query logging will show the parameters used for the slow query, even when `pg_stat_statements` does not. # Collect regular statistics from pg_stat* views This recipe describes how to collect the statistics needed to understand what is going on in the database system on a regular basis so that they can be used to further optimize the queries that are slow or are becoming slow as the database changes. We have included an example extension, called `pgstatslog`. It can be used to track these changes. The extension works on PostgreSQL 9.1+. Look at the _Using an installed module_ and m _anaging installed extensions_ recipes from Chapter 3, _Configuration_ , for an overview of the extensions infrastructure in PostgreSQL. # Getting ready Find the `pgstatslog` directory in the set of files distributed along with this book. Find out the directory to place shared files using `pg_config --sharedir` and then copy the files to the `extension` subdirectory of that directory. Now that the extension has been installed in your PostgreSQL server, it is time to install it in each database that you want to monitor: **postgres=# CREATE EXTENSION pgstatslog; ** **CREATE EXTENSION** You can verify that the extension is installed by typing `\dx` in `psql`. # How to do it... You can collect information by executing the following query for each database that you intend to monitor: **SELECT collect_deltas();** This will collect the changes in the `pg_stat_user_*` and `pg_statio_user_*` tables that have occurred since the last invocation. You should probably set up a cron job to run on a regular basis so that you have good coverage of what happens at what time of the day and week. Running it at an interval of 5 – 15 minutes should usually give you enough temporal resolution to understand what is going on with your tables. For example, you can add this (or a similar variation) to the `postgres` user's cron table: ***/5 * * * * /usr/bin/psql -c 'SELECT collect_deltas()' mydbname** # How it works... The `collect_deltas()` function makes static copies of the `pg_stat_user_tables`, `pg_statio_user_tables`, `pg_stat_user_indexes`, and `pg_statio_user_indexes` tables at each run. It then compares the current copies with the copies saved at the last run, and saves the timestamped deltas in the `stat_user_tables_delta_log` and `stat_user_indexes_delta_log` log tables. These tables can then be analyzed later to get an insight into access and I/O patterns. The latest set of deltas is also kept in the `stat_user_tables_delta` and `stat_user_indexes_delta` tables, which can be used for external monitoring systems, such as Cacti, to get a graphical representation of it. # There's more... The `collect_deltas()` function simply appends data to the same tables. This should not cause performance problems, as the large log tables are without indexes. Thus, insertions in them are fast, but if you are low on disk space and have many tables, you may want to introduce a rotation scheme for these tables that throws away older data. In case you experience performance issues with the proposed approach, you might want to either purge the old data from the `*_delta_log` tables (and keep a window of the last four weeks) or use horizontal partitioning. In the first approach, you can set a weekly cron job that deletes all records that are older than four weeks from the tables. For this purpose, we have created the `rotate_deltas()` function in the `pgstatslog` extension. Take some time and investigate the content of the extension, in particular the `pgstatslog--1.0.sql` file. It contains definitions for tables, views, and functions, as well as usage instructions. In the second approach, you can keep longer series of data, by creating weekly partitions, for example, and let PostgreSQL manage partitioning. PostgreSQL 10's partitioning scheme should be effective for the use case of time series data logging, as shown at <http://www.postgresql.org/docs/current/static/ddl-partitioning.html> and <http://www.postgresql.org/docs/current/static/tutorial-inheritance.html>. # Another statistics collection package If you are interested in a more powerful way of tracking database statistics over time, I suggest you look at `pg_statsinfo`, an open source package available at <http://pgstatsinfo.sourceforge.net/> and developed by our friends from NTT. # Finding out what makes SQL slow An SQL statement can be slow for a lot of reasons. Here, we will give a short list of these, with at least one way of recognizing each reason. # Getting ready If the SQL statement is still running, look at Chapter 8, _Monitoring and Diagnosis_. # How to do it... The core issues are likely to be one of these: * You're asking it to do too much work * Something is stopping it from doing the work This might not sound that helpful at first, but it's good to know that there's nothing really magical going on that you can't understand if you look. In more detail, the main reasons are: * Returning too much data * Processing too much data index needed * Wrong plan for other reasons * Cache or I/O problems * Locking problems The first reason can be handled as described in the Reducing the number of rows returned recipe. Reasons 2-4 can be investigated from two perspectives: The SQL itself and the objects that the SQL touches. Let's start by looking at the SQL itself by running the query with `EXPLAIN` `ANALYZE`. We're going to use the optional form as follows: **postgres=# EXPLAIN (ANALYZE, BUFFERS) ...SQL...** The `EXPLAIN` command provides output to describe the execution plan of the SQL, showing access paths and costs (in abstract units). The `ANALYZE` option causes the statement to be executed (be careful), with instrumentation to show the number of rows accessed and the timings for that part of the plan. The `BUFFERS` option provides information about the number of database buffers read and the number of buffers that were hit in the cache. Taken together, we have everything we need to diagnose whether the SQL performance is slow from reasons _2_ - _4_ : **postgres=# EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM t; ** **QUERY PLAN ** **--------------------------------------------------------------** **Aggregate (cost=4427.27..4427.28 rows=1 width=0) \ ** **(actual time=32.953..32.954 rows=1 loops=1)** **Buffers: shared hit=X read=Y ** **- > Seq Scan on t (cost=0.00..4425.01 rows=901 width=0) \ ** **(actual time=30.350..31.646 rows=901 loops=1)** **Buffers: shared hit=X read=Y ** **Planning time: 0.045 ms** **Execution time: 33.128 ms ** **(6 rows)** Let's use the technique to look at an SQL statement that would benefit from an index. For example, if you want to get the three latest rows in a one million row table, run this query: **SELECT * FROM events ORDER BY id DESC LIMIT 3;** You can either read through just three rows using an index on the `id SERIAL` column, or you can perform a sequential scan of all rows followed by a sort, as shown in the following snippet. Your choice depends on whether you have an usable index on the field from which you want to get the top three rows: **postgres=# CREATE TABLE events(id SERIAL); ** **CREATE TABLE ** **postgres=# INSERT INTO events SELECT generate_series(1,1000000); ** **INSERT 0 1000000 ** **postgres=# EXPLAIN (ANALYZE)** **SELECT * FROM events ORDER BY id DESC LIMIT 3; ** **QUERY PLAN ** **--------------------------------------------------------------** **Limit (cost=25500.67..25500.68 rows=3 width=4) \ ** **(actual time=3143.493..3143.502 rows=3 loops=1) ** **- > Sort (cost=25500.67..27853.87 rows=941280 width=4) ** **(actual time=3143.488..3143.490 rows=3 loops=1) ** **Sort Key: id DESC ** **Sort Method: top-N heapsort Memory: 25kB ** **- > Seq Scan on events ** **(cost=0.00..13334.80 rows=941280 width=4) ** **(actual time=0.105..1534.418 rows=1000000 loops=1) ** **Planning time: 0.331 ms** **Execution time: 3143.584 ms ** **(10 rows) ** **postgres=# CREATE INDEX events_id_ndx ON events(id); ** **CREATE INDEX ** **postgres=# EXPLAIN (ANALYZE)** **SELECT * FROM events ORDER BY id DESC LIMIT 3; ** **QUERY PLAN ** **----------------------------------------------------------------------** **Limit (cost=0.00..0.08 rows=3 width=4) (actual** **time=0.295..0.311 rows=3 loops=1) ** **- > Index Scan Backward using events_id_ndx on events ** **(cost=0.00..27717.34 rows=1000000 width=4) (actual** **time=0.289..0.295 rows=3 loops=1) ** **Total runtime: 0.364 ms ** **(3 rows)** This produces a huge difference in query runtime, even when all of the data is in the cache. If you run the same analysis using `EXPLAIN` `(ANALYZE, BUFFERS)` on your production system you'll be able to see the cache effects as well. Remember that each new index you add increases the pressure on the cache so it is possible to have too many indexes. As we mentioned earlier, you can also look at the statistics for the objects touched by queries. In `pg_stat_user_tables`, fast growth of `seq_tup_read` means that there are lots of sequential scans occurring. The ratio of `seq_tup_read` to `seq_scan` shows how many tuples each `seqscan` reads. Similarly, the `idx_scan` and `idx_tup_fetch` columns show whether indexes are being used, and how effective they are. # There's more... If not enough of the data fits in shared buffers, lots of rereading of the same data happens, causing performance issues. In `pg_statio_user_tables`, watch the `heap_blks_hit` and `heap_blks_read` fields, or the equivalent ones for index and toast relations. They give you a fairly good idea of how much of your data is found in PostgreSQL's shared buffers (`heap_blks_hit`) and how much had to be fetched from the disk (`heap_blks_read`). If you see large numbers of blocks being read from the disk continuously, you may want to tune those queries; or if you determine that the disk reads were justified, you can make the configured `shared_buffers` value bigger. If your `shared_buffers` parameter is tuned properly and you can't rewrite the query to perform less block I/O, you might need a beefier computer. You can find a lot of resources on the Web that explain how shared buffers work and how to set them based on your available hardware and your expected data access patterns. Our professional advice is to always test your database servers and perform benchmarks before you deploy them in production. Information on the `shared_buffers` configuration parameter can be found at http://www.postgresql.org/docs/current/static/runtime-config-resource.html. # Not enough CPU power or disk I/O capacity for the current load These issues are usually caused by suboptimal query plans, but sometimes, your computer is just not powerful enough. In this case, `top` is your friend. For quick checks, run this from the command line: **user@host:~$ top** First, watch the percentage of idle CPU from `top`. If this is in low single digits for most of the time, you probably have problems with the CPU's power. If you have a high load average with a lot of CPU idle left, you are probably out of disk bandwidth. In this case, you should also have lots of postgres processes in the `D` status, meaning that the process is in an uninterruptible state (usually waiting for I/O). # Locking problems Thanks to its MVCC design, PostgreSQL does not suffer from most locking problems, such as writers locking out readers or readers locking out writers, but it still has to take locks when more than one process wants to update the same row. Also, it has to hold the write lock until the current writer's transaction finishes. So, if you have a database design where many queries update the same record, you can have a locking problem. Refer to the _Knowing who is blocking a query_ recipe of Chapter 8, _Monitoring and Diagnosis_ , for more detailed information. To diagnose locking problems retrospectively, use the `log_lock_waits` parameter to generate log output for locks held for a long time. # EXPLAIN options Use the `FORMAT` option, to retrieve the output of `EXPLAIN` in a different format, such as `JSON`, `XML`, and `YAML`. This could allow us to write programs to manipulate the outputs. The following command is an example of this: **EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT count(*) FROM t;** # See also * For further information on the syntax of the `EXPLAIN` SQL command, refer to the PostgreSQL documentation at http://www.postgresql.org/docs/current/static/sql-explain.html. # Reducing the number of rows returned Although often the problem is producing many rows in the first place, it is made worse by returning all of the unnecessary rows to the client. This is especially true if the client and server are not on the same host. Here are some ways to reduce the traffic between the client and server. # How to do it... Consider the following scenario: a full-text search returns 10,000 documents, but only the first 20 are displayed to users. In this case, order the documents by ranking on the server, and return only the top 20 that actually need to be displayed: **SELECT title, ts_rank_cd(body_tsv, query, 20) AS text_rank** **FROM articles, plainto_tsquery('spicy potatoes') AS query** **WHERE body_tsv @@ query** **ORDER BY rank DESC** **LIMIT 20** **;** If you need the next 20 documents, don't just query with a limit of 40 and throw away the first 20. Instead, use `OFFSET 20 LIMIT 20` to return the next 20 documents. To gain some stability so that documents with the same rank still come out in the same order when using `OFFSET 20`, add a unique field (like the `id` column of the `articles` table) to `ORDER BY` in both queries: **SELECT title, ts_rank_cd(body_tsv, query, 20) AS text_rank** **FROM articles, plainto_tsquery('spicy potatoes') AS query** **WHERE body_tsv @@ query** **ORDER BY rank DESC, articles.id** **OFFSET 20 LIMIT 20;** Another use case is an application that requests all products of a branch office, to run a complex calculation over them. In such a case, try to do as much data analysis as possible inside the database. There is no need to run the following: **SELECT * FROM accounts WHERE branch_id = 7;** Also, instead of counting and summing the rows on the client side, you can run this: **SELECT count(*), sum(balance) FROM accounts WHERE branch_id = 7;** With some research on the SQL language, which is supported by PostgreSQL, you can carry out an amazingly large portion of your computation using plain SQL (for example, do not underestimate the power of window functions). If SQL is not enough, you can use PL/pgSQL, or any other embedded procedural languages supported by PostgreSQL for even more flexibility. # There's more... Consider one more scenario: an application runs a huge number of small lookup queries. This can easily happen with modern **Object Relational Mappers** ( **ORMs** ) and other toolkits that do a lot of work for the programmer, but at the same time, hide a lot of what is happening. For example, if you define an HTML report over a query in a templating language, and then define a lookup function to resolve an ID inside the template, you may end up with a form that performs a separate, small lookup for each row displayed, even when most of the values looked up are the same. This doesn't usually pose a big problem for the database, as queries of the `SELECT name FROM departments WHERE id = 7` form are really fast when the row for `id = 7` is in shared buffers. However, repeating this query thousands of times still takes seconds, due to network latency, process scheduling for each request, and other factors. The two proposed solutions are as follows: * Make sure that the value is cached by your ORM * Perform the lookup inside the query that gets the main data so that it can be displayed directly Exactly how to carry out these solutions depends on the toolkit, but they are both worth investigating, as they really can make a difference in speed and resource usage. # See also * PostgreSQL 9.5 introduced the `TABLESAMPLE` clause into SQL. This allows you to run commands much faster by using a sample of a table's rows, giving an approximate answer. In certain cases, this can be just as useful as the most accurate answer: **postgres=# SELECT avg(id) FROM events;** **avg** **---------------------** **500000.500** **(1 row)** **postgres=# SELECT avg(id) FROM events TABLESAMPLE system(1);** **avg** **---------------------** **507434.635** **(1 row)** **postgres=# EXPLAIN (ANALYZE, BUFFERS) SELECT avg(id) FROM events;** **QUERY PLAN** **------------------------------------------------------------------------------------------------------------------------** **Aggregate (cost=16925.00..16925.01 rows=1 width=32) (actual time=204.841..204.841 rows=1 loops=1)** **Buffers: shared hit=96 read=4329** **- > Seq Scan on events (cost=0.00..14425.00 rows=1000000 width=4) (actual time=1.272..105.452 rows=1000000 loops=1) ** **Buffers: shared hit=96 read=4329** **Planning time: 0.059 ms** **Execution time: 204.912 ms** **(6 rows)** **postgres=# EXPLAIN (ANALYZE, BUFFERS)** **SELECT avg(id) FROM events TABLESAMPLE system(1);** **QUERY PLAN** **-------------------------------------------------------------------------------------------------------------------** **Aggregate (cost=301.00..301.01 rows=1 width=32) (actual time=4.627..4.627 rows=1 loops=1)** **Buffers: shared hit=1 read=46** **- > Sample Scan on events (cost=0.00..276.00 rows=10000 width=4) (actual time=0.074..2.833 rows=10622 loops=1) ** **Sampling: system ('1'::real)** **Buffers: shared hit=1 read=46** **Planning time: 0.066 ms** **Execution time: 4.702 ms** **(7 rows)** # Simplifying complex SQL queries There are two types of complexity that you can encounter in SQL queries. First, the complexity can be directly visible in the query, if it has hundreds or even thousands of rows of SQL code in a single query. This can cause both maintenance headaches and slow execution. The complexity can also be hidden in subviews, so the SQL code of the query may seem simple, but it uses other views and/or functions to do part of the work, which can, in turn, use others. This is much better for maintenance, but it can still cause performance problems. Both types of queries can either be written manually by programmers or data analysts, or emerge as a result of a query generator. # Getting ready First, verify that you really have a complex query. A query that simply returns lots of database fields is not complex by itself. In order to be complex, the query has to join lots of tables in complex ways. The easiest way to find out whether the query is complex is to look at the output of `EXPLAIN`. If it has lots of rows, the query is complex, and it's not just that there is a lot of text. All examples in this recipe have been written with a very typical use case in mind: sales. What follows is a description of the fictitious model used in this recipe. The most important fact is the `sale` event, stored in the `sale` table (I specifically used the word fact, as this is the right term to use in a _data warehousing_ context). Every sale takes place at a point of sale (the `salespoint` table), at a specific time, and involves an item. That item is stored in a warehouse (see the `item` and `warehouse` tables, as well as the `item_in_wh` link table). Both the `warehouse` and the `salespoint` are located in a geographical area (the `location` table). This is important, for example, to study the provenance of a transaction. Here is a simplified entity-relationship model, useful for understanding all the joins that occur in the following queries: # How to do it... Simplifying a query usually means restructuring it so that parts of it can be defined separately, and then used by other parts. We'll illustrate the possibilities by rewriting the following query in several ways. The complex query in our example case is a so-called **pivot** or **cross-tab** query. This query retrieves the quarterly profit for non-local sales from all shops, as shown in the following: **SELECT shop.sp_name AS shop_name,** **q1_nloc_profit.profit AS q1_profit,** **q2_nloc_profit.profit AS q2_profit,** **q3_nloc_profit.profit AS q3_profit,** **q4_nloc_profit.profit AS q4_profit,** **year_nloc_profit.profit AS year_profit** **FROM (SELECT * FROM salespoint ORDER BY sp_name) AS shop** **LEFT JOIN (** **SELECT** **spoint_id,** **sum(sale_price) - sum(cost) AS profit,** **count(*) AS nr_of_sales** **FROM sale s** **JOIN item_in_wh iw ON s.item_in_wh_id=iw.id** **JOIN item i ON iw.item_id = i.id** **JOIN salespoint sp ON s.spoint_id = sp.id** **JOIN location sploc ON sp.loc_id = sploc.id** **JOIN warehouse wh ON iw.whouse_id = wh.id** **JOIN location whloc ON wh.loc_id = whloc.id** **WHERE sale_time >= '2013-01-01'** **AND sale_time < '2013-04-01'** **AND sploc.id != whloc.id** **GROUP BY 1** **) AS q1_nloc_profit** **ON shop.id = Q1_NLOC_PROFIT.spoint_id** **LEFT JOIN (** **< similar subquery for 2nd quarter >** **) AS q2_nloc_profit** **ON shop.id = q2_nloc_profit.spoint_id** **LEFT JOIN (** **< similar subquery for 3rd quarter >** **) AS q3_nloc_profit** **ON shop.id = q3_nloc_profit.spoint_id** **LEFT JOIN (** **< similar subquery for 4th quarter >** **) AS q4_nloc_profit** **ON shop.id = q4_nloc_profit.spoint_id** **LEFT JOIN (** **< similar subquery for full year >** **) AS year_nloc_profit** **ON shop.id = year_nloc_profit.spoint_id** **ORDER BY 1** **;** As the preceding query has an almost identical repeating part for finding the sales for a period (the four quarters of 2013, in this case), it makes sense to move it to a separate view (for the whole year), and then use that view in the main reporting query, as follows: **CREATE VIEW non_local_quarterly_profit_2013 AS ** **SELECT ** **spoint_id, ** **extract('quarter' from sale_time) as sale_quarter, ** **sum(sale_price) - sum(cost) AS profit, ** **count(*) AS nr_of_sales ** **FROM sale s ** **JOIN item_in_wh iw ON s.item_in_wh_id=iw.id ** **JOIN item i ON iw.item_id = i.id ** **JOIN salespoint sp ON s.spoint_id = sp.id ** **JOIN location sploc ON sp.loc_id = sploc.id ** **JOIN warehouse wh ON iw.whouse_id = wh.id ** **JOIN location whloc ON wh.loc_id = whloc.id ** **WHERE sale_time >= '2013-01-01' ** **AND sale_time < '2014-01-01' ** **AND sploc.id != whloc.id ** **GROUP BY 1,2; ** **SELECT shop.sp_name AS shop_name, ** **q1_nloc_profit.profit as q1_profit, ** **q2_nloc_profit.profit as q2_profit, ** **q3_nloc_profit.profit as q3_profit, ** **q4_nloc_profit.profit as q4_profit, ** **year_nloc_profit.profit as year_profit ** **FROM (SELECT * FROM salespoint ORDER BY sp_name) AS shop ** **LEFT JOIN non_local_quarterly_profit_2013 AS q1_nloc_profit ** **ON shop.id = Q1_NLOC_PROFIT.spoint_id ** **AND q1_nloc_profit.sale_quarter = 1 ** **LEFT JOIN non_local_quarterly_profit_2013 AS q2_nloc_profit ** **ON shop.id = Q2_NLOC_PROFIT.spoint_id ** **AND q2_nloc_profit.sale_quarter = 2 ** **LEFT JOIN non_local_quarterly_profit_2013 AS q3_nloc_profit ** **ON shop.id = Q3_NLOC_PROFIT.spoint_id ** **AND q3_nloc_profit.sale_quarter = 3 ** **LEFT JOIN non_local_quarterly_profit_2013 AS q4_nloc_profit ** **ON shop.id = Q4_NLOC_PROFIT.spoint_id ** **AND q4_nloc_profit.sale_quarter = 4 ** **LEFT JOIN ( ** **SELECT spoint_id, sum(profit) AS profit ** **FROM non_local_quarterly_profit_2013 GROUP BY 1 ** **) AS year_nloc_profit ** **ON shop.id = year_nloc_profit.spoint_id ** **ORDER BY 1;** Moving the subquery to a view has not only made the query shorter, but also easier to understand and maintain. You might want to consider **materialized views**. Even though their support does not yet allow differential updates, you can still benefit from on-demand refreshing of the view results and, most importantly, indexes. Materialized views are described later in this recipe. Before that, we will be using common table expressions (also known as `WITH` queries) instead of a separate view. Starting with PostgreSQL version 8.4 indeed, you can use the `WITH` statement to define the view in line, as follows: **WITH nlqp AS ( ** **SELECT ** **spoint_id, ** **extract('quarter' from sale_time) as sale_quarter, ** **sum(sale_price) - sum(cost) AS profit, ** **count(*) AS nr_of_sales ** **FROM sale s ** **JOIN item_in_wh iw ON s.item_in_wh_id=iw.id ** **JOIN item i ON iw.item_id = i.id ** **JOIN salespoint sp ON s.spoint_id = sp.id ** **JOIN location sploc ON sp.loc_id = sploc.id ** **JOIN warehouse wh ON iw.whouse_id = wh.id ** **JOIN location whloc ON wh.loc_id = whloc.id ** **WHERE sale_time >= '2013-01-01' ** **AND sale_time < '2014-01-01' ** **AND sploc.id != whloc.id ** **GROUP BY 1,2 ** **) ** **SELECT shop.sp_name AS shop_name, ** **q1_nloc_profit.profit as q1_profit, ** **q2_nloc_profit.profit as q2_profit, ** **q3_nloc_profit.profit as q3_profit, ** **q4_nloc_profit.profit as q4_profit, ** **year_nloc_profit.profit as year_profit ** **FROM (SELECT * FROM salespoint ORDER BY sp_name) AS shop ** **LEFT JOIN nlqp AS q1_nloc_profit ** **ON shop.id = Q1_NLOC_PROFIT.spoint_id ** **AND q1_nloc_profit.sale_quarter = 1 ** **LEFT JOIN nlqp AS q2_nloc_profit ** **ON shop.id = Q2_NLOC_PROFIT.spoint_id ** **AND q2_nloc_profit.sale_quarter = 2 ** **LEFT JOIN nlqp AS q3_nloc_profit ** **ON shop.id = Q3_NLOC_PROFIT.spoint_id ** **AND q3_nloc_profit.sale_quarter = 3 ** **LEFT JOIN nlqp AS q4_nloc_profit ** **ON shop.id = Q4_NLOC_PROFIT.spoint_id ** **AND q4_nloc_profit.sale_quarter = 4 ** **LEFT JOIN ( ** **SELECT spoint_id, sum(profit) AS profit ** **FROM nlqp GROUP BY 1 ** **) AS year_nloc_profit ** **ON shop.id = year_nloc_profit.spoint_id ** **ORDER BY 1;** For more information on `WITH` queries (also known as **Common Table Expressions** ( **CTEs** )), read the official documentation at http://www.postgresql.org/docs/current/static/queries-with.html. # There's more... Another ace in the hole is represented by temporary tables used for parts of the query. By default, a temporary table is dropped at the end of a Postgres session, but the behavior can be changed at the time of creation. PostgreSQL itself can choose to materialize parts of the query during the query optimization phase, but sometimes, it fails to make the best choice for the query plan, either due to insufficient statistics, or because-as it can happen for large query plans, where **genetic query optimization** ( **GEQO** ) is used-it may have just overlooked some possible query plans. If you think that materializing (separately preparing) some parts of the query is a good idea, you can do it using a temporary table, simply by running `CREATE TEMPORARY TABLE my_temptable01 AS <the part of the query you want to materialize>` and then using `my_temptable01` in the main query, instead of the materialized part. You can even create indexes on the temporary table for PostgreSQL to use in the main query: **BEGIN; ** **CREATE TEMPORARY TABLE nlqp_temp ON COMMIT DROP ** **AS ** **SELECT ** **spoint_id, ** **extract('quarter' from sale_time) as sale_quarter, ** **sum(sale_price) - sum(cost) AS profit, ** **count(*) AS nr_of_sales ** **FROM sale s ** **JOIN item_in_wh iw ON s.item_in_wh_id=iw.id ** **JOIN item i ON iw.item_id = i.id ** **JOIN salespoint sp ON s.spoint_id = sp.id ** **JOIN location sploc ON sp.loc_id = sploc.id ** **JOIN warehouse wh ON iw.whouse_id = wh.id ** **JOIN location whloc ON wh.loc_id = whloc.id ** **WHERE sale_time >= '2013-01-01' ** **AND sale_time < '2014-01-01' ** **AND sploc.id != whloc.id ** **GROUP BY 1,2 ** **;** You can create indexes on the table and analyze the temporary table here: **SELECT shop.sp_name AS shop_name, ** **q1_NLP.profit as q1_profit, ** **q2_NLP.profit as q2_profit, ** **q3_NLP.profit as q3_profit, ** **q4_NLP.profit as q4_profit, ** **year_NLP.profit as year_profit ** **FROM (SELECT * FROM salespoint ORDER BY sp_name) AS shop ** **LEFT JOIN nlqp_temp AS q1_NLP ** **ON shop.id = Q1_NLP.spoint_id AND q1_NLP.sale_quarter = 1 ** **LEFT JOIN nlqp_temp AS q2_NLP ** **ON shop.id = Q2_NLP.spoint_id AND q2_NLP.sale_quarter = 2 ** **LEFT JOIN nlqp_temp AS q3_NLP ** **ON shop.id = Q3_NLP.spoint_id AND q3_NLP.sale_quarter = 3 ** **LEFT JOIN nlqp_temp AS q4_NLP ** **ON shop.id = Q4_NLP.spoint_id AND q4_NLP.sale_quarter = 4 ** **LEFT JOIN ( ** **select spoint_id, sum(profit) AS profit FROM nlqp_temp GROUP BY 1 ** **) AS year_NLP ** **ON shop.id = year_NLP.spoint_id ** **ORDER BY 1 ** **; ** **COMMIT; -- here the temp table goes away** # Using materialized views (long-living, temporary tables) If the part you put in the temporary table is large, does not change very often, and/or is hard to compute, then you may be able to do it less often for each query by using a technique named **materialized views**. Materialized views are views that are prepared before they are used (similar to a cached table). They are either fully regenerated as underlying data changes or in some cases, can update only those rows that depend on the changed data. PostgreSQL natively supports materialized views through the `CREATE MATERIALIZED VIEW`, `ALTER MATERIALIZED VIEW`, `REFRESH MATERIALIZED VIEW`, and `DROP MATERIALIZED VIEW` commands. At the time of writing, PostgreSQL supports full regeneration only of the cached tables, using concurrent `REFRESH` of the `MATERIALIZED VIEW`. A fundamental aspect of materialized views is that they can have their own indexes, like any other table. See http://www.postgresql.org/docs/current/static/sql-creatematerializedview.html for more information on creating materialized views. For instance, you can rewrite the example of the previous recipe using a `materialized view` instead of a temporary table: **CREATE MATERIA** L **IZED VIEW nlqp_temp AS ** **SELECT spoint_id, ** **extract('quarter' from sale_time) as sale_quarter, ** **sum(sale_price) - sum(cost) AS profit, ** **count(*) AS nr_of_sales ** **FROM sale s ** **JOIN item_in_wh iw ON s.item_in_wh_id=iw.id ** **JOIN item i ON iw.item_id = i.id ** **JOIN salespoint sp ON s.spoint_id = sp.id ** **JOIN location sploc ON sp.loc_id = sploc.id ** **JOIN warehouse wh ON iw.whouse_id = wh.id ** **JOIN location whloc ON wh.loc_id = whloc.id ** **WHERE sale_time >= '2013-01-01' ** **AND sale_time < '2014-01-01' ** **AND sploc.id != whloc.id ** **** **GROUP BY 1,2** # Using set-returning functions for some parts of queries Another possibility for achieving similar results to temporary tables and/or materialized views is by using a **set-returning function** for some parts of the query. It is easy to have a materialized view freshness check inside a function. However, a detailed analysis and an overview of these techniques go beyond the goals of this book, as they require a deep understanding of the PL/pgSQL procedural language. # Speeding up queries without rewriting them Often, you either can't or don't want to rewrite the query. However, you can still try and speed it up through any of the techniques discussed here. # How to do it... By now, we assume that you've looked at various problems already, so the following are more advanced ideas for you to try. # Increasing work_mem For queries involving large sorts or for join queries it may be useful to increase the amount of working memory that can be used for query execution. Try setting: **SET work_mem = '1TB';** Then, run `EXPLAIN` (not `EXPLAIN ANALYZE`). If the `EXPLAIN` changes for the query, then it may benefit from more memory. I'm guessing that you don't have access to 1 terabyte of RAM; the previous setting was only used to prove that the query plan is dependent upon available memory. So now, issue the following: **RESET work_mem;** And choose a more appropriate value for production use, such as: **SET work_mem = '128MB';** Remember to increase `maintenace_work_mem` when creating indexes or adding foreign keys, rather than `work_mem`. # More ideas with indexes Try and add a multicolumn index that is specifically tuned for that query. If you have a query that, for example, selects rows from the `t1` table on the `a` column and sorts on the `b` column, then creating the following index enables PostgreSQL to do it all in one index scan: **CREATE INDEX t1_a_b_ndx ON t1(a, b);** PostgreSQL 9.2 introduced a new plan type: **index-only scans**. This allows you to utilize a technique known as **covering indexes.** If all the columns requested by the `SELECT` list of a query are available in an index, that particular index is a covering index for that query. This technique allows PostgreSQL to fetch valid rows directly from the index, without accessing the table ( **heap** ), so performance improves significantly. Another often underestimated (or unknown) feature of PostgreSQL is **partial indexes**. If you use `SELECT` on a condition, especially if this condition only selects a small number of rows, you can use a conditional index on that expression, like this: **CREATE INDEX t1_proc_ndx ON t1(i1)** **WHERE needs_processing = TRUE;** The index will be used by queries that have a `WHERE` clause that includes the index clause, like the following **SELECT id, ... WHERE needs_processing AND i1 = 5;** There are many types of indexes in Postgres, so you may find that there are multiple types of indexes that can be used for a particular task, and many options to choose from: * Identifier data: BTREE, HASH * Text data: GIST, GIN * JSONB or XML data:GIN * Time-range data: BRIN * Geographical data: BRIN, GIST, and SP-GIST Performance gains in Postgres can also be obtained with another technique: **clustering tables on specific indexes**. However, index access may still not be very efficient if the values accessed by the index are distributed randomly all over the table. If you know that some fields are likely to be accessed together, then cluster the table on an index defined on those fields. For a multicolumn index, you can use the following command: **CLUSTER t1_a_b_ndx ON t1;** Clustering a table on an index rewrites the whole table in index order. This can lock the table for a long time, so don't do it on a busy system. Also, `CLUSTER` is a one-time command. New rows do not get inserted in cluster order, and to keep the performance gains, you may need to cluster the table every now and then. Once a table is clustered on an index, you don't need to specify the index name in following `cluster` commands. It is enough to type this: **CLUSTER t1;** It still takes time to rewrite the entire table, though it is probably a little faster once most of the table is in index order. # There's more... We complete this recipe by listing four examples of query performance issues that can be addressed with a specific solution. # Time Series Partitioning If you have a huge table and a query to select only a subset of that table, then you may wish to use a **BRIN index** ( **block range index** ). These give performance improvements when the data is naturally ordered as it is added to the table, such as logtime columns or a naturally ascending `OrderId` column. Adding a BRIN index is fast and very easy and works well for the use case of time series data logging, though less well under intensive updates. An INSERTs into BRIN indexes are specifically designed to **not** slow down as the table gets bigger, so they perform much better than btree indexes. You may also think that you need to manually partition a table. This can involve significant effort to set up an effective partitioning scheme so it doesn't really count as a technique without rewriting anything, so try BRIN first. **CREATE TABLE measurement (** **logtime TIMESTAMP NOT NULL,** **measures JSONB NOT NULL);** **CREATE INDEX ON measurement USING BRIN (logtime);** Partitioning syntax was introduced in PostgreSQL 10. In this release, it is effective for INSERTs and large/slow `SELECT` queries, which makes it suitable for time series logging and business intelligence. It is not yet fully optimized for fast OLTP `SELECT`, `UPDATE`, or `DELETE` commands unless you explicitly request those commands against the specific partition you wish to target. Those restrictions are substantially lifted in the forthcoming PostgreSQL 11 release, allowing partitioning to be effective for more use cases. For example, to create a table for time series data, you may want something like this: **CREATE TABLE measurement (** **logtime TIMESTAMP NOT NULL,** **measures JSONB NOT NULL** **) PARTITION BY RANGE (logtime);** **CREATE TABLE measurement_week1 PARTITION OF measurement** **FOR VALUES FROM ('2018-04-01') TO ('2018-05-01');** **CREATE INDEX ON measurement_week1 USING BRIN (logtime);** **CREATE TABLE measurement_week2 PARTITION OF measurement** **FOR VALUES FROM ('2018-05-01') TO ('2018-06-01');** **CREATE INDEX ON measurement_week2 USING BRIN (logtime);** **etc** Notice that you can use both BRIN indexes and partitioning at the same time, so there is less need to have huge numbers of partitions. Typical partition size should allow the whole current partition to sit within shared buffers. <http://www.postgresql.org/docs/current/static/ddl-partitioning.html>. # Using a TABLESAMPLE view Where some queries access a table, replace that with a view that retrieves fewer rows using a `TABLESAMPLE` clause. In this example, we use a sampling method that produces a sample of the table using a scan lasting no longer than 5 secs; if the table is small enough the answer is exact - otherwise progressive sampling is used to ensure that we meet out time objective: **CREATE EXTENSION tsm_system_time;** **CREATE SCHEMA fast_access_schema;** **CREATE VIEW tablename AS** **SELECT * FROM data_schema TABLESAMPLE system_time(5000); --5 secs** **SET search_path = 'fast_access_schema, data_schema';** So, the application can use the new table without changing the SQL. Be careful, as some answers can change when you're accessing fewer rows (for example, `sum()`), making this particular idea somewhat restricted; the overall idea of using views is still useful. # In case of many updates, set fillfactor on the table If you often update only some tables and can arrange your query/queries so that you don't change any indexed fields, then setting `fillfactor` to a lower value than the default of `100` for those tables enables PostgreSQL to use **Heap-Only Tuples** ( **HOT** ) updates, which can be an order of magnitude faster than ordinary updates. HOT updates not only avoid creating new index entries, but can also perform a fast mini-vacuum inside the page to make room for new rows: **ALTER TABLE t1 SET (fillfactor = 70);** This tells PostgreSQL to fill only `70` percent of each page in table `t1` when performing insertions, so that 30 percent is left for use by in-page (HOT) updates. # Rewriting the schema – a more radical approach In some cases, it may make sense to rewrite the database schema and provide an old view for unchanged queries using views, triggers, rules, and functions. One such case occurs when refactoring the database, and you would want old queries to keep running while changes are made. Another case is an external application that is unusable with the provided schema, but can be made to perform OK with a different distribution of data between tables. # Discovering why a query is not using an index This recipe explains what to do if you think your query should use an index, yet it does not. There could be several reasons for this, but most often, the reason is that the optimizer believes that, based on the available distribution statistics, it is cheaper and faster to use a query plan that does not use that specific index. # Getting ready First, check that your index exists, and ensure that the table has been analyzed. If there is any doubt, rerun it to be sure: **postgres=# ANALYZE;** **ANALYZE** # How to do it... Force index usage and compare plan costs with an index and without, as follows: **postgres=# EXPLAIN ANALYZE SELECT count(*) FROM itable WHERE id > 500; ** **QUERY PLAN ** **---------------------------------------------------------------------** **Aggregate (cost=188.75..188.76 rows=1 width=0) ** **(actual time=37.958..37.959 rows=1 loops=1) ** **- > Seq Scan on itable (cost=0.00..165.00 rows=9500 width=0) ** **(actual time=0.290..18.792 rows=9500 loops=1) ** **Filter: (id > 500) ** **Total runtime: 38.027 ms ** **(4 rows) ** **postgres=# SET enable_seqscan TO false; ** **SET ** **postgres=# EXPLAIN ANALYZE SELECT count(*) FROM itable WHERE id > 500; ** **QUERY PLAN ** **---------------------------------------------------------------------** **Aggregate (cost=323.25..323.26 rows=1 width=0) ** **(actual time=44.467..44.469 rows=1 loops=1) ** **- > Index Scan using itable_pkey on itable ****(cost=0.00..299.50 rows=9500 width=0) ** **(actual time=0.100..23.240 rows=9500 loops=1) ** **Index Cond: (id > 500) ** **Total runtime: 44.556 ms ** **(4 rows)** Note that you must use `EXPLAIN ANALYZE`, rather than just `EXPLAIN`. `EXPLAIN ANALYZE` shows you how much data is being requested and measures the actual execution time, while `EXPLAIN` only shows what the optimizer thinks will happen. `EXPLAIN ANALYZE` is slower, but it gives an accurate picture of what is happening. # How it works... Setting the `enable_seqscan` parameter to `off`, we greatly increase the cost of sequential scans for the query. This setting is never recommended for production use, only for testing. This allows us to generate two different plans, one with a `SeqScan` and one without. The optimizer works by selecting the lowest cost option available. In this case, the cost of the `SeqScan` is 188.75 and the cost of the `IndexScan` is 323.25, so for this specific case, the `IndexScan` will not be used. Remember that each case is different, and always relates to the exact data distribution. # There's more... Be sure that the `WHERE` clause you are using can be used with the type of index you have. For example, the `WHERE` clause `abs(val) < 2` won't use an index, because you're performing a function on the column, while `val BETWEEN -2 AND 2` could use the index. With more advanced operators and data types, it's easy to get confused as to the type of clause that will work, so check the docs for the data type carefully. In PostgreSQL 10, join statistics are also improved by the use of foreign keys, since they can be used in some queries to prove that joins on those keys return exactly one row. # Forcing a query to use an index Often, we think we know better than the database optimizer. Most of the time your expectation is wrong and if you look carefully you'll see that. So recheck everything and come back later. It is a classic error to try to get the database optimizer to use indexes when the database has very little data in it. Put some genuine data in the database first, then worry about it. Better yet, load some data on a test server first, rather than doing this in production. Sometimes the optimizer gets it wrong. You feel elated, and possibly angry, that the database optimizer doesn't see what you see. Please bear in mind that the data distributions within your database change over time, and this causes the optimizer to change its plans over time, also. If you have found a case where the optimizer is wrong, it might have been correct last week, and will be correct again next week: it correctly calculated that a change of plan was required, but it made that change slightly ahead of time, or slightly too late. Again, trying to force the optimizer to do the right thing _now_ might prevent it from doing the right thing _later_ , when the plan changes again. Some optimizer estimation errors can be corrected using `CREATE STATISTICS`, a new command in PostgreSQL 10, described in this recipe's _There's more..._ section. In the long run, it is not recommended to try to force the use of a particular index. # Getting ready Still here? Oh well. In fact, it is not possible to tell PostgreSQL to use an index by submitting an access path hint, like other DBMS products do. However, you can trick it into using an index by telling the optimizer that all other options are prohibitively expensive. First, you have to make sure that it is worth it to use the index. This is best done on a development or testing system, but if you are careful, it can also be done on the production server. Sometimes, it is very hard to generate a load similar to a live system in a test environment, and then your best option may be to carefully test it on the production server. As the PostgreSQL optimizer does not take into account the parallel load caused by other backends, it may make sense to lie to PostgreSQL about some statistics in order to make it use indexes. # How to do it... The most common problem is selecting too much data. A typical point of confusion comes from data that has a few very common values among a larger group. Requesting data for the very common values costs more because we need to bring back more rows. As we bring back more rows the cost of using the index increases. So it is possible that we won't use the index for the very common values, whereas we would use the index for the less common values. To use an index effectively, make sure you're reducing the number of rows returned. Another technique for making indexes more usable is **partial indexes**. Instead of indexing all values in a column, you might choose to index only the set of rows that are frequently accessed; for example, by excluding `NULL` or other unwanted data. By making the index smaller, it will be cheaper to access and fit within the cache better, avoiding pointless work by targeting the index at only the important data. Data statistics are kept for such indexes, so it can also improve the accuracy of query planning. For example: **CREATE INDEX ON customer(id)** **WHERE blocked = false AND subscription_status = 'paid';** Another nudge towards using indexes is to set `random_page_cost` to a lower value—maybe even equal to `seq_page_cost`. This makes PostgreSQL prefer index scans on more occasions, but it still does not produce entirely unreasonable plans, at least for cases where data is mostly cached in shared buffers, or system disk caches or underlying disks are solid-state drives. The default values for these parameters are as follows: **random_page_cost = 4;** **seq_page_cost = 1;** Try setting this: **set random_page_cost = 2;** See if it helps; if not, you can try setting it to `1`. Changing `random_page_cost` allows you to react to whether data is on disk or in memory. Letting the optimizer know that more of an index is in the cache will help it to understand that using the index is actually cheaper. Index scan performance for larger scans can also be improved by allowing multiple asynchronous I/O operations by increasing the `effective_io_concurrency`. Both `random_page_cost` and `effective_io_concurrency` can be set for specific tablespaces, or for individual queries. Rather than trying to force the use of an index, you might want to consider using a parallel query to speed up scans, so refer to the _Using parallel query_ recipe. # There's more... If you have multi-column indexes (or joins), the optimizer will assume that the column values are independent of each other, which can lead to mis-estimation in cases where there is a correlation between the values. If you have two dependent columns, such as `state` and `area_code`, then you can define additional statistics that will be collected when you next `ANALYZE` the table: **CREATE STATISTICS cust_s1 (ndistinct, dependencies) ON state, area_code FROM cust;** Execution time of `ANALYZE` will increase to collect the additional stats information, plus there is a small increase in query planning time so use this sparingly when you can confirm this will make a difference. You don't need to have both ndistinct and dependencies in all cases, only when it matters. Include the table name in the statistics you create since the name cannot be repeated on different tables. In future releases we will also add cross-table statistics. Unfortunately you cannot yet collect statistics on individual fields within JSON documents, nor collect dependency information between them; this command applies to whole column values only at this time. # There's even more If you absolutely, positively have to use the index, then you'll want to know about an extension called `pg_hint_plan`. It is available for PostgreSQL 9.1 and later versions. For more information and to download it, go to <http://pghintplan.sourceforge.jp/>. It works, but as I said before, try to avoid fixing things now and causing yourself pain later. # Using parallel query PostgreSQL 10 now has an increasingly effective parallel query feature. Response times from long running queries can be improved by the use of parallel processing. The concept is that we divide a large task up into multiple smaller pieces. We get the answer faster, but we use more resources to do that. Very short queries won't get faster by using parallel query, so if you have lots of those you'll gain more by thinking about better indexing strategies. Parallel Query is aimed at making very large tasks faster, so it is useful for reporting and business intelligence queries. # How to do it... Take a query that needs to do a big chunk of work, such as this: **\timing** **SELECT count(*) FROM accounts;** **count** **---------** **1000000** **(1 row)** **Time: 261.652 ms** **SET max_parallel_workers_per_gather = 8;** **SELECT count(*) FROM accounts;** **count** **---------** **1000000** **(1 row)** **Time: 180.513 ms** By setting the `max_parallel_workers_per_gather` parameter, we've improved performance using parallel query. Note that we didn't need to change the query at all. In PostgreSQL 9.6 and 10, parallel query only works for read-only queries, so only `SELECT` statements that do not contain the `FOR` clause (for example, `SELECT ... FOR UPDATE`). In addition, a parallel query can only use functions or aggregates that are marked as `PARALLEL SAFE`. No user-defined functions are marked `PARALLEL SAFE` by default, so read the docs carefully to see if your functions can be enabled for parallelism for the current release. # How it works... By default a query will use only one process. Parallel query is enabled by setting `max_parallel_workers_per_gather` to a value higher than zero. This parameter specifies the maximum number of **additional** processes that are available, if needed. So a setting of `1` will mean you have the leader process plus one additional worker process, so two processes in total. The query optimizer will decide if parallel query is a useful plan based upon cost, just like other aspects of the optimizer. Importantly, it will decide how many parallel workers to use in its plan, up to the maximum you specify. Across the whole server the maximum number of worker processes available is specified by the `max_worker_processes` parameter, set at server start only. PostgreSQL 10 introduces the `max_parallel_workers` parameter to further control the number of worker processes available. At execution time, the query will use its planned number of worker processes if that many are available. The plan for our earlier example of parallel query looks like this: **postgres=# EXPLAIN ANALYZE** **SELECT count(*) FROM demo;** **QUERY PLAN** **---------------------------------------------------------------------** **Finalize Aggregate (cost=78117.63..78117.64 rows=1 width=8) (actual time=203.426..203.426 rows=1 loops=1)** **- > Gather (cost=78117.21..78117.62 rows=4 width=8) (actual time=203.286..203.421 rows=5 loops=1) ** **Workers Planned: 4** **Workers Launched: 4** **- > Partial Aggregate (cost=77117.21..77117.22 rows=1 width=8) (actual time=194.315..194.315 rows=1 loops=5) ** **- > Parallel Seq Scan on demo (cost=0.00..76863.57 rows=101457 width=0) (actual time=115.632..164.688 rows=200200 loops=5) ** **Planning time: 0.076 ms** **Execution time: 206.197 ms** **(8 rows)** If worker processes aren't available, the query will run with fewer worker processes. As a result, it pays to not be too greedy, since if all concurrent users specify more workers than are available, you'll end up with variable performance as the number of concurrent parallel queries changes. Also note that the performance increase from adding more workers isn't linear for anything other than simple plans, so there are diminishing returns from using too many workers, anyway. The biggest gains are from adding the first few extra processes. As a result of those factors, I recommend a setting of just 1-3 extra worker processes for general use—meaning two processes will be used for queries, when needed. For specific long running queries, there may be as many as 8-16 workers, though that will vary considerably, depending on the kind of servers you're running on. # There's more... PostgreSQL 9.6 includes the basic parallel query feature. In this release, it works with Seq Scans, aggregation, and to a certain extent with joins. For many cases this is a very useful addition. PostgreSQL 10 adds plan improvements that allows parallel query to work with btree index scans, bitmap heap scans, merge joins and non-correlated subqueries. Also, in PostgreSQL 10 you can now get parallel query plans from SQL inside procedural language functions. If you have an immediate requirement for higher levels of scalability or very large databases then you'll want to look at the Postgres-XL project. Postgres-XL is an open source project using The PostgreSQL License that has modified PostgreSQL to provide multi-node parallel query, or massively parallel processing (MPP) as it's commonly known. MPP parallel queries are much faster than single node parallel queries. The project has been running for many years now and provides a full function version of Postgres aimed at larger and/or more scalable workloads. Almost all operations are fully parallelized, including many types of queries as well as maintenance commands and DDL operations. Postgres-XL features are expected to be integrated into PostgreSQL core within the next two-three years. # Using optimistic locking If you perform work in one long transaction the database will lock rows for long periods of time. Long lock times often result in application performance issues because of long lock waits: **BEGIN;** **SELECT * FROM accounts WHERE holder_name ='BOB' FOR UPDATE;** **< do some calculations here>** **UPDATE accounts SET balance = 42.00 WHERE holder_name ='BOB';** **COMMIT;** If that is happening, then you may gain some performance by moving from explicit locking (`SELECT ... FOR UPDATE`) to optimistic locking. Optimistic locking assumes that others don't update the same record, and checks this at update time, instead of locking the record for the time it takes to process the information on the client side. # How to do it... Rewrite your application so that the SQL is transformed into two separate transactions, with a double-check to ensure that the rows haven't changed (pay attention to the placeholders): **SELECT A.*, (A.*::text) AS old_acc_info** **FROM accounts a WHERE holder_name ='BOB';** **< do some calculations here>** **UPDATE accounts SET balance = 42.00** **WHERE holder_name ='BOB'** **AND (A.*::text) = <old_acc_info from select above>;** Then, check whether the `UPDATE` operation really did update one row in your application code. If it did not, then the account for `BOB` was modified between `SELECT` and `UPDATE`, and you probably need to rerun your entire operation (both transactions). # How it works... Instead of locking Bob's row for the time the data from the first `SELECT` command is processed in the client, PostgreSQL queries the old state of Bob's account record in the `old_acc_info` variable, and then uses this value to check that the record has not changed when we eventually update. You can also save all fields individually, and then check them all in the `UPDATE` query; or, if you have an automatic `last_change` field, then you can use it. Alternatively, if you actually care about only a few fields changing, such as `balance`, and can ignore others, such as `email`, then you only need to check the relevant fields in the `UPDATE` statement. # There's more... You can also use the serializable transaction isolation level when you need to be absolutely sure that the data you are looking at is not affected by other user changes. The default transaction isolation level in PostgreSQL is read committed, but you can choose from two more levels, repeatable read and serializable, if you require stricter control over visibility of data within a transaction; see http://www.postgresql.org/docs/current/static/transaction-iso.html. Another design pattern available in some cases is to use a single statement for the `UPDATE` and return data to the user via the `RETURNING` clause; for example: **UPDATE accounts** **SET balance = balance - i_amount** **WHERE username = i_username** **AND balance - i_amount > - max_credit** **RETURNING balance;** In some cases, moving the entire computation to the database function is a very good idea. If you can pass all of the necessary information to the database for processing as a database function, it will run even faster, as you save several round-trips to the database. If you use a PL/pgSQL function, you also benefit from automatically saving query plans on the first call in a session and using saved plans in subsequent calls. Therefore, the preceding transaction is replaced by a function in the database like the following: **CREATE OR REPLACE FUNCTION consume_balance** **( i_username text** **, i_amount numeric(10,2)** **, max_credit numeric(10,2)** **, OUT success boolean** **, OUT remaining_balance numeric(10,2)** **) AS** **$$** **BEGIN** ** UPDATE accounts SET balance = balance - i_amount** ** WHERE username = i_username** ** AND balance - i_amount > - max_credit** ** RETURNING balance** ** INTO remaining_balance;** ** IF NOT FOUND THEN** ** success := FALSE;** ** SELECT balance** ** FROM accounts** ** WHERE username = i_username** ** INTO remaining_balance;** ** ELSE** ** success := TRUE;** ** END IF;** **END;** **$$ LANGUAGE plpgsql;** You can call it by simply running this line from your client: **SELECT * FROM consume_balance ('bob', 7, 0);** The output will return the success variable. It tells you whether there was a sufficient balance in Bob's account. The output will also return a number telling the balance `bob` has left after this operation. # Reporting performance problems Sometimes you face performance issues and feel lost, but you should never feel alone when working with one of the most successful open source projects ever. # How to do it... If you need to get some advice on your performance problems, then the right place to do so is the performance mailing list at http://archives.postgresql.org/pgsql-performance/. You may want to first ensure that it is not a well-known problem by searching the mailing list archives. A very good description of what to include in your performance problem report is available at http://wiki.postgresql.org/wiki/Guide_to_reporting_problems. # There's more... More performance-related information can be found at http://wiki.postgresql.org/wiki/Performance_Optimization. # Backup and Recovery In this chapter, we will cover the following recipes: * Understanding and controlling crash recovery * Planning backups * Hot logical backup of one database * Hot logical backup of all databases * Backup of database object definitions * Standalone hot physical database backup * Hot physical backup and continuous archiving * Recovery of all databases * Recovery to a point in time * Recovery of a dropped/damaged table * Recovery of a dropped/damaged database * Improving performance of backup/recovery * Incremental/differential backup and restore * Hot physical backups with Barman * Recovery with Barman # Introduction Most people admit that backups are essential, though they also devote a very small amount of time to thinking about the topic. The first recipe is about understanding and controlling crash recovery. You need to understand what happens if the database server crashes so that you can understand when you might need to perform a recovery operation. The next recipe is all about planning. That's really the best place to start before you perform backups. The physical backup mechanisms here were initially written by Simon Riggs (one of the authors of this book) for PostgreSQL 8.0 in 2004, and have been supported by him ever since, now with increasing help from the community as its popularity grows. 2ndQuadrant has also been providing database recovery services since 2004, and regrettably, many people have needed them as a result of missing or damaged backups. It is important to note that, in the last few years, the native streaming replication protocol has become more and more relevant in PostgreSQL. It can be used for backup purposes too; not only to take a base backup with `pg_basebackup`, but also to stream WAL files using `pg_receivewal`. As authors, we had a dilemma when planning this book. Should we introduce streaming replication before backups or leave it to the replication section? For now we decided to leave it out of this chapter and postpone it until the next. We would like your feedback on this subject for future editions of the book. As a final note, all of the examples regarding physical backup and recovery in this chapter are thoroughly explained so that you understand what is happening behind the scenes. However, unless you have a specific task that you have to do, we highly recommend that, when in production, you use Barman (our open source backup and recovery tool), or a similar product that is specialized in this area. The last two recipes in this chapter will introduce Barman. # Understanding and controlling crash recovery Crash recovery is the PostgreSQL subsystem that saves us, should the server crash or fail as part of a system crash. It's good to understand a little about it and to do what we can to control it in our favor. # How to do it... If PostgreSQL crashes, there will be a message in the server log with the severity level set to `PANIC`. PostgreSQL will immediately restart and attempt to recover using the transaction log or **Write-Ahead Log** ( **WAL** ). The WAL consists of a series of files written to the `pg_wal` subdirectory of the PostgreSQL `data` directory. Each change made to the database is recorded first in WAL, hence the name _write-ahead_ log, as a synonym of _transaction log_. When a transaction commits, the default (and safe) behavior is to force the WAL records to disk. Should PostgreSQL crash, the WAL will be replayed, which returns the database to the point of the last committed transaction, and thus ensures the durability of any database changes. Database changes themselves aren't written to disk at transaction commit. Those changes are written to disk some time later by the background writer on a well-tuned server. Crash recovery replays the WAL, but from what point does it start to recover? Recovery starts from points in the WAL known as **checkpoints**. The duration of a crash recovery depends on the number of changes in the transaction log since the last checkpoint. A checkpoint is a known safe starting point for recovery, since it guarantees that all the previous changes to the database have already been written to disk. A checkpoint can become a performance bottleneck on busy database servers because of the number of writes required. We will see a number of ways to fine-tune that, but you must also understand the effect that those tuning options may have on crash recovery. A checkpoint can be either immediate or scheduled. Immediate checkpoints are triggered by some action of a superuser, such as the `CHECKPOINT` command. Scheduled checkpoints are decided automatically by PostgreSQL. Two parameters control the occurrence of scheduled checkpoints. The first is `checkpoint_timeout`, which is the number of seconds until the next checkpoint. While this parameter is time-based, the second parameter, `max_wal_size`, influences the amount of WAL data that will be written before a checkpoint is triggered; the actual limit is computed from that parameter, taking into account the fact that WAL files can be deleted after two checkpoints. A checkpoint is called whenever either of these two limits is reached. It's tempting to banish checkpoints as much as possible by setting the following parameters: **max_wal_size = 20GB** **checkpoint_timeout = 3600** However, if you do this, you should give some thought to how long crash recovery will take if you do, and whether you want that; you must consider as well how many changes will accumulate before the next checkpoint—and more importantly how much I/O those changes will generate. Also, you should make sure that the `pg_wal` directory is mounted on disks with enough disk space. By default, `max_wal_size` is set to 1 GB. The amount of disk space required by `pg_wal` might also be influenced by: * Unexpected spikes in workload * Failures in continuous archiving (see `archive_command` in the _Hot physical backup and continuous archiving_ section) * The `wal_keep_segments` setting (you will need _16 MB x wal_keep_segments of space_ ) In contrast with `max_wal_size`, with `min_wal_size` you can control the minimum size allotted to WAL storage, and allow PostgreSQL to recycle existing WAL files instead of removing them. # How it works... Recovery continues until the end of the transaction log. WAL data is being written continually, so there is no defined end point; it is literally the last correct record. Each WAL record is individually CRC-checked so that we know whether a record is complete and valid before trying to process it. Each record contains a pointer to the previous record, so we can tell that the record forms a valid link in the chain of actions recorded in the WAL. As a result of that, recovery always ends with some kind of error in reading the next WAL record. That is normal and means _the next record does not exist (yet)_. Recovery performance can be very fast, though its speed does depend on the actions being recovered. The best way to test recovery performance is to set up a standby replication server, described in Chapter 12, _Replication and Upgrades_ , because it is actually implemented as a variant of crash recovery. # There's more... It's possible for a problem to be caused by replaying the transaction log, so that the database server will fail to start. Some people's response to this is to use a utility named `pg_resetwal`, which removes the current transaction log files and tidies up after that operation has taken place. The `pg_resetwal` utility destroys data changes, and that means data loss. If you do decide to run that utility, make sure you take a backup of the `pg_wal` directory first. Our advice is to seek immediate assistance rather than do this. You don't know for certain that doing this will fix a problem, though once you've done it, you will have difficulty going back. # Planning backups This recipe is all about thinking ahead and planning. If you're reading this recipe before you take a backup, well done! The key thing to understand is that you should plan your recovery, not your backup. The type of backup you take influences the type of recovery that is possible, so you must give some thought to what you are trying to achieve beforehand. If you want to plan your recovery, then you need to consider the different types of failure that can occur. What type of recovery do you wish to perform? You need to consider the following main aspects: * Full or partial database? * Everything or just object definitions? * **Point-in-time recovery** ( **PITR** ) * Restore performance We need to look at the characteristics of the utilities to understand what our backup and recovery options are. It's often beneficial to have multiple types of backup to cover the different types of failure possible. Your main backup options are the following: * Logical backup, using `pg_dump` * Physical backup, which is a filesystem backup The `pg_dump` utility comes in two main flavors—`pg_dump` and `pg_dumpall`. The `pg_dump` utility has a `-F` option for producing backups in various file formats. The file format is very important when it comes to restoring from backup, so you need to pay close attention to it. As far as physical backup is concerned, in this chapter we focus on file system backup using `pg_start_backup()` and `pg_stop_backup()`. However, it is important to note that PostgreSQL has its own built-in application for physical base backups, `pg_basebackup`, which relies on the native streaming replication protocol. As authors, in order to distribute the content more evenly, we have decided to cover `pg_basebackup` and streaming replication in the next chapter, that is, Chapter 12, _Replication and Upgrades_. # How to do it... The following table shows the features available, depending on the backup technique selected. The details of these techniques are covered in the remaining recipes in this chapter: | SQL dump to an archive file: `pg_dump -F c` | SQL dump to a script file: `pg_dump -F p` or `pg_dumpall` | Filesystem backup using: `pg_start_backup` ---|---|---|--- Backup type | Logical | Logical | Physical Recover to point in time | No | No | Yes Zero data loss | No | No | Yes (see note 6) Back up all databases | One at a time | Yes (`pg_dumpall`) | Yes All databases backed up at the same time | No | No | Yes Selective backup | Yes | Yes | No (see note 2) Incremental backup | No | No | Possible (see note 3) Selective restore | Yes | Possible (see note 1) | No (see note 4) `DROP TABLE` recovery | Yes | Yes | Possible (see note 4) Compressed backup files | Yes | Yes | Yes Backup in multiple files | No | No | Yes | **SQL dump to an archive file** : `pg_dump -F c` | **SQL dump to a script file** : `pg_dump -F p` or `pg_dumpall` | **Filesystem backup using** : `pg_start_backup` Parallel backup possible | No | No | Yes Parallel restore possible | Yes | No | Yes Restore to later release | Yes | Yes | No Standalone backup | Yes | Yes | Yes (see note 6) Allows DDL during backup | No | No | Yes The following notes were referenced in the preceding table: 1. If you've generated a script with `pg_dump` or `pg_dumpall` and need to restore just a single object, then you will need to go deeper. You will need to write a Perl script (or similar) to read the file and extract the parts you want. This is messy and time-consuming, but probably faster than restoring the whole thing to a second server and then extracting just the parts you need with another `pg_dump`. 2. Selective backup with a physical backup is possible, but will cause problems later when you try to restore. 3. See the _Incremental/differential backup and restore_ recipe. 4. Selective restore with a physical backup isn't possible with the currently supplied utilities. See the _Recovery of a dropped/damaged table_ recipe for partial recovery. 5. See the _Standalone hot physical database backup_ recipe. 6. See the _Hot physical backups with Barman_ recipe. Barman 2 fully supports synchronous WAL streaming, allowing you to achieve **recovery point objective** ( **RPO** ) equal to 0, meaning __zero__ _data loss_. # Hot logical backups of one database Logical backup makes a copy of the data in the database by dumping the content of each table as well as object definitions for that same database (such as schemas, tables, indexes, views, privileges, triggers, constraints, and so on). # How to do it... The command to do this is simple. The following is an example using a database called `pgbench`: **pg_dump -F c pgbench > dumpfile** Or, you can use the following command: **pg_dump -F c -f dumpfile pgbench** You can also do this through pgAdmin 4, as shown in the following screenshot: # How it works... The `pg_dump` utility produces a single output file. This output file can use the `split` command to separate the file into multiple pieces, if required. The `pg_dump` archive file, also known as the **custom format** , is lightly compressed by default. Compression can be removed or made more aggressive. Even though, by default, `pg_dump` writes an SQL script directly to standard output, it is recommended to use the archive file instead, by enabling the custom format through the `"-F c"` option. As covered later in the chapter, backing up in the form of archive files gives you more flexibility and versatility when restoring. Archive files must be used with a tool called `pg_restore`. The `pg_dump` utility runs by executing SQL statements against the database to unload data. When PostgreSQL runs an SQL statement, we take a _snapshot_ of transactions that are currently running, which freezes our viewpoint of the database. The `pg_dump` utility can take a parallel dump of a single database using the **snapshot export** feature. We can't (yet) share that snapshot across sessions connected to more than one database, so we cannot run an exactly consistent `pg_dump` in parallel across multiple databases. The time of the snapshot is the only moment we can recover to—we can't recover to a time either before or after. Note that the snapshot time is the start of the backup, not the end. When `pg_dump` runs, it holds the very lowest kind of lock on the tables being dumped. Those are designed to prevent DDL from running against the tables while the dump takes place. If a dump is run at the point at which other DDLs are already running, then the dump will sit and wait. If you want to limit the waiting time, you can do so by setting the `--lock-wait-timeout` option. Since `pg_dump` runs SQL queries to extract data, it will have some performance impact. This must be taken into account when executing on a live server. The `pg_dump` utility allows you to take a selective backup of tables. The `-t` option also allows you to specify views and sequences. There's no way to dump other object types individually using `pg_dump`. You can use some supplied functions to extract individual snippets of information from the catalog. More details on these functions are available at https://www.postgresql.org/docs/current/static/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE The `pg_dump` utility works against earlier releases of PostgreSQL, so it can be used to migrate data between releases. When migrating your database from an earlier version, it is generally recommended to use `pg_dump` of the same version of the target PostgreSQL. For example, if you are migrating a PostgreSQL 9.3 database to PostgreSQL 10, you should use `pg_dump` v10 to remotely connect to the 9.3 server and back up the database. As far as extensions are concerned, `pg_dump` is aware of any objects (namely tables and functions) that have been installed as part of an additional package, such as PostGIS or Slony. Thanks to that, they can be recreated by issuing appropriate `CREATE EXTENSION` commands instead of dumping and restoring them together with the other database objects. Extension support removes such difficulties when restoring from a logical backup, maintaining the list of additional tables that have been created as part of the software installation process. Look at the _Managing installed extensions_ recipe in Chapter 3, _Configuration,_ for more details. # There's more... What time was the `pg_dump` taken? The snapshot for a `pg_dump` is taken at the beginning of a backup. The file modification time will tell you when the dump finished. The dump is consistent at the time of the snapshot, so you may need to know that time. If you are making a script dump, you can do a verbose dump, as follows: **pg_dump -v** This then adds the time to the top of the script. Custom dumps store the start time as well, and that can be accessed using the following: **pg_restore --schema-only -v dumpfile 2 >/dev/null | head | grep Started ** **-- Started on 2017-06-03 09:05:46 BST** # See also Note that `pg_dump` does not dump roles (such as users and groups) and tablespaces. Those two are only dumped by `pg_dumpall`; see the following recipes for more detailed descriptions. # Hot logical backups of all databases If you have more than one database in your PostgreSQL server, you may want to take a logical backup of all the databases at the same time. # How to do it... Our recommendation is that you do exactly what you did for one database to each database in your cluster. You can run individual dumps in parallel if you want to speed things up. Once this is complete, dump the global information also using the following: **pg_dumpall -g** # How it works... To back up all databases, you may be told you need to use the `pg_dumpall` utility. The following are four good reasons why you shouldn't do that: * If you use `pg_dumpall` the only output produced will be in a script file. Script files can't benefit from all the features of archive files, such as parallel and selective restore of `pg_restore`. By making your backup in this way, you will immediately deprive yourself of flexibility and versatility at restore time. * The `pg_dumpall` utility produces dumps of each database one after another. This means that `pg_dumpall` is slower than running multiple `pg_dump` tasks in parallel, one against each database. * The dumps of individual databases are not consistent to a particular point in time. As we pointed out in a previous recipe, if you start the dump at 04:00 and it ends at 07:00, then you cannot be sure exactly what time the dump relates to; it could be anytime between 04:00 and 07:00. * Options for `pg_dumpall` and `pg_dump` are similar in many ways. `pg_dump` has more options and therefore gives you more flexibility. # See also If you are taking a logical backup of all your databases for disaster recovery purposes, you should look at _hot physical backup_ options instead. # Backups of database object definitions Sometimes, it's useful to get a dump of the object definitions that make up a database. This is useful for comparing what's in the database against the definitions in a data-or object-modeling tool. It's also useful to make sure you can recreate objects in the correct schema, tablespace, and database with the correct ownership and permissions. # How to do it... The basic command to dump the definitions only for every database of your PostgreSQL instance is the following: **pg_dumpall --schema-only > myscriptdump.sql** This includes all objects, including roles, tablespaces, databases, schemas, tables, indexes, triggers, constraints, views, functions, ownerships, and privileges. If you want to dump PostgreSQL role definitions, use this command: **pg_dumpall --roles-only > myroles.sql** If you want to dump PostgreSQL tablespace definitions, use the following: **pg_dumpall --tablespaces-only > mytablespaces.sql** If you want to dump both roles and tablespaces, use this command: **pg_dumpall --globals-only > myglobals.sql** The output is a human-readable script file that can be re-executed to recreate each of the databases. The short form for the `--globals-only` option is `-g`, which we have already seen in a previous recipe, _Hot logical backups of all databases_. Similar abbreviations exist for `--schema-only` (`-s`), `--tablespaces-only` (`-t`), and `--roles-only` (`-r`). # There's more... In PostgreSQL, the word _schema_ is also used to organize a set of related objects of a database in a logical container, similar to a directory. It is also known as a _namespace_. Be careful that you don't confuse what is happening here. The `--schema-only` option makes a backup of the _database schema_ , that is, the definitions of all objects in the database (and in all namespaces). To make a backup of the data and definitions in just one namespace and one database, use `pg_dump` with the `-n` option. To make a backup of only the definitions, in just one namespace and one database, use `pg_dump` with both `-n` and `--schema-only` together. You can also take advantage of a previously generated archive file (see _Hot logical backups of one database_ ) and generate a script file using `pg_restore`, as follows: **pg_restore --schema-only mydumpfile > myscriptdump.sql** # Standalone hot physical database backup Hot physical backup is an important capability for databases. Physical backup allows us to get a completely consistent view of the changes to all databases at once. Physical backup also allows us to back up even while DDL changes are being executed on the database. Apart from resource constraints, there is no additional overhead or locking with this approach. Physical backup procedures used to be slightly more complex than logical backup procedures, but in version 10 some defaults have been changed, making them easier; after these changes, making a backup with `pg_basebackup` has become very easy, even with default settings. As specified in the introduction to this chapter, taking a backup with `pg_basebackup` is covered in Chapter 12, _Replication and Upgrades_ , and in this chapter we will focus on the variant of the filesystem backup that uses `pg_start_backup()` and `pg_stop_backup()`, which is the only way to overcome some of the limitations of `pg_basebackup`, for instance if you want an incremental backup, or a parallel backup. For similar reasons, this method is also supported by many advanced backup solutions, such as Barman. So, let's start with a simple procedure to produce a standalone backup. # Getting ready The following steps assume that a number of environment variables have been set, which are as follows: * `$PGDATA` is the path to the PostgreSQL data directory, ending with `/` * All required PostgreSQL connection parameters have been set These assumptions are not strictly required, but they make the whole procedure simpler and more readable, because we can avoid adding lots of command line options to specify the data directory or any connection detail every time we connect to the database. The initial procedure is step 1 onwards. If you are running subsequent backups, start from step _3_. # How to do it... The steps are as follows: 1. Create a new backup directory as a sibling of `$PGDATA`, if it is not already present, as follows: **cd $PGDATA** **mkdir ../standalone** 2. Create the `archive` directory as follows: **mkdir ../standalone/archive** 3. **** Start archiving with the following command: **pg_receivewal -D ../standalone/archive/** This command will not return, because `pg_receivewal` will run until interrupted. So you must open a new terminal session to perform the next steps, starting with step _4_. We describe first how to configure streaming archiving (steps _2_ and _3_ ); for file-based archiving follow the alternate steps _2a_ and _3a_ instead. * * 2a: Set an `archive_command`. In `postgresql.conf` you will need to add the following lines and restart the server, or just confirm that they are present: **archive_mode = on** **archive_command = 'test ! -f ../standalone/archiving_active ||** **cp -i %p ../standalone/archive/%f'** The last setting is only split into two lines for typesetting reasons; in `postgresql.conf`, you must keep it in a single line. You must also check that `wal_level` is set to either `replica` or `logical`, which is normally true as `replica` is the default setting. * * 3a: Start archiving, as follows: **cd $PGDATA ** **mkdir ../standalone/archive ** **touch ../standalone/archiving_active** Irrespective of whether you have chosen streaming archiving, or file-based archiving, you can now proceed with step _4_ : 4. Define the name of the backup file. The following example includes time information in the file name: **BACKUP_FILENAME=$(date '+%Y%m%d%H%M').tar** 5. Start the backup, as follows: **psql -c "select pg_start_backup('standalone')" ** This step could take a while, because PostgreSQL performs a checkpoint before returning, to ensure that the data files copied in the next step include all the latest data changes. See the recipe _Understanding and controlling crash recovery_ earlier in this chapter for more details about checkpoints. 6. Take a base backup-copy the data files (excluding the content of the `pg_wal` directory), using this command: **tar -cv --exclude="pg_wal/*" \ ** **-f ../standalone/$BACKUP_FILENAME *** 7. Stop the backup, as follows: **psql -c "select pg_stop_backup(), current_timestamp"** 8. If you have followed preceding steps _2_ and _3_ (for example, if you are using streaming archiving), stop archiving by hitting _CTRL_ \+ _C_ in the terminal session where `pg_receivewal` is running: * 8a: Alternatively, if you have chosen steps _2a_ and _3a_ above instead (for example, file-based archiving), enter the `standalone` directory and stop archiving, as follows: **rm ../standalone/archiving_active** 9. Add the archived files to the standalone backup, as follows: **cd ../standalone tar -rf $BACKUP_FILENAME archive** 10. Write a `recovery.conf` file with which to recover: **echo "restore_command = 'cp archive/%f %p'" > recovery.conf ** **echo "recovery_end_command = 'rm -R archive' " >> recovery.conf** 11. Add the `recovery.conf` to the `tar` archive, as follows: **tar -rf $BACKUP_FILENAME recovery.conf** 12. Clean up: **rm -rf archive recovery.conf** 13. Store `$BACKUP_FILENAME` somewhere safe. A safe place is definitely not on the same server. This procedure ends with a file named `$BACKUP_FILENAME` in the standalone directory. It is imperative to remember to copy it somewhere safe. This file contains everything that you need to recover, including a recovery parameter file. # How it works... The backup produced by the preceding procedure only allows you to restore to a single point in time. That point is the time of the `pg_stop_backup()` function. A physical backup takes a copy of all files in the database (step _6—_ the _base backup_ ). That alone is not sufficient as a backup and you need the other steps as well. A simple copy of the database produces a time-inconsistent copy of the database files. To make the backup time consistent, we need to add all the changes that took place from the start to the end of the backup. That's why we have steps _5_ and _7_ to bracket our backup step. In technical terms, steps _5_ and _7_ take advantage of the API that controls exclusive backups, meaning that there can only be one physical backup at a time and it has to be performed on a master server. PostgreSQL supports non-exclusive backups as well, allowing users to perform `pg_start_backup()` and `pg_stop_backup()` functions on a read-only standby server. To make a backup non-exclusive, just add the parameter `exclusive := false` to those functions. However, programming backup scripts for the non-exclusive backup method is more complex and it is not covered in this recipe. The changes made are put in the standalone/archive directory as a set of archived transaction log or WAL files. Steps _2_ and _3_ start streaming archiving, while the alternate steps, _2a_ and _3a_ , set the parameters that copy the files to the archive and start file-based archiving. Note that changing `archive_mode` requires us to restart the database server, so we use a well-known trick to avoid restarting while switching archiving on and off—`archive_command` is conditional upon the existence of a file named `archiving_active`, whose presence enables or disables the archiving process. Note that these are just two of the possible ways to configure archiving, so PostgreSQL doesn't always need to work this way. Steps _3_ and _8_ enable and disable archiving respectively, so we only store copies of the WAL files created during the period of the backup. Thus, steps _1_ and _2_ are setup and steps _3_ to _9_ are where the backup happens. Step _10_ onwards is gift wrapping, so that the backup script ends with everything in one neat file and proper cleanup operations take place. Step _9_ appends the WAL files to the backup file so that it is just one file. Steps _10_ and _11_ add a `recovery.conf` file with its parameters set up so that there are no manual steps when we recover from this backup. This is explained in detail in the _Recovery of all databases_ recipe. In case your `PGDATA` does not contain configuration files, such as `postgresql.conf` and `pg_hba.conf`, you might have to manually copy them before performing a recovery. Remember that standard Debian and Ubuntu installations keep configuration files outside `PGDATA`, specifically under `/etc/postgresql`. The important thing to understand in this recipe is that we need both the base backup and the appropriate archived WAL files to allow us to recover. Without both of these, we have nothing. Most of the steps are designed to ensure that we really will have the appropriate WAL files in all cases. # There's more... One advantage of file-based WAL archiving is that it works in a _push_ mode, without requiring inbound access to the database server. On the other hand, streaming WAL archiving has the advantage of transferring WAL as soon as it is produced, without waiting that the 16 MB WAL segment is completed, which usually results in little or no data loss even in the event of a disaster. Summing up, neither choice is superior to the other one, so we opted for documenting both. PostgreSQL ships a command-line utility called `pg_basebackup`, which uses the streaming replication infrastructure to carry out steps _4_ to _6_ , as reported previously. As an alternative, it is simpler than using `rsync` and issuing `pg_start_backup()` and `pg_stop_backup()` manually, but it's not a complete replacement because it has some limitations and restrictions. If you want to make your life easier, you can rely on software that is specialized in backup and recovery. In this book we will cover a software that we at 2ndQuadrant have written and that has become very popular among PostgreSQL users: Barman. This open source tool is covered in two recipes— _Hot physical backups with Barman_ and _Recovery with Barman_. # See also It's common to use continuous archiving when using the physical backup technique because this allows you to recover to any point in time, should you need that. # Hot physical backup and continuous archiving This recipe describes how to set up a hot physical backup with a continuous archiving mechanism. The purpose of continuous archiving is to allow us to recover to any point in time after the completion of the backup. Manually performing each step of this procedure is a great way to gain a clear understanding of PostgreSQL's backup and restore infrastructure. However, to reduce the chances of human errors, it is best practice to avoid reliance on complex activities that must be performed by a human operator. Procedures such as taking a hot physical backup or restoring it up to a given point in time can be performed using specialized third-party tools such as: * **Barman** : <http://www.pgbarman.org/> * **OmniPITR** : <https://github.com/omniti-labs/omnipitr> * **PgBackRest** : <http://www.pgbackrest.org/> * **PgHoard** : <https://github.com/ohmu/pghoard> * **WAL-E** : <https://github.com/wal-e/wal-e> Being the creators and developers of Barman, our preference goes with this tool. However, we strongly advise that you to look at each of the aforementioned tools and make your own decision based on your needs. If you are interested in Barman, you can read two recipes later in this chapter— _Hot physical backups with Barman,_ and _Recovery with Barman_. # Getting ready This recipe builds upon the previous recipe, _Standalone hot physical database backup_. You should read that before following this recipe. Before starting, you need to decide a few things: * Where will you store the WAL files (known as the archive)? * How will you send WAL files to the archive? * Where will you store your base backups? * How will you take base backups? * How many backups (also known as retention policies) will you keep? * What is your policy for maintaining the archive? These are hard questions to answer immediately. So, we will give a practical example as a way of explaining how this works, and then let you decide how you would like it to operate. # How to do it... The rest of this recipe assumes the following answers to the key questions: * The archive is a directory, such as `/backups/archive`, on a remote server for disaster recovery named `$DRNODE` * We send WAL files to the archive using `rsync`; however, WAL streaming can also be used, by changing the recipe in a way similar to the previous one * Base backups are also stored on `$DRNODE`, in the `/backups/base` directory * Base backups are made using `rsync` The following steps assume that a number of environment variables have been set, which are as follows: * `$PGDATA` is the path to the PostgreSQL data directory, ending with `/` * `$DRNODE` is the name of the remote server * `$BACKUP_NAME` is an identifier for the backup * All the required PostgreSQL connection parameters have been set We also assume that the Postgres user can connect via SSH to the backup server from the server where PostgreSQL is running, without having to type a passphrase. This standard procedure is described in detail in several places, including Barman's documentation at <http://docs.pgbarman.org/>. The procedure is as follows: 1. Create the archive and backup directories on a backup server. 2. Set an `archive_command`. In `postgresql.conf`, you will need to add the following lines and restart the server, or just confirm that they are present: **archive_mode = on archive_command = 'rsync -a %p $DRNODE:/archive/%f'** 3. Define the name of the backup, like this example: **BACKUP_NAME=$(date '+%Y%m%d%H%M')** 4. Start the backup, as follows: **psql -c "select pg_start_backup('$BACKUP_NAME')"** 5. Copy the data files (excluding the content of the `pg_wal` directory), like this: **rsync -cva --inplace -exclude='pg_wal/*' \ ** **${PGDATA}/ $DRNODE:/backups/base/$BACKUP_NAME/** 6. Stop the backup, as follows: **psql -c "select pg_stop_backup(), current_timestamp"** It's also good practice to put a `README.backup` file in the data directory prior to the backup so that it forms part of the set of files that make up the base backup. This should say something intelligent about the location of the archive, including any identification numbers, names, and so on. Notice that we didn't put a `recovery.conf` in the backup this time. That's because we're assuming we want flexibility at the time of recovery, rather than a gift-wrapped solution. The reason for that is that we don't know when, where, or how we will be recovering, nor do we need to make that decision yet. # How it works... The key point here is that we must have both the base backup and the archive in order to recover. Where you put them is entirely up to you. You can use any filesystem backup technology and/or filesystem backup management system to do this. Many backup management systems have claimed that they have a PostgreSQL interface or plugin, but most of the time they only support logical backups. However, there's no need for them to officially support PostgreSQL; there is no any _Runs on PostgreSQL_ badge or certification required. If you can copy files, then you can run the preceding processes to keep your database safe. In the event the network or backup server goes down, then the command will begin to fail. When the `archive_command` fails, it will repeatedly retry until it succeeds. You can monitor the status of the `archive_command` and get current statistics through the `pg_stat_archiver` view in the catalog. PostgreSQL does not remove WAL files from `pg_wal` directory until they have been successfully archived, so the end result is that your `pg_wal` directory fills up. It's a good idea to have an `archive_command` that reacts better to that condition, though this is left as an improvement for the sysadmin. A typical action is to make it an emergency call-out so that we can resolve the problem manually. Automatic resolution is difficult to get right, as this condition is one for which it is hard to test. While continuously archiving, we will generate a considerable number of WAL files. If `archive_timeout` is set to 30 seconds, we will generate a minimum of _2*60*24 = 2,880_ files per day, with each being 16 MB in size. This amounts to a total volume of 46 GB per day (minimum). With a reasonable transaction rate, a database server might generate 100 GB of archive data per day. Use this as a rough figure for calculations until you get actual measurements. Of course, the rate could be much higher, with rates of 1 TB per day or higher being possible. Clearly, we would only want to store WAL files that are useful for backup, so when we decide that we no longer wish to keep a backup, we will also want to remove files from the archive. In each base backup, you will find a file called `backup_label`. The earliest WAL file required by a physical backup is the filename mentioned in the first line of the `backup_label` file. We can use a `contrib` module called `pg_archive_cleanup` to remove any WAL files created earlier than the earliest file. # Recovery of all databases Recovery of a complete database server, including all of its databases, is an important feature. This recipe covers how to execute a recovery in the simplest way possible. Some complexities are discussed here, though most are covered in later recipes. # Getting ready Find a suitable server on which to perform the restore. Before you recover onto a live server, always take another backup. Whatever problem you thought you had could get worse if you aren't prepared. # How to do it... Here, we'll provide four distinct examples, depending on what type of backup was taken. # Logical – from custom dump taken with pg_dump -F c The procedure is as follows: 1. Restore of all databases means simply restoring each individual database from each dump you took. Confirm that you have the correct backup before you restore: **pg_restore --schema-only -v dumpfile | head | grep Started** 2. Reload global objects from the script file, as follows: **psql -f myglobals.sql** 3. Reload all databases. Create the databases using parallel tasks to speed things up. This can be executed remotely without the need to transfer a `dumpfile` between systems. Note that there is a separate `dumpfile` for each database: **pg_restore -C -d postgres -j 4 dumpfile** # Logical – from the script dump created by pg_dump -F p As in the previous method, this can be executed remotely without needing to transfer the dumpfile between systems: 1. Confirm that you have the correct backup before you restore. If the following command returns nothing, then it means the file is not timestamped, and you'll have to identify it in a different way: **head myscriptdump.sql | grep Started** 2. Reload globals from the script file, as follows: **psql -f myglobals.sql** 3. Reload all scripts as follows: **psql -f myscriptdump.sql** # Logical – from the script dump created by pg_dumpall In order to recover a full backup generated by `pg_dumpall`, you need to execute the following steps on a PostgreSQL server that has just been initialized: 1. Confirm that you have the correct backup before you restore. If the following command returns nothing, then it means the file is not timestamped, and you'll have to identify it in a different way: **head myscriptdump.sql | grep Started** 2. Reload the script in full: **psql -f myscriptdump.sql** # Physical The steps are as follows: 1. If you've used the Standalone hot physical database backup recipe, then recovery is very easy. Restore the backup file in the target server. 2. Extract the backup file to the new data directory. 3. Confirm that you have the correct backup before you restore: **$ cat backup_label ** **START WAL LOCATION: 0/12000020 (file 000000010000000000000012) ** **CHECKPOINT LOCATION: 0/12000058 ** **START TIME: 2017-06-03 19:53:23 BST ** **LABEL: standalone** 4. Verify that all file permissions and ownerships are correct and links are valid. This should already be the case if you are using the Postgres user ID everywhere, which is recommended. 5. Start the server. This procedure is so simple because in the _Standalone hot physical database backup_ recipe we gift-wrapped everything for you. That also helped you understand that you need both a base backup and the appropriate WAL files. If you've used other techniques, then you need to step through the tasks to make sure you cover everything required, as follows: 1. Shut down any server running in the data directory. 2. Restore the backup so that any files in the data directory that have matching names are replaced with the version from the backup. (The manual says, _delete all files and then restore the backup_. You could speed up the recovery operation reusing the existing data directory, but unless you are familiar with `rsync` we recommend going by the book. You can look at the source code of Barman for an example, or otherwise simply use it.) Remember that this step can be performed in parallel to speed things up, though it is up to you to script that. 3. Ensure that all file permissions and ownerships are correct and links are valid. This should already be the case if you are using the Postgres user ID everywhere, which is recommended. 4. Remove any files that are in `pg_wal/`. If you've been following our recipes, you'll be able to skip this step because they were never backed up in the first place. 5. Add a `recovery.conf` file and set its file permissions correctly. 6. Start the server. The only part that requires some thought and checking is selecting which parameters to use for the `recovery.conf` file. There's only one that matters here, and that is the `restore_command`. The `restore_command` tells us how to restore archived WAL files. It needs to be the command that will be executed to bring back WAL files from the archive. If you are thinking ahead, there'll be a `README.backup` file for you to read to find out how to set the `restore_command`. If it is not there, then presumably you've got the location of the WAL files you've been saving written down somewhere. Say, for example, that your files are being saved to a directory named `/backups/pg/servername/archive`, owned by the Postgres user. On a remote server named `backup1`, we would then write all this on one line of the `recovery.conf` file, as follows: **restore_command = 'scp backup1:/backups/pg/servername/archive/%f** **%p'** # How it works... PostgreSQL is designed to require very minimal information to perform a recovery. We'll try hard to wrap all the details up for you: * **Logical recovery** : Recreates database objects by executing SQL statements. If performance is an issue, look at the _Improving performance of backup/recovery_ recipe. * **Physical recovery** : Reapplies data changes at the block level, and so tends to be much faster than logical recovery. It requires both a base backup and a set of archived WAL files. There is a file named `backup_label` in the data directory of the base backup. If you want to know the start and stop WAL locations of the base backup, look for a `.backup` file in the archive. Recovery then starts to apply changes from the starting WAL location and it must proceed as far as the stop address for the backup to be valid. After the recovery is complete, the `recovery.conf` file is renamed to `recovery.done` to prevent the server from re-entering recovery. The server log records each WAL file restored from the archive, so you can check the progress and rate of recovery. You can query the archive to find the name of the latest restored WAL file to allow you to calculate how many files are left to recover. The `restore_command` should return 0 if a file has been restored and non-zero for cases of failure. Recovery will proceed until there are no more WAL files remaining, so eventually there will be an error recorded in the logs. If you have lost some of the WAL files, or they are damaged, then recovery will stop at that point. No further changes after that will be applied, and you will likely lose those changes. This would be the time to call your support vendor. # There's more... You can start and stop the server once recovery has started without any problems. It will not interfere with the recovery. You can connect to the database server while it is recovering and run queries, if that is useful. This is known as **hot standby** mode, and is discussed in Chapter 12, _Replication and Upgrades_. # See also * Once the recovery reaches the stop address, you can stop it at any point, as discussed in the _Recovery to a point in time_ recipe * The procedure described in this recipe is covered by the command-line utility, Barman, mentioned in the _Hot physical backup and continuous archiving_ recipe # Recovery to a point in time If your database suffers a problem at 3:22 p.m. and your backup was taken at 4:00 a.m. you're probably hoping there is a way to recover the changes made between those two times. What you need is known as **Point-in-Time Recovery** ( **PITR** ). Regrettably, if you've made a backup with the `pg_dump` utility at 4:00 a.m., then you won't be able to recover to any other time. As a result, the term PITR has become synonymous with the physical backup and restore technique in PostgreSQL. # Getting ready If you have a backup made with `pg_dump` utility, then give up all hope of using that as a starting point for a PITR. It's a frequently asked question, but the answer is still _no_. The reason it gets asked is exactly why we are pleading with you to plan your backups ahead of time. First, you need to decide from what point in time you would like to recover. If the answer is _as late as possible_ , then you don't need to do a PITR at all, just recover until the end of the logs. # How to do it... How do you decide to what point to recover? The point where we stop recovery is known as the recovery target. The most straightforward way is to do this based on a timestamp. In `recovery.conf` file, you can add (or uncomment) a line that says the following, or something similar: `recovery_target_time = '2017-06-01 16:59:14.27452+01'` Note that you need to be careful to specify the time zone of the target so that it matches the time zone of the server that wrote the log. That might differ from the time zone of the current server, so be sure to double-check them. After that, you can check the progress during a recovery by running queries in hot standby mode. By default, when hot standby is enabled, the recovered server is paused once the target is reached. You can change this behavior with the `recovery_target_action` option in `recovery.conf` file, as discussed in the _Delaying, pausing, and synchronizing replication_ recipe in Chapter 12, _Replication and Upgrades_. # How it works... Recovery works by applying individual WAL records. These correspond to individual block changes, so there are many WAL records for each transaction. The final part of any successful transaction is a commit WAL record, though there are abort records as well. Each transaction completion record has a timestamp that allows us to decide whether or not to stop at that point. You can also define a recovery target using a transaction ID (xid), though finding out which xid to use is somewhat difficult, and you may need to refer to external records, if they exist. Another practical way, which rarely applies after an unexpected disaster, is to define a recovery target with a label, formally known as a named restore point. A restore point is created with the `pg_create_restore_point()` function, requiring superuser privileges. For example: you have to perform a critical update of part of the data in your database. As a precaution, before you start the update, you can execute the following query as a superuser: **SELECT pg_create_restore_point('before_critical_update');** Then use the label `before_critical_update` in the `recovery_target_name` option. The recovery target is specified in the `recovery.conf` file and cannot change while the server is running. If you want to change the recovery target, you can shut down the server, edit `recovery.conf`, and then restart the server. Be careful, however; if you change the recovery target and recovery is already past the new point, it can lead to errors. If you define a `recovery_target_timestamp` that has already been passed, then the recovery will stop almost immediately, though this will be after the correct stopping point. If you define a `recovery_target_xid` or `recovery_target_name` that has already been passed, then the recovery will just continue until the end of the logs. Restarting a recovery from the beginning using a fresh restore of the base backup is always the safest option. Once a server completes the recovery, it will assign a new timeline. Once a server is fully available, we can write new changes to the database. Those changes might differ from the changes we made in a previous future history of the database. So, we differentiate between alternate futures using different timelines. If we need to go back and run the recovery again, we can create a new server history using the original or subsequent timelines. The best way to think about this is that it is exactly like a _Sci-fi_ novel—you can't change the past, but you can return to an earlier time and take a different action instead. However, you'll need to be careful not to get confused. # There's more... The `pg_dump` utility cannot be used as a base backup for a PITR. The reason is that a log replay contains the physical changes to data blocks, not the logical changes based on primary keys. If you reload the `pg_dump` utility, the data will likely go back into different data blocks, so the changes won't correctly reference the data. WAL files don't contain enough information to fully reconstruct all the SQL that produced those changes. Later feature additions to PostgreSQL may add the required information to WAL files. It will be very interesting and exciting to follow how logical replication evolves in the future. # See also PostgreSQL can pause, resume, and stop recovery while the server is up dynamically. This allows you to use the hot standby facility to locate the correct stopping point more easily. You can trick hot standby into stopping recovery, which may help. See the _Delaying, pausing, and synchronizing replication_ recipe in Chapter 12, _Replication and Upgrade_ s, on managing hot standby. This procedure is also covered by the command-line utility Barman, mentioned in the _Hot physical backup and continuous archiving_ recipe. You can use the `pg_waldump` utility to print the content of WAL files in a human-readable way. This can be very valuable to locate the exact transaction ID, or timestamp, or when a certain change was committed, for instance if we want to stop recovery exactly before that. `pg_waldump` is part of PostgreSQL and is described here: <https://www.postgresql.org/docs/10/static/pgwaldump.html> # Recovery of a dropped/damaged table You may drop or even damage a table in some way. Tables could be damaged for physical reasons, such as disk corruption, or they could also be damaged by running poorly specified `UPDATE` or `DELETE` commands, which update too many rows or overwrite critical data. Recovering from this backup situation is a common request. # How to do it... The methods differ, depending on the type of backup you have available. If you have multiple types of backup, you have a choice. # Logical - from custom dump taken with pg_dump -F c If you've taken a logical backup using the `pg_dump` utility in a custom file, then you can simply extract the table you want from the `dumpfile`, like the following: **pg_restore -t mydroppedtable dumpfile | psql** Alternatively, you can directly connect to the database using `-d`. The preceding command tries to recreate the table and then load data into it. Note that the `pg_restore -t` option does not dump any of the indexes on the selected table. This means we need a slightly more complex procedure than would first appear, and the procedure needs to vary depending on whether we are repairing a damaged table or putting back a dropped table. To repair a damaged table, we want to replace the data in the table in a single transaction. There isn't a specific option to do this, so we need to do the following: 1. Dump the data of the table (the `-a` option) to a script file, as follows: **pg_restore -a -t mydamagedtable dumpfile > mydamagedtable.sql** 2. Edit a script named `repair_mydamagedtable.sql` with the following code: **BEGIN;** **TRUNCATE mydamagedtable;** **\i mydamagedtable.sql** **COMMIT;** 3. Then, run it using the following command: **psql -f repair_mydamagedtable.sql** If you've dropped a table then you need to perform these steps: 1. Create a new database in which to work, and name it `restorework`, as follows: **CREATE DATABASE restorework;** 2. Restore the complete schema (`-s` option) to the new database, like this: **pg_restore -s -d restorework dumpfile** 3. Now, dump only the definitions of the dropped table in a new file. It will contain `CREATE TABLE`, indexes, and other constraints and grants. Note that this database has no data in it, so specifying `-s` is optional, as follows: **pg_dump -t mydroppedtable -s restorework > mydroppedtable.sql** 4. Now, recreate the table on the main database: **psql -f mydroppedtable.sql** 5. Now, reload only the data into the `maindb` database: **pg_restore -t mydroppedtable -a -d maindb dumpfile** If you've got a very large table, then the fourth step can be a problem because it builds indexes as well. If you want, you can manually edit the script in two pieces, one before the load ( _preload_ ) and one after the load ( _postload_ ). There are some ideas for that at the end of this recipe. # Logical – from the script dump Once you have located the PostgreSQL server on which you will prepare and verify the data to restore (the staging server), you can proceed like this: 1. Reload the script in full on the staging server, as follows: **psql -f myscriptdump.sql** 2. From the recovered database server, dump the table, its data, and all the definitions of the dropped table into a new file: **pg_dump -t mydroppedtable -F c mydatabase > dumpfile** 3. Now, recreate the table in the original server and database, using parallel tasks to speed things up: **pg_restore -d mydatabase -j 2 dumpfile** The last step can be executed remotely without having to transfer the `dumpfile` between systems. Just add connection parameters to `pg_restore`, as in the following example: `pg_restore -h remotehost -U remoteuser ...`. The only way to extract a single table from a script dump without doing all the preceding steps is to write a custom script to read and extract only those parts of the file that you want. This can be complicated because you may need certain SET commands at the top of the file, the table, and data in the middle of the file, and the indexes and constraints on the table are near the end of the file. Writing a custom script can be very complex. The safer route is to follow the recipe we just described. # Physical To recover a single table from a physical backup, you first need to recreate a PostgreSQL server from scratch, usually in a confined environment. Typically, this server is called the **recovery server** , if dedicated to recovery drills and procedures, or the **staging server** , if used for a broader set of cases including testing. Then you need to proceed as follows: 1. Recover the database server in full, as described in previous recipes on physical recovery, including all databases and all tables. You may wish to stop at a useful point in time, in which case you can look at the _Recovery to a point in time_ recipe later in the chapter. 2. From the recovered database server, dump the table, its data, and all the definitions of the dropped table into a new file, as follows: **pg_dump -t mydroppedtable -F c mydatabase > dumpfile** 3. Now, recreate the table in the original server and database using parallel tasks to speed things up. This can be executed remotely without needing to transfer the `dumpfile` between systems: **pg_restore -d mydatabase -j 2 dumpfile** # How it works... Restoring a single table from a logical backup is relatively easy, as each logical object is backed up separately from the others, and its data and metadata can be filtered out. However, a physical backup is composed by a set of binary data files, in a complex storage format that can be interpreted by a PostgreSQL engine. This means that the only way to extract individual objects from it, at present, is to restore the backup on a new instance, and then make a logical dump as explained in the previous recipe: there's no way to restore a single table from a physical backup in just a single step. # See also The `pg_dump` and `pg_restore` utilities are able to split the dump into three parts—pre-data, data, and post-data. Both commands support a section option used to specify which section(s) should be dumped or reloaded. # Recovery of a dropped/damaged database Recovering a complete database is also required sometimes. It's actually a lot easier than recovering a single table. Many users choose to place all their tables in a single database; in that case, this recipe isn't relevant. # How to do it... The methods differ, depending on the type of backup you have available. If you have multiple types of backup, you have a choice. # Logical – from the custom dump -F c Recreate the database in the original server using parallel tasks to speed things along. This can be executed remotely without needing to transfer the `dumpfile` between systems, as shown in the following example, where we use the `-j` option to specify four parallel processes: **pg_restore -h myhost -d postgres --create -j 4 dumpfile** # Logical – from the script dump created by pg_dump Recreate the database in the original server. This can be executed remotely without needing to transfer the dumpfile between systems, as shown here, where we must create the empty database first: **createdb -h myhost myfreshdb** **psql -h myhost -f myscriptdump.sql myfreshdb** # Logical – from the script dump created by pg_dumpall There's no easy way to extract the required tables from a script dump. You need to operate on a separate PostgreSQL server, for recovery or staging purposes, and then: 1. Reload the script in full, as follows: **psql -f myscriptdump.sql** 2. Once the restore is complete, you can dump the tables in the database by following the _Hot logical backups of one database_ recipe. 3. Now, recreate the database on the original server as described for logical dumps earlier in this recipe. # Physical To recover a single database from a physical backup, you need to work on a separate PostgreSQL server (for recovery or staging purposes) and then you must: 1. Recover the database server in full, as described in the previous recipes on physical recovery, including all databases and all tables. You may wish to stop at a useful point in time, in which case you can look at the _Recovery to a point in time_ recipe, earlier in the chapter. 2. Once the restore is complete, you can dump the tables in the database by following the _Hot logical backups of one database_ recipe. 3. Now, recreate the database on the original server as described for logical dumps earlier in this recipe. # Improving performance of backup/recovery Performance is often a concern in any medium-sized or large database. Backup performance is often a delicate issue, because resource usage may need to be limited to remain within certain boundaries. There may also be a restriction on the maximum runtime for the backup, for example, a backup that runs every Sunday. Again, restore performance may be more important than backup performance, even if backup is the more obvious concern. # Getting ready If performance is a concern or is likely to be, then you should read the _Planning backups_ recipe first. # How to do it... Backup and restore performance can be improved in different ways, depending on the backup type: * **Physical backup** : Improving the performance of a physical backup can be done by performing the backup in parallel and copying the files using more than one task. The more tasks you use, the more it will impact the current system. When backing up, you can skip certain files. You won't need the following: * Any files placed in the data directory by DBA that shouldn't actually be there * Any files in `pg_wal` * Any old server log files in `pg_log` (even the current one) Remember, it's safer not to try to exclude files at all because, if you miss something critical, you may end up with data loss. Also remember that your backup speed may be bottlenecked by your disks or your network. Some larger systems have dedicated networks in place, solely for backups. * **Logical backup** : As explained in a previous recipe, if you want to back up all databases in a database server, then you should use multiple `pg_dump` tasks running in parallel. You may want to increase the dump speed of a `pg_dump` task, but there really isn't an easy way of doing that right now. If you're using compression, look at the _There's more..._ at the end of this recipe. * **Physical restore** : Just as with physical backup, it's possible for us to put everything back quicker if we use parallel copy, which is able to speed things up by automatically reusing existing files. * **Logical restore** : Whether you use `psql` or `pg_restore`, you can speed up the program by assigning `maintenance_work_mem = 128MB` or more, either in `postgresql.conf` or on the user that will run the restore. If neither of those ways is easily possible, you can specify the option using the `PGOPTIONS` environment variable, as follows: **export PGOPTIONS ="-c work_mem = 128000"** This will then be used to set that option value for subsequent connections. If you are running archiving or streaming replication, then transaction log writes may become a problem. This can be mitigated by increasing the size of the WAL buffer and making checkpoints less frequent for the duration of the recovery operation. Set `wal_buffers` between 16 MB and 64 MB, and set `max_wal_size` to a large value such as 20 GB so that it has room to breathe. If you aren't running archiving or streaming replication, or you've turned it off during the restore, then you'll be able to minimize the amount of transaction log writes. In that case, you may wish to use the single-transaction option, as that will also help improve performance. If a `pg_dump` was made using -F c (custom format), then we can restore in parallel, as follows: **pg_restore -j NumJobs** You'll have to be careful about how you select the degree of parallelism to use. A good starting point is the number of CPUs of the server. Be very careful that you don't overflow the available memory when using parallel restore. Each job will use memory up to the value of `maintenance_work_mem`, so the whole restore could begin swapping when it hits larger indexes later in the restore. Plan the size of `shared_buffers` and `maintenance_work_mem` according to the number of jobs specified. Whatever you do, make sure you run `ANALYZE` afterwards on every object that was created. This will happen automatically if `autovacuum` is enabled. It often helps to disable `autovacuum` completely while running a large restore, so double-check that you have it switched on again after the restore. The consequence of skipping this step will be extremely poor performance when you start your application again, which can easily make everybody panic. # How it works... A physical backup and restore is completely up to you. Copy those files as fast as you like, and in any way you like. Put them back in the same way or a different way. Logical backup and restore involves moving data out of and into the database. That's typically going to be slower than physical backup and restore. Particularly with a restore, rebuilding indexes and constraints takes time, even when run in parallel. Plan ahead and measure the performance of your backup and restore techniques so that you have a chance when you need your database back in a hurry. # There's more... Compressing backups is often considered as a way to reduce the size of the backup for storage. Even mild compression can use large amounts of CPU. In some cases, this might offset network transfer costs, so there isn't any hard rule as to whether compression is always good. Compression for WAL files from physical backups is a common practice. Physical backups can be compressed in various ways, depending on the exact backup mechanism used. By default, the custom dump format for logical backups will be compressed. Even when compressed, the objects can be accessed individually if required. Using `--compress` with script dumps will result in a compressed text file, just as if you had dumped the file and then compressed it. Access to individual tables is not possible. Using multiple processes is known as pipeline parallelism. If you're using physical backup, then you can copy the data in multiple streams, which also allows you to take advantage of parallel compression/decompression. # See also If taking a backup is an expensive operation, then a way around that is to take the backup from a replica instead, which offloads the cost of the backup operation away from the master. Look at the recipes in Chapter 12, _Replication and Upgrades_ , to see how to set up a replica. # Incremental/differential backup and restore If you have performance problems with a backup of a large PostgreSQL database, then you may consider incremental or differential backups. An incremental backup is a backup of all files that have changed since the last backup, either incremental or full. In order to restore a given incremental backup, you must restore the full backup and then all the incremental backups in between. A differential backup is a backup of all individual changes since the last full backup. In order to restore a differential backup you need only that backup and the full backup it refers to. # How to do it... To perform a differential physical backup, you can use `rsync` to compare the existing files against the previous full backup, and then overwrite only the changed data blocks. It's a bad plan to overwrite your last backup because, if the new backup fails, you are left without backups. Therefore, keep two or more copies. An example backup schedule can be as follows: **Day of the week** | **Backup set 1** | **Backup set 2** ---|---|--- Sunday | New full backup to set 1 | New full backup to set 2 Monday | Differential to set 1 | Differential to set 2 Tuesday | Differential to set 1 | Differential to set 2 Wednesday | Differential to set 1 | Differential to set 2 Thursday | Differential to set 1 | Differential to set 2 Friday | Differential to set 1 | Differential to set 2 Saturday | Differential to set 1 | Differential to set 2 You should keep at least two full backup sets. Many large databases have tables that are insert-only. In that case, it's easy to store parts of those tables. If the tables are partitioned by insertion date, creation date, or a similar field, it makes our task much simpler. Either way, you're still going to need a good way of recording which data is where in your backup. In general, there's no easy way to run a differential backup using `pg_dump`. # How it works... PostgreSQL doesn't explicitly keep track of the last changed date or similar information for a file or table. PostgreSQL tables are held as files, so you should be able to rely on the modification time (`mtime`) of the files on the filesystem. Another problem with this approach is that filesystem timestamps might not have a resolution that is sufficiently granular to separate all changes. This means that some additional verification, such as computing a checksum, is required to confirm that two files with the same `mtime` are indeed identical. If, for this or some other reason, you don't trust `mtime`, or it has been disabled, then incremental and differential backups are not for you. The `pg_dump` utility doesn't allow `WHERE` clauses to be specified, so even if you add your own columns to track `last_changed_date`, you'll still need to manually perform that somehow. # There's more... The article at http://en.wikipedia.org/wiki/Backup_rotation_scheme gives further useful information. When thinking about incremental backups, you should note that replication techniques work by continually applying changes to a full backup. This could be considered a technique for an incremental updated backup, also known as an _incremental forever_ backup strategy. The changes are applied ahead of time so that you can restore easily and quickly. You should still take a backup, but you can take it from the replication standby instead. It's possible to write a utility that takes a differential backup of data blocks. You can read each data block and check the block's **Log Sequence Number** ( **LSN** ) to see whether it has changed in comparison to a previous copy. This is similar to the approach followed by `pgBackRest`. In the _Hot physical backup and continuous archiving_ recipe, we discussed using third-party backup and recovery software. All the tools we mentioned support compression of WAL files by invoking popular general-purpose compression utilities such as `bzip2`, `gzip` and `lzh` directly on WAL files. This is safe and does not increase the actual risk of data loss. Such utilities have been extensively used for many years, and all serious bugs have been ironed out. The `pg_rman` and `pgBackRest` utilities can also read changed data pages and interpret their contents, for instance to compress them using detailed knowledge of the internals of PostgreSQL's data page format, or for deciding whether to include the page in an incremental/differential backup. Any bugs that exist there could cause data loss in your backups, and issues with third-party tools aren't resolved by the main PostgreSQL project. This is why we personally advise against using third party software that operates on individual data pages without a formal support contract. Various companies support this; ask them. In order to avoid taking those risks, the Barman utility follows the opposite approach of not handling directly the contents of each PostgreSQL data page, choosing instead to delegate the file transfer logic to other well-known tools such as `rsync` or `pg_basebackup`. # Hot physical backups with Barman The main reason we came up with the idea of starting a new open source project for disaster recovery of PostgreSQL databases was the lack (back in 2011) of a simple and standard procedure for managing backups and, most importantly, recovery. Disasters and failures in ICT will happen. As a database administrator, your duty is to plan for backups and recovery of PostgreSQL databases and perform regular tests in order to sweep away stress and fear, which typically follow those unexpected events. Barman, which stands for Backup and Recovery Manager, is definitely a tool that you can use for these purposes. Before you dive into this recipe and the next one, which will introduce you to Barman, I recommend that you read the following recipes from earlier in this chapter— _Understanding and controlling crash recovery_ , _Planning backups_ , _Hot physical backup and continuous archiving_ , and _Recovery to a point in time_. Although Barman hides the complexity of the underlying concepts, it is important that you be aware of them, as it will make you more resilient to installation, configuration, and recovery issues with Barman. Barman is currently available only for Linux systems and is written in Python. It supports PostgreSQL versions from 8.3 onwards. Among its main features worth citing are remote backup, remote recovery, multiple server management, backup catalogs, incremental backups, retention policies, WAL streaming, compression of WAL files, and backup from a standby server. For the sake of simplicity, in this recipe we will assume the following architecture: * One Linux server named `angus`, running your PostgreSQL production database server * One Linux server named `malcolm`, running Barman for disaster recovery of your PostgreSQL database server * Both the servers are in the same LAN and, for better business continuity objectives, the only resource they share is the network Later on, we will see how easy it is with Barman to add more Postgres servers (such as `bon`) to our disaster recovery solution on malcolm. # Getting ready Although Barman can be installed via sources or through pip—Python's main package manager, the easiest way to install Barman is by using the software package manager of your Linux distribution. Currently, 2ndQuadrant maintains packages for RHEL, CentOS 6/7, Debian, and Ubuntu systems. If you are using a different distribution or another Unix system, you can follow the instructions written in the official documentation of Barman, available at <http://docs.pgbarman.org/>. In this book, we will cover the installation of Barman 2.3 (currently the latest stable release) on CentOS 7 and Ubuntu 16.04 LTS Linux servers. If you are using RHEL or CentOS 7 on the malcolm server, you need to install the following repositories: * Fedora **Extra Packages Enterprise Linux** ( **EPEL** ), available at <http://fedoraproject.org/wiki/EPEL> * PostgreSQL Global Development Group RPM repository, available at <http://yum.postgresql.org/> Then, as root, type this: **yum install barman** If you are using Ubuntu on `malcolm`, you need to install the APT PostgreSQL repository, following the instructions available at <http://apt.postgresql.org/>. Then, as root, type this: **apt-get install barman** From now on, we will assume the following: * A freshly installed PostgreSQL is running on `angus` as the `postgres` system user and listening to the default port (`5432`). Its configuration allows the `barman` system user on `malcolm` to connect as the `postgres` database user without having to type a password. * Barman is installed on `malcolm` and runs as the `barman` system user. * TCP connections for SSH and PostgreSQL are allowed between the two servers (check your firewall settings). * Two-way automated communication via SSH is properly set up between these users. * You have created a superuser called Barman in your PostgreSQL server on `angus` and it can only connect from the `malcolm` server. See Chapter 1, _First Steps_ , the _Enabling access for network/remote users_ recipe and Chapter 6, _Security_ , the _PostgreSQL Superuser_ recipe. The last operation requires exchanging a public SSH key without passphrase between the `postgres` user on `angus` and the `barman` user on `malcolm`. If you are not familiar with this topic, which goes beyond the scope of this book, you are advised to follow Barman's documentation or surf the net for more information. Alternatively, if your system administrator complains about opening SSH access to your PostgreSQL server, you can always take your backups via streaming replication. Indeed, Barman transparently integrates with `pg_basebackup`, meaning that base backups can be taken through the `5432` port and permissions can be granted at PostgreSQL level. However, in this book we will concentrate on the copy method, which uses `rsync` via SSH. If you are interested in setting up backups via streaming replication, look at Barman's documentation, in particular the `backup_method` and `streaming_conninfo` options, as well as _Setting up streaming replication_ recipe in Chapter 12, _Replication and Upgrades_. # How to do it... We will start by looking at Barman's main configuration file: 1. As root on `malcolm`, open the `/etc/barman.conf` file for editing. This file contains global options for Barman. Once you are familiar with the main configuration options, I recommend that you set the default compression method by uncommenting the following line: **compression = gzip** 2. Add the configuration file for the `angus` server. Drop the `angus.conf` file, containing the following lines, into the `/etc/barman.d` directory: **[angus]** **description = "PostgreSQL Database on angus"** **active = off** **archiver = on** **backup_method = rsync** **ssh_command = ssh postgres@angus** **conninfo = host=angus user=barman dbname=postgres** 3. You have just added the `angus` server to the list of Postgres servers managed by Barman. The server is temporarily inactive until configuration is completed. You can verify this by typing `barman list-server`, as follows: **[root@malcolm]# barman list-server** **angus - PostgreSQL Database on angus (inactive)** 4. In this recipe, you will be executing commands as root user. Be aware, however, that every command will be executed by the `barman` system user (or, more generally, as specified in the configuration file by the `barman_user` option). Anyway, it is now time to set up continuous archiving of WAL files between Postgres and Barman. Execute the `barman show-server angus` command and write down the directory for incoming WALs `(incoming_wals_directory)`: **[root@malcolm]# barman show-server angus** **Server angus (inactive):** **active: False** **archive_command: None** **archive_mode: None** ******incoming_wals_directory: /var/lib/barman/angus/incoming** 5. The next task is to initialize the directory layout for the `angus` server, through the `check` command. You are advised to add this command to your monitoring infrastructure as, among other things, it ensures that the connection to the Postgres server via `SSH` and `libpq` is working properly, as well as continuous archiving. It returns `0` if everything is fine: **[root@malcolm]#** **barman check angus** **Server angus (inactive):** **WAL archive: FAILED (please make sure WAL shipping is setup)** **PostgreSQL: OK** **superuser: OK** **wal_level: FAILED (please set it to a higher level than 'minimal')** **directories: OK** **retention policy settings: OK** **backup maximum age: OK (no last_backup_maximum_age provided)** **compression settings: OK** **failed backups: OK (there are 0 failed backups)** **minimum redundancy requirements: OK (have 0 backups, expected at least 0)** **ssh: OK (PostgreSQL server)** **not in recovery: OK** **archive_mode: FAILED (please set it to 'on' or 'always')** **archive_command: FAILED (please set it accordingly to documentation)** **archiver errors: OK** **[root@malcolm]# echo $?** **1** 6. As you can see, the returned value is `1`, meaning that the `angus` server is not yet ready for backup. The output suggests that `archive_mode` and `archive_command` in Postgres are not set for continuous archiving. Connect to `angus` and modify the `postgresql.conf` file by adding this: **archive_mode = on** **archive_command = 'rsync -a %p barman@malcolm:/var/lib/barman/angus/incoming/%f'** **wal_level = replica** 7. Restart the PostgreSQL server. 8. Activate the server in Barman, by removing the line that starts with `active`. 9. Run the `check` command on `malcolm` (suppressing the output with `-q`) again, and compare the results with what you got earlier: **[root@malcolm]# barman -q check angus** **[root@malcolm]# echo $?** **0** It returned `0`. Everything is all good! PostgreSQL on `angus` should now be regularly shipping WAL files to Barman on `malcolm`, depending on the write workload of your database. Do not worry if the `check` command complains with the following error: **WAL archive: FAILED (please make sure WAL shipping is setup)** It is a precautionary measure we had to take in order to prevent users from going live without a working archiving process. That means that your server (like `angus` in this case) has a very low workload and no WAL files have yet been produced, shipped, and archived. If you want to speed up the installation, you can execute the following commands: **[root@malcolm]# barman switch-wal --force --archive angus [root@malcolm]# barman archive-wal angus** I recommend that you check both the PostgreSQL and Barman log files and verify that WALs are correctly shipped. Continuous archiving is indeed the main requirement for physical backups in Postgres. 10. Once you have set up continuous archiving, in order to add the disaster recovery capability to your Postgres server, you need to have at least one full base backup. Taking a full base backup in Barman is as easy as typing one single command. It should not be hard for you to guess that the command to execute is `barman backup angus`. Barman initiates the physical backup procedure and waits for the checkpoint to happen, before copying the data files from `angus` to `malcom` using `rsync`: **[root@malcolm]# barman backup angus** **Starting backup using rsync-exclusive method for server angus in /var/lib/barman/angus/base/20171003T194717** **Backup start at xlog location: 0/3000028 (000000010000000000000003, 00000028)** **This is the first backup for server angus** **WAL segments preceding the current backup have been found:** **000000010000000000000001 from server angus has been removed** **Copying files.** **Copy done.** **This is the first backup for server angus** **Asking PostgreSQL server to finalize the backup.** **Backup size: 21.1 MiB** **Backup end at xlog location: 0/3000130 (000000010000000000000003, 00000130)** **Backup completed** **Processing xlog segments from file archival for angus** **000000010000000000000002** **000000010000000000000003** **000000010000000000000003.00000028.backup** It is worth noting that, during the backup procedure, your PostgreSQL server is available for both read and write operations. This is because PostgreSQL natively implements hot backup, a feature that other DBMS vendors might make you pay for. From now on, your `angus` PostgreSQL server is continuously backed up on `malcolm`. You can now schedule weekly backups (using the `barman` user's cron) and manage retention policies so that you can build a catalog of backups covering you for weeks, months, or years of data, and allowing you to perform recovery operations at any point in time between the first available backup and the last successfully archived WAL file. # How it works... Barman is a Python application that wraps PostgreSQL core technology for continuous backup and PITR. It also adds some practical functionality focused on helping the database administrator manage disaster recovery of one or more PostgreSQL servers. When devising Barman, we decided to keep the design simple and not to use any daemon or client/server architecture. Maintenance operations are simply delegated to the `barman cron` command, which is mainly responsible for archiving WAL files (moving them from the incoming directory to the WAL file and compressing them) and managing retention policies. If you have installed Barman through RPM or APT packages, you will notice that maintenance is run every minute through cron: **[root@malcolm ~]# cat /etc/cron.d/barman ** **# m h dom mon dow user command ** *** * * * * barman [ -x /usr/bin/barman ] && /usr/bin/barman -q cron** Barman follows the _convention over configuration_ paradigm and uses an INI format configuration file with options operating at two different levels: * **Global options** : These are options specified in the [`barman`] section, used by any Barman command and for every server. Several global options can be overridden at the server level. * **Server options** : These are options specified in the [`SERVER_ID`] section, used by server commands. These options can be customized at the server level (including overriding general settings). The `SERVER_ID` placeholder (such as `angus`) is fundamental, as it identifies the server in the catalog (therefore, it must be unique). Similarly, commands in Barman are of two types: * **Global commands** : These are general commands, not tied with any server in particular, such as a list of the servers managed by the Barman installation (`list-server`) and maintenance (`cron`) * **Server commands** : These are commands executed on a specific server, such as diagnostics (`check` and `status`), backup control (`backup`, `list-backup`, `delete` and `show-backup`), and recovery control (recover, which is discussed in the next recipe, _Recovery with Barman_ ) The previous sections of this recipe showed you how to add a server (`angus`) to a Barman installation on the `malcolm` server. You can easily add a second server (`bon`) to the Barman server on malcolm. All you have to do is create the `bon.conf` file in the `/etc/barman.d` directory and repeat the steps outlined in the _How it works..._ section, as you have done for `angus`. # There's more... Every time you execute the `barman backup` command for a given server, you take a full base backup (a more generic term for this is periodical full backup). Once completed, this backup can be used as a base for any recovery operation from the start time of the backup to the last available WAL file for that server (provided there is continuity among all the WAL segments). As mentioned earlier, by scheduling daily or weekly automated backups, you end up having several periodic backups for a server. In Barman's jargon, this is known as the backup catalog and it is one of our favorite features of this tool. At any time, you can get a list of available backups for a given server through the `list-backup` command: **[root@malcolm ~]# barman list-backup angus** **7angus 20171003T194717 - Mon Oct 3 19:47:20 2017 - Size: 21.1 MiB - WAL Size: 26.6 KiB** The last informative command you might want to get familiar with is `show-backup`, which gives you detailed information on a specific backup regarding the server, base backup time, WAL archive, and context within the catalog (for example, the last available backup): **[root@malcolm ~]# barman show-backup angus 20171003T194717** Rather than the full backup ID (`20171003T194717`), you can use a few synonyms, such as these: * **Last or latest** : This refers to the latest available backup (the last in the catalog) * **First or oldest** : This refers to the oldest available backup (the first in the catalog) For the `show-backup` command, however, we will use a real and concrete example, taken directly from one of our customer's installations of Barman on a 16.4 TB Postgres 9.4 database: **Backup 20170930T130002:** **Server Name : skynyrd** **Status : DONE** **PostgreSQL Version : 90409** **PGDATA directory : /srv/pgdata** **Base backup information:** **Disk usage : 16.4 TiB (16.4 TiB with WALs)** **Incremental size : 5.7 TiB (-65.08%)** **Timeline : 1** **Begin WAL : 000000010000358800000063** **End WAL : 00000001000035A0000000A2** **WAL number : 6208** **WAL compression ratio: 79.15%** **Begin time : 2017-09-30 13:00:04.245110+00:00** **End time : 2017-10-01 13:24:47.322288+00:00** **Begin Offset : 24272** **End Offset : 11100576** **Begin XLOG : 3588/63005ED0** **End XLOG : 35A0/A2A961A0** **WAL information:** **No of files : 3240** **Disk usage : 11.9 GiB** **WAL rate : 104.33/hour** **Compression ratio : 76.43%** **Last available : 00000001000035AD0000004A** **Catalog information:** **Retention Policy : not enforced** **Previous Backup : 20170923T130001** **Next Backup : - (this is the latest base backup)** As you can see, Barman is a production-ready tool that can be used in large, business-critical contexts, as well as in basic Postgres installations. It provides good **Recovery Point Objective** ( **RPO** ) outcomes, allowing you to limit potential data loss to a single WAL file. Finally, Barman also supports WAL streaming, which dramatically reduces the amount of data you can lose. With synchronous replication and replication slot support, you can achieve _zero data loss_ backups. For further information, please refer to Barman's documentation, in particular: `streaming_archiver`, `streaming_archiver_name`, `streaming_conninfo`, and `slot_name`. Barman is distributed under GNU GPL 3 terms and is available for download at <http://www.pgbarman.org/>. There is also a module for Puppet available at <https://github.com/2ndquadrant-it/puppet-barman>. For further and more detailed information, refer to the following: * The `man barman` command, which gives the man page for the Barman application * The `man 5 barman` command, which gives the man page for the configuration file * The `barman help` command, which gives a list of the available commands * The official documentation for Barman, publicly available at <http://docs.pgbarman.org/> * The mailing list for community support at <http://www.pgbarman.org/support/> # Recovery with Barman This recipe assumes that you have read the previous recipe, _Hot physical backups with Barman_ , and successfully installed Barman on the `malcolm` server, backing up the Postgres databases running on `angus` and `bon`. We will use the same nomenclature in the examples in this recipe. A recovery procedure is a reaction to a failure. In database terms, this could be related to an unintentional human error (for example, a DROP operation on a table), an attack (think of Little Bobby Tables), a hardware failure (for example, a broken hard drive), or (less likely) a natural disaster. Even though you might be tempted to think that you are immune to disasters or failures (we wish you were), you are advised to perform regular tests and simulations of recovery procedures. If you have a team of engineers, we suggest that you schedule a simulation every six months (at least) and regularly test your backups through the safest way of checking their content—performing a recovery. You don't want to take backups for years and, in the moment of need, suddenly discover that they have not been working for the last three months. Barman allows you to perform two types of recovery: * **Local recovery** : This involves restoring a PostgreSQL instance on the same server where Barman resides * **Remote recovery** : This involves restoring a PostgreSQL instance directly from the Barman server to another server, through the network It is important to note that the terms _local_ and _remote_ are defined from Barman's standpoint, as every recovery command is executed where Barman is installed. In this recipe, we will cover a single use case—total failure of one of the servers where PostgreSQL is running (fortunately, it is backed up by Barman) and a full remote recovery on a third server. # Getting ready Even though Barman can centrally manage backups of several servers that have different versions of PostgreSQL, when it comes to recovery, the same requirements for PostgreSQL's PITR technology apply. In particular, the following: * You must recover on a server with the same hardware architecture and PostgreSQL version * Recovery is full, meaning the entire Postgres cluster will be restored (and not a single database) The use case of this recipe is the following: * The `bon` server has been lost forever, due to a permanent hardware failure * The `brian` server, having similar characteristics to `bon`, has been selected for recovery * The same Linux distribution and PostgreSQL packages have been installed on ``brian`` * Barman will be used to perform remote recovery of the latest backup available for `bon` on the `brian` server In order to proceed, you need to add the public SSH key of the `barman` user on `malcolm` in the `~/.ssh/authorized_keys` file of the `Postgres` user on `brian`. If you are not familiar with the process of exchanging a public SSH key, which goes beyond the scope of this book, you are advised to follow Barman's documentation or surf the net for more information. The first step is to make sure that the `PGDATA directory`, as specified in the `bon` backup, exists on brian and can be written by the `postgres` user. Ask `barman` for the location of `PGDATA` by querying the latest available `backup` metadata: **barman show-backup bon last** Write down the content of the `PGDATA directory` entry: **PGDATA directory : /var/lib/pgsql/10/data** You might have noticed that we are using the default `PGDATA directory` for a RHEL/CentOS cluster based on packages maintained by the PostgreSQL community. On Ubuntu, you will probably have `/var/lib/postgresql/10/main`. As the second step, also make sure that PostgreSQL is not running on `Brian`, using either the `service` or `pg_ctl` command. Executing a recovery operation on a target directory used by a running PostgreSQL instance will permanently damage that instance. Be extremely careful when you perform such an operation. # How to do it... Connect as the `barman` user on `malcolm` and type the following: **barman recover --remote-ssh-command 'ssh postgres@brian' bon last /var/lib/pgsql/9.6/data** The preceding command will use the latest available backup for the `bon` server and prepare everything you need to restore your server in the PostgreSQL destination directory (`/var/lib/pgsql/10/data`), as shown in the output: **Starting remote restore for server bon using backup 20171003T194717** **Destination directory: /var/lib/pgsql/10/data** **Copying the base backup.** **Copying required WAL segments.** **Generating archive status files** **Identify dangerous settings in destination directory.** **IMPORTANT** **These settings have been modified to prevent data losses** **postgresql.conf line 645: archive_command = false** **Your PostgreSQL server has been successfully prepared for recovery!** Once again, Ubuntu users will have to use a different destination directory, such as `/var/lib/postgresql/10/main`. Before you start the server, you are advised to connect to `Brian` as Postgres and inspect the content of the Postgres destination directory. You should notice that its content should be very similar to what was in the `bon` server before the crash. You are also strongly encouraged to review the content of the `postgresql.conf` file before starting the server, even though Barman takes care of disabling or removing some potentially dangerous options. The most critical option is `archive_command`, which is preemptively set to `false`, forcing you to deliberately analyze and consider new continuous archiving strategies (for example, you might want to add the new `Brian` server to Barman by repeating the steps outlined in the previous recipe). When you are ready, you can start Postgres as a standard service. On CentOS 7, for example, you can execute as root, as follows: **systemctl start postgresql-10** On Ubuntu, use this command: **systemctl start postgresql** Look at the logs to verify that you do not have any problems, and then at `ps -axf`. Your PostgreSQL databases that were hosted on `bon` have been successfully restored on `brian`, using all the WAL files shipped to the backup server. # How it works... When executed with the `--remote-ssh-command` option, the `recover` command will activate remote recovery and will use those credentials to connect to the remote server (similar to what the `ssh-command` configuration option does in the backup phase but in reverse—see the _Hot physical backups with Barman_ recipe). Internally, Barman relies on `rsync` for this operation. When performing a full recovery (up to the latest available archived WAL file), Barman recreates the structure of the `PGDATA` according to the backup. It will then deposit all the needed WAL files in the `pg_wal` directory. A careful analysis of the content of the restored `PGDATA directory` shows that no `recovery.conf` file is generated by Barman in the case of a full recovery. It will just simulate a standard crash recovery of PostgreSQL and start replaying the WAL files from the REDO point, contrary to the _Recovery of all databases_ recipe, where `recovery.conf` was used. We decided to adopt this strategy in Barman so that we could maintain the same timeline (as a `recovery.conf` file would start a new era in the cluster's existence), and avoid setting `restore_command`. # There's more... If you are using tablespaces, you may be wondering if and how Barman manages them. Barman fully supports tablespaces, including their relocation at recovery time, through the `--tablespace runtime` option. For information on the syntax of the relocation rules, type any of the following commands: * `barman help recover` * `man barman` In this recipe, we have seen only one use case, which covers remote recovery. As mentioned before, however, Barman also allows DBAs to recover instances of PostgreSQL on the same server as Barman. This is called local recovery. For local recovery, you will need to have installed the binaries and libraries of the same version of PostgreSQL on the Barman server as the backup file you want to restore. You can dedicate a directory in Barman for local recovery, to be used as the destination directory for your recover commands. A typical use case for local recovery is to restore the situation of a PostgreSQL server at a specific point in time, usually before an unintentional action such as the DROP of a table. Barman supports PITR, as explained in the _Recovery to a point in time_ recipe, through three options that define the recovery target: * `--target-time TARGET_TIME`: The target is a timestamp * `--target-xid TARGET_XID`: The target is a transaction ID * `--target-name TARGET_NAME`: The target is a named restore point, previously created with the `pg_create_restore_point(name)` function When executed with one of these options, Barman will generate the `recovery.conf` file for you. Advanced users might want to activate the hot standby facility and take advantage of the `recovery_target_action` option (by default set to `pause`, and effective only if `hot_standby` is enabled in the `postgresql.conf` file). This will allow you to check whether the database is in the desired state or not. If not, you can stop the server, change the recovery target time, and start it again. Repeat this operation until you reach your goal, keeping in mind that PostgreSQL can only roll forward WAL files (they are called REDO operations for a reason). You can then follow the instructions outlined in the _Recovery of a dropped/damaged table_ recipe to restore the objects in the primary database. At the end of any recovery operation, remember to stop the running of local servers and remove recovered instances (even though this is not mandatory, as Barman uses `rsync` and will be able to perform an incremental copy of the files where applicable). Another interesting feature of Barman is the `get-wal` command, which transforms Barman in an infinite basin of WAL files. Instead of copying WAL files before the actual start of the server, you can let PostgreSQL pull the required WAL files on demand at recovery time, via `restore_command`. For further information, look at the `barman-cli` package, specifically the `barman-wal-restore` script at <https://github.com/2ndquadrant-it/barman-cli>[ ](https://github.com/2ndquadrant-it/barman-cli) As a final note for this recipe, another important use case for Barman is to regularly create copies of the server to be used for business intelligence purposes or even staging/development. These environments do not normally require a strict up-to-date situation and are very often happy to work on a snapshot of the previous day. A typical workflow for this use case can be like this: 1. Stop the PostgreSQL server on the BI/staging server. 2. Issue a full remote recovery operation of the desired backup from Barman to the BI server (`rsync` will use the existing data directory for incremental copy). 3. Start the PostgreSQL server on the BI/staging server. This recipe has covered only a few aspects of the recovery process in Barman. For further and more detailed information, refer to: * The official documentation for Barman, publicly available at <http://docs.pgbarman.org/> * The mailing list for community support at <http://www.pgbarman.org/support/> * The Barman section of our blog at <https://blog.2ndquadrant.com/tag/barman>. # Replication and Upgrades Replication isn't magic, though it can be pretty cool! It's even cooler when it works, and that's what this chapter is all about. Replication requires understanding, effort, and patience. There are a significant number of points to get right. My emphasis here is on providing simple approaches to get you started, and some clear best practices on operational robustness. PostgreSQL has included some form of native or in-core replication since version 8.2, though that support has steadily improved over time. External projects and tools have always been a significant part of the PostgreSQL landscape, with most of them being written and supported by very skilled PostgreSQL technical developers. Some people with a negative viewpoint have observed that this weakens PostgreSQL or emphasizes shortcomings. My view would be that PostgreSQL has been lucky enough to be supported by a huge range of replication tools, together offering a wide set of supported use cases from which to build practical solutions. This view extends throughout this chapter on replication, with many recipes using tools that are not part of the core PostgreSQL project yet. All the tools mentioned in this chapter are actively enhanced by current core PostgreSQL developers. The pace of change in this area is high, and it is likely that some of the restrictions mentioned here could well be removed by the time you read this book. Double-check the documentation for each tool or project. _Which technique is the best?_ is a question that gets asked many times. The answer varies depending on the exact circumstances. In many cases, people use one technique on one server and a different technique on other servers. Even the developers of particular tools use other tools when it is appropriate. Use the right tools for the job. All the tools and techniques listed in this chapter have been recommended by me at some time, in relevant circumstances. If something isn't mentioned here by me, that does probably imply that it is less favorable for various reasons, and there are some tools and techniques that I would personally avoid altogether in their present form or level of maturity. I ( _Simon Riggs_ ) must also confess to being the developer or designer of many parts of the basic technology presented here. That gives me some advantages and disadvantages over other authors. It means I understand some things better than others, which hopefully translates into better descriptions and comparisons. It may also hamper me by providing too narrow a focus, though the world is big and this book is already long enough! This book, and especially this chapter, cover technology in depth. As a result, we face the risk of minor errors. We've gone to a lot of trouble to test all of our recommendations, but just as with software, I learn that books can be buggy too. I hope our efforts to present actual commands rather than just words will be appreciated by you. In this chapter, we will cover the following recipes: * Replication best practices * Setting up file-based replication – deprecated * Setting up streaming replication * Setting up streaming replication security * Hot Standby and read scalability * Managing streaming replication * Using repmgr * Using replication slots * Monitoring replication * Performance and synchronous replication * Delaying, pausing, and synchronizing replication * Logical replication * Bi-Directional Replication * Archiving transaction log data * Upgrading – minor releases * Major upgrades in-place * Major upgrades online # Replication concepts Replication technology can be confusing. You might be forgiven for thinking that people have a reason to keep it that way. My observation is that there are many techniques, each with their own advocates, and the strengths and weaknesses are often hotly debated. There are some simple underlying concepts that can help you understand the various options available. The terms used here are designed to avoid favoring any particular technique, and we've used standard industry terms whenever available. # Topics **Database replication** is the term we use to describe the technology used to maintain a copy of a set of data on a remote system. There are usually two main reasons for you wanting to do this, and those reasons are often combined: * **High Availability** : Reducing the chances of data unavailability by having multiple systems, each holding a full copy of the data. * **Data Movement** : Allowing data to be used by additional applications or workload on additional hardware. Examples of this are **Reference Data Management** ( **RDM** ), where a single central server might provide information to many other applications, and **Business Intelligence** / **Reporting Systems**. Of course, both of those topics are complex areas, and there are many architectures and possibilities for implementing each of them. What we will talk about here is High Availability, where there is _no transformation_ of the data. We simply copy the data from one PostgreSQL database server to another. So we are specifically avoiding all discussion on ETL tools, EAI tools, inter-database migration, data warehousing strategies, and so on. Those are valid topics in IT architecture; it's just that we don't cover them in this book. # Basic concepts Let's look at the basic architecture. Typically, individual database servers are referred to as nodes. The whole group of database servers involved in replication is known as a cluster. That is the common usage of the term, but be careful; the term **cluster** is also used for two other quite separate meanings elsewhere in PostgreSQL. Firstly, cluster is sometimes used to refer to the database instance, though I prefer the term **database server**. Secondly, there is a command named `cluster`. It is designed to sort data in a specific order within a table. A database server that allows a user to make changes is known as a **master** or **primary** , or may be described as a source of changes. A database server that only allows read-only access is known as a **Hot Standby** , or sometimes, a slave server or read replica. The key aspect of replication is that data changes are captured on a master, and then transferred to other nodes. In some cases, a node may send data changes to other nodes, which is a process known as **cascading** or **relay**. Thus, the master is a sending node, but a sending node does not need to be a master. Replication is often categorized by whether more than one master node is allowed, in which case it will be known as multimaster replication. There is a significant difference between how single-master and multimaster systems work, so we'll discuss that aspect in more detail later. Each has its advantages and disadvantages. # History and scope PostgreSQL didn't always have in-core replication. For many years, PostgreSQL users needed to use one of many external packages to provide this important feature. Slony was the first package to provide useful replication features. Londiste was a variant system that was somewhat easier to use. Both of those systems provided single-master replication based around triggers. Another variant of this idea was the **Bucardo** package, which offered multimaster replication using triggers. Trigger-based replication has now been superseded by transaction-log-based replication, which provides considerable performance improvements. There is some discussion on exactly how much difference that makes, but log-based replication is approximately twice as fast, though many users have reported much higher gains. Trigger-based systems also have considerably higher replication lag. Lastly, triggers need to be added to each table involved in replication, making these systems more time-consuming to manage and sensitive to production problems. These factors taken together mean that trigger-based systems will likely be avoided for new developments, and I'm taking the decision not to cover them at all in the latest edition of this book. Outside the world of PostgreSQL, there are many competing concepts and much recent research. This is a practical book, so we've mostly avoided comments on research or topics on computer science. The focus of this chapter is replication technologies that are part of the core software of PostgreSQL, or will be so in the reasonably near future. The first of these is known as **streaming replication** , introduced in PostgreSQL 9.0, but based on earlier file-based mechanisms for physical transaction log replication. In this book, we refer to this as **Physical Streaming Replication** ( **PSR** ) because we take the transaction log (often known as the **Write-Ahead Log** ( **WAL** )) and ship that data to the remote node. The WAL contains an exact physical copy of the changes made to a data block, so the remote node is an exact copy of the master. Therefore, the remote node cannot execute transactions that write to the database; this type of node is known as a standby. Starting in PostgreSQL 9.4, we introduced an efficient mechanism for reading the transaction log (WAL) and transforming it into a stream of changes, a process known as **logical decoding**. This is then the basis for the later, even more useful mechanism, known as **Logical Streaming Replication** ( **LSR** ). This allows a receiver to replicate data without needing to keep an exact copy of the data blocks, as we do with PSR. This has significant advantages, which we will discuss later. PSR requires us to have only a single master node, though it allows multiple standbys. LSR can be used for all the same purposes as PSR. It just has fewer restrictions and allows a great range of additional use cases. Crucially, LSR can be used as the basis of multimaster clusters. PSR and LSR are sometimes known as **Physical Log Streaming Replication** ( **PLSR** ) and **Logical Log Streaming Replication** ( **LLSR** ). Those terms are sometimes used to explain differences between transaction-log-based and trigger-based replication. # Practical aspects Since we refer to the transfer of replicated data as streaming, it becomes natural to talk about the flow of data between nodes as if it were a river or stream. Cascaded data can flow through a series of nodes to create complex architectures. From the perspective of any node, it may have downstream nodes that receive replicated data from it and/or upstream nodes that send data to it. Practical limits need to be understood to allow us to understand and design replication architectures. After a transaction commits on the master, the time taken to transfer data changes to a remote node is usually referred to as the **latency** , or **replication delay**. Once the remote node has received the data, changes must then be applied to the remote node, which takes an amount of time known as the **apply delay**. The total time a record takes from the master to a downstream node is the replication delay plus the apply delay. Be careful to note that some authors describe those terms differently, and sometimes confuse the two, which is easy to do. Also, note that these delays will be different for any two nodes. Replication delay is best expressed as an interval (in seconds), but that is much harder to measure than it first appears. In PostgreSQL 10, the delays of particular phases of replication are given with the lag columns on `pg_stat_replication`. These are derived from sampling the message stream and interpolating the current delay from recent samples. All forms of replication are initialized in roughly the same way. First, you enable change capture, and then make a full replica of the dataset on the remote node, which we refer to as the **base backup**. After that, we begin applying the changes, starting from the point immediately before the base backup started and continuing with any changes that occurred while the base backup was taking place. As a result, the replication delay immediately following the initial copy task will be equal to the duration of the initial copy task. The remote node will then begin to catch up with the master, and the replication delay will begin to reduce. The time taken to get the lowest replication delay possible is known as the catch-up interval. If the master is busy generating new changes, which can increase the time it takes for the new node to catch up, you should try to generate new nodes during quieter periods, if any exist. Note that in some cases, the catch-up period will be too long to be acceptable. Be sure to include this understanding in your planning and monitoring. The faster and more efficient your replication system, the easier it will be to operate in the real world. _Performance matters!_ Either replication will copy all tables, or in some cases, we can copy a subset of tables, in which case we call it **selective replication**. If you choose selective replication, you should note that the management overhead increases roughly as the number of objects managed increases. Replicated objects are often manipulated in groups known as **replication sets** to help minimize the administrative overhead. # Data loss By default, PostgreSQL provides **asynchronous replication** , where data is streamed out whenever convenient for the server. If replicated data is acknowledged back to the user prior to commit, we refer to that as **synchronous replication**. With synchronous replication, the replication delay _directly_ affects the elapsed time of transactions on the master. With asynchronous replication, the master may continue at full speed, though this opens up a possible risk that the standby may not be able to keep pace with the master. All replication must be monitored to ensure that a significant lag does not develop, which is why we must be careful to monitor the replication delay. Synchronous replication guarantees that data is written to at least two nodes before the user or application is told that a transaction has committed. You can specify the number of nodes and other details that you wish to use in your configuration. # Single-master replication In single-master replication, if the master dies, one of the standbys must take its place. Otherwise, we will not be able to accept new write transactions. Thus, the designations master and standby are just roles that any node can take at some point. To move the master role to another node, we perform a procedure named **switchover**. If the master dies and does not recover, then the more severe role change is known as a **failover**. In many ways, these can be similar, but it helps to use different terms for each event. We use the term clusterware for software that manages the cluster. Clusterware may provide features such as automatic failover, and in some cases, load balancing. The complexity of failover makes single-master replication harder to configure correctly than many people would like it to be. The good news is that from an application perspective it is safe and easy to retrofit this style of replication to an existing system. Or put another way, since application developers frequently don't worry about High Availability and replication until the very end of the project, single-master replication is frequently the best solution, be it PSR or LSR. # Multinode architectures Multinode architectures allow users to write data to multiple nodes concurrently. There are two main categories: tightly coupled and loosely coupled: * **Tightly coupled database clusters** : These allow a single image of the database, so there is less perception that you're even connected to a cluster at all. This consistency comes at a price—the nodes of the cluster cannot be geographically separated, which means if you need to protect against site disasters, then you'll need additional technology to allow disaster recovery. Clustering requires replication as well. * **Loosely coupled database clusters** : These have greater independence for each node, allowing us to spread out nodes across wide areas, such as across multiple continents. You can connect to each node individually. There are two benefits of this. The first is that all data access can be performed quickly against local copies of the data. The second benefit is that we don't need to work out how to route read-only transactions to (a) standby node (s) and read/write transactions to the master node. # Clustered or massively parallel databases An example of a tightly coupled system is the open source Postgres-XL. This supersedes the earlier Postgres-XC clustering software. These systems introduced the concept of a **Global Transaction Manager** ( **GTM** ), which allows nodes in a tightly coupled system to work together while guaranteeing consistency across reads and writes. Postgres-XL spreads data across multiple nodes. Larger tables can be distributed evenly, using a hash-based distribution scheme. This feature allows Postgres-XL to scale well for both high-transaction-rate (OLTP) and business intelligence (OLAP) systems. On Postgres-XL, smaller tables can be duplicated on all nodes. Changes to smaller tables are coordinated, so there is no possibility of the multiple copies diverging from one another. The synchronization cost is high, and XL is not suitable for geographically distributed databases, though it does support High Availability. Postgres-XL is not covered in more detail in this book, simply because of lack of time and space. Postgres-XL is released with _The PostgreSQL licence_. # Multimaster replication An example of a loosely coupled system would be **Bi-Directional Replication** ( **BDR** ). Postgres-BDR does not utilize a GTM, so the nodes contain data that is eventually consistent between nodes. This is a performance optimization since tests showed that trying to use tightly coupled approaches catastrophically limits performance when servers are geographically separated. In its simplest multimaster configuration, each node has a copy of similar data. You can update data on any node and the changes will flow to other nodes. This makes it ideal for databases that have users in many different locations, which is probably the case with most websites. Each location can have its own copy of the application code and database, giving fast response times for all your users, wherever they are located. It is _possible_ to make changes to the same data at the same time on different nodes, causing update conflicts. These could become a problem, but the reality is that it is also _easily possible_ to design applications that do not generate conflicts in normal running, especially if each user is modifying their own data (for example, in social media, retail, and so on). We need to understand where conflicts might arise so that we can resolve them. On a single node, any application that allows concurrent updates to the same data will experience poor performance because of contention. The negative effect of contention will get much worse on multimaster clusters. In addition, multiple nodes require us to allow for the possibility that the updated data differs, so we must implement conflict-handling logic to resolve data differences between nodes. With some thought and planning, we can use multimaster technologies very effectively in the real world. Visit http://en.wikipedia.org/wiki/Replication_(computer_science)) for more information on this. # Scalability tools Many PostgreSQL users have designed applications that scale naturally by routing database requests based on the client number or a similar natural sharding key. This is what we call manual sharding at the application level. For PostgreSQL 10 and earlier versions, PostgreSQL does not directly support features for automatic write scalability, such as sharding. This is an active area of work, and much will change in this area, though it may take some time. Postgres-XL provides automatic hash sharding and is currently the most complete open source implementation that allows automatic write scalability at the database level. PL/Proxy provides a mature mechanism for database scalability. It was originally designed for Skype, but it is also in use at a number of high-volume sites. It provides most of the things that you'll need to create a scalable cluster. PL/Proxy requires that you define your main database accesses as functions, which requires early decisions about your application architecture. # Other approaches to replication This book covers in-database replication only. Replication is also possible in the application layer (that is, above the database) or in the **Operating System** ( **OS** ) layers (that is, below the database): * **Application-level replication** : For example, HA-JDBC and rubyrep * **OS-level replication** : For example, DRBD None of these approaches are very satisfying, since core database features cannot easily integrate with them in ways that truly work. From a sysadmin's perspective, they work, but not very well from the perspective of a database architect. # Replication best practices Some general best practices for running replication systems are described in this recipe. # Getting ready Reading the list of best practices should be the very first thing you do when designing your database architecture. So the best way to get ready for it is to avoid doing anything and start with the next section _How to do it_. # How to do it... * Use the latest release of PostgreSQL. Replication features are changing fast, with each new release improving on the previous in major ways based on our real-world experience. The idea that earlier releases are somehow more stable, and thus more easily usable, is definitely not the case for replication. * Use similar hardware and OS on all systems. Replication allows nodes to switch roles. If we switchover or failover to different hardware, we may get performance issues and it will be hard to maintain a smoothly running application. * Configure all systems identically as far as possible. Use the same mount points, directory names, and users; keep everything possible the same. Don't be tempted to make one system more important than others in some way. It's just a single point of failure and gets confusing. * Give systems/servers good names to reduce confusion. Never, ever call one of your systems master and the other slave. When you do a switchover, you will get very confused! Try to pick system names that have nothing to do whatsoever with their role. Replication roles will inevitably change; system names should not. If one system fails, and you add a new system, never reuse the name of the old system: pick another name, or it will be too confusing. Don't pick names that relate to something in the business. Colors are also a bad choice, because if you have two servers named yellow and red, you then end up saying things like _there is a red alert on server yellow_ , which can easily be confusing. Don't pick place names either. Otherwise, you'll be confused trying to remember that London is in Edinburgh and Paris is in Rome. Make sure you use names, rather than IP addresses. * Set the `application_name` parameter to be the server name in the replication connection string. Set the `cluster_name` parameter to be the server name in the `postgresql.conf`. * Make sure all tables are marked as `LOGGED` (the default). `UNLOGGED` and `TEMPORARY` tables will not be replicated by either **PSR** or **LSR**. * Keep the system clocks synchronized. This helps you keep sane when looking at log files produced by multiple servers. You should automate this, rather than do it manually, but however you do it, make sure it works. * Use a single, unambiguous time zone. Use **Coordinated Universal Time** ( **UTC** ) or something similar. Don't pick a time zone that has **Daylight Saving Time** ( **DST** ), especially in regions that have complex DST rules. This just leads to (human) confusion with replication, as servers are often in different countries and time zone differences vary throughout the year. Do this even if you start with all servers in one country, because over the lifetime of the application, you may need to add new servers in different locations. Think ahead. * Monitor each of the database servers. If you want High Availability, then you'll need to regularly check that your servers are operational. I speak to many people who would like to regard replication as a one-shot deal. Think of it more as a marriage, and plan for it to be a happy one! * Monitor the replication delay between servers. All forms of replication are only useful if the data is flowing correctly between the servers. Monitoring the time it takes for the data to go from one server to another is essential to understanding whether replication is working for you or not. Replication can be bursty, so you'll need to watch to make sure it stays within sensible limits. You may be able to set tuning parameters to keep things low, or you may need to look at other factors. The important point is that your replication delay is directly related to the amount of data you're likely to lose when running asynchronous replication. Be careful here because it is the replication delay, not the apply delay, that affects data loss. A long apply delay may be more acceptable as a result. As described previously, your initial replication delay will be high, and it should reduce to a lower and more stable value over a period of time. For large databases, this could take days, so be careful to monitor during the catch-up period. # There's more... The preceding list doesn't actually say this explicitly, but you should use the same major version of PostgreSQL for all systems. With PSR, you are required to do that, so it doesn't even need to be said. I've heard people argue that it's OK to have dissimilar systems and even that it's a good idea because if you get a bug, it only affects one node. I'd say that the massive increase in complexity is much more likely to cause problems. # Setting up file-based replication – deprecated This technique is mostly superseded by streaming replication (PSR), so if you are a novice, you probably do not want this recipe yet. Nonetheless, this is relevant and useful as part of a comprehensive backup strategy. It is also worth understanding how this works, as this technique can also be used as the starting phase for a large streaming replication setup. Look at the following recipes for some further details on that. Log shipping is a replication technique used by many database management systems. The master records database changes in its transaction log, and then the log files are shipped from the master to the standby, where the log is replayed. File-based log shipping has been available for PostgreSQL for many years now. It is simple, has very low overhead, and is a trustworthy form of replication. # Getting ready If you haven't read the _Replication concepts_ section and the _Replication best practices_ recipe at the start of this chapter, go and read them now. Replication is complex, and even if you think _no problem, I know that_ , it's worth just checking out the basic concepts and names that I'll be using here. Note that log-shipping replication refers to the master node as the primary node, and these two terms are used interchangeably. # How to do it... Follow these steps for initial configuration of file-based log shipping: 1. Identify your archive location and ensure that it has sufficient space. This recipe assumes that the archive is a directory on the standby node, identified by the `$PGARCHIVE` environment variable. This is set on both the master and standby nodes, as the master must write to the archive and the standby must read from it. The standby node is identified on the master using `$STANDBYNODE`. 2. Configure replication security. Perform a key exchange to allow the master and the standby to run the `rsync` command in either direction. 3. Adjust the master's parameters in `postgresql.conf`, as follows: **wal_level = 'archive'** **archive_mode = on** **archive_command = 'scp %p $STANDBYNODE:$PGARCHIVE/%f'** **archive_timeout = 30** 4. Adjust Hot Standby parameters if required (see the _Hot Standby and read scalability_ recipe). 5. Take a base backup, very similar to the process for taking a physical backup described in Chapter 11, _Backup and Recovery_. 6. Start the backup by running the following command: **psql -c "select pg_start_backup('base backup for log shipping')"** 7. Copy the data files (excluding the `pg_wal` directory). Note that this requires some security configuration to ensure that `rsync` can be executed without needing to provide a password when it executes. If you skipped step _2_ , do this now, as follows: **rsync -cva --inplace --exclude=*pg_wal* \ ${PGDATA}/ $STANDBYNODE:$PGDATA** 8. Stop the backup by running the following command: **psql -c "select pg_stop_backup(), current_timestamp"** 9. Set the `recovery.conf` parameters in the `data` directory on the `standby` server, as follows: **standby_mode = 'on'** **restore_command = 'cp $PGARCHIVE/%f %p' archive_cleanup_command = 'pg_archivecleanup $PGARCHIVE %r' trigger_file = '/tmp/postgresql.trigger.5432'** 10. Start the `standby` server. 11. Carefully monitor the replication delay until the catch-up period is over. During the initial catch-up period, the replication delay will be much higher than we would normally expect it to be. You are advised to set `hot_standby` to `off` for the initial period only. Use a script; don't do this by hand, even when testing or just exploring the capabilities. If you make a mistake, you'd want to rerun things from the start again, and doing things manually is both laborious and an extra source of error. # How it works... Transaction log (WAL) files will be written on the master. Setting `wal_level` to `archive` ensures that we collect all of the changed data, and that WAL is never optimized away. WAL is sent from the master to the archive using `archive_command`, and from there, the standby reads WAL files using `restore_command`. Then, it replays the changes. The `archive_command` is executed when a file becomes full, or an `archive_timeout` number of seconds have passed since any user inserted change data into the transaction log. If the server does not write any new transaction log data for an extended period, then files will switch every `checkpoint_timeout` seconds. This is normal, and not a problem. The preceding configuration assumes that the archive is on the standby, so the `restore_command` shown is a simple copy command (`cp`). If the archive were on a third system, then we would need to either mount the filesystem remotely or use a network copy command. The `archive_cleanup_command` ensures that the archive only holds the files that the standby needs for restarting, in case it stops for any reason. Files older than the last file required are deleted regularly to ensure that the archive does not overflow. Note that if the standby is down for an extended period, then the number of files in the archive will continue to accumulate, and eventually they will overflow. The number of files in the archive should also be monitored. In the configuration shown in this recipe, a command named `pg_archivecleanup` is used to remove files from the archive. (This used to be a contrib module but is now part of the main server). The `pg_archivecleanup` module is designed to work with one standby node at a time. Note that `pg_archivecleanup` requires two parameters: the `archive` directory and `%r`, with a space between them. PostgreSQL transforms `%r` into the cut-off filename. If you wish to have multiple standby nodes, then a shared archive would be a single point of failure and should be avoided, so each standby should maintain its own archive. We must modify the `archive_command` to be a script, rather than execute the command directly. This allows us to handle archiving to multiple destinations: **archive_command = 'myarchivescript %p %f'** Then, we can write `myarchivescript` so that it looks something like the following, though you'll need to add suitable error checking for your environment: **scp $1 $STANDBYNODE1:$PGARCHIVE/$2** **scp $1 $STANDBYNODE2:$PGARCHIVE/$2** **scp $1 $STANDBYNODE3:$PGARCHIVE/$2** The initial copy, or base backup, is performed using the `rsync` utility, which may require you to have direct security authorization, for example, using SSH and key exchange. You may also choose to perform the base backup a different way. If so, feel free to substitute your preferred method. # There's more... Monitoring file-based log shipping can be performed in a number of ways. You can look at the current files on both the `master` and `standby`, as follows: **ps -ef | grep archiver on master** **postgres: archiver process last was 000000010000000000000040** **ps -ef | grep startup on standby** **postgres: startup process waiting for 000000010000000000000041** This allows you to see the replication delay in terms of the number of WAL files by which the `standby` is behind the `master`. Prior to PostgreSQL 9.0, it was difficult to measure the replication delay as a time interval with any accuracy, and some hackish methods were needed. Those aren't presented here. The latest ways of monitoring replication are covered in more detail in the _Monitoring replication_ recipe. # See also * If you have configuration instructions written for versions ranging from PostgreSQL 8.2 to 8.4, then they will work almost exactly the same from PostgreSQL 9.0 onwards. The only difference is that you will also need to specify `wal_level`, as just shown. * Note that the procedures covered here are not the default configuration, and they do differ from earlier releases. In PostgreSQL 9.0, the `pg_standby` utility is no longer required, as many of its features are now performed directly by the server. * If you prefer to continue using `pg_standby` with PostgreSQL 9.0, then you do not need to use the `archive_cleanup_command`, `standby_mode`, or `trigger_file` parameters at all. # Setting up streaming replication Log shipping is a replication technique used by many database management systems. The master records change in its transaction log (WAL), and then the log data is shipped from the master to the standby, where the log is replayed. In PostgreSQL, PSR transfers WAL data directly from the master to the standby, giving us integrated security and reduced replication delay. There are two main ways to set up streaming replication: with or without an additional archive. Setting it up without an external archive is presented here, as it is the more simple and efficient way. However, there is one downside that suggests that the simple approach may not be appropriate for larger databases, which is explained later in the recipe. # Getting ready If you haven't read the _Replication concepts_ section and the _Replication best_ _practices_ recipes at the start of this chapter, go and read them now. Note that streaming replication refers to the master node as the primary node, and the two terms can be used interchangeably. # How to do it... You can use the following procedure for base backups: 1. Identify your master and standby nodes, and ensure that they have been configured according to the _Replication best practices_ recipe. 2. Configure replication security. Create or confirm the existence of the replication user on the master node: **CREATE USER repuser** **REPLICATION** **LOGIN** **CONNECTION LIMIT 2** **ENCRYPTED PASSWORD 'changeme';** 3. Allow the replication user to authenticate. The following example allows access from any IP address using MD5-encrypted password authentication; you may wish to consider other options. Add the following line to `pg_hba.conf`: **host replication repuser 0.0.0.1/0 md5** 4. Set the logging options in `postgresql.conf` on both the master and the standby so that you can get more information regarding replication connection attempts and associated failures: **log_connections = on** 5. Set `max_wal_senders` on the master in `postgresql.conf`, or increase it if the value is already nonzero: **max_wal_senders = 2** **wal_level = 'archive'** **archive_mode = on** **archive_command = 'cd .'** 6. Adjust the Hot Standby parameters if required (see later recipe). 7. Create replication slot, if needed (see later recipe). 8. Take a base backup: **pg_basebackup -d 'connection string' -D /path/to_data_dir** 9. You are advised to use the following additional option on the `pg_basebackup` command line. This option allows the required WAL files to be streamed alongside the base backup on a second session, greatly improving the startup time on larger databases, without the need to fuss over large settings of `wal_keep_segments` (as seen in step _6_ ): **--wal-method=stream** 10. If the backup uses too many server resources (CPU, memory, disk, or bandwidth), you can throttle down the speed for the backup using the following additional option on the `pg_basebackup` command line. The `RATE` value is specified in kb/s by default: **--max-rate=RATE** 11. If you are using replication slots, specify the slot name: **--slot=myslotname** 12. Set the `recovery.conf` parameters on the standby. Note that `primary_conninfo` must not specify a database name, though it can contain any other PostgreSQL connection option. Note also that all options in `recovery.conf` are enclosed in quotes, whereas the `postgresql.conf` parameters need not be. For PostgreSQL 9.4 and later versions, you can skip this step if you wish by specifying the `--write-recovery-conf` option on `pg_basebackup`: **standby_mode = 'on'** **primary_conninfo = 'host=192.168.0.1 user=repuser'** **# trigger_file = '' # no need for trigger file 9.1+** 13. Start the standby server. 14. Carefully monitor the replication delay until the catch-up period is over. During the initial catch-up period, the replication delay will be much higher than we would normally expect it to be. The `pg_basebackup` utility also allows you to produce a compressed TAR file, using this command: **pg_basebackup -F -z** An alternate procedure can be used if needed or desirable: 1. First, perform steps _1_ to _5_ of the preceding procedure. 2. Use `wal_keep_segments`, or use replication slots (see later recipe). 3. Adjust `wal_keep_segments` on the master in `postgresql.conf`. Set this to a value no higher than the amount of free space on the drive on which the `pg_wal` directory is mounted, divided by 16 MB (note: this value is configurable from PG 10+). 4. If `pg_wal` isn't mounted on a separate drive, then don't assume that all of the current free space is available for transaction log files: `wal_keep_segments = 10000 # 160 GB` 5. Adjust the Hot Standby parameters if required (see the _Hot Standby and read scalability_ recipe). Take a base backup, very similar to the process for taking a physical backup, as described in Chapter 11, _Backup and Recovery_. 6. Start the backup: **psql -c "select pg_start_backup('base backup for streaming rep')"** 7. Copy the data files (excluding the `pg_wal` directory): **rsync -cva --inplace --exclude=*pg_wal* \ ** **${PGDATA}/ $STANDBYNODE:$PGDATA** 8. Stop the backup: **psql -c "select pg_stop_backup(), current_timestamp"** 9. Set the `recovery.conf` parameters on the standby. Note that `primary_conninfo` must not specify a database name, though it can contain any other PostgreSQL connection option. Note also that all options in `recovery.conf` are enclosed in quotes, whereas the `postgresql.conf` parameters need not be: **standby_mode = 'on'** **primary_conninfo = 'host=alpha user=repuser'** **trigger_file = '/tmp/postgresql.trigger.5432'** 9. Start the standby server. 10. Carefully monitor the replication delay until the catch-up period is over. During the initial catch-up period, the replication delay will be much higher than we would normally expect it to be. # How it works... Multiple standby nodes can connect to a single master. Set `max_wal_senders` to the number of standby nodes, plus at least one. If you are planning to use `pg_basebackup -wal-method=stream`, then allow for an additional connection per concurrent backup you plan for. You may wish to set up an individual user for each standby node, though it may be sufficient just to set the `application_name` parameter in `primary_conninfo`. The architecture for streaming replication is this: on the master, one `WALSender` process is created for each standby that connects for streaming replication. On the standby node, a `WALReceiver` process is created to work cooperatively with the master. Data transfer has been designed and measured to be very efficient-data is typically sent in 8,192-byte chunks, without additional buffering at the network layer. Both `WALSender` and `WALReceiver` will work continuously on any outstanding data to be replicated until the queue is empty. If there is a quiet period, then `WALReceiver` will sleep for a while. The standby connects to the master using native PostgreSQL libpq connections. This means that all forms of authentication and security work for replication just as they do for normal connections. Note that, for replication sessions, the standby is the client and the master is the server, if any parameters need to be configured. Using standard PostgreSQL libpq connections also means that normal network port numbers are used, so no additional firewall rules are required. You should also note that if the connections use SSL, then encryption costs will slightly increase the replication delay and the CPU resources required. # There's more... If the connection between the master and standby drops, it will take some time for that to be noticed across an indirect network. To ensure that a dropped connection is noticed as soon as possible, you may wish to adjust the timeout settings. The standby will notice that the connection to the master has dropped after `wal_receiver_timeout` milliseconds. Once the connection is dropped the standby will retry the connection to the sending server every `wal_retrieve_retry_interval` milliseconds. Set these parameters in the `postgresql.conf` file on the standby. A sending server will notice that the connection has dropped after `wal_sender_timeout` milliseconds, set in the `postgresql.conf` file on the sender. Once the connection is dropped the standby is responsible for re-establishing the connection. You may also wish to increase `max_wal_senders` to one or two more than the current number of nodes so that it will be possible to reconnect even before a dropped connection is noted. This allows a manual restart to re-establish connections more easily. If you do this, then also increase the connection limit for the replication user. Changing that setting requires a restart. Data transfer may stop if the connection drops or the standby server or the standby system is shut down. If replication data transfer stops for any reason, it will attempt to restart from the point of the last transfer. Will that data still be available? Let's see. For streaming replication, the master keeps a number of files that is at least equal to `wal_keep_segments`. If the standby database server has been down for long enough, the master will have moved on and will no longer have the data for the last point of transfer. If that should occur, then the standby needs to be reconfigured using the same procedure with which we started. You should plan to use `pg_basebackup --wal-method=stream`. If you choose not to, you should note that the standby database server will not be streaming during the initial base backup. So, if the base backup is long enough, we might end up with a situation where replication will never start because the desired starting point is no longer available on the master. This is the error that you'll get: **FATAL: requested WAL segment 000000010000000000000002 has already been removed** It's very annoying, and there's no way out of it—you need to start over. So start with a very high value of `wal_keep_segments`. Don't guess this randomly; set it to the available disk space on `pg_wal` divided by 16 MB, or less if it is a shared disk. If you still get that error, then you need to increase `wal_keep_segments` and try again, possibly also using techniques to speed up the base backup, which are discussed in Chapter 11, _Backup and Recovery_. If you can't set `wal_keep_segments` high enough, there is an alternative. You must configure a third server or storage pool with increased disk storage capacity, which you can use as an archive. The master will need to have an `archive_command` that places files on the archive server, rather than the dummy command shown in the preceding procedure, in addition to parameter settings to allow streaming to take place. The standby will need to retrieve files from the archive using `restore_command`, as well as streaming using `primary_conninfo`. Thus, both the master and standby have two modes for sending and receiving, and they can switch between them should failures occur. This is the typical configuration for large databases. Note that this means that the WAL data will be copied twice, once to the archive and once directly to the standby. Two copies are more expensive, but also more robust. # Setting up streaming replication security Streaming replication is at least as secure as normal user connections to PostgreSQL. Replication uses standard libpq connections, so we have all the normal mechanisms for authentication and SSL support, and all the firewall rules are similar. Replication must be specifically enabled on both the sender and standby sides. Cascading replication does not require any additional security. When performing a base backup, the `pg_basebackup`, `pg_receivewal`, and `pg_recvlogical` utilities will use the same type of libpq connections as a running streaming standby. You can use other forms of base backup, such as `rsync`, though you'll need to manually set up the security configuration. Standbys are identical copies of the master, so all users exist on all nodes with identical passwords. All of the data is identical (eventually) and all the permissions are the same too. If you wish to control access more closely, then you'll need different `pg_hba.conf` rules on each server to control this. Obviously, if your config files differ between nodes, then failover will be slightly more dramatic, unless you've given that some prior thought. # Getting ready Identify or create a user/role to be used solely for replication. Decide what form of authentication will be used. If you are going across data centers or the wider internet, take this very seriously. # How to do it... On the master, perform these steps: 1. Enable replication by setting a specific host access rule in `pg_hba.conf.` 2. Give the selected replication user/role the `REPLICATION` and `LOGIN` attributes: **ALTER ROLE replogin REPLICATION;** 3. Alternatively, create it using this command: **CREATE ROLE replogin REPLICATION LOGIN;** On the standby, perform these steps: 1. Request replication by setting `primary_conninfo` in `recovery.conf` 2. If you are using SSL connections, use `sslmode=verify-full` 3. Enable per-server rules, if any, for this server in `pg_hba.conf.` # How it works... Streaming replication connects to a virtual database called `replication`. We do this because the WAL data contains changes to objects in all databases, so in a way, we aren't just connecting to one database—we are connecting to all of them. Streaming replication connects similar to a normal user, except that instead of a normal user process, we are given a `WALSender` process. You can set a connection limit on the number of replication connections in two ways: * At the role level by issuing the following command: **ALTER ROLE replogin CONNECTION LIMIT 2;** * By limiting the overall number of `WALSender` processes via the `max_wal_senders` parameter Always allow one more connection than you think is required, to allow for disconnections and reconnections. # There's more... You may notice that the `WALSender` process may hit 100 percent CPU if you use SSL with compression enabled and write lots of data, or generate a large WAL volume from things such as DDL or vacuuming. You can disable compression on fast networks when you aren't paying per bandwidth charges, using `sslcompression=0` in the connection string specified for `primary_conninfo`. # Hot Standby and read scalability Hot Standby (or read replicas) is the name for the PostgreSQL feature that allows us to connect to a standby node and execute read-only queries. Most importantly, Hot Standby allows us to run queries while the standby is being continuously updated through either file-based or streaming replication. Hot Standby allows you to offload large or long running queries or parts of your read-only workload to the standby nodes. Should you need to switchover or failover to the standby node, your queries will keep executing during the promotion process to avoid any interruption of service. You can add additional Hot Standby nodes to scale the read-only workload. There is no hard limit on the number of standby nodes, as long as you ensure enough server resources are available and parameters are set correctly – 10, 20, or more nodes are easily possible. There are two main capabilities provided by a Hot Standby node. The first is that the standby node provides a secondary node in case the primary node fails. The second capability is that we can run queries on that node. In some cases, these two aspects can come into conflict with each other and can result in queries being cancelled. We need to decide ahead of time the importance we attach to each capability so that we can prioritize between them. In most cases, the role of standby will take priority. Queries are good, but it's OK to cancel them to ensure that we have a viable standby. If we have more than one Hot Standby node, it may be possible to have one node nominated as standby and others dedicated to serving queries, without any regard for their need to act as standbys. Standby nodes are started and stopped using the same server commands as master servers, which were covered in earlier chapters. # Getting ready Hot Standby is usable with the following: * File-based replication * Streaming replication * While performing a point-in-time recovery * When using a permanently frozen standby For the first two replication mechanisms, you will need to configure replication as described in earlier recipes. In addition, you will need to configure the following parameters: On the master, set the following in `postgresql.conf`: **wal_level = 'replica' # PostgreSQL 9.6 and above, else hot_standby** On the standby, set the following in `postgresql.conf`: **hot_standby = on** Both of those settings are now the default in PostgreSQL 10. In earlier versions you will need to make these changes. You will need to do a clean restart of the database server on the master. Then, wait a few seconds and restart the standby for those changes to take effect. If you restart the standby too quickly, it will still keep reading the older transaction log data and fail to start. It will give a log message saying you need to enable Hot Standby, so be patient. You only need to configure this once, not every time you restart. See the _Delaying, pausing, and synchronizing replication_ recipe to work out how to wait for actions on the master to arrive on the standby. A permanently frozen standby can be created by specific settings in the `recovery.conf` file. Neither `restore_command` nor `primary_conninfo` should be set, in the case of `standby_mode = on`. In this mode, the server will start, but will always remain at the exact state of the database as it was when the `pg_stop_backup()` function completed. Another point to note is that during the initial catch-up period, the replication delay will be much higher than we would normally expect it to be. You are advised to set `hot_standby = off` for the initial period immediately following the creation of the standby only. User connections during that initial period may use system resources or cause conflicts that could extend the catch-up delay. When the standby is fully caught up with the primary, then we can set `hot_standby = on` and restart, or simply prevent user access via `pg_hba.conf` until the standby catches up. # How to do it... On the standby node, changes from the master are read from the transaction log and applied to the standby database. Hot Standby works by emulating running transactions from the master so that queries on the standby have the visibility information they need to fully respect MVCC. This makes the Hot Standby mode particularly suitable for serving a large workload of short or fast `SELECT` queries. If the workload is consistently short, then few conflicts will delay the standby, and the server will run smoothly. Queries that run on the standby node see a version of the database that is slightly behind the primary node. We describe this as eventually consistent. _How long is eventually?_ That time is exactly the replication delay plus the apply delay, as discussed in the _Replication concepts_ section. You may also request that standby servers delay applying changes. See the _Delaying, pausing, and synchronizing replication_ recipe later on in this section. Resource contention (CPU, I/O, and so on) may increase apply delay. If the server is busy applying changes from the master, then you will have fewer resources to use for queries. This means that if there are no changes arriving, then you'll get more query throughput. If there are predictable changes in the write workload on the master, then you may need to throttle back your query workload on the standby when they occur. Replication apply may also generate conflicts with running queries. Conflict may cause the replay to pause, and eventually queries on the standby may be canceled or disconnected. There are three main types of conflicts that can occur between the master and queries on the standby, which are as follows: * Locks such as Access Exclusive locks * Cleanup records * Other special cases If cancellations do occur, they will throw either error or fatal-level errors. These will be marked with `SQLSTATE 40001 SERIALIZATION FAILURE`. This could be trapped by an application, and the SQL can be resubmitted. You can monitor the number of conflicts that occur in two places. The total number of conflicts in each database can be seen using this query: **SELECT datname, conflicts FROM pg_stat_database;** You can drill down further to look at the types of conflict seen using the following query: **SELECT datname ,confl_tablespace ,confl_lock ,confl_snapshot ,confl_bufferpin ,confl_deadlock FROM pg_stat_database_conflicts;** Tablespace conflicts are the easiest to understand. If you try to drop a tablespace that someone is still using, then you're going to get a conflict. Don't do that! Lock conflicts are also easy to understand. If you wish to run a command on the master, such as `ALTER TABLE ... DROP COLUMN`, then you must lock the table first to prevent all types of access. The lock request is sent to the standby server as well, which will then cancel standby queries that are currently accessing that table after a configurable delay. On high-availability systems, making DDL changes to tables that cause long periods of locking on the master can be difficult. You may want the tables on the standby to stay available for reads during the period in which the changes are being made on the master. To do that, temporarily set these parameters on the standby: `max_standby_streaming delay = -1` and `max_standby_archive_delay = -1`. Then, reload the server. As soon as the first lock record is seen on the standby, all further changes will be held. Once the locks on the master are released, you can reset the original parameter values on the standby, which will then allow the changes to be made there. Setting the `max_standby_streaming_delay` and `max_standby_archive_delay` parameters to `-1` is very timid and may not be useful for normal running if the standby is intended to provide High Availability. No user query will ever be canceled if it conflicts with applying changes. It will cause the apply process to wait indefinitely. As a result, the apply delay can increase significantly over time, depending on the frequency and duration of queries and the frequency of conflicts. To work out an appropriate setting for these parameters, you need to understand more about the other types of conflict, though there is also a simple way to avoid this problem entirely. Snapshot conflicts require some understanding of the internal workings of MVCC, which many people find confusing. To avoid snapshot conflicts, you should set `hot_standby_feedback = on` in the standby's `postgresql.conf` file. In some cases, this could cause table bloat on the master, so it is not set by default. If you don't wish to set `hot_standby_feedback = on`, then you have further options to consider. You can set an upper limit on the acceptable apply delay caused by conflicts by controlling two similar parameters: `max_standby_streaming_delay` and `max_standby_archive_delay`. As a last resort, you can also provide some protection against cancelled queries by setting `vacuum_defer_cleanup_age` to a value higher than `0`. This parameter is fairly hard to set accurately, though I would suggest starting with a value of `1000` and then tune upwards. A vague and inaccurate assumption would be to say that each `1000` will be approximately one second of additional delay. This is probably helpful more often than it is wrong. Other conflict types (bufferpin, deadlocks, and so on) are possible, but they are rare. If you want a completely static standby database with no further changes applied, then you can do this by stopping the server, modifying `recovery.conf` such that neither `restore_command` nor `primary_conninfo` are set but `standby_mode` is on, and then restarting the server. You can come back out of this mode, but only if the archive contains the required WAL files to catch up. Otherwise, you will need to reconfigure the standby from a base backup again. If you attempt to run a non-read-only query, then you will receive an error marked with `SQLSTATE 25006 READ ONLY TRANSACTION`. That could be used to redirect SQL to the master, where it can execute successfully. # How it works... Changes made by a transaction on the master will not be visible until the commit is applied onto the standby. So, for example, we have a master and a standby with a replication delay of four seconds between them. A long-running transaction may write changes to the master for one hour. How long does it take before those changes are visible on the standby? With Hot Standby, the answer is four seconds after the commit on the master. This is because the changes made during the transaction on the master are streamed while the transaction is still in progress, and in most cases, they are already applied on the standby when the commit record arrives. You may also wish to use the `remote_apply` mode; see the _Delaying, pausing, and synchronizing replication_ recipe later on this section. Hot Standby can also be used when running a point-in-time recovery, so the WAL records applied to the database need not arrive immediately from a live database server. We can just use file-based recovery in that case, not streaming replication. Finally, query performance has been dramatically improved in Hot Standby over time, so it's a good idea to upgrade for that reason alone. # Managing streaming replication Replication is great, provided that it works. Replication works well if it's understood and works even better if it's tested. # Getting ready You need to have a plan for the objectives for each individual server in the cluster. _Which standby server will be the failover target?_ # How to do it... Switchover is a controlled switch from the master to the standby. If performed correctly, there will be no data loss. To be safe, simply shut down the master node cleanly, using either the `smart` or `fast` shutdown modes. Do not use the `immediate` mode shutdown because you will almost certainly lose data that way. Failover is a forced switch from the master node to a standby because of the loss of the master. So, in that case, there is no action to perform on the master; we presume it is not there anymore. Next, we need to promote one of the standby nodes to be the new master. A standby node can be triggered into becoming a master node in one of two ways: * `pg_ctl promote` * Suppose you originally specified a `trigger_file` parameter like this: **trigger_file = '/tmp/postgresql.trigger.5432'** Then, you can create the `trigger` file by executing this: **touch /tmp/postgresql.trigger.5432** The `trigger_file` will be deleted when the transition is complete. Note that the `trigger` file has nothing to do whatsoever with trigger-based replication. The `trigger` filename can be anything you like. We use a suffix of `5432` to ensure that we trigger only one server if there are multiple PostgreSQL servers operating on the same system. The standby will become the master only once it has fully caught up. If you haven't been monitoring replication, this could take some time. In versions before PostgreSQL 9.3, switching from standby to master may take some time while the database performs an immediate checkpoint, at least with database servers with large caches and high rate of changes being replicated from the master. From PostgreSQL 9.3 onwards, we can switch from the standby to the master very quickly, and then perform a smooth background checkpoint. There may still be significant I/O as writes begin on the new master. Once the ex-standby becomes a master, it will begin to operate all normal functions, including starting to archive files if configured. Be careful to verify that you have all the correct settings for when this node begins to operate as a master. It is likely that the settings will be different from those on the original master from which they were copied. Note that I refer to this new server as **a master** , not **the master**. It is up to you to ensure that the previous master doesn't continue to operate a situation known as **split-brain**. You must be careful to ensure that the previous master stays down. Management of complex failover situations is not provided with PostgreSQL, nor is automated failover. Situations can be quite complex with multiple nodes, and clusterware is used in many cases to manage this. The role of the `recovery_end_command` is to clean up at the end of the switchover or failover process. You do not need to explicitly remove the `trigger` file, as was recommended in previous releases. # There's more... Following a switchover from one node to another, it is common to think of performing a switchover back to the old master server, which is sometimes called failback or switchback. Once a standby has become a master, it cannot go back to being a standby again. So, with log replication, there is no explicit switchback operation. This is a surprising situation for many people and is a repeated question, but it is quick to work around. Once you have performed a switchover, all you need to do is the following: * Reconfigure the old master node again, repeating the same process as before to set up a standby node * Switchover from the current to the old master node The important part here is that if we perform the first step without deleting the files on the old master, it allows `rsync` to go much faster. When no files are present on the destination, `rsync` just performs a copy. When similarly named files are present on the destination, then `rsync` will compare the files and send only the changes. So, the `rsync` we perform on a switchback operation performs much less data transfer than in the original copy. It is likely that this will be enhanced in later releases of PostgreSQL. There are also ways to avoid this, as shown in the `repmgr` utility, which will be discussed later. The `pg_rewind` utility has been developed as a way to perform an automated switchback operation. It performs a much faster switchback when there is a large database with few changes to apply. To allow correct operation, this program must run using the `wal_log_hints = on` parameter. Using that parameter can cause more I/O on large databases, so while it improves performance for switchback it has a considerable overhead for normal running. If you think you would like to run `pg_rewind`, then make sure you work out how it behaves ahead of time. Trying to run it for the first time in a stress situation with a down server is a bad idea. # See also Clusterware may provide additional features, such as automated failover, monitoring, or ease of management of replication: * The `repmgr` utility is designed to manage PostgreSQL replication and failover. This is discussed in more detail in the _Using repmgr_ recipe. * The `pgpool` library is designed to allow session pooling and routing of requests to standby nodes. # Using repmgr As said before, replication is great provided it works. It works well if it's understood and works even better if it's tested. This is a great reason to use `repmgr` utility. `repmgr` 4.0 is an open source tool designed specifically for PostgreSQL replication. To get additional information about repmgr, visit http://www.repmgr.org/. The `repmgr` utility provides a command-line interface and a management process (daemon) used to monitor and manage PostgreSQL servers involved in replication. The `repmgr` utility easily supports more than two nodes, with automatic failover detection. # Getting ready Install `repmgr` utility from binary packages on each PostgreSQL node. Set up replication security and network access between nodes according to the _Setting up streaming replication security_ recipe. # How to do it... The `repmgr` utility provides a set of single command-line actions that perform all the required activities on one node: 1. To start a new cluster with `repmgr` with the current node as its primary, use the following command: **repmgr primary register** 2. To add an existing standby to the cluster with `repmgr`, use the following command: **repmgr standby register** 3. Use the following command to request `repmgr` to create a new standby for you by copying `node1`. This will fail if you specify an existing `data` directory: **repmgr standby clone node1 -D /path/of_new_data_directory ** 4. To reuse an old master as a standby, use the `rejoin` command: **repmgr node rejoin -d 'host=node2 user=repmgr'** 5. To switch from one primary to another one, run this command on the `standby` which you want to make a primary: **repmgr standby switchover** 6. To promote a `standby` to be the new primary, use the following command: **repmgr standby promote** 6. To request a `standby` to follow a new primary, use the following command: **repmgr standby follow** 7. Check the status of each registered node in the cluster, like this: **repmgr cluster show** 8. Request cleanup of monitoring data, as follows. This is relevant only if `--monitoring-history` is used: **repmgr cluster cleanup** 9. Create a `witness` server for use with auto-failover voting, like this: **repmgr witness create** The preceding commands are presented in a simplified form. Each command also takes one of these options: * `--verbose`: This is useful when exploring new features * `-f`: This specifies the path to the `repmgr.conf` file For each node, create a `repmgr.conf` file containing at least the following parameters. Note that the `node_id` and `node_name` parameters need to be different on each node: **node_id=2** **node_name=beta** **conninfo='host=beta user=repmgr'** **data_directory=/var/lib/pgsql/10/data** Once all the nodes are registered, you can start the `repmgr` daemon on each node, like this: **repmgrd -d -f /var/lib/pgsql/repmgr/repmgr.conf &** If you would like the daemon to generate monitoring information for that node, you should set `monitoring_history=yes` in the `repmgr.conf` file. Monitoring data can be accessed using this: **repmgr=# select * from repmgr.replication_status; ** **-[ RECORD 1 ]-------------+------------------------------** **primary_node_id | 1** **standby_node_id | 2 standby_name | node2 node_type | standby active | t** **last_monitor_time | 2017-08-24 16:28:41.260478+09** **last_wal_primary_ location | 0/6D57A00** **last_wal_standby_ location | 0/5000000 ** **replication_lag | 29 MB ** **replication_time_lag | 00:00:11.736163 ** **apply_lag | 15 MB** **communication_time_lag | 00:00:01.365643** # How it works... repmgr 4 works with PostgreSQL 9.3+ and PostgreSQL 10 and later versions. repmgr supports the latest features of PostgreSQL, such as cascading, synchronous replication, and replication slots. It uses `pg_basebackup`, allowing you to clone from a standby. The use of `pg_basebackup` also removes the need for `rsync` and key exchange between servers. Also, cascaded standby nodes no longer need to re-follow. # There's more... The default behavior for `repmgr` utility is manual failover. The `repmgr` utility also supports automatic failover capabilities. It can automatically detect failures of other nodes and then decide which server should become the new master by voting among all of the still available standby nodes. The `repmgr` utility supports a witness server to ensure that there are an odd number of voters in order to get a clear winner in any decision. # Using replication slots Replication slots allow you to define your replication architecture explicitly. They also allow you to track details of nodes even when they are disconnected. Replication slots work with both PSR and LSR. Replication slots ensure that data required by a downstream node persists until the node receives it. They are crash-safe, so if a connection is lost, the slot still continues to exist. By tracking data on downstream nodes, we avoid these problems: * When a standby disconnects, the feedback data provided by `hot_standby_feedback` is lost. When the standby reconnects, it may be sent cleanup records that result in query conflicts. Replication slots remember the standby's `xmin` value even when disconnected, ensuring that cleanup conflicts can be avoided. * When a standby disconnects, the knowledge of which WAL files were required is lost. When the standby reconnects, we may have discarded the required WAL files, requiring us to completely regenerate the downstream node (assuming that this is possible). Replication slots ensure that nodes retain the WAL files needed by all downstream nodes. Replication slots are required by LSR and for any other use of logical decoding. Replication slots are optional with PSR. # Getting ready This recipe assumes that you have already set up replication according to the earlier recipes so that `wal_level`, `max_wal_senders`, and other parameters are set. A replication slot represents one link between two nodes. At any time, each slot can support one connection. If you draw a diagram of your replication architecture, then each connecting line is one slot. Each slot must have a unique name. The slot name must contain only lowercase letters, numbers, and underscores. As discussed previously, each node should have a unique name. So a suggestion would be to construct the slot name from the two node names that it links. For various reasons, there may be a need for multiple slots between two nodes, so additional information is also required for uniqueness. For two servers called `alpha` and `beta`, an example of a slot name would be `alpha_beta_1`. For LSR, each slot refers to a single database rather than the whole server. In that case, slot names could also include database names. # How to do it... 1. Set `max_replication_slots > 0` on each sending node. This change requires a restart. Set the value to at least one more than the number of planned slots: **max_replication_slots = 2** 2. For PSR slots, you have to first create the slot on the sending node, like this: **SELECT (pg_create_physical_replication_slot ('alpha_beta_1', true)).wal_position;** ** wal_position** **-----------------** **0/5000060** 3. Monitor it in use by using the following: **SELECT * FROM pg_replication_slots;** 4. In the `recovery.conf` file in the `data` directory on the standby, set the `primary_slot_name` parameter using the unique name that you assigned earlier: **primary_slot_name = 'alpha_beta_1'** Slots can be removed using the following query: **SELECT pg_drop_physical_replication_slot('alpha_beta_1');** # There's more... Replication slots can be used to support applications where downstream nodes are disconnected for extended periods of time. Replication slots prevent removal of WAL files, which are needed by disconnected nodes. Therefore, it is important to be careful that WAL files don't build up, causing _out of disk space_ errors due to physical replication slots created with no currently connected standby. # See also * See the _Logical replication_ recipe for more details on using slots with LSR # Monitoring replication Monitoring the status and progress of your replication is essential. We'll start by looking at the server status and then query the progress of replication. # Getting ready You'll need to start by checking the state of your server(s). Check whether a server is up using `pg_isready` or another program that uses the `PQping()` API call. You'll get one of the following responses: * `PQPING_OK (return code 0)`: The server is running and appears to be accepting connections. * `PQPING_REJECT (return code 1)`: The server is running, but is in a state that disallows connections (startup, shutdown, or crash recovery) or a standby that is not enabled with Hot Standby. * `PQPING_NO_RESPONSE (return code 2)`: The server could not be contacted. This might indicate that the server is not running, there is something wrong with the given connection parameters (for example, wrong port number), or there is a network connectivity problem (for example, a firewall blocking the connection request). * `PQPING_NO_ATTEMPT (return code 3)`: No attempt was made to contact the server, for example, invalid parameters. We don't differentiate between a master and a standby, though this may change in later releases. Neither do we say whether a server is accepting write transactions or only read-only transactions (a standby or a master connection in read-only mode). You can know whether a server is a master or a standby by connecting and executing this query: **SELECT pg_is_in_recovery();** There are also two other states that may be important for backup and replication: paused and in-exclusive-backup. The paused state doesn't affect user queries, but replication will not progress at all when paused. Only one exclusive backup may occur at any one time. You can also check whether replay is paused by executing this query: **SELECT pg_is_wal_replay_paused();** If you want to check whether a server is in-exclusive-backup mode, execute the following query: **SELECT pg_is_in_backup();** There is no supported function that shows whether a non-exclusive backup is in progress, though there isn't as much to worry about if there is. If you care about that, make sure you set the `application_name` of the backup program so that it shows up in the session status output of `pg_stat_activity`, as discussed in Chapter 8, _Monitoring and Diagnosis_. # How to do it... The rest of this recipe assumes that you have enabled `hot_standby`. This is not an absolute requirement, but it makes things much, much easier. Both `repmgr` and `pgpool` provide replication monitoring facilities. Munin plugins are available for graphing replication and apply delay. Replication works by processing the WAL transaction log on other servers. You can think of WAL as a single, serialized stream of messages. Each message in the WAL is identified by an 8-byte integer known as a **Log Sequence Number** ( **LSN** ). For historical reasons, we show this as two separate hex numbers; for example, the LSN value `X` is shown as `XXXX/YYYY`. You can compare any two LSNs using `pg_wal_lsn_diff()`. In some places, prior to PostgreSQL 10, an LSN was referred to as a "location", a term no longer in use. To understand how to monitor progress, you need to understand a little more about replication as a transport mechanism. The stream of messages flows through the system like water through a pipe. You can work out how much progress has been made by measuring the LSN at different points in the pipe. You can also check for blockages in the pipe by measuring the relative progress between points. New WAL records are inserted into the WAL files on the master. The current insert LSN can be found using this query: **SELECT pg_current_wal_insert_lsn();** However, WAL records are not replicated until they have been written and synced to the WAL files on the master. The LSN of the most recent WAL write is given by this query on the master: **SELECT pg_current_wal_lsn();** Once written, WAL records are then sent to the standby. The recent status can be found by running this query on the standby (this and the later functions return `NULL` on a master): **SELECT pg_last_wal_receive_lsn();** Once WAL records have been received, they are written to WAL files on the standby. When the standby has written those records, they can then be applied to it. The LSN of the most recent apply is found using this standby query: **SELECT pg_last_wal_replay_lsn();** Remember that there will always be timing differences if you run status queries on multiple nodes. What we really need is to see all of the information on one node. A view called `pg_stat_replication` provides the information that we need: **SELECT pid, application_name /* or other unique key */** **,pg_current_wal_insert_lsn() /* WAL Insert lsn */** **,sent_lsn /* WALSender lsn */** **,write_lsn /* WALReceiver write lsn */** **,flush_lsn /* WALReceiver flush lsn */** **,replay_lsn /* Standby apply lsn */** **,backend_start /* Backend start */** **FROM pg_stat_replication;** **-[ RECORD 1 ]-------------------+------------------------------ pid | 16496** **application_name | pg_basebackup pg_current_wal_insert_lsn | 0/80000D0** **sent_lsn |** **write_lsn |** **flush_lsn |** **replay_lsn |** **backend_start | 2017-01-27 15:25:42.988149+00** **-[ RECORD 2 ]-------------------+-------------------pid** **16497** **application_name | pg_basebackup pg_current_wal_insert_lsn | 0/80000D0** **sent_lsn | 0/80000D0** **write_lsn | 0/8000000** **flush_lsn | 0/8000000** **replay_lsn |** **backend_start | 2017-01-27 15:25:43.18958+00** Each row in this view represents one replication connection. The preceding snippet shows the output from a `pg_basebackup` that is using `--wal-method=stream`. The first connection shown is the base backup, while the second session is streaming WAL changes. Note that the `replay_lsn` is NULL, indicating that this is not a standby. Standby nodes send regular status messages to let the sender know how far it has progressed. If you run this query on the master, you'll be able to see all the directly connected standbys. If you run this query on a standby, you'll see values representing any cascaded standbys, but nothing about the master or any of the other standbys connected to the master. Note that because the data has been sent from a remote node, it is very likely that processing will have progressed beyond the point being reported, but we don't know that for certain. That's just physics. Welcome to the world of distributed systems! In PostgreSQL 10, replication delay times are provided directly using sampled message timings to provide the most accurate viewpoint of current delay times. Use this query: **SELECT pid, application_name /* or other unique key */** **,write_lag, flush_lag, replay_lag** **FROM pg_stat_replication;** Another view called `pg_stat_wal_receiver` provides information about the standby that we may be interested in; this view returns zero rows on the master. # There's more... The `pg_stat_replication` view shows only the currently connected nodes. If a node is supposed to be connected but it isn't, then there is no record of it at all, anywhere. If you don't have a list of the nodes that are supposed to be connected, then you'll just miss it. Replication slots give you a way to define which connections are supposed to be present. If you have defined a slot and it is currently connected, then you will get one row in `pg_stat_replication` for the connection and one row in `pg_replication_slots` for the corresponding slot. To find out which slots don't have current connections, you can run this query: **SELECT slot_name, database, age(xmin), age(catalog_xmin) FROM pg_replication_slots WHERE NOT active;** To find the details of the currently connected slots, run something like this query: **SELECT slot_name FROM pg_replication_slots JOIN pg_stat_replication ON pid = active_pid;** # Performance and synchronous replication We usually refer to synchronous replication as simply **sync rep**. The sync rep allows us to offer a confirmation to the user that a transaction has been committed and fully replicated on at least one standby server. To do that, we must wait for the transaction changes to be sent to at least one standby, and then have that feedback returned to the master. The additional time taken for the message's round trip will add elapsed time for write transactions, which increases in proportion to the distance between servers. PostgreSQL offers a choice to the user as to what balance they would like between durability and response time. # Getting ready The user application must be connected to a master to issue transactions that write data. The default level of durability is defined by the `synchronous_commit` parameter. That parameter is user settable, so it can be set for different applications, sessions, or even individual transactions. For now, ensure that the user application is using this level: **SET synchronous_commit = on;** We must decide which standbys should take over from the master in the event of a failover. We do this by setting a parameter called `synchronous_standby_names`. You will need to configure at least three nodes to use sync rep correctly. # How to do it... Make sure you have set the `application_name` on each standby node. Decide the order of servers to be listed in the `synchronous_standby_names` parameter. Note that the standbys named must be directly attached standby nodes or else their names will be ignored. Synchronous replication is not possible for cascaded nodes, though cascaded standbys may be connected downstream. An example for a simple four node config of `nodeA` (master), `nodeB`, `nodeC`, and `nodeD` (standbys) would be set on `nodeA` as follows: **synchronous_standby_names = 'nodeB, nodeC, nodeD'** If you want to receive replies from the first two of the nodes in a list then we would specify this using the following special syntax: **synchronous_standby_names = '2 (nodeB, nodeC, nodeD)'** If you want to receive replies from any two nodes, known as quorum commit, then: **synchronous_standby_names = 'any 2 (nodeB, nodeC, nodeD)'** Set `synchronous_standby_names` on all of the nodes, not just the master. You can see the `sync_state` of connected standbys using this query on the master: **SELECT** **application_name ,state /* startup, backup, catchup or streaming */ ,sync_priority /* 0, 1 or more */ ,sync_state /* async, sync or potential */ FROM pg_stat_replication ORDER BY sync_priority;** There are a few columns here with similar names, so be careful not to confuse them. The `sync_state` column is just a human-readable form of `sync_priority`. When `sync_state` is `async`, the `sync_priority` value will be zero (`0`). Standby nodes mentioned in the `synchronous_standby_names` parameter will have a nonzero priority that corresponds to the order in which they are listed. The standby node with a priority of one (`1`) will be listed as having a `sync_state` value of `sync`. We refer to this node as the **sync standby**. Other standby nodes configured to provide feedback are shown with a `sync_state` value of `potential` and a `sync_priority` value more than `1`. If a server is listed in the `synchronous_standby_names` parameter, but is not currently connected, then it will not be shown at all by the preceding query, so it is possible that the node is shown with a lower actual priority value than the stated ordering in the parameter. Setting `wal_receiver_status_interval` to `0` on the standby will disable status messages completely, and the node will show as an `async` node, even if it is named in the `synchronous_standby_names` parameter. You may wish to do this when you are completely certain that a standby will never need to be a failover target, such as a test server. The state for each server is shown as one of `startup`, `catchup`, or `streaming`. When another node connects, it will first show as `startup`, though only briefly before it moves to `catchup`. Once the node has caught up with the master, it will move to `streaming`, and only then will `sync_priority` be set to a nonzero value. Catch-up typically occurs quickly after a disconnection or reconnection, such as when a standby node is restarted. When performing an initial base backup, the server will show as `backup`. After this, it will stay for an extended period at `catchup`. The delay at this point will vary according to the size of the database, so it could be a long period. Bear this in mind when configuring sync rep. When a new standby node moves to the `streaming` mode, you'll see a message like this in the master node log: **LOG standby $APPLICATION_NAME is now the synchronous** **standby with priority N** # How it works... Standby servers send feedback messages that describe the LSN of the latest transaction they have processed. Transactions committing on the master will wait until they receive feedback saying that their transaction has been processed. If there are no standbys available for sending feedback, then the transactions on the master will wait for standbys, possibly for a very long time. That is why we say that you must have at least three servers to sensibly use sync rep. It probably occurs to you that you could run with just two servers. You can, but such a configuration does not offer any transaction guarantees; it just appears to. Many people are confused on that point, but please don't listen to them! Sync rep increases the elapsed time of write transactions (on the master). This can reduce performance of applications from a user perspective. The server itself will spend more time waiting than before, which may increase the required number of concurrently active sessions. Remember that when using sync rep, the overall system is still eventually consistent. Transactions committing on the master are visible first on the standby, and a brief moment later those changes will be visible on the master (yes, standby, and then master). This means that an application that issues a write transaction on the master followed by a read transaction on the sync standby will be guaranteed to see its own changes. You can increase performance somewhat by setting the `synchronous_commit` parameter to `remote_write`, though you will lose data if both master and standby crashes. You can also set the `synchronous_commit` parameter to `remote_apply` when you want to ensure that all changes are committed to the synchronous standbys and the master before we confirm back to the user. However, this is not the same thing as synchronous visibility—the changes become visible on the different standbys at different times. # There's more... There is a small window of uncertainty for any transaction that is in progress just at the point the master goes down. This can be handled within the application by checking the return code following a commit operation, rather than just assuming that it has completed successfully, as developers often do. If the commit fails, it is possible that the server committed the transaction successfully, but was unable to communicate that to the client, but we don't know for certain. We can resolve that uncertainty by rechecking a unique aspect of the transaction, such as reconfirming the existence of an object identifier that was inserted. If such an object identifier doesn't exist, we can create a table for this purpose: **CREATE TABLE TransactionCheck (TxnId SERIAL PRIMARY KEY);** During the transaction, we insert a row into that table using this query: **INSERT INTO TransactionCheck DEFAULT VALUES RETURNING TxnId;** Then, if the commit appears to fail, we can later reread this value to confirm the transaction state as committed or aborted. # Delaying, pausing, and synchronizing replication Some advanced features and thoughts for replication are covered here. # Getting ready If you have multiple standby servers, you may want to have one or more servers operating in a delayed apply state, for example, one hour behind the master. This can be useful to help recover from user errors such as mistaken transactions or dropped tables. # How to do it... Normally, a standby will apply changes as soon as possible. When you set the `recovery_min_apply_delay` parameter in `recovery.conf`, the application of commit records will be delayed by the specified duration. Note that only commit records are delayed, so you may receive Hot Standby cancellations using this feature. You can prevent that by setting `hot_standby_feedback` to `on`, but use this with caution, since it can cause significant bloat on a busy master if `recovery_min_apply_delay` is large. If something bad happens, then hit the pause button. Hot Standby allows you to pause and resume replay of change: 1. To pause the replay, issue this query: **SELECT pg_wal_replay_pause();** Once paused, all queries will receive the same snapshot, allowing lengthy repeated analyses of the database, or retrieval of a dropped table. 2. To resume (un-pause) processing, use this query: **SELECT pg_wal_replay_resume();** Be careful not to promote a delayed standby. If your delayed standby is the last server available, you should reset `recovery_min_apply_delay`, then restart the server, and allow it to catch up before issuing a promote action. # There's more... A standby is an exact copy of the master. But how do you synchronize things so that the query results you get from a standby are guaranteed to be the same as you'd get from the master? Well, that in itself is not possible. It's just the physics of an eventually consistent system. We need it to be eventually consistent because otherwise, the synchronization would become a performance bottleneck. What we can do is synchronize two requests on different servers, for example, if we wish to issue a write on the master and then later issue a read from a standby. Such a case is automatically handled by synchronous replication. If we aren't using sync rep, then we can wait for the standby to catch up with an action on the master, remembering that the master will have moved on by the time we've done this. To perform the wait you need to do the following: 1. On the master, perform an action that writes WAL. Just for testing purposes—not for real usage—we can issue a request like this: **SELECT pg_create_restore_point('my action name')** 2. On the master, commit the transaction using `commit`; with any setting other than ``synchronous_commit = off`` 3. On the master, find the current write LSN using this query: **SELECT pg_current_wal_write_lsn();** 4. On the standby, execute the following query repeatedly until the LSN value returned is equal to or higher than the LSN from the master: **SELECT pg_last_wal_replay_lsn();** The following function performs such a wait: **CREATE OR REPLACE FUNCTION wait_for_lsn(lsn pg_lsn)** **RETURNS VOID** **LANGUAGE plpgsql** **AS $$** **BEGIN** **LOOP** **IF pg_last_wal_replay_lsn() IS NULL OR** **pg_last_wal_replay_lsn() >= lsn THEN** **RETURN;** **END IF;** **PERFORM pg_sleep(0.1); /* 100ms */** **END LOOP;** **END $$;** This isn't ideal since it can be cancelled while waiting. Later releases may contain better solutions. # See also * Logical replication allows us to control the flow of data in various ways. For `pglogical` use these commands: **SELECT alter_subscription_disable(); SELECT alter_subscription_enable();** * We can also create a subscription with a parameter of `apply_delay` * For PostgreSQL 10 subscriptions, use these commands: ** ** **ALTER SUBSCRIPTION mysub DISABLE;** **ALTER SUBSCRIPTION mysub ENABLE;** # Logical replication Logical replication allows us to stream logical data changes between two nodes. By logical, we mean streaming changes to data without referring to specific physical attributes such as block number and row ID. The main benefits of logical replication are as follows: * Performance is roughly two times as better than that of the best trigger-based mechanisms * Selective replication is supported, so we don't need to replicate the entire database (only available with pglogical at present) * Replication can occur between different major releases, which can allow a zero-downtime upgrade PostgreSQL 9.4 onwards provides a feature called logical decoding. This allows you to stream a set of changes out of a master server. This allows a master to become a sending node in logical replication. The receiving node requires a logical replication plugin to allow replication between two nodes. Previously, we referred to physical replication as **streaming replication**. Now, we have to modify our descriptions so that we can refer to PSR and LSR. In terms of security, network data transfer, and general management, the two modes are very similar. Concepts used to monitor PSR can also be used to monitor LSR. Since the target systems are fully writable masters in their own right, we can use the full power of PostgreSQL without restrictions. We can use temporary tables, triggers, different user accounts, and GRANT permissions differently. We can also define indexes differently, collect statistics differently, and run VACUUM on different schedules. As a result, calling nodes just as sending and receiving nodes isn't enough. LSR works on a publish/subscribe model, so we refer to the nodes as publishers and subscribers. LSR works on a per-database level, not a whole server level like PSR. One publishing node can feed multiple subscriber nodes without incurring additional disk write overhead. PostgreSQL 10 contains native logical replication between servers for PostgreSQL 10 and above. Another option is the more flexible **pglogical** utility, which can send and receive data from PostgreSQL 9.4 and above, see (https://2ndquadrant.com/en/resources/pglogical/). pglogical 2.1 allows you to perform the following actions: * Full database replication * Selective replication of subsets of tables using replication sets * Selective replication of table rows at either the publisher or subscriber side * Upgrades between major versions (see later recipe) * Data forwarding to Postgres-XL or Postgres-BDR # Getting ready To use `pglogical`, the publisher and subscriber must be running PostgreSQL 9.4 or higher and you must install the `pglogical` extension on both nodes. The procedure is the following: 1. Identify all the nodes that will work together as parts of your replication architecture. 2. Each LSR link can replicate changes from a single database. If you have multiple databases in your PostgreSQL server, you will need one LSR link per database (not counting `template0` and `template1`). 3. Each LSR link will use one connection and one slot. Set the `max_replication_slots` and `max_connections` parameters to match those requirements. 4. Each LSR link requires one WAL sender on the publisher. Set `max_wal_senders` to match this requirement. 5. Each LSR link requires one apply process on the subscriber. Set `max_worker_processes` to match this requirement. 6. On each node do all of the following steps: **CREATE EXTENSION pglogical;** 7. If using PostgreSQL 9.4, then also install the following: **CREATE EXTENSION pglogical_origin;** 8. Any user-installed data types must be installed on both nodes. 9. Add this to `postgresql.conf` `shared_preload_libraries = 'pglogical' --add` to any existing list. 10. Set this parameter in `postgresql.conf`: **wal_level = 'logical'** 11. On each database, declare the node to `pglogical`: **SELECT pglogical.create_node( node_name := 'nodeA', dsn := 'host=nodeA dbname=postgres');** An example of a `postgresql.conf` file on the source node for the preceding steps looks like this: **# Record data for Logical replication** **wal_level = 'logical'** **# Load the pglogical extension** **shared_preload_libraries = 'pglogical'** **# Allow replication slot creation (we need just one but it** **does not hurt to have more)** **max_replication_slots = 10** **# Allow streaming replication (we need one for slot and** **one for basebackup but again, it does not hurt to have more)** **max_wal_senders = 10** **max_worker_processes = 10** Logical replication supports selective replication, which means that you don't need to specify all the tables in the database. Identify the tables to be replicated. Define replication sets that correspond to groups of tables that should be replicated together. Ensure that all the transactions that touch any table in the set touch only a subset of the set, or the whole set. Tables that will be replicated may need some preparatory steps as well. To allow logical replication to apply `UPDATE` and `DELETE` commands correctly on the target node, we need to define how we search for unique rows. This is known as the replica identity. By default, the replica identity will be the primary key of a table, so you need not take any action if you have already defined primary keys on your tables. In some cases, you may need to define the replica identity explicitly, using a command like this: **ALTER TABLE mytable REPLICA IDENTITY USING INDEX myuniquecol_idx;** Tables on the publisher and subscriber must have the same names and be in the same schema. Tables must also have the same columns with the same data types in each column. Tables must have the same `PRIMARY KEY` on both nodes. `CHECK`, `NOT NULL`, and `UNIQUE` constraints must be the same or weaker (more permissive) on the subscriber. Logical replication also supports filtered replication, which means that only certain actions are replicated on the target node; for example, we can specify that `INSERT` commands are replicated while `DELETE` commands are filtered away. We can also specify a subset of the rows to be sent from the publisher or applied on the subscriber. This allows logical replication to support a greater range of data movement applications than was previously possible with trigger replication. Replication requires superuser access for the roles providing replication. # How to do it... Let's look at a few different examples of how to use logical replication: 1. To publish changes from all tables on a `postgres` database on `nodeA`, use the following: **SELECT pglogical.replication_set_add_all_tables( set_name := 'default', schema_names := ARRAY['public'], true);** And then, by issuing the following command on `nodeB`: **SELECT pglogical.create_subscription( subscription_name := 'my_subscription_name', provide_dsn := 'host=nodeA dbname=postgres' );** 2. Publish changes for `TableX` on the `MyApp` database on `nodeA` by using the following: **SELECT pglogical.create_replication_set( set_name := 'SmallSet');** **SELECT pglogical.replication_set_add_table( set_name := 'SmallSet', relation := 'TableX');** And then immediately copy all table data and then subscribe to changes for `TableX`: **SELECT pglogical.create_subscription( subscription_name := 'SmallSet_subscription', replication_sets := ARRAY['SmallSet'], provide_dsn := 'host=nodeA dbname=postgres' );** 3. Publish changes for rows on `TableY` where `status=7` on the `MyApp` database on `nodeA`, adding this into the existing replication set and immediately synchronizing data to all subscribing nodes: ****SELECT pglogical.replication_set_add_table( set_name := 'SmallSet', relation := 'TableY', row_filter := 'status = 7', synchronize_data = true);** ** # How it works... Logical decoding is very efficient because it reuses the transaction log data (WAL) that was already being written for crash safety. Triggers are not used at all for this form of replication. Physical WAL records are translated into logical changes, which are then sent to the receiving node. Only real data changes are sent; no records are generated from changes to indexes, cleanup records from VACUUM, and so on. So bandwidth requirements are somewhat reduced, depending on the exact application. Changes are discarded if the top-level transaction aborts (save points and other subtransactions are supported normally). Changes are applied in the order of the transactions committed, so replication never breaks because it sees an inconsistent sequence of activities, as can occur with other cruder replication techniques such as statement-based replication. On the receiving side, changes are applied using direct database calls, leading to a very efficient mechanism. SQL is not re-executed, so volatile functions in the original SQL don't produce any surprises. For example, if you make an update like this: **UPDATE table** **SET** **col1 = col1 + random()** **,col2 = col2 + random()** **WHERE key = value** Then, the final calculated values of `col1` and `col2` are sent, instead of repeating the execution of the functions when we apply the changes. Triggers are fired on the subscribing node, so if you wish to filter the rows applied on the subscriber, you can define `BEFORE ROW` triggers that block or filter rows as you wish. Logical replication will work even if you update one or more columns of the key (or any other replica identity), since it will detect that situation and send the old values of the columns with the changed row values. Statements that write many rows get turned into a stream of single row changes. Locks taken at table-level (`LOCK`) or row-level (`SELECT ... FOR...`) are not replicated, nor are `SET` or `NOTIFY` commands. Logical replication doesn't suffer from cancellations of queries on the apply node in the way Hot Standby does. There isn't any need for a feature such as `hot_standby_feedback.` Both the publishing and subscribing nodes are masters, so it would be technically possible for writes (`INSERT`, `UPDATE`, and `DELETE`) and/or row-level locks (`SELECT ... FOR...`) to be made on the apply-side database. As a result, it is possible that local changes could lock out, slow down, or interfere with the application of changes from the source node. It is up to the user to enforce restrictions to ensure that this does not occur. You can do this by having a user role defined specifically for replication and then using `REVOKE` on all access apart from the `SELECT` privilege to replicated tables, rather than the user role applying the changes. Data can be read on the apply side while changes are being made. That is just normal, and it's the beautiful power of PostgreSQL's MVCC feature. The use of replication slots means that if the network drops, or if one of the nodes is offline, we can pick up the replication again from the precise point that we stopped. # There's more... LSR can work alongside PSR. There are no conflicting parameters; just ensure that all requirements are met for both PSR and LSR. With LSR and pglogical, neither DDL nor sequences are replicated; only the data changes (DML) are sent. Only the full version of Postgres-BDR provides these features at present. Logical replication is one-way only, so if you want multi-master replication, see the _Bi-Directional Replication_ recipe. Logical replication provides cascaded replication. # See also In PostgreSQL 10, some aspects of LSR have been included with the core server. The same idea of publish and subscribe has been included as commands, allowing these to be dumped and restored between servers. Let's look at the same examples as we saw earlier: 1. To publish changes from all tables on a `postgres` database on `nodeA`, use the following: **CREATE PUBLICATION pub_nodeA_postgres_all** **FOR ALL TABLES;** And then immediately copy all table data and then subscribe to changes from the default replication set on the `nodeA` database `postgres`, by issuing the following command on `nodeB`: **CREATE SUBSCRIPTION sub_nodeA_postgres_all** **CONNECTION 'conninfo'** **PUBLICATION pub_nodeA_postgres_all;** 2. Publish changes for `TableX` on the `MyApp` database on `nodeA` by using the following: **CREATE PUBLICATION pub_nodeA_postgres_tablex** **FOR TABLE TableX;** And then immediately copy all table data and then subscribe to changes for `TableX`: **CREATE SUBSCRIPTION sub_nodeA_postgres_tablex** **CONNECTION 'conninfo'** **PUBLICATION pub_nodeA_postgres_tablex;** Publishing a subset of DML operations is possible, though it isn't yet possible to filter rows. Creating a `PUBLICATION` requires `CREATE` privilege on current database. Creating a `SUBSCRIPTION` object will by default enable replication and have it start immediately, though it is often convenient to define these first with the option `WITH (enabled = off)` and then re-enable them later using `ALTER SUBSCRIPTION`. Subscriptions use normal user access security, so there is no need to enable _replication_ via `pg_hba.conf`. It is also possible to override the `synchronous_commit` parameter and demand that the server provides synchronous replication. # Bi-directional replication **Bi-directional replication** (Postgres-BDR) is a project used to allow multi-master replication with PostgreSQL. There is a range of possible architectures. The first use case we support is all-nodes-to-all-nodes. Postgres-BDR will eventually support a range of complex architectures, which is discussed later. Postgres-BDR aims for eventual inclusion within core PostgreSQL, though knowing that is a long and rigorous process, it also aims to provide working software solutions, now! Postgres-BDR aims to allow the nodes of the cluster to be physically distributed, allowing worldwide access to data and allowing for disaster recovery. Each Postgres-BDR master node runs individual transactions; there is no globally distributed transaction manager. Postgres-BDR includes replication of data changes and data definition (DDL) changes. New tables are added automatically, ensuring that managing BDR is a low-maintenance overhead for applications. Postgres-BDR also provides global sequences, if you wish to have a sequence that works across a distributed system. Normal local sequences are not replicated. The key advantage of Postgres-BDR is that you can segregate your write workload across multiple nodes by application, user group, or geographical proximity. Each node can be configured differently, yet all work together to provide access to the same data. Some examples of use cases for this are as follows: * Social media applications, where users need fast access to their local server, yet the whole database needs a single database view to cater for links and interconnections. * Distributed businesses, where orders are taken by phone in one location and by websites in another location. Then, they are fulfilled via several other locations. * Multinational companies that need fast access to data from many locations, yet wish to see a single, common view of their data. Postgres-BDR builds upon the basic technology of logical replication, enhancing it in various ways. We refer heavily to the previous recipe, _Logical replication_. # Getting ready Currently, Postgres-BDR can be deployed in the all-to-all architecture, which has been tested on clusters of up to 99 master nodes. Each of those nodes is a normal, fully functioning PostgreSQL server that can perform both reads and writes. Postgres-BDR connects directly between each node, forming a mesh of connections. Changes flow directly to other nodes in constant time, no matter how many nodes are in use. This is quite different from circular replication used by other DBMS. All Postgres-BDR nodes should have `pg_hba.conf` definitions to allow paths between each node. It would be easier to have these settings the same on all nodes, but that is not required. Each node requires an LSR link to all other nodes for each replicated database. So, a 32-node Postgres-BDR cluster will require 31 LSR links per node. Ensure that the parameters are configured to allow for this and any possible future expansion. The parameters should be the same on all nodes to avoid confusion. Remember that these changes require restarting. Postgres-BDR nodes also require configuring the mechanism for conflict detection: track_commit_timestamps = on Postgres-BDR 1 requires a modified version of PostgreSQL 9.4. Postgres-BDR 2 is available only as an interim measure as an extension for PostgreSQL 9.6. Postgres-BDR 3 will be available in 2018 for PostgreSQL 10 and above. For latest info, please consult https://www.2ndquadrant.com/en/resources/bdr/. Future versions of PostgreSQL may contain multi-master replication, though this will not be until at least PostgreSQL 12 as we go to press. # How to do it... To create a new node, we take a copy of one of the databases on the source nodes. This can be accomplished using either a physical base backup or a logical base backup. A physical copy includes all databases on the source node, so this mechanism is most suitable where there is only one active database on that node. Command specifications are subject to change. Check out <https://www.2ndquadrant.com/en/resources/bdr/> for the latest details on them. # How it works... Postgres-BDR optimistically assumes that changes on one node do not conflict with changes on other nodes. Any conflicts are detected and then resolved automatically using a predictable last update wins strategy, though custom conflict handlers are supported to allow more precise definition for particular applications. Applications that regularly cause conflicts won't run very well on Postgres-BDR. Having said that, such applications would also suffer from lock waits and resource contention on a normal database; the effects will be somewhat amplified by the distributed nature of Postgres-BDR, but only the existing problems are amplified. Applications that are properly designed to be scalable and contention free will work well on Postgres-BDR. Postgres-BDR replicates changes at the row level, though work is underway to apply changes at column level and in a conflict-free manner. The current mechanism has some implications for applications: * Suppose we perform two simultaneous updates on different nodes like this: **UPDATE foo SET col1 = col1 + 1 WHERE key = value;** * Then, in the event of a conflict, we will keep only one of the changes (the last change). What we might like in this case is to make the changes additive. This requires a custom conflict handler. * Two updates that change different columns on different nodes will still cause replication conflicts. At the time of writing, Postgres-BDR supports only post-commit conflict resolution, though work is in progress to provide eager consistency (pre-commit resolution) in future releases. Postgres-BDR provides tools to diagnose and correct contention problems. Conflicts are logged so that they can be identified and removed at the application level. You can log either the conflicting statement or the entire conflicting transaction. Optionally, they can be also saved in a table for easier analysis. # There's more... If a node fails, there is no requirement for failover, so other nodes continue processing normally—there is no wait for failover, nor is there the need for complex voting algorithms to identify the best new master. Failed servers will need to rejoin the cluster. Postgres-BDR will eventually support a range of complex architectures: * **Cascading** : Postgres-BDR doesn't support cascading yet * **Circular replication** : This reduces overhead of connections, but is brittle, and the delay for changes to propagate through the cluster increases as the number of nodes increases * **Group to group** : This involves more complex regional or geographically disparate systems * **Central rollup** : This involves central servers sending changes from remote nodes * **Central broadcast** : This involves central servers sending changes out to remote nodes # Archiving transaction log data PSR can send transaction log data to a remote node even if the node is not a full PostgreSQL server. This can be useful for archiving copies of transaction log data for various purposes. PostgreSQL includes two client tools to stream data from the server to the client. The tools are designed using a pull model; that is, you run the tools on the node you wish the data to be saved on: * `pg_receivewal` archives physical transaction log data (WAL files). This utility produces a straight copy of the original WAL files. Replication slots are recommended when using this tool from 9.4 onwards. * `pg_recvlogical` archives the results of logical decoding of transaction log data. This utility produces a copy of the transformed data rather than physical WAL. Replication slots are required for this tool. You will need to use that with a logical decoding plugin. # Getting ready This recipe assumes that you have already set up replication according to the earlier recipes so that `wal_level`, `max_wal_senders`, and other parameters are set. Remember that for `pg_recvlogical`, you must set `wal_level` to `logical`. This recipe is a different way of archiving WAL files than using `archive_command`, so you will likely want to unset that parameter if you use this recipe. You will need to configure security just as you did for replication. So, you will need a PostgreSQL connection string, just as before. Decide where you want to put the data on the client. Remember that WAL files look the same for each server, so you need to put them in a directory with a useful name so that you don't confuse files from different servers. You don't need to do this step for normal replication because streaming replication normally copies the files to the downstream node's `pg_wal` directory. # How to do it... To archive a physical WAL from a server called `alpha`, follow these steps: 1. If you decide to use replication slots, then create a slot using steps _1_ to _3_ of the _Using replication slots_ recipe. 2. Execute the tool on the client: **pg_receivewal -D /pgarchive/alpha -d $MYCONNECTIONSTRING &** 3. If using slots, also use the `--slot=slotname` parameter on the command line. If the connection from the client tool to the server is lost, the default behavior is to loop indefinitely while trying to re-establish a connection. If you want the client tool to exit if the connection is lost, then specify the `-n` or `--no-loop` options. The `pg_recvlogical` utility requires some form of logical decoding plugin, so look at the instructions for the plugin you are using to describe exactly how to use that. # There's more... While playing with this feature for the first time, try the `--verbose` option. For more detail on logical decoding plugins, we refer to the _L ogical replication_ recipe earlier in this chapter. Replication monitoring will show `pg_receivewal` and `pg_recvlogical` in exactly the same way as it shows other connected nodes, so there is no additional monitoring required. The default `application_name` is the same as the name of the tool, so you may want to set that parameter to something more meaningful to you. With `pg_receivewal` and `pg_recvlogical,` you can use the `--create-slot` and `--drop-slot` options to control replication slots. You can archive WAL files using synchronous replication by specifying `pg_receivewal --synchronous`. This causes a disk flush (`fsync`) on the client so that WAL data is robustly saved to the disk. It then passes status information back to the server to acknowledge that the data is safe (regardless of the setting of the `-s` parameter). # See also * If you want to browse the content of the WAL files, you'll need the `pg_waldump` program, which is an additional server-side utility # Upgrading minor releases Minor release upgrades are released regularly by all software developers, and PostgreSQL has its share of corrections. When a minor release occurs, we bump the last number, usually by one. So the first release of a major release 10 is 10.0. The first set of bug fixes is 10.1, then 10.2, and so on. This recipe is about moving from a minor release to minor release. # Getting ready First, get hold of the new release, by downloading either the source or fresh binaries. # How to do it... In most cases, PostgreSQL aims for minor releases to be simple upgrades. We make great efforts to keep the on-disk format the same for both data/index files and transaction log (WAL) files, but this isn't always the case; some files can change sometimes. The upgrade process is as follows: 1. Read the release notes to see whether there are any special actions that need to be taken for this particular release. Make sure you consider steps required by all extensions that you have installed. 2. If you have professional support, talk to your support vendor to see whether additional safety checks over and above the upgrade instructions are required or recommended. Also, verify that the target release is fully supported by your vendor on your hardware, OS, and OS release level; it may not be, yet. 3. Apply any special actions or checks; for example, if the WAL format has changed, then you may need to reconfigure log-based replication following the upgrade. You may need to scan tables, rebuild indexes, or perform some other actions. Not every release has such actions, but watch closely for them, because if they exist, then they are important. 4. If you are using replication, test the upgrade by disconnecting one of your standby servers from the master. 5. Follow the instructions for your OS distribution and binary packager to complete the upgrade. These can vary considerably. 6. Start up the database server being used for this test, apply any post-upgrade special actions, and check that things are working for you. 7. Repeat steps _4_ to _6_ for other standby servers. 8. Repeat steps _4_ to _6_ for the primary server. # How it works... Minor upgrades mostly affect the binary executable files, so it should be a simple matter of replacing those files and restarting. But check. # Major upgrades in-place PostgreSQL provides an additional supplied program, called `pg_upgrade`, which allows you to migrate between major releases, such as from 9.2 to 9.6; or you can upgrade straight to the latest server version. These upgrades are performed in-place, meaning that we upgrade your database without moving to a new system. That does sound good, but `pg_upgrade` has a few things that you may wish to consider as potential negatives, which are as follows: * The database server must be shut down while the upgrade takes place. * Your system must be large enough to hold two copies of the database server: old and new copies. If it's not, then you have to use the `link` option of `pg_upgrade`, or use the _Major upgrades online_ recipe later. If you use the `link` option on `pg_upgrade`, then there is no `pg_downgrade` utility. The only option in that case is a restore from backup, and that means extended unavailability while you restore. * If you copy the database, then the upgrade time will be proportional to the size of the database. * The `pg_upgrade` utility does not validate all your additional add-in modules, so you will need to set up a test server and confirm that these work, ahead of performing the main upgrade. The `pg_upgrade` utility supports versions from PostgreSQL 8.4 onwards and allows you to go straight from your current release to the latest release in one hop. # Getting ready Find out the size of your database (using the _How much disk space does a database use?_ recipe in Chapter 2, _Exploring the Database_ ). If the database is large or you have an important requirement for availability, you should consider doing the major upgrade using replication tools as well. Then, check out the next recipe. # How to do it... 1. Read the release notes for the new server version to which you are migrating, including all of the intervening releases. Pay attention to the incompatibilities section carefully; PostgreSQL does change from release to release. Assume this will take some hours. 2. Set up a test server with the old software release on it. Restore one of your backups on it. Upgrade that system to the new release to verify that there are no conflicts from software dependencies. Test your application. Make sure you identify and test each add-in PostgreSQL module you were using to confirm that it still works at the new release level. 3. Back up your production server. Prepare for the worst; hope for the best! 4. Most importantly, work out who you will call if things go badly, and exactly how to restore from that backup you just took. 5. Install new versions of all the required software on the production server, and create a new database server. 6. Don't disable security during the upgrade. Your security team will do backflips if they hear about this. Keep your job! 7. Now, go and do that backup. Don't skip this step; it isn't optional. Check whether the backup is actually readable, accessible, and complete. 8. Shut down the database servers. 9. Run `pg_upgrade -v` and then run any required post-upgrade scripts. Make sure you check whether any were required. 10. Start up the new database server and immediately run a server-wide `ANALYZE` operation using `vacuumdb -analyze-in-stages`. 11. Run through your tests to check whether it worked or you need to start performing the contingency plan. 12. If all is OK, re-enable wide access to the database server. Restart the applications. 13. Don't delete your old server directory if you used the link method. The old `data` directory still contains the data for the new database server. Confusing! So don't get caught by this. # How it works... The `pg_upgrade` utility works by creating a new set of database catalog tables, and then creating the old objects again in the new tables using the same identifiers as before. The `pg_upgrade` utility works easily because the data block format hasn't changed between some releases. Since we can't (always) see the future, make sure you read the release notes. # Major upgrades online Upgrading between major releases is hard, and it should be deferred until you have some good reasons and sufficient time to get it right. You can use replication tools to minimize the downtime required for an upgrade, so we refer to this recipe as an **online upgrade**. # How to do it... The following general steps should be followed, allowing at least a month for the complete process to ensure that everything is tested and everybody understands the implications: 1. Set up a new release of the software on a new test system. 2. Take a standalone backup from the main system and copy it to the test system. 3. Test the applications extensively against the new release on the test system. When everything works and performs correctly, then do the following: 1. Set up a connection pooler to the main database (it may be there already). 2. Set up `pglogical` for all tables from old to new database servers. Make sure you wait until all the initial copy tasks have completed for all tables. Retest the application extensively against the new release on live data, then when ready for the final cut-over, we can do the following: 1. Pause the connection pool. 2. Switch the config of the pool over to the new system, reload. 3. Resume the connection pool (so it now accesses a new server). Downtime for the application is the length of time to these last three steps. # How it works... The preceding recipe allows online upgrades with zero data loss because of the use of the clean switchover process. There's no need for lengthy downtime during the upgrade, and there's much reduced risk in comparison with an in-place upgrade. It works best with new hardware, and is a good way to upgrade the hardware or change the disk layout at the same time. This procedure is also very useful for those cases where binary compatibility is not possible, such as changing server encoding, or migrating the database to a different operating system or architecture, where on-disk format will change as a result of low-level differences, such as endianness and alignment. # Other Books You May Enjoy If you enjoyed this book, you may be interested in these other books by Packt: **Mastering PostgreSQL 10** Hans-Jürgen Schönig ISBN: 978-1-78847-229-6 * Get to grips with the advanced features of PostgreSQL 10 and handle advanced SQL * Make use of the indexing features in PostgreSQL and fine-tune the performance of your queries * Work with stored procedures and manage backup and recovery * Master replication and failover techniques * Troubleshoot your PostgreSQL instance for solutions to common and not-so-common problems * Learn how to migrate your database from MySQL and Oracle to PostgreSQL without any hassle **Learning PostgreSQL 10 - Second Edition** Salahaldin Juba, Andrey Volkov ISBN: 978-1-78839-201-3 * Understand the fundamentals of relational databases, relational algebra, and data modeling * Install a PostgreSQL cluster, create a database, and implement your data model * Create tables and views, define indexes, and implement triggers, stored procedures, and other schema objects * Use the Structured Query Language (SQL) to manipulate data in the database * Implement business logic on the server side with triggers and stored procedures using PL/pgSQL * Make use of advanced data types supported by PostgreSQL 10: Arrays, hstore, JSONB, and others * Develop OLAP database solutions using the most recent features of PostgreSQL 10 * Connect your Python applications to a PostgreSQL database and work with the data efficiently * Test your database code, find bottlenecks, improve performance, and enhance the reliability of the database applications # Leave a review - let other readers know what you think Please share your thoughts on this book with others by leaving a review on the site that you bought it from. If you purchased the book from Amazon, please leave us an honest review on this book's Amazon page. This is vital so that other potential readers can see and use your unbiased opinion to make purchasing decisions, we can understand what our customers think about our products, and our authors can see your feedback on the title that they have worked with Packt to create. It will only take a few minutes of your time, but is valuable to other potential customers, our authors, and Packt. Thank you!
{ "redpajama_set_name": "RedPajamaBook" }
1,691
"Gladstone" redirects here. For other uses, see Gladstone (disambiguation). William Ewart Gladstone FRS FSS (/ˈɡlædstən/; 29 December 1809 – 19 May 1898) was a British statesman and Liberal politician. In a career lasting over 60 years, he served for 12 years as Prime Minister of the United Kingdom, spread over four terms beginning in 1868 and ending in 1894. He also served as Chancellor of the Exchequer four times, serving over 12 years. FRS FSS Prime Minister of the United Kingdom 15 August 1892 – 2 March 1894 The Marquess of Salisbury Succeeded by The Earl of Rosebery 1 February 1886 – 20 July 1886 23 April 1880 – 9 June 1885 The Earl of Beaconsfield 3 December 1868 – 17 February 1874 28 April 1880 – 16 December 1882 Stafford Northcote Hugh Childers 11 August 1873 – 17 February 1874 18 June 1859 – 26 June 1866 The Viscount Palmerston The Earl Russell 28 December 1852 – 28 February 1855 The Earl of Aberdeen George Cornewall Lewis Secretary of State for War and the Colonies 23 December 1845 – 27 June 1846 The Earl of Derby The Earl of Grey President of the Board of Trade 15 May 1843 – 5 February 1845 The Earl of Ripon The Earl of Dalhousie 26 August 1847 – 7 August 1895 Thomas Grimston Estcourt Thomas Gibson-Carmichael Oxford University (1847–65) South Lancashire (1865–68) Greenwich (1868–80) Midlothian (1880–95) 8 January 1833 – 30 January 1846 Thomas Wilde (1809-12-29)29 December 1809 62 Rodney Street, Liverpool, Lancashire, England 19 May 1898(1898-05-19) (aged 88) Hawarden Castle, Flintshire, Wales Tory (1828–1834) Conservative (1834–1846) Peelite (1846–1859) Liberal (1859–1898) Spouse(s) Catherine Glynne (m. 1839)​ 8; including William, Helen, Henry and Herbert Sir John Gladstone Anne MacKenzie Robertson Christ Church, Oxford Gladstone was born in Liverpool to Scottish parents. He first entered the House of Commons in 1832, beginning his political career as a High Tory, a grouping which became the Conservative Party under Robert Peel in 1834. Gladstone served as a minister in both of Peel's governments, and in 1846 joined the breakaway Peelite faction, which eventually merged into the new Liberal Party in 1859. He was Chancellor under Lord Aberdeen (1852–1855), Lord Palmerston (1859–1865) and Lord Russell (1865–1866). Gladstone's own political doctrine—which emphasised equality of opportunity and opposition to trade protectionism—came to be known as Gladstonian liberalism. His popularity amongst the working-class earned him the sobriquet "The People's William". In 1868, Gladstone became Prime Minister for the first time. Many reforms were passed during his first ministry, including the disestablishment of the Church of Ireland and the introduction of secret voting. After electoral defeat in 1874, Gladstone resigned as leader of the Liberal Party. From 1876 he began a comeback based on opposition to Turkey's reaction to the Bulgarian April Uprising. His Midlothian Campaign of 1879–80 was an early example of many modern political campaigning techniques.[1][2] After the 1880 general election, Gladstone formed his second ministry (1880–1885), which saw the passage of the Third Reform Act as well as crises in Egypt (culminating in the Fall of Khartoum) and Ireland, where his government passed repressive measures but also improved the legal rights of Irish tenant farmers. Back in office in early 1886, Gladstone proposed home rule for Ireland but was defeated in the House of Commons. The resulting split in the Liberal Party helped keep them out of office – with one short break – for 20 years. Gladstone formed his last government in 1892, at the age of 82. The Government of Ireland Bill 1893 passed through the Commons but was defeated in the House of Lords in 1893. Gladstone left office in March 1894, aged 84, as both the oldest person to serve as Prime Minister and the only Prime Minister to have served four terms. He left Parliament in 1895 and died three years later. Gladstone was known affectionately by his supporters as "The People's William" or the "G.O.M." ("Grand Old Man", or, to political rivals "God's Only Mistake").[3] Historians often call him one of Britain's greatest leaders.[4][5][6][7] 1 Early life 2 House of Commons 2.1 First term 2.2 Attitude towards slavery 2.3 Opposition to the Opium Wars 3 Minister under Peel (1841–1846) 4 Opposition MP (1846–1851) 5 Chancellor of the Exchequer (1852–1855) 6 Opposition (1855–1859) 7.1 American Civil War 7.2 Electoral reform 7.3 Leader of the Liberal Party, from 1867 8 First premiership (1868–1874) 9.1 Anti-Catholicism 9.2 Self help and opposition to socialism 9.3 Bulgarian Horrors 10 Second premiership (1880–1885) 10.1 Foreign policy 10.2 Ireland 10.3 Franchise 10.4 Failure 11 Third premiership (1886) 12 Opposition (1886–1892) 13 Fourth premiership (1892–1894) 14 Final years (1894–1898) 15 Religion 16 Marriage and family 16.1 Descendants 17.1 Rivalry with Disraeli 18 Monuments and archives 21 Portrayal in film and television 26.1 Biographies 26.2 Special studies 26.3 Midlothian campaign 26.4 Historiography 26.5 Primary sources Early lifeEdit Born in 1809 in Liverpool, at 62 Rodney Street, William Ewart Gladstone was the fourth son of the merchant John Gladstone, and his second wife, Anne MacKenzie Robertson. In 1835, the family name was changed from Gladstones to Gladstone by royal licence. His father was made a baronet, of Fasque and Balfour, in 1846.[8] Although born and raised in Liverpool, William Gladstone was of purely Scottish ancestry.[9] His grandfather Thomas Gladstones (1732–1809) was a prominent merchant from Leith, and his maternal grandfather, Andrew Robertson, was Provost of Dingwall and a Sheriff-Substitute of Ross-shire.[8] His biographer John Morley described him as "a highlander in the custody of a lowlander", and an adversary as "an ardent Italian in the custody of a Scotsman". One of his earliest childhood memories was being made to stand on a table and say "Ladies and gentlemen" to the assembled audience, probably at a gathering to promote the election of George Canning as MP for Liverpool in 1812. In 1814, young "Willy" visited Scotland for the first time, as he and his brother John travelled with their father to Edinburgh, Biggar and Dingwall to visit their relatives. Willy and his brother were both made freemen of the burgh of Dingwall.[10] In 1815, Gladstone also travelled to London and Cambridge for the first time with his parents. Whilst in London, he attended a service of thanksgiving with his family at St Paul's Cathedral following the Battle of Waterloo, where he saw the Prince Regent.[11] William Gladstone was educated from 1816 to 1821 at a preparatory school at the vicarage of St. Thomas' Church at Seaforth, close to his family's residence, Seaforth House.[9] In 1821, William followed in the footsteps of his elder brothers and attended Eton College before matriculating in 1828 at Christ Church, Oxford, where he read Classics and Mathematics, although he had no great interest in the latter subject. In December 1831, he achieved the double first-class degree he had long desired. Gladstone served as President of the Oxford Union, where he developed a reputation as an orator, which followed him into the House of Commons. At university, Gladstone was a Tory and denounced Whig proposals for parliamentary reform. Gladstone in the 1830s Following the success of his double first, William travelled with his brother John on a Grand Tour of western Europe. Although Gladstone entered Lincoln's Inn in 1833, with intentions of becoming a barrister, by 1839 he had requested that his name should be removed from the list because he no longer intended to be called to the Bar.[9] House of CommonsEdit First termEdit When Gladstone was 22 the Duke of Newcastle, a Conservative party activist, provided him with one of two seats at Newark where he controlled about a fourth of the very small electorate. The Duke spent thousands of pounds entertaining the voters. Gladstone displayed remarkably strong technique as a campaigner and stump speaker.[12] He won his seat at the 1832 United Kingdom general election with 887 votes.[13] Initially a disciple of High Toryism, Gladstone's maiden speech as a young Tory was a defence of the rights of West Indian sugar plantation magnates — slave-owners — among whom his father was prominent. He immediately came under attack from anti-slavery elements. He also surprised the duke by urging the need to increase pay for unskilled factory workers.;[14] After new bills to protect child workers were proposed following the publication of the Sadler report, he voted against the 1833 Factory Acts that would regulate the hours of work and welfare of minors employed in cotton mills.[15] Attitude towards slaveryEdit Gladstone's early attitude towards slavery was highly shaped by his father, Sir John Gladstone, one of the largest slave owners in the British Empire. Both father and son opposed emancipation, saying the slaves first had to have better morals. They also opposed the international slave trade (which lowered the value of the slaves the father already owned).[16][17][18] The antislavery movement demanded the immediate abolition of slavery. Gladstone opposed this and said in 1832 that emancipation should come after moral emancipation through the adoption of an education and the inculcation of "honest and industrious habits" among the slaves Then "with the utmost speed that prudence will permit, we shall arrive at that exceedingly desired consummation, the utter extinction of slavery."[19] In 1831, when the Oxford Union considered a motion in favour of the immediate emancipation of the slaves in the West Indies, Gladstone moved an amendment in favour of gradual manumission along with better protection for the personal and civil rights of the slaves and better provision for their Christian education.[20] His early Parliamentary speeches followed a similar line: in June 1833, Gladstone concluded his speech on the 'slavery question' by declaring that though he had dwelt on "the dark side" of the issue, he looked forward to "a safe and gradual emancipation".[21] In 1834, when slavery was abolished across the British Empire, the owners were paid full value for the slaves. Gladstone helped his father obtain £106,769 in official reimbursement by the government for the 2,508 slaves he owned across nine plantations in the Caribbean.[22] In later years Gladstone's attitude towards slavery became more critical as his father's influence over his politics diminished. In 1844 Gladstone broke with his father when, as President of the Board of Trade, he advanced proposals to half duties on foreign sugar not produced by slave labour, in order to "secure the effectual exclusion of slave-grown sugar" and to encourage Brazil and Spain to end slavery.[23] Sir John Gladstone, who opposed any reduction in duties on foreign sugar, wrote a letter to The Times criticizing the measure.[24] Looking back late in life, Gladstone named the abolition of slavery as one of ten great achievements of the previous sixty years where the masses had been right and the upper classes had been wrong.[25] Opposition to the Opium WarsEdit The opium trade faced intense opposition from Gladstone.[26][27] Gladstone called it "most infamous and atrocious" referring to the opium trade between China and British India in particular.[28] Gladstone was fiercely against both of the Opium Wars Britain waged in China, in the First Opium War initiated in 1840 and the Second Opium War initiated in 1857, denouncing British violence against Chinese, and was ardently opposed to the British trade of opium in China.[29] Gladstone lambasted it as "Palmerston's Opium War" and said that he felt "in dread of the judgements of God upon England for our national iniquity towards China" in May 1840.[30] A famous speech was made by Gladstone in Parliament against the First Opium War.[31][32] Gladstone criticised it as "a war more unjust in its origin, a war more calculated in its progress to cover this country with permanent disgrace".[33] His hostility to opium stemmed from the effects of opium upon his sister Helen.[34] Due to the First Opium war brought on by Palmerston, there was initial reluctance to join the government of Peel on the part of Gladstone before 1841.[35] Minister under Peel (1841–1846)Edit Gladstone was re-elected in 1841. In September 1842 he lost the forefinger of his left hand in an accident while reloading a gun. Thereafter he wore a glove or finger sheath (stall). In the second ministry of Robert Peel he served as President of the Board of Trade (1843–1845). Gladstone was responsible for the Railways Act 1844—regarded by historians as the birth of the regulatory state, of network industry regulation, of rate of return regulation, and telegraph regulation. Examples of its foresight are the clauses empowering government to take control of railway in time of war, the concept of Parliamentary trains limited in cost to a penny a mile, of universal service and of control of the recently invented electric telegraph which ran alongside railway lines. Railways were the largest investment (as a percentage of GNP) in human history and this Bill the most heavily lobbied in Parliamentary history. Gladstone succeeded in guiding the Act through Parliament at the height of the railway bubble.[36] Gladstone became concerned with the situation of "coal whippers". These were the men who worked on London docks, "whipping" in baskets from ships to barges or wharves all incoming coal from the sea. They were called up and relieved through public houses, therefore a man could not get this job unless he possessed the favourable opinion of the publican, who looked most favourably upon those who drank. The man's name was written down and the "score" followed. Publicans issued employment solely on the capacity of the man to pay, and men often left the pub to work drunk. They spent their savings on drink to secure the favourable opinion of publicans and therefore further employment. Gladstone passed the Coal Vendors Act 1843 to set up a central office for employment. When this Act expired in 1856 a Select Committee was appointed by the Lords in 1857 to look into the question. Gladstone gave evidence to the Committee: "I approached the subject in the first instance as I think everyone in Parliament of necessity did, with the strongest possible prejudice against the proposal [to interfere]; but the facts stated were of so extraordinary and deplorable a character, that it was impossible to withhold attention from them. Then the question being whether legislative interference was required I was at length induced to look at a remedy of an extraordinary character as the only one I thought applicable to the case ... it was a great innovation".[37] Looking back in 1883, Gladstone wrote that "In principle, perhaps my Coalwhippers Act of 1843 was the most Socialistic measure of the last half century".[38] He resigned in 1845 over the Maynooth Grant issue, a matter of conscience for him.[39] To improve relations with the Catholic Church, Peel's government proposed increasing the annual grant paid to Maynooth Seminary for training Catholic priests in Ireland. Gladstone, who had previously argued in a book that a Protestant country should not pay money to other churches, nevertheless supported the increase in the Maynooth grant and voted for it in Commons, but resigned rather than face charges that he had compromised his principles to remain in office. After accepting Gladstone's resignation, Peel confessed to a friend, "I really have great difficulty sometimes in exactly comprehending what he means."[40] Gladstone returned to Peel's government as Colonial Secretary in December 1845. "As such, he had to stand for re-election, but the strong protectionism of the Duke of Newcastle, his patron in Newark, meant that he could not stand there and no other seat was available. Throughout the corn law crisis of 1846, therefore, Gladstone was in the highly anomalous and possibly unique position of being a secretary of state without a seat in either house and thus unanswerable to parliament."[41] Opposition MP (1846–1851)Edit In 1846 Peel's government fell over the repeal of the Corn Laws and Gladstone followed his leader into a course of separation from mainstream Conservatives. After Peel's death in 1850, Gladstone emerged as the leader of the Peelites in the House of Commons. He was re-elected for the University of Oxford (i.e. representing the MA graduates of the University) at the General Election in 1847—Peel had once held this seat but had lost it because of his espousal of Catholic Emancipation in 1829. Gladstone became a constant critic of Lord Palmerston.[42] In 1847 Gladstone helped to establish Glenalmond College, then The Holy and Undivided Trinity College at Glenalmond. The school was set up as an episcopal foundation to spread the ideas of Anglicanism in Scotland, and to educate the sons of the gentry.[43] As a young man Gladstone had treated his father's estate, Fasque, in Forfarshire, southwest of Aberdeen, as home, but as a younger son he would not inherit it. Instead, from the time of his marriage, he lived at his wife's family's estate at Hawarden in Flintshire, Wales. He never actually owned Hawarden, which belonged first to his brother-in-law Sir Stephen Glynne, and was then inherited by Gladstone's eldest son in 1874. During the late 1840s, when he was out of office, he worked extensively to turn Hawarden into a viable business.[44] In 1848 he founded the Church Penitentiary Association for the Reclamation of Fallen Women. In May 1849 he began his most active "rescue work" and met prostitutes late at night on the street, in his house or in their houses, writing their names in a private notebook. He aided the House of Mercy at Clewer near Windsor (which exercised extreme in-house discipline) and spent much time arranging employment for ex-prostitutes. In a "Declaration" signed on 7 December 1896 and only to be opened after his death, Gladstone wrote, "I desire to record my solemn declaration and assurance, as in the sight of God and before His Judgement Seat, that at no period of my life have I been guilty of the act which is known as that of infidelity to the marriage bed."[45] In 1850/51 Gladstone visited Naples. Italy, for the benefit of his daughter Mary's eyesight. Giacomo Lacaita, legal adviser to the British embassy, was at the time imprisoned by the Neapolitan government, as were other political dissidents. Gladstone became concerned at the political situation in Naples and the arrest and imprisonment of Neapolitan liberals. In February 1851 Gladstone visited the prisons where thousands of them were held and was extremely outraged. In April and July he published two Letters to the Earl of Aberdeen against the Neapolitan government and responded to his critics in An Examination of the Official Reply of the Neapolitan Government in 1852. Gladstone's first letter described what he saw in Naples as "the negation of God erected into a system of government".[46] Chancellor of the Exchequer (1852–1855)Edit A pensive Gladstone, from the book Great Britain and Her Queen, by Anne E. Keeling In 1852, following the appointment of Lord Aberdeen as Prime Minister, head of a coalition of Whigs and Peelites, Gladstone became Chancellor of the Exchequer. The Whig Sir Charles Wood and the Tory Disraeli had both been perceived to have failed in the office and so this provided Gladstone with a great political opportunity.[47] His first budget in 1853 almost completed the work begun by Peel eleven years before in simplifying Britain's tariff of duties and customs.[48] 123 duties were abolished and 133 duties were reduced.[49] The income tax had legally expired but Gladstone proposed to extend it for seven years to fund tariff reductions: We propose, then, to re-enact it for two years, from April, 1853, to April, 1855, at the rate of 7d. in the £; from April, 1855, to enact it for two more years at 6d. in the £; and then for three years more ... from April, 1857, at 5d. Under this proposal, on 5 April 1860, the income-tax will by law expire.[50] Gladstone wanted to maintain a balance between direct and indirect taxation and to abolish income tax. He knew that its abolition depended on a considerable retrenchment in government expenditure. He therefore increased the number of people eligible to pay it by lowering the threshold from £150 to £100. The more people that paid income tax, Gladstone believed, the more the public would pressure the government into abolishing it.[51] Gladstone argued that the £100 line was "the dividing line ... between the educated and the labouring part of the community" and that therefore the income tax payers and the electorate were to be the same people, who would then vote to cut government expenditure.[51] The budget speech (delivered on 18 April), nearly five hours long, raised Gladstone "at once to the front rank of financiers as of orators".[52] H.C.G. Matthew has written that Gladstone "made finance and figures exciting, and succeeded in constructing budget speeches epic in form and performance, often with lyrical interludes to vary the tension in the Commons as the careful exposition of figures and argument was brought to a climax".[53] The contemporary diarist Charles Greville wrote of Gladstone's speech: ... by universal consent it was one of the grandest displays and most able financial statement that ever was heard in the House of Commons; a great scheme, boldly, skilfully, and honestly devised, disdaining popular clamour and pressure from without, and the execution of it absolute perfection. Even those who do not admire the Budget, or who are injured by it, admit the merit of the performance. It has raised Gladstone to a great political elevation, and, what is of far greater consequence than the measure itself, has given the country assurance of a man equal to great political necessities, and fit to lead parties and direct governments.[54] During wartime, he insisted on raising taxes and not borrowing funds to pay for the war. The goal was to turn wealthy Britons against expensive wars. Britain entered the Crimean War in February 1854, and Gladstone introduced his budget on 6 March. He had to increase expenditure on the military and a vote of credit of £1,250,000 was taken to send a force of 25,000 to the front. The deficit for the year would be £2,840,000 (estimated revenue £56,680,000; estimated expenditure £59,420,000). Gladstone refused to borrow the money needed to rectify this deficit and instead increased income tax by half, from sevenpence to tenpence-halfpenny in the pound (from 2.92% to 4.38%). By May another £6,870,000 was needed for the war and Gladstone raised the income tax from tenpence halfpenny to fourteen pence in the pound to raise £3,250,000. Spirits, malt, and sugar were taxed to raise the rest of the money needed.[55] He proclaimed: The expenses of a war are the moral check which it has pleased the Almighty to impose upon the ambition and lust of conquest that are inherent in so many nations ... The necessity of meeting from year to year the expenditure which it entails is a salutary and wholesome check, making them feel what they are about, and making them measure the cost of the benefit upon which they may calculate[56] He served until 1855, a few weeks into Lord Palmerston's first premiership, and resigned along with the rest of the Peelites after a motion was passed to appoint a committee of inquiry into the conduct of the war. Opposition (1855–1859)Edit Gladstone in 1859, painted by George Frederic Watts. The Conservative Leader Lord Derby became Prime Minister in 1858, but Gladstone—who like the other Peelites was still nominally a Conservative—declined a position in his government, opting not to sacrifice his free trade principles. Between November 1858 and February 1859, Gladstone, on behalf of Lord Derby's government, was made Extraordinary Lord High Commissioner of the Ionian Islands embarking via Vienna and Trieste on a twelve-week mission to the southern Adriatic entrusted with complex challenges that had arisen in connection with the future of the British protectorate of the United States of the Ionian Islands.[57] In 1858, Gladstone took up the hobby of tree felling, mostly of oak trees, an exercise he continued with enthusiasm until he was 81 in 1891. Eventually, he became notorious for this activity, prompting Lord Randolph Churchill to observe: "For the purposes of recreation he has selected the felling of trees; and we may usefully remark that his amusements, like his politics, are essentially destructive. Every afternoon the whole world is invited to assist at the crashing fall of some beech or elm or oak. The forest laments in order that Mr Gladstone may perspire."[58] Less noticed at the time was his practice of replacing the trees felled by planting new saplings. Gladstone was a lifelong bibliophile.[59] In his lifetime, he read around 20,000 books, and eventually owned a library of over 32,000.[60] Gladstone in 1861, photographed by John Mayall. In 1859, Lord Palmerston formed a new mixed government with Radicals included, and Gladstone again joined the government (with most of the other remaining Peelites) as Chancellor of the Exchequer, to become part of the new Liberal Party. Gladstone inherited a deficit of nearly £5,000,000, with income tax now set at 5d (fivepence). Like Peel, Gladstone dismissed the idea of borrowing to cover the deficit. Gladstone argued that "In time of peace nothing but dire necessity should induce us to borrow".[61] Most of the money needed was acquired through raising the income tax to 9d. Usually not more than two-thirds of a tax imposed could be collected in a financial year so Gladstone therefore imposed the extra four pence at a rate of 8d. during the first half of the year so that he could obtain the additional revenue in one year. Gladstone's dividing line set up in 1853 had been abolished in 1858 but Gladstone revived it, with lower incomes to pay 6½d. instead of 9d. For the first half of the year the lower incomes paid 8d. and the higher incomes paid 13d. in income tax.[62] On 12 September 1859 the Radical MP Richard Cobden visited Gladstone, who recorded it in his diary: "... further conv. with Mr. Cobden on Tariffs & relations with France. We are closely & warmly agreed".[63] Cobden was sent as Britain's representative to the negotiations with France's Michel Chevalier for a free trade treaty between the two countries. Gladstone wrote to Cobden: "... the great aim—the moral and political significance of the act, and its probable and desired fruit in binding the two countries together by interest and affection. Neither you nor I attach for the moment any superlative value to this Treaty for the sake of the extension of British trade. ... What I look to is the social good, the benefit to the relations of the two countries, and the effect on the peace of Europe".[64] Gladstone's budget of 1860 was introduced on 10 February along with the Cobden–Chevalier Treaty between Britain and France that would reduce tariffs between the two countries.[65] This budget "marked the final adoption of the Free Trade principle, that taxation should be levied for Revenue purposes alone, and that every protective, differential, or discriminating duty ... should be dislodged".[66] At the beginning of 1859, there were 419 duties in existence. The 1860 budget reduced the number of duties to 48, with 15 duties constituting the majority of the revenue. To finance these reductions in indirect taxation, the income tax, instead of being abolished, was raised to 10d. for incomes above £150 and at 7d. for incomes above £100.[67] In 1860 Gladstone intended to abolish the duty on paper - a controversial policy - because the duty traditionally inflated the cost of publishing and hindered the dissemination of radical working-class ideas. Although Palmerston supported continuation of the duty, using it and income tax revenue to buy arms, a majority of his Cabinet supported Gladstone. The Bill to abolish duties on paper narrowly passed Commons but was rejected by the House of Lords. No money bill had been rejected by Lords for over 200 years, and a furore arose over this vote. The next year, Gladstone included the abolition of paper duty in a consolidated Finance Bill (the first ever) to force the Lords to accept it, and accept it they did. The proposal in the Commons of one bill only per session for the national finances was a precedent uniformly followed from that date until 1910, and it has been ever since the rule.[68] Gladstone steadily reduced Income tax over the course of his tenure as Chancellor. In 1861 the tax was reduced to ninepence (£0–0s–9d), in 1863 to sevenpence, in 1864 to fivepence and in 1865 to fourpence.[69] Gladstone believed that government was extravagant and wasteful with taxpayers' money and so sought to let money "fructify in the pockets of the people" by keeping taxation levels down through "peace and retrenchment". In 1859 he wrote to his brother, who was a member of the Financial Reform Association at Liverpool: "Economy is the first and great article (economy such as I understand it) in my financial creed. The controversy between direct and indirect taxation holds a minor, though important place".[70] He wrote to his wife on 14 January 1860: "I am certain, from experience, of the immense advantage of strict account-keeping in early life. It is just like learning the grammar then, which when once learned need not be referred to afterwards".[71][incomplete short citation][a] Due to his actions as Chancellor, Gladstone earned the reputation as the liberator of British trade and the working man's breakfast table, the man responsible for the emancipation of the popular press from "taxes upon knowledge" and for placing a duty on the succession of the estates of the rich.[73] Gladstone's popularity rested on his taxation policies which meant to his supporters balance, social equity and political justice.[74] The most significant expression of working-class opinion was at Northumberland in 1862 when Gladstone visited. George Holyoake recalled in 1865: When Mr Gladstone visited the North, you well remember when word passed from the newspaper to the workman that it circulated through mines and mills, factories and workshops, and they came out to greet the only British minister who ever gave the English people a right because it was just they should have it ... and when he went down the Tyne, all the country heard how twenty miles of banks were lined with people who came to greet him. Men stood in the blaze of chimneys; the roofs of factories were crowded; colliers came up from the mines; women held up their children on the banks that it might be said in after life that they had seen the Chancellor of the People go by. The river was covered like the land. Every man who could ply an oar pulled up to give Mr Gladstone a cheer. When Lord Palmerston went to Bradford the streets were still, and working men imposed silence upon themselves. When Mr Gladstone appeared on the Tyne he heard cheer no other English minister ever heard ... the people were grateful to him, and rough pitmen who never approached a public man before, pressed round his carriage by thousands ... and thousands of arms were stretched out at once, to shake hands with Mr Gladstone as one of themselves.[75] When Gladstone first joined Palmerston's government in 1859, he had opposed further electoral reform, but he changed his position during Palmerston's last premiership, and by 1865 he was firmly in favour of enfranchising the working classes in towns. The policy caused friction with Palmerston, who strongly opposed enfranchisement. At the beginning of each session, Gladstone would passionately urge the Cabinet to adopt new policies, while Palmerston would fixedly stare at a paper before him. At a lull in Gladstone's speech, Palmerston would smile, rap the table with his knuckles, and interject pointedly, "Now, my Lords and gentlemen, let us go to business".[76] Although he personally was not a Nonconformist, and rather disliked them in person, he formed a coalition with the Nonconformists that gave the Liberals a powerful base of support.[77] American Civil WarEdit Shortly after the outbreak of the American Civil War Gladstone wrote to his friend the Duchess of Sutherland that "the principle announced by the vice-president of the South...which asserts the superiority of the white man, and therewith founds on it his right to hold the black in slavery, I think that principle detestable, and I am wholly with the opponents of it" but that he felt that the North was wrong to try to restore the Union by military force, which he believed would end in failure.[78] Palmerston's government adopted a position of British neutrality throughout the war, while declining to recognise the independence of the Confederacy. In October 1862 Gladstone made a speech in Newcastle in which he said that Jefferson Davis and the other Confederate leaders had "made a nation", that the Confederacy seemed certain to succeed in asserting its independence from the North, and that the time might come when it would be the duty of the European powers to "offer friendly aid in compromising the quarrel."[79] The speech caused consternation on both sides of the Atlantic and led to speculation that the Britain might be about to recognise the Confederacy."[80][81] Gladstone was accused of sympathising with the South, a charge he rejected.[82][83] Gladstone was forced to clarify in the press that his comments in Newcastle had not been intended to signal a change in Government policy, but to express his belief that the North's efforts to defeat the South would fail, due to Southern resistance.[84][85] In a memorandum to the Cabinet later that month Gladstone wrote that, although he believed the Confederacy would probably win the war, it was "seriously tainted by its connection with slavery" and argued that the European powers should use their influence on the South to effect the "mitigation or removal of slavery."[86] Electoral reformEdit In May 1864 Gladstone said that he saw no reason in principle why all mentally able men could not be enfranchised, but admitted that this would only come about once the working classes themselves showed more interest in the subject. Queen Victoria was not pleased with this statement, and an outraged Palmerston considered it a seditious incitement to agitation.[87] Gladstone's support for electoral reform and disestablishment of the (Anglican) Church of Ireland won support from Nonconformists but alienated him from constituents in his Oxford University seat, and he lost it in the 1865 general election. A month later he stood as a candidate in South Lancashire, where he was elected third MP (South Lancashire at this time elected three MPs). Palmerston campaigned for Gladstone in Oxford because he believed that his constituents would keep him "partially muzzled"; many Oxford graduates were Anglican clergymen at that time. A victorious Gladstone told his new constituency, "At last, my friends, I am come among you; and I am come—to use an expression which has become very famous and is not likely to be forgotten—I am come 'unmuzzled'."[88] On Palmerston's death in October, Earl Russell formed his second ministry.[89] Russell and Gladstone (now the senior Liberal in the House of Commons) attempted to pass a reform bill, which was defeated in the Commons because the "Adullamite" Whigs, led by Robert Lowe, refused to support it. The Conservatives then formed a ministry, in which after long Parliamentary debate Disraeli passed the Second Reform Act of 1867; Gladstone's proposed bill had been totally outmanoeuvred; he stormed into the Chamber, but too late to see his arch-enemy pass the bill. Gladstone was furious; his animus commenced a long rivalry that would only end on Disraeli's death and Gladstone's encomium in the Commons in 1881.[90] Leader of the Liberal Party, from 1867Edit Lord Russell retired in 1867 and Gladstone became leader of the Liberal Party.[91] In 1868 the Irish Church Resolutions was proposed as a measure to reunite the Liberal Party in government (on the issue of disestablishment of the Church of Ireland—this would be done during Gladstone's First Government in 1869 and meant that Irish Roman Catholics did not need to pay their tithes to the Anglican Church of Ireland).[92] When it was passed Disraeli took the hint and called a General Election. First premiership (1868–1874)Edit Main articles: First premiership of William Gladstone, First Gladstone ministry, and Foreign Policy of William Ewart Gladstone Gladstone's Cabinet of 1868, painted by Lowes Cato Dickinson.[93] Use a cursor to see who is who.[94] In the next general election in 1868, the South Lancashire constituency had been broken up by the Second Reform Act into two: South East Lancashire and South West Lancashire. Gladstone stood for South West Lancashire and for Greenwich, it being quite common then for candidates to stand in two constituencies simultaneously.[95] To his great surprise he was defeated in South Lancashire but winning in Greenwich was able to remain in Parliament. He became Prime Minister for the first time and remained in the office until 1874. Evelyn Ashley famously described the scene in the grounds of Hawarden Castle on 1 December 1868: One afternoon...in the Park at Hawarden, I was standing by Mr. Gladstone holding his coat on my arm while he, in his shirt sleeves, was wielding an axe to cut down a tree. Up came a telegraph messenger. He took the telegram, opened it and read it, then handed it to me, speaking only two words, namely, 'Very significant', and at once resumed his work. The message merely stated that General Grey would arrive that evening from Windsor. This, of course, implied that a mandate was coming from the Queen charging Mr. Gladstone with the formation of his first Government. I said nothing, but waited while the well-directed blows resounded in regular cadence. After a few minutes the blows ceased and Mr. Gladstone, resting on the handle of his axe, looked up, and with deep earnestness in his voice, and great intensity in his face, exclaimed: 'My mission is to pacify Ireland.' He then resumed his task, and never said another word till the tree was down.[96] In the 1860s and 1870s, Gladstonian Liberalism was characterised by a number of policies intended to improve individual liberty and loosen political and economic restraints. First was the minimisation of public expenditure on the premise that the economy and society were best helped by allowing people to spend as they saw fit. Secondly, his foreign policy aimed at promoting peace to help reduce expenditures and taxation and enhance trade. Thirdly, laws that prevented people from acting freely to improve themselves were reformed. When an unemployed miner (Daniel Jones) wrote to him to complain of his unemployment and low wages, Gladstone gave what H. C. G. Matthew has called "the classic mid-Victorian reply" on 20 October 1869: The only means which have been placed in my power of 'raising the wages of colliers' has been by endeavouring to beat down all those restrictions upon trade which tend to reduce the price to be obtained for the product of their labour, & to lower as much as may be the taxes on the commodities which they may require for use or for consumption. Beyond this I look to the forethought not yet so widely diffused in this country as in Scotland, & in some foreign lands; & I need not remind you that in order to facilitate its exercise the Government have been empowered by Legislation to become through the Dept. of the P.O. the receivers & guardians of savings.[97] Gladstone's first premiership instituted reforms in the British Army, civil service, and local government to cut restrictions on individual advancement. The Local Government Board Act 1871 put the supervision of the Poor Law under the Local Government Board (headed by G.J. Goschen) and Gladstone's "administration could claim spectacular success in enforcing a dramatic reduction in supposedly sentimental and unsystematic outdoor poor relief, and in making, in co-operation with the Charity Organization Society (1869), the most sustained attempt of the century to impose upon the working classes the Victorian values of providence, self-reliance, foresight, and self-discipline".[98] Gladstone was associated with the Charity Organization Society's first annual report in 1870.[99] Some leading Conservatives at this time were contemplating an alliance between the aristocracy and the working class against the capitalist class, an idea called the New Social Alliance.[100] At a speech at Blackheath on 28 October 1871, he warned his constituents against these social reformers: ... they are not your friends, but they are your enemies in fact, though not in intention, who teach you to look to the Legislature for the radical removal of the evils that afflict human life. ... It is the individual mind and conscience, it is the individual character, on which mainly human happiness or misery depends. (Cheers.) The social problems that confront us are many and formidable. Let the Government labour to its utmost, let the Legislature labour days and nights in your service; but, after the very best has been attained and achieved, the question whether the English father is to be the father of a happy family and the centre of a united home is a question which must depend mainly upon himself. (Cheers.) And those who ... promise to the dwellers in towns that every one of them shall have a house and garden in free air, with ample space; those who tell you that there shall be markets for selling at wholesale prices retail quantities—I won't say are impostors, because I have no doubt they are sincere; but I will say they are quacks (cheers); they are deluded and beguiled by a spurious philanthropy, and when they ought to give you substantial, even if they are humble and modest boons, they are endeavouring, perhaps without their own consciousness, to delude you with fanaticism, and offering to you a fruit which, when you attempt to taste it, will prove to be but ashes in your mouths. (Cheers.)[101] Gladstone as caricatured by Vanity Fair in 1869. Gladstone instituted abolition of the sale of commissions in the army: he also instituted the Cardwell Reforms in 1869 that made peacetime flogging illegal. In 1871 his government passed the Trade Union Act allowing trade unions to organise and operate legally for the first time (although picketing remained illegal). Gladstone later counted this reform as one of the most significant of the previous half century, saying that prior to its passage the law had effectively "compelled the British workman to work...in chains."[102] He secured passage of the Ballot Act for secret ballots, and the Licensing Act 1872. In 1873, his leadership led to the passage of laws restructuring the High Courts. In 1870, the Irish Land Act and Forster's Education Act. In 1871, he instituted the Universities Tests Act. In foreign affairs his over-riding aim was to promote peace and understanding, characterised by his settlement of the Alabama Claims in 1872 in favour of the Americans. Gladstone unexpectedly dissolved Parliament in January 1874 and called a general election. [b] Gladstone's proposals went some way to meet working-class demands, such as the realisation of the free breakfast table through repealing duties on tea and sugar, and reform of local taxation which was increasing for the poorer ratepayers.[104] According to the working-class financial reformer Thomas Briggs, writing in the trade unionist newspaper The Bee-Hive, the manifesto relied on "a much higher authority than Mr. Gladstone...viz., the late Richard Cobden".[105] The dissolution itself was reported in The Times on 24 January. On 30 January, the names of the first fourteen MPs for uncontested seats were published. By 9 February a Conservative victory was apparent. In contrast to 1868 and 1880 when the Liberal campaign lasted several months, only three weeks separated the news of the dissolution and the election. The working-class newspapers were so taken by surprise they had little time to express an opinion on Gladstone's manifesto before the election was over.[106] Unlike the efforts of the Conservatives, the organisation of the Liberal Party had declined since 1868 and they had also failed to retain Liberal voters on the electoral register. George Howell wrote to Gladstone on 12 February: "There is one lesson to be learned from this Election, that is Organization. ... We have lost not by a change of sentiment so much as by want of organised power".[107] The Liberals received a majority of the vote in each of the constituent countries of the United Kingdom and 189,000 more votes nationally than the Conservatives. However, they obtained a minority of seats in the House of Commons.[108] Gladstone in 1874, painted by Franz von Lenbach. In the wake of Benjamin Disraeli's victory, Gladstone retired from the leadership of the Liberal party, although he retained his seat in the House. Anti-CatholicismEdit Further information: Anti-Catholicism in the United Kingdom Gladstone had a complex ambivalence about Catholicism. He was attracted by its international success in majestic traditions. More important, he was strongly opposed to the authoritarianism of its pope and bishops, its profound public opposition to liberalism, and its refusal to distinguish between secular allegiance on the one hand and spiritual obedience on the other. The danger came when the pope or bishops attempted to exert temporal power, as in the Vatican decrees of 1870 as the climax of the papal attempt to control churches in different nations, despite their independent nationalism.[109] On the other hand, when ritual practices in the Church of England—such as vestments and incense—came under attack as too ritualistic and too much akin to Catholicism, Gladstone strongly opposed passage of the Public Worship Regulation Act in 1874.[110] In November 1874, he published the pamphlet The Vatican Decrees in their Bearing on Civil Allegiance, directed at the First Vatican Council's dogmatising Papal Infallibility in 1870, which had outraged him.[111] Gladstone claimed that this decree had placed British Catholics in a dilemma over conflicts of loyalty to the Crown. He urged them to reject papal infallibility as they had opposed the Spanish Armada of 1588. The pamphlet sold 150,000 copies by the end of 1874. A second pamphlet followed in Feb 1875, a defence of the earlier pamphlet and a reply to his critics, entitled Vaticanism: an Answer to Reproofs and Replies.[112] He described the Catholic Church as "an Asian monarchy: nothing but one giddy height of despotism, and one dead level of religious subservience". He further claimed that the Pope wanted to destroy the rule of law and replace it with arbitrary tyranny, and then to hide these "crimes against liberty beneath a suffocating cloud of incense".[113] Portrait of Gladstone at Hawarden in 1877 Self help and opposition to socialismEdit In a speech to the Hawarden Amateur Horticultural Society on 17 August 1876, Gladstone remarked "I am delighted to see how many young boys and girls have come forward to obtain honourable marks of recognition on this occasion,—if any effectual good is to be done to them, it must be done by teaching and encouraging them and helping them to help themselves. All the people who pretend to take your own concerns out of your own hands and to do everything for you, I won't say they are impostors; I won't even say they are quacks; but I do say they are mistaken people. The only sound, healthy description of countenancing and assisting these institutions is that which teaches independence and self-exertion".[114] Lord Kilbracken, one of Gladstone's secretaries added: It will be borne in mind that the Liberal doctrines of that time, with their violent anti-socialist spirit and their strong insistence on the gospel of thrift, self-help, settlement of wages by the higgling of the market, and non-interference by the State.... I think that Mr. Gladstone was the strongest anti-socialist that I have ever known among persons who gave any serious thought to social and political questions. It is quite true, as has been often said, that "we are all socialists up to a certain point"; but Mr. Gladstone fixed that point lower, and was more vehement against those who went above it, than any other politician or official of my acquaintance. I remember his speaking indignantly to me of the budget of 1874 as "That socialistic budget of Northcote's," merely because of the special relief which it gave to the poorer class of income-tax payers. His strong belief in Free Trade was only one of the results of his deep-rooted conviction that the Government's interference with the free action of the individual, whether by taxation or otherwise, should be kept at an irreducible minimum. It is, indeed, not too much to say that his conception of Liberalism was the negation of Socialism.[115] Bulgarian HorrorsEdit Further information: April Uprising of 1876 A pamphlet Gladstone published on 6 September 1876, Bulgarian Horrors and the Question of the East,[116][117][118] attacked the Disraeli government for its indifference to the Ottoman Empire's violent repression of the Bulgarian April uprising. Gladstone made clear his hostility focused on the Turkish people, rather than on the Muslim religion. The Turks he said: were, upon the whole, from the black day when they first entered Europe, the one great anti-human specimen of humanity. Wherever they went, a broad line of blood marked the track behind them; and as far as their dominion reached, civilisation disappeared from view. They represented everywhere government by force, as opposed to government by law. For the guide of this life they had a relentless fatalism: for its reward hereafter, a sensual paradise.[119] Gladstone in 1879, painted by John Everett Millais. The historian Geoffrey Alderman has described Gladstone as 'unleashing the full fury of his oratorical powers against Jews and Jewish influence' during the Bulgarian Crisis (1885–88), telling a journalist in 1876 that: "I deeply deplore the manner in which, what I may call Judaic sympathies, beyond as well as within the circle of professed Judaism, are now acting on the question of the East'.[120] Gladstone similarly refused to speak out against the persecution of Romanian Jews in the 1870s and Russian Jews in the early 1880s.[120] In response, the Jewish Chronicle attacked Gladstone in 1888, arguing that 'Are we, because there was once a Liberal Party, to bow down and worship Gladstone—the great Minister who was too Christian in his charity, too Russian in his proclivities, to raise voice or finger' to defend Russian Jews...[121] Alderman attributes these developments, along with other factors, to the collapse of the previously strong ties between British Jews and Liberalism.[120] During the 1879 election campaign, called the Midlothian campaign, he rousingly denounced Disraeli's foreign policies during the ongoing Second Anglo-Afghan War in Afghanistan. (See Great Game). He saw the war as "great dishonour" and also criticised British conduct in the Zulu War. Gladstone also (on 29 November) condemned what he saw as the Conservative government's profligate spending: ...the Chancellor of the Exchequer shall boldly uphold economy in detail; and it is the mark ... of ... a chicken-hearted Chancellor of the Exchequer, when he shrinks from upholding economy in detail, when, because it is a question of only £2,000 or £3,000, he says that is no matter. He is ridiculed, no doubt, for what is called saving candle-ends and cheese-parings. No Chancellor of the Exchequer is worth his salt who is not ready to save what are meant by candle-ends and cheese-parings in the cause of his country. No Chancellor of the Exchequer is worth his salt who makes his own popularity either his first consideration, or any consideration at all, in administrating the public purse. You would not like to have a housekeeper or steward who made her or his popularity with the tradesmen the measure of the payments that were to be delivered to them. In my opinion the Chancellor of the Exchequer is the trusted and confidential steward of the public. He is under a sacred obligation with regard to all that he consents to spend.... I am bound to say hardly ever in the six years that Sir Stafford Northcote has been in office have I heard him speak a resolute word on behalf of economy.[122] Second premiership (1880–1885)Edit Main articles: Second premiership of William Ewart Gladstone and Second Gladstone ministry The Cabinet Council, 1883 by Théobald Chartran, published in Vanity Fair, 27 November 1883 In 1880, the Liberals won again and the Liberal leaders, Lord Hartington (leader in the House of Commons) and Lord Granville, retired in Gladstone's favour. Gladstone won his constituency election in Midlothian and also in Leeds, where he had also been adopted as a candidate. As he could lawfully only serve as MP for one constituency, Leeds was passed to his son Herbert. One of his other sons, Henry, was also elected as an MP. Queen Victoria asked Lord Hartington to form a ministry, but he persuaded her to send for Gladstone. Gladstone's second administration—both as Prime Minister and again as Chancellor of the Exchequer till 1882—lasted from June 1880 to June 1885. He originally intended to retire at the end of 1882, the 50th anniversary of his entry into politics, but did not do so.[123] Foreign policyEdit Main article: Foreign Policy of William Ewart Gladstone Historians have debated the wisdom of Gladstone's foreign-policy during his second ministry.[124][125] Paul Hayes says it "provides one of the most intriguing and perplexing tales of muddle and incompetence in foreign affairs, unsurpassed in modern political history until the days of Grey and, later, Neville Chamberlain."[126] Gladstone opposed himself to the "colonial lobby" pushing for the scramble for Africa. His term saw the end of the Second Anglo-Afghan War, the First Boer War, and the war against the Mahdi in Sudan. On 11 July 1882, Gladstone ordered the bombardment of Alexandria, starting the short, Anglo-Egyptian War of 1882. The British won decisively, and although they repeatedly promised to depart in a few years, the actual result was British control of Egypt for four decades, largely ignoring Ottoman nominal ownership. France was seriously unhappy, having lost control of the canal that it built and financed and had dreamed of for decades. Gladstone's role in the decision to invade was described as relatively hands-off, and the ultimate responsibility was borne by certain members of his cabinet such as Lord Hartington, Secretary of State for India, Thomas Baring, 1st Earl of Northbrook, First Lord of the Admiralty, Hugh Childers, Secretary of State for War, and Granville Leveson-Gower, 2nd Earl Granville, the Foreign Secretary.[127] Historian A.J.P. Taylor says that the seizure of Egypt "was a great event; indeed, the only real event in international relations between the Battle of Sedan and the defeat of Russia in the Russo-Japanese war."[128] Taylor emphasizes long-term impact: The British occupation of Egypt altered the balance of power. It not only gave the British security for their route to India, it made them masters of the Eastern Mediterranean and the Middle East. It made it unnecessary for them to stand in the front line against Russia at the Straits....And thus prepared the way for the Franco-Russian Alliance ten years later.[129] Gladstone and the Liberals had a reputation for strong opposition to imperialism, so historians have long debated the explanation for this reversal of policy. The most influential was a study by John Robinson and Ronald Gallagher, Africa and the Victorians (1961) Which focused on The Imperialism of Free Trade and was promoted by the Cambridge School of historiography. They argue there was no long-term Liberal plan in support of imperialism. Instead they saw the urgent necessity to act to protect the Suez Canal in the face of what appeared to be a radical collapse of law and order, and a nationalist revolt focused on expelling the Europeans, regardless of the damage it would do to international trade and the British Empire. Gladstone's decision came against strained relations with France, and maneuvering by "men on the spot" in Egypt. Critics such as Cain and Hopkins have stressed the need to protect large sums invested by British financiers and Egyptian bonds, while downplaying the risk to the viability of the Suez Canal. Unlike the Marxists, they stress "gentlemanly" financial and commercial interests, not the industrial capitalism that Marxists believe was always central.[130] More recently, specialists on Egypt have been interested primarily in the internal dynamics among Egyptians that produce the failed Urabi Revolt.[131][132] IrelandEdit Main article: Irish issue in British politics In 1881 he established the Irish Coercion Act, which permitted the Lord Lieutenant of Ireland to detain people for as "long as was thought necessary", as there was rural disturbance in Ireland between landlords and tenants as Cavendish, the Irish Secretary, had been assassinated by Irish rebels in Dublin.[133] He also passed the Second Land Act (the First, in 1870, had entitled Irish tenants, if evicted, to compensation for improvements which they had made on their property, but had had little effect) which gave Irish tenants the "3Fs"—fair rent, fixity of tenure and free sale.[134] He was elected a Fellow of the Royal Society (FRS) in 1881.[135] FranchiseEdit Gladstone in 1884, photographed by Rupert Potter Gladstone extended the vote to agricultural labourers and others in the 1884 Reform Act, which gave the counties the same franchise as the boroughs—adult male householders and £10 lodgers—and added six million to the total number of people who could vote in parliamentary elections. Parliamentary reform continued with the Redistribution of Seats Act 1885.[136] Gladstone was increasingly uneasy about the direction in which British politics was moving. In a letter to Lord Acton on 11 February 1885, Gladstone criticised Tory Democracy as "demagogism" that "put down pacific, law-respecting, economic elements that ennobled the old Conservatism" but "still, in secret, as obstinately attached as ever to the evil principle of class interests". He found contemporary Liberalism better, "but far from being good". Gladstone claimed that this Liberalism's "pet idea is what they call construction,—that is to say, taking into the hands of the state the business of the individual man". Both Tory Democracy and this new Liberalism, Gladstone wrote, had done "much to estrange me, and had for many, many years".[137] FailureEdit Historian Sneh Mahajan has concluded, "Gladstone's second ministry remained barren of any achievement in the domestic sphere."[138] His downfall came in Africa, where he delayed the mission to rescue General Gordon's force which had been under siege in Khartoum for 10 months. It arrived in January 1885 two days after a massacre killed thousands. The disaster proved a major blow to Gladstone's popularity. Queen Victoria sent him a telegram of rebuke which found its way into the press. Critics said Gladstone had neglected military affairs and had not acted promptly enough to save the besieged Gordon. Critics inverted his acronym, "G.O.M." (for "Grand Old Man"), to "M.O.G." (for "Murderer of Gordon"). He resigned as Prime Minister in June 1885 and declined Queen Victoria's offer of an earldom.[139] Third premiership (1886)Edit Main articles: Third premiership of William Ewart Gladstone and Third Gladstone ministry A political cartoon depicting Gladstone "kicked out of office" in 1886 The Hawarden Kite was a December 1885 press release by Gladstone's son and aide Herbert Gladstone announcing that he had become convinced that Ireland needed a separate parliament.[140][141] The bombshell announcement resulted in the fall of Lord Salisbury's Conservative government. Irish Nationalists, led by Charles Parnell's Irish Parliamentary Party, held the balance of power in Parliament. Gladstone's conversion to Home Rule convinced them to switch away from the Conservatives and support the Liberals using the 86 seats in Parliament they controlled. The main purpose of this administration was to deliver Ireland a reform which would give it a devolved assembly, similar to those which would be eventually put in place in Scotland and Wales in 1999. In 1886 Gladstone's party allied with Irish Nationalists to defeat Lord Salisbury's government. Gladstone regained his position as Prime Minister and combined the office with that of Lord Privy Seal. During this administration he first introduced his Home Rule Bill for Ireland. The issue split the Liberal Party (a breakaway group went on to create the Liberal Unionist party) and the bill was thrown out on the second reading, ending his government after only a few months and inaugurating another headed by Lord Salisbury. Gladstone, says his biographer, "totally rejected the widespread English view that the Irish had no taste for justice, common sense, moderation or national prosperity and looked only to perpetual strife and dissension".[142] The problem for Gladstone was that his rural English supporters would not support home rule for Ireland. A large faction of Liberals, led by Joseph Chamberlain, formed a Unionist faction that supported the Conservative party. Whenever the Liberals were out of power, home rule proposals languished. Gladstone in 1886, as painted by Franz von Lenbach. Gladstone supported the London dockers in their strike of 1889. After their victory he gave a speech at Hawarden on 23 September in which he said: "In the common interests of humanity, this remarkable strike and the results of this strike, which have tended somewhat to strengthen the condition of labour in the face of capital, is the record of what we ought to regard as satisfactory, as a real social advance [that] tends to a fair principle of division of the fruits of industry".[143] This speech has been described by Eugenio Biagini as having "no parallel in the rest of Europe except in the rhetoric of the toughest socialist leaders".[144] Visitors at Hawarden in October were "shocked...by some rather wild language on the Dock labourers question".[145] Gladstone was impressed with workers unconnected with the dockers' dispute who "intended to make common cause" in the interests of justice. On 23 October at Southport, Gladstone delivered a speech where he said that the right to combination, which in London was "innocent and lawful, in Ireland would be penal and...punished by imprisonment with hard labour". Gladstone believed that the right to combination used by British workers was in jeopardy when it could be denied to Irish workers.[146] In October 1890 Gladstone at Midlothian claimed that competition between capital and labour, "where it has gone to sharp issues, where there have been strikes on one side and lock-outs on the other, I believe that in the main and as a general rule, the labouring man has been in the right".[147] On 11 December 1891 Gladstone said that: "It is a lamentable fact if, in the midst of our civilisation, and at the close of the nineteenth century, the workhouse is all that can be offered to the industrious labourer at the end of a long and honourable life. I do not enter into the question now in detail. I do not say it is an easy one; I do not say that it will be solved in a moment; but I do say this, that until society is able to offer to the industrious labourer at the end of a long and blameless life something better than the workhouse, society will not have discharged its duties to its poorer members".[148] On 24 March 1892 Gladstone said that the Liberals had: ...come generally...to the conclusion that there is something painful in the condition of the rural labourer in this great respect, that it is hard even for the industrious and sober man, under ordinary conditions, to secure a provision for his own old age. Very large propositions, involving, some of them, very novel and very wide principles, have been submitted to the public, for the purpose of securing such a provision by means independent of the labourer himself....our duty [is] to develop in the first instance, every means that we may possibly devise whereby, if possible, the labourer may be able to make this provision for himself, or to approximate towards making such provision far more efficaciously and much more closely than he can now do.[149][150] Gladstone wrote on 16 July 1892 in autobiographica that "In 1834 the Government...did themselves high honour by the new Poor Law Act, which rescued the English peasantry from the total loss of their independence".[151] There were many who disagreed with him. Gladstone wrote to Herbert Spencer, who contributed the introduction to a collection of anti-socialist essays (A Plea for Liberty, 1891), that "I ask to make reserves, and of one passage, which will be easily guessed, I am unable even to perceive the relevancy. But speaking generally, I have read this masterly argument with warm admiration and with the earnest hope that it may attract all the attention which it so well deserves".[152] The passage Gladstone alluded to was one where Spencer had spoken of "the behaviour of the so-called Liberal party".[153] Fourth premiership (1892–1894)Edit Main articles: Fourth premiership of William Ewart Gladstone, Fourth Gladstone ministry, and Foreign Policy of William Ewart Gladstone A political cartoon depicting Gladstone as a radical bent on abolishing the House of Lords The general election of 1892 resulted in a minority Liberal government with Gladstone as Prime Minister. The electoral address had promised Irish Home Rule and the disestablishment of the Scottish and Welsh Churches.[154] In February 1893 he introduced the Second Home Rule Bill, which was passed in the Commons at second reading on 21 April by 43 votes and third reading on 1 September by 34 votes. The House of Lords defeated the bill by voting against by 419 votes to 41 on 8 September. The Elementary Education (Blind and Deaf Children) Act, passed in 1893, required local authorities to provide separate education for blind and deaf children.[155] Conservative MP Colonel Howard Vincent questioned Gladstone in the Commons on what his government would do about unemployment on 1 September 1893. Gladstone replied: I cannot help regretting that the honourable and gallant Gentleman has felt it his duty to put the question. It is put under circumstances that naturally belong to one of those fluctuations in the condition of trade which, however unfortunate and lamentable they may be, recur from time to time. Undoubtedly I think that questions of this kind, whatever be the intention of the questioner, have a tendency to produce in the minds of people, or to suggest to the people, that these fluctuations can be corrected by the action of the Executive Government. Anything that contributes to such an impression inflicts an injury upon the labouring population.[156][157] In December 1893, an Opposition motion proposed by Lord George Hamilton called for an expansion of the Royal Navy. Gladstone opposed increasing public expenditure on the naval estimates, in the tradition of free trade liberalism of his earlier political career as Chancellor. All his Cabinet colleagues believed in some expansion of the navy. He declared in the Commons on 19 December that naval rearmament would commit the government to expenditure over a number of years and would subvert "the principle of annual account, annual proposition, annual approval by the House of Commons, which...is the only way of maintaining regularity, and that regularity is the only talisman which will secure Parliamentary control".[158] In January 1894, Gladstone wrote that he would not "break to pieces the continuous action of my political life, nor trample on the tradition received from every colleague who has ever been my teacher" by supporting naval rearmament.[159] Gladstone also opposed Chancellor Sir William Harcourt's proposal to implement a graduated death duty. In a fragment of autobiography dated 25 July 1894, Gladstone denounced the tax as ...by far the most Radical measure of my lifetime. I do not object to the principle of graduated taxation: for the just principle of ability to pay is not determined simply by the amount of income.... But, so far as I understand the present measure of finance from the partial reports I have received, I find it too violent. It involves a great departure from the methods of political action established in this country, where reforms, and especially financial reforms, have always been considerate and even tender.... I do not yet see the ground on which it can be justly held that any one description of property should be more heavily burdened than others, unless moral and social grounds can be shown first: but in this case the reasons drawn from those sources seem rather to verge in the opposite direction, for real property has more of presumptive connection with the discharge of duty than that which is ranked as personal...the aspect of the measure is not satisfactory to a man of my traditions (and these traditions lie near the roots of my being).... For the sudden introduction of such change there is I think no precedent in the history of this country. And the severity of the blow is greatly aggravated in moral effect by the fact that it is dealt only to a handful of individuals.[160] Gladstone had his last audience with Queen Victoria on 28 February 1894 and chaired his last Cabinet on 1 March—the last of 556 he had chaired. On that day he gave his last speech to the House of Commons, saying that the government would withdraw opposition to the Lords' amendments to the Local Government Bill "under protest" and that it was "a controversy which, when once raised, must go forward to an issue".[161] He resigned from the premiership on 2 March. The Queen did not ask Gladstone who should succeed him, but sent for Lord Rosebery (Gladstone would have advised on Lord Spencer).[162] He retained his seat in the House of Commons until 1895. He was not offered a peerage, having earlier declined an earldom. Gladstone is both the oldest person to form a government—aged 82 at his appointment—and the oldest person to occupy the Premiership—being 84 at his resignation.[163] Final years (1894–1898)Edit Gladstone in old age In 1895, at the age of 85, Gladstone bequeathed £40,000 (equivalent to approximately £4.65 million today)[164] and much of his 32,000 volume library to found St Deiniol's Library in Hawarden, Wales.[165] It had begun with just 5,000 items at his father's home Fasque, which were transferred to Hawarden for research in 1851. On 8 January 1896, in conversation with L.A. Tollemache, Gladstone explained that: "I am not so much afraid of Democracy or of Science as of the love of money. This seems to me to be a growing evil. Also, there is a danger from the growth of that dreadful military spirit".[166] On 13 January, Gladstone claimed he had strong Conservative instincts and that "In all matters of custom and tradition, even the Tories look upon me as the chief Conservative that is".[167] On 15 January Gladstone wrote to James Bryce, describing himself as "a dead man, one fundamentally a Peel–Cobden man".[168] In 1896, in his last noteworthy speech, he denounced Armenian massacres by Ottomans in a talk delivered at Liverpool. On 2 January 1897, Gladstone wrote to Francis Hirst on being unable to draft a preface to a book on liberalism: "I venture on assuring you that I regard the design formed by you and your friends with sincere interest, and in particular wish well to all the efforts you may make on behalf of individual freedom and independence as opposed to what is termed Collectivism".[169][170] In the early months of 1897, Gladstone and his wife stayed in Cannes. Gladstone met Queen Victoria, and she shook hands with him for (to his recollection) the first time in the 50 years he had known her.[171] One of the Gladstones' neighbours observed that "He and his devoted wife never missed the morning service on Sunday ... One Sunday, returning from the altar rail, the old, partially blind man stumbled at the chancel step. One of the clergy sprang involuntarily to his assistance, but retreated with haste, so withering was the fire which flashed from those failing eyes."[172] The Gladstones returned to Hawarden Castle at the end of March and he received the Colonial Premiers in their visit for the Queen's Jubilee. At a dinner in November with Edward Hamilton, his former private secretary, Hamilton noted that "What is now uppermost in his mind is what he calls the spirit of jingoism under the name of Imperialism which is now so prevalent". Gladstone riposted "It was enough to make Peel and Cobden turn in their graves".[173] On the advice of his doctor Samuel Habershon in the aftermath of an attack of facial neuralgia, Gladstone stayed at Cannes from the end of November 1897 to mid-February 1898. He gave an interview for The Daily Telegraph.[174] Gladstone then travelled to Bournemouth, where a swelling on his palate was diagnosed as cancer by the leading cancer surgeon Sir Thomas Smith on 18 March. On 22 March, he retired to Hawarden Castle. Despite being in pain he received visitors and quoted hymns, especially Cardinal Newman's "Praise to the Holiest in the Height". Gladstone's grave in Westminster Abbey His last public statement was dictated to his daughter Helen in reply to receiving the Vice-Chancellor of the University of Oxford's "sorrow and affection": "There is no expression of Christian sympathy that I value more than that of the ancient University of Oxford, the God-fearing and God-sustaining University of Oxford. I served her perhaps mistakenly, but to the best of my ability. My most earnest prayers are hers to the uttermost and to the last".[175] He left the house for the last time on 9 April. After 18 April he did not come down to the ground floor but still came out of bed to lie on the sofa. The Bishop of St Andrews, Dunkeld and Dunblane George Wilkinson recorded when he ministered to him along with Stephen Gladstone: Shall I ever forget the last Friday in Passion Week, when I gave him the last Holy Communion that I was allowed to administer to him? It was early in the morning. He was obliged to be in bed, and he was ordered to remain there, but the time had come for the confession of sin and the receiving of absolution. Out of his bed he came. Alone he knelt in the presence of his God till the absolution has been spoken, and the sacred elements received.[176] Gladstone died on 19 May 1898 at Hawarden Castle, Hawarden, aged 88. He had been cared for by his daughter Helen who had resigned her job to care for her father and mother.[177] The cause of death is officially recorded as "Syncope, Senility". "Syncope" meant failure of the heart and "senility" in the 19th century was an infirmity of advanced old age, rather than a loss of mental faculties.[178] The House of Commons adjourned on the afternoon of Gladstone's death, with A.J. Balfour giving notice for an Address to the Queen praying for a public funeral and a public memorial in Westminster Abbey. The day after, both Houses of Parliament approved of the Address and Herbert Gladstone accepted a public funeral on behalf of the Gladstone family.[179] His coffin was transported on the London Underground before his state funeral at Westminster Abbey, at which the Prince of Wales (the future King Edward VII) and the Duke of York (the future King George V) acted as pallbearers.[180] His wife, Catherine Gladstone (née Glynne), died two years later on 14 June 1900; and was buried next to him. ReligionEdit Gladstone's intensely religious mother was an evangelical of Scottish Episcopal origins,[181] and his father joined the Church of England, having been a Presbyterian when he first settled in Liverpool. As a boy William was baptised into the Church of England. He rejected a call to enter the ministry, and on this his conscience always tormented him. In compensation he aligned his politics with the evangelical faith in which he fervently believed.[182] In 1838 Gladstone nearly ruined his career when he tried to force a religious mission upon the Conservative Party. His book The State in its Relations with the Church argued that England had neglected its great duty to the Church of England. He announced that since that church possessed a monopoly of religious truth, nonconformists and Roman Catholics ought to be excluded from all government positions. The historian Thomas Babington Macaulay and other critics ridiculed his arguments and refuted them. Sir Robert Peel, Gladstone's chief, was outraged because this would upset the delicate political issue of Catholic Emancipation and anger the Nonconformists. Since Peel greatly admired his protégé, he redirected his focus from theology to finance.[183] Gladstone altered his approach to religious problems, which always held first place in his mind. Before entering Parliament he had already substituted a high church Anglican attitude, with its dependence on authority and tradition, for the evangelical outlook of his boyhood, with its reliance upon the direct inspiration of the Bible. In middle life he decided that the individual conscience would have to replace authority as the inner citadel of the Church. That view of the individual conscience affected his political outlook and changed him gradually from a Conservative into a Liberal.[184] Marriage and familyEdit Gladstone c. 1835, painted by William Cubley. Gladstone's early attempts to find a wife proved unsuccessful, with his being rejected by Caroline Eliza Farquhar (daughter of Sir Thomas Harvie Farquhar, 2nd Baronet) in 1835, and by Lady Frances Harriet Douglas (daughter of George Douglas, 17th Earl of Morton) in 1837.[185] The following year, having met her in 1834 at the London home of Old Etonian friend and then fellow-Conservative MP James Milnes Gaskell,[186] he married Catherine Glynne, to whom he remained married until his death 59 years later. They had eight children together: William Henry Gladstone MP (3 June 1840 – 4 July 1891); married Hon. Gertrude Stuart (daughter of Charles Stuart, 12th Lord Blantyre) on 30 September 1875. They had three children. Agnes Gladstone (18 October 1842 – 9 May 1931); she married Very Rev. Edward Wickham on 27 December 1873. They had three children. The Rev. Stephen Edward Gladstone (4 April 1844 – 23 April 1920); he married Annie Wilson on 29 January 1885. They had five children and were ancestors of the Gladstone baronets after 1945. Catherine Jessy Gladstone (27 July 1845 – 9 April 1850) Mary Gladstone (23 November 1847 – 1 January 1927); she married Reverend Harry Drew on 2 February 1886. They had two daughters. Helen Gladstone (28 August 1849 – 19 August 1925), Vice-Principal of Newnham College, Cambridge Henry Neville Gladstone (2 April 1852 – 28 April 1935); he married Hon. Maud Rendel on 30 January 1890. Herbert John Gladstone MP (7 January 1854 – 6 March 1930); he married Dorothy Paget on 2 November 1901. Gladstone's eldest son William (known as "Willy" to distinguish him from his father), and youngest, Herbert, both became Members of Parliament. William Henry predeceased his father by seven years. Gladstone's private secretary was his nephew Spencer Lyttelton.[187] DescendantsEdit Gladstone at Hawarden with his grandchild Dorothy Drew (1890-1982),[188] daughter of Mary Gladstone Two of Gladstone's sons and a grandson, William Glynne Charles Gladstone, followed him into parliament, making for four generations of MPs in total. One of his collateral descendants, George Freeman, has been the Conservative Member of Parliament for Mid Norfolk since 2010.[189] Sir Albert Gladstone, 5th baronet and Sir Charles Gladstone, 6th baronet (from whom the 7th and 8th baronets are descended) were also grandsons. LegacyEdit The historian H. C. G. Matthew states that Gladstone's chief legacy lay in three areas: his financial policy, his support for Home Rule (devolution) that modified the view of the unitary state of the United Kingdom and his idea of a progressive, reforming party broadly based and capable of accommodating and conciliating varying interests, along with his speeches at mass public meetings.[190] Historian Walter L. Arnstein concludes: Notable as the Gladstonian reforms had been, they had almost all remained within the 19th-century Liberal tradition of gradually removing the religious, economic and political barriers that prevented men of varied creeds and classes from exercising their individual talents in order to improve themselves and their society. As the third quarter of the century drew to a close, the essential bastions of Victorianism still held firm: respectability; a government of aristocrats and gentlemen now influenced not only by middle-class merchants and manufacturers but also by industrious working people: a prosperity that seemed to rest largely on the tenets of laissez-faire economics; and a Britannia that ruled the waves and many a dominion beyond.[191] Lord Acton wrote in 1880 that he considered Gladstone one "of the three greatest Liberals" (along with Edmund Burke and Lord Macaulay).[192] In 1909 the Liberal Chancellor David Lloyd George introduced his "People's Budget", the first budget which aimed to redistribute wealth. The Liberal statesman Lord Rosebery ridiculed it by asserting Gladstone would reject it, "Because in his eyes, and in my eyes, too as his humble disciple, Liberalism and Liberty were cognate terms; they were twin-sisters."[193] Lloyd George had written in 1913 that the Liberals were "carving the last few columns out of the Gladstonian quarry".[194] Lloyd George said of Gladstone in 1915: "What a man he was! Head and shoulders above anyone else I have ever seen in the House of Commons. I did not like him much. He hated Nonconformists and Welsh Nonconformists in particular and he had no real sympathy with the working classes. But he was far and away the best Parliamentary speaker I have ever heard. He was not so good in exposition."[195] Asquithian Liberals continued to advocate traditional Gladstonian policies of sound finance, peaceful foreign relations and the better treatment of Ireland. They often compared Lloyd George unfavourably with Gladstone.[citation needed] Writing in 1944 the classical liberal economist Friedrich Hayek said of the change in political attitudes that had occurred since the Great War: "Perhaps nothing shows this change more clearly than that, while there is no lack of sympathetic treatment of Bismarck in contemporary English literature, the name of Gladstone is rarely mentioned by the younger generation without a sneer over his Victorian morality and naive utopianism".[196] In the latter half of the 20th century Gladstone's economic policies came to be admired by Thatcherite Conservatives. Margaret Thatcher proclaimed in 1983: "We have a duty to make sure that every penny piece we raise in taxation is spent wisely and well. For it is our party which is dedicated to good housekeeping—indeed, I would not mind betting that if Mr. Gladstone were alive today he would apply to join the Conservative Party".[197] In 1996, she said: "The kind of Conservatism which he and I...favoured would be best described as 'liberal', in the old-fashioned sense. And I mean the liberalism of Mr Gladstone, not of the latter-day collectivists".[198] Nigel Lawson, one of Thatcher's Chancellors, believed Gladstone to be the "greatest Chancellor of all time".[199] A. J. P. Taylor wrote: William Ewart Gladstone was the greatest political figure of the nineteenth century. I do not mean by that that he was necessarily the greatest statesman, certainly not the most successful. What I mean is that he dominated the scene.[200] Rivalry with DisraeliEdit Historical writers have often played Disraeli and Gladstone against each other as great rivals.[201] Roland Quinault, however, cautions us not to exaggerate the confrontation: they were not direct antagonists for most of their political careers. Indeed initially they were both loyal to the Tory party, the Church and the landed interest. Although their paths diverged over the repeal of the Corn Laws in 1846 and later over fiscal policy more generally, it was not until the later 1860s that their differences over parliamentary reform, Irish and Church policy assumed great partisan significance. Even then their personal relations remained fairly cordial until their dispute over the Eastern Question in the later 1870s.[202] Monuments and archivesEdit Thomas Edison's European agent, Colonel Gouraud, recorded Gladstone's voice several times on phonograph. The accent on one of the recordings is North Welsh.[203] The National Library of Wales holds many pamphlets that were sent to Gladstone during his political career. These pamphlets show the concerns of people from all strands of society and together form a historical resource of the social and economical conditions of mid to late nineteenth century Britain. Many of the pamphlets bear the handwriting of Gladstone, which provides direct evidence of Gladstone's interest in various topics. A statue of Gladstone by Albert Bruce-Joy and erected in 1882, stands near the front gate of St. Marys Church in Bow, London. Paid for by the industrialist Theodore Bryant, it is viewed as a symbol of the later 1888 match girls strike, which took place at the nearby Bryant & May Match Factory. Led by the socialist Annie Besant, hundreds of women working in the factory, where many sickened and died from poisoning from the white phosphorus used in the matches, went on strike to demand improved working conditions and pay, eventually winning their cause. In recent years, the statue of Gladstone has been repeatedly daubed with red paint, suggesting that it was paid for with the "blood of the match girls".[204] A statue of Gladstone in bronze by Sir Thomas Brock, erected in 1904, stands in St John's Gardens, Liverpool.[205] A statue of Gladstone erected in 1905 stands at Aldwych, London, near the Royal Courts of Justice.[206] A Grade II listed statue of Gladstone stands in Albert Square, Manchester.[207] A monument to Gladstone, Member of Parliament for Midlothian 1880–1895 was unveiled in Edinburgh in 1917 (and moved to its present location in 1955). It stands in Coates Crescent Gardens. The sculptor was James Pittendrigh MacGillivray.[208] A statue to Gladstone, who was Rector of the University of Glasgow 1877–1880 was unveiled in Glasgow in 1902. It stands in George Square. The sculptor was Sir William Hamo Thornycroft.[209] A bust of Gladstone is in the Hall of Heroes of the National Wallace Monument in Stirling. Dollis House, Gladstone Park, as seen from the gardens Gladstone Park in the Municipal Borough of Willesden, London was named after him in 1899. Dollis Hill House, within what later became the park, was occupied by Sir Dudley Coutts Marjoribanks, who subsequently became Lord Tweedmouth. In 1881 Lord Tweedmouth's daughter and her husband, Lord Aberdeen, took up residence. They often had Gladstone to stay as a guest. In 1897 Lord Aberdeen was appointed Governor-General of Canada and the Aberdeens moved out. When Willesden acquired the house and land in 1899, they named the park Gladstone Park after the old Prime Minister.[citation needed] Near Hawarden in the town of Mancot, there is a small hospital named after Catherine Gladstone. A statue of Gladstone stands prominently in the front grounds of the eponymous Gladstone's Library (formerly known as St. Deiniol's), near the commencement of Gladstone Way at Hawarden.[citation needed] Gladstone Rock, a large boulder about 12 ft high in Cwm Llan on the Watkin Path on the south side of Snowdon where Gladstone made a speech in 1892, was named for him. A plaque on the rock states that he "addressed the people of Eryri upon justice to Wales".[210] A statue of Gladstone stands in front of the Kapodistrian University building in the centre of Athens.[211] Gladstone, Oregon, Gladstone, New Jersey, Gladstone, Michigan,[212] and Gladstone, New Mexico, in the United States are named for him. The city of Gladstone, Queensland, Australia, was named after him and has a 19th-century marble statue on display in its town museum.[213] Gladstone, Manitoba, was named after him in 1882.[214] Streets in the cities of Athens, Sofia, Plovdiv, Varna, Burgas, Ruse, Stara Zagora, Limassol, Springs, Newark-on-Trent, Waterford City, Clonmel, Brighton, Bradford, Scarborough, Swindon, Vancouver (including a school), Windsor, Ottawa, Halifax and Brisbane are named for him. There is also Gladstone Avenue and adjoining Ewart Road in his hometown of Liverpool in a part of the city where he was a landowner.[215] There is a Gladstone statue at Glenalmond College, unveiled in 2010, which is located in Front Quad.[216] A Gladstone memorial was unveiled on 23 February 2013 in Seaforth, Liverpool by MP Frank Field. It is located in the grounds of Our Lady Star of the Sea Church facing the former site of St Thomas's Church where Gladstone was educated from 1816 to 1821. The Seaglam (Seaforth Gladstone Memorial) Project, whose chairman is local historian Brenda Murray (BEM), was started to raise the profile of Seaforth Village by installing a memorial to Gladstone. Funds for the memorial were raised by voluntary effort and additional funding was provided by the Heritage Lottery Fund. Sculptor Tom Murphy created the bronze bust.[217] There is an imposing "Arts and Crafts" pub in Dulwich Hill NSW Australia named for him on the corner of Marrickville Road and New Canterbury Road;also a street is named for him in Dulwich Hill which is Ewart street which does also traverse into the adjoining suburb of Marrickville. Statue at Aldwych, London, near to the Royal Courts of Justice and opposite Australia House Statue in Albert Square, Manchester, Manchester Statue on the Gladstone Monument in Coates Crescent Gardens, Edinburgh A statue in Athens A high school named after Gladstone in Sofia, Bulgaria In popular cultureEdit This section needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. (December 2016) (Learn how and when to remove this template message) Gladstone was popularly known in his later years as the "Grand Old Man" or "G.O.M.". The term was used occasionally during the Midlothian election campaign, first became widely associated with him during the 1880 general election, and was ubiquitous in the press by 1882. Henry Labouchère and Sir Stafford Northcote have both been credited with coining it; it appears to have been in use before either of them used it publicly, though they may have helped popularise it. While it was originally used to show affectionate reverence, it was quickly adopted more sarcastically by his opponents, using it to emphasise his age. The acronym was sometimes satirised as "God's Only Mistake", or after the fall of Khartoum, inverted to "M.O.G.", "Murderer of Gordon". (Disraeli is often credited with the former, but Lord Salisbury is a more likely origin). The term is still widely used today and is virtually synonymous with Gladstone.[218] A Gladstone bag, a light travelling bag, is named after him.[219] Gladstone's burial in 1898 was commemorated in a poem by William McGonagall.[220] There is a scene in the Turkish film Free Man about Islamic scholar Said Nursi who is deeply troubled by Gladstone. Nursi reads in a newspaper report of a speech made in the House of Commons by Gladstone: "So long as the Muslims have the Qur'an, we shall be unable to dominate them. We must either take it from them, or make them lose their love of it." He was filled with zeal. It overturned his ideas and changed the direction of his interest. Thus, the explicit threats of Gladstone to the Qur'an and Islamic world caused a revolution in Nursi's ideas, clarifying them and setting him in the direction he would now follow. The threats caused him to declare: "I shall prove and demonstrate to the world that the Qur'an is an undying, inextinguishable Sun!"[221] Portrayal in film and televisionEdit Since 1937, Gladstone has been portrayed some 37 times in film and television.[222] Portrayals include: Montagu Love in the film Parnell (1937) Arthur Young in the films Victoria the Great (1937) and The Lady with a Lamp (1951) Malcolm Keen in the film Sixty Glorious Years (1938) Stephen Murray in the film The Prime Minister (1941) Gordon Richards in the film The Imperfect Lady (1947) Ralph Richardson in the film Khartoum (1966)[223] Graham Chapman in the Monty Python's Flying Circus episode Sex and Violence (1969) Willoughby Gray in the film Young Winston (1972) David Steuart in the television serial Jennie: Lady Randolph Churchill (1974) Michael Hordern in the television series Edward the Seventh (1975) John Carlisle in the television serial Disraeli (1978) John Phillips in the television series Lillie (1978) Roland Culver in the television series The Life and Times of David Lloyd George (1981) Denis Quilley in the television series Number 10 (1983) WorksEdit Gladstone, William Ewart (1841). The State in its relations with the Church (4th ed.). London: John Murray. Retrieved 13 October 2017 – via Internet Archive. Gladstone, William Ewart (1858). Studies on Homer and the Homeric Age. Oxford: At The University Press – via Internet Archive. , volume 1, volume 2, volume 3. Gladstone, William Ewart (1868). A Chapter of Autobiography. London: John Murray. Retrieved 14 October 2017 – via Internet Archive. Gladstone, William Ewart (1870). Juventus Mundi: The Gods and Men of the Heroic Age (2nd ed.). London: Macmillan and Co. Retrieved 13 October 2017 – via Internet Archive. Gladstone, William Ewart (1890). On books and the Housing of them. New York: Dodd, Mead & Company. Retrieved 11 October 2017 – via Internet Archive. A treatise on the storing of books and the design of bookshelves as employed in his personal library. Gladstone, William Ewart (1890). The impregnable rock of Holy Scripture (Revised and Enlarged from Good Words). London: Isbister and Company – via Internet Archive. William Ewart Gladstone, Baron Arthur Hamilton-Gordon Stanmore (1961). Gladstone-Gordon correspondence, 1851–1896: selections from the private correspondence of a British Prime Minister and a colonial Governor, Volume 51. American Philosophical Society. p. 116. ISBN 9780871695147. Retrieved 28 June 2010. (Volume 51, Issue 4 of new series, Transactions of the American Philosophical Society) (Original from the University of California) Liberalism in the United Kingdom ^ The Austrian economist, Joseph Schumpeter, described Gladstonian finance in his History of Economic Analysis: ... there was one man who not only united high ability with unparalleled opportunity but also knew how to turn budgets into political triumphs and who stands in history as the greatest English financier of economic liberalism, Gladstone. ... The greatest feature of Gladstonian finance ... was that it expressed with ideal adequacy both the whole civilisation and the needs of the time, ex visu of the conditions of the country to which it was to apply; or, to put it slightly differently, that it translated a social, political, and economic vision, which was comprehensive as well as historically correct, into the clauses of a set of co-ordinated fiscal measures. ... Gladstonian finance was the finance of the system of 'natural liberty,' laissez-faire, and free trade ... the most important thing was to remove fiscal obstructions to private activity. And for this, in turn, it was necessary to keep public expenditure low. Retrenchment was the victorious slogan of the day ... it means the reduction of the functions of the state to a minimum ... retrenchment means rationalisation of the remaining functions of the state, which among other things implies as small a military establishment as possible. The resulting economic development would in addition, so it was believed, make social expenditures largely superfluous. ... Equally important was it ... to raise the revenue that would still have to be raised in such a way as to deflect economic behaviour as little as possible from what it would have been in the absence of all taxation ('taxation for revenue only'). And since the profit motive and the propensity to save were considered of paramount importance for the economic progress of all classes, this meant in particular that taxation should as little as possible interfere with the net earnings of business. ... As regards indirect taxes, the principle of least interference was interpreted by Gladstone to mean that taxation should be concentrated on a few important articles, leaving the rest free. ... Last, but not least, we have the principle of the balanced budget.[72] ^ In his election address to his constituents on 23 January, Gladstone said: Upon a review of the finance of the last five years, we are enabled to state that, notwithstanding the purchase of the telegraphs for a sum exceeding 9,000,000l., the aggregate amount of the national debt has been reduced by more than 20,000,000l.; that taxes have been lowered or abolished (over and above any amount imposed) to the extent of 12,500,000l.; that during the present year the Alabama Indemnity has been paid, and the charge of the Ashantee War will be met out of revenue; and that in estimating, as we can now venture to do, the income of the coming year (and, for the moment assuming the general scale of charge to continue as it was fixed during the last Session), we do not fear to anticipate as the probable balance a surplus exceeding rather than falling short of 5,000,000l. ... The first item ... which I have to set down in the financial arrangements proper for the first year is relief, but relief coupled with reform, of local taxation. ... It has ... been the happy fortune of Mr. Lowe to bring it [the income tax] down, first from 6d. to 4d., and then from 4d. to 3d., in the pound. The proceeds of the Income Tax for the present year are expected to be between 5,000,000l. and 6,000,000l., and at a sacrifice for the financial year of something less than 5,500,000l. the country may enjoy the advantage and relief of its total repeal. I do not hesitate to affirm that an effort should now be made to attain this advantage, nor to declare that, according to my judgment, it is in present circumstances practicable ... we ought not to aid the rates, and remove the Income Tax, without giving to the general consumer, and giving him simultaneously, some marked relief in the class of articles of popular consumption. ... I for one could not belong to a Government which did not on every occasion seek to enlarge its resources by a wise economy.[103] ^ Wiesner-Hanks, Merry E.; Evans, Andrew D.; Wheeler, William Bruce; Ruff, Julius (2014). Discovering the Western Past, Volume II: Since 1500. Cengage Learning. p. 336. ISBN 978-1111837174. ^ Price, Richard (1999). British Society 1680–1880: Dynamism, Containment and Change. Cambridge University Press. p. 289. ISBN 978-0521657013. ^ Gardham, Duncan (12 June 2008). "David Davis's Victorian inspiration: William Gladstone". The Daily Telegraph. London. ^ J.F.C. Harrison (2013). Late Victorian Britain 1875–1901. p. 31. ISBN 978-1136116445. ^ Richard Aldous (2007). The Lion and the Unicorn: Gladstone Vs Disraeli. p. 4. ISBN 978-0393065701. ^ Paul Brighton (2016). Original Spin: Downing Street and the Press in Victorian Britain. I.B.Tauris. p. 193. ISBN 978-1780760599. ^ Paul Grey; et al. (2016). Challenge and Transformation: Britain, c. 1851–1964. Cambridge UP. p. 2. ISBN 978-1107572966. ^ a b Mosley, Charles, ed. (2003). Burke's Peerage, Baronetage & Knighthood (107 ed.). Burke's Peerage & Gentry. ISBN 978-0971196629. ^ a b c Shannon, 1985 ^ Sydney Checkland, The Gladstones: A Family Biography, 1764–1851 (Cambridge University Press, 1971), p. 95. ^ Checkland, p. 94. ^ Morley 1:92 ^ Partridge, (2003) p 32 ^ Morley (1901) 1:90-91. ^ Hansard's Parliamentary Debates. Hansard: Great Britain. Parliament. 1833. p. 482. ^ Trevor Burnard and Kit Candlin. "Sir John Gladstone and the debate over the amelioration of slavery in the British West Indies in the 1820s." Journal of British Studies 57.4 (2018): 760-782. ^ Quinault, R (2009). "Gladstone and Slavery". The Historical Journal. 52 (2): 372. doi:10.1017/S0018246X0900750X. ^ Michael Taylor, "The British West India interest and its allies, 1823–1833." English Historical Review 133.565 (2018): 1478-1511. https://doi.org/10.1093/ehr/cey336 ^ Quinault, pp 366–367. ^ Quinault, R (2009). "Gladstone and Slavery". The Historical Journal. 52 (2): 366. doi:10.1017/S0018246X0900750X. doi:10.1017/S0018246X0900750X ^ Henry Barrow, John (1833). The Mirror of Parliament, 1833. 2. pp. 2079–82. ^ "Britain's colonial shame: Slave-owners given huge payouts after abolition". Independent on Sunday. 24 February 2013. ^ Quinault, p 374. ^ The Times (14 June 1844), p. 7. ^ The Times (29 June 1886), p. 11. ^ Bruce D. Johnson, "Righteousness before revenue: The forgotten moral crusade against the Indo-Chinese opium trade." Journal of Drug Issues 5.4 (1975): 304-326. ^ Kathleen L. Lodwick (2015). Crusaders Against Opium: Protestant Missionaries in China, 1874–1917. University Press of Kentucky. pp. 86–. ISBN 978-0813149684. ^ Pierre-Arnaud Chouvy (2009). Opium: Uncovering the Politics of the Poppy. Harvard University Press. pp. 9–. ISBN 978-0674051348. ^ Dr Roland Quinault; Dr Ruth Clayton Windscheffel; Mr Roger Swift (2013). William Gladstone: New Studies and Perspectives. Ashgate Publishing, Ltd. pp. 238–. ISBN 978-1409483274. ^ Ms Louise Foxcroft (2013). The Making of Addiction: The 'Use and Abuse' of Opium in Nineteenth-Century Britain. Ashgate Publishing, Ltd. pp. 66–. ISBN 978-1409479840. ^ William Travis Hanes; Frank Sanello (2004). Opium Wars: The Addiction of One Empire and the Corruption of Another. Sourcebooks, Inc. pp. 78–. ISBN 978-1402201493. ^ W. Travis Hanes III; Frank Sanello (2004). The Opium Wars: The Addiction of One Empire and the Corruption of Another. Sourcebooks. pp. 88–. ISBN 978-1402252051. ^ Peter Ward Fay (2000). The Opium War, 1840–1842: Barbarians in the Celestial Empire in the Early Part of the Nineteenth Century and the War by which They Forced Her Gates Ajar. Univ of North Carolina Press. pp. 290–. ISBN 978-0807861363. ^ Anne Isba (2006). Gladstone and Women. A&C Black. pp. 224–. ISBN 978-1-85285-471-3. ^ David William Bebbington (1993). William Ewart Gladstone: Faith and Politics in Victorian Britain. Wm. B. Eerdmans Publishing. pp. 108–. ISBN 978-0802801524. ^ Iain McLean and Christopher Foster, "The political economy of regulation: interests, ideology, voters, and the UK Regulation of Railways Act 1844." Public Administration 70.3 (1992): 313-331. ^ Viscount Gladstone, After Thirty Years (Macmillan, 1928), pp. 90–91. ^ H.C.G. Matthew, Gladstone. 1875–1898 (Oxford University Press, 1995), p. 90. ^ John-Paul McCarthy, "History and pluralism: Gladstone and the Maynooth grant controversy." in Gladstone and Ireland (Palgrave Macmillan, 2010) pp. 15-40. ^ By Robert Peel, George Peel (Hon.), George Peel Sir Robert Peel: from his private papers, Volume 3 Spottiswoode and Co London p. 164 ^ "William Gladstone". Oxford Dictionary of National Biography (online ed.). Oxford University Press. 2004. doi:10.1093/ref:odnb/10787. (Subscription or UK public library membership required.) ^ Magnus, p. 475. ^ Morley, 1:230-31. ^ Richard Shannon, Gladstone: Heroic Minister, 1865–1898 (1999), pp. 583–84. ^ Matthew, Gladstone. 1809–1874, pp. 80–81. ^ H.C.G. Matthew, "Disraeli, Gladstone, and the politics of mid-Victorian budgets." Historical Journal 22.3 (1979): 615-643. ^ John Morley, The Life of William Ewart Gladstone. Volume I (Macmillan, 1903), p. 461. ^ Sir Wemyss Reid (ed.), The Life of William Ewart Gladstone (Cassell, 1899), p. 412. ^ Reid, p. 410. ^ a b Matthew, Gladstone, 1809–1874, p. 127. ^ Sydney Buxton, Finance and Politics: An Historical Study, 1783–1885. Volume I (John Murray, 1888), pp. 108–09. ^ Matthew, Gladstone. 1809–1874, p. 121. ^ Buxton, p. 109. ^ Sydney Buxton, Finance and Politics: An Historical Study, 1783–1885. Volume I (1888), pp. 150–51. ^ Olive Anderson, "Loans versus taxes: British financial policy in the Crimean War." Economic History Review (1963): 314-327 at p. 314. However he did float £6 million in bonds, and his successor borrowed much more. p. 315–17. online. ^ Holland, Robert; Markides, Diana (2006). The British and the Hellenes. ISBN 978-0199249961. Retrieved 1 May 2010 – via Google Books. ^ The Speeches of Lord Randolph Churchill, ed. J.J. Jennings, Longman (1889), pp. 111–12. ^ Geoffrey Scarre, "'The Compages, the Bonds and Rivets of the Race': W.E. Gladstone on the Keeping of Books." Library & Information History 33.3 (2017): 182-194 online. ^ "Retrieved 24 November 2009". The Daily Telegraph. London. 7 October 2009. Retrieved 1 May 2010. ^ Richard Shannon, Gladstone. 1809–1865 (London: Hamish Hamilton, 1982), p. 395. ^ Asaana A. Iliasu, "The Cobden-Chevalier commercial treaty of 1860." Historical Journal 14.1 (1971): 67-98 online. ^ McKechnie, The reform of the House of Lords ^ L.C.B. Seaman, Victorian England: Aspects of English and Imperial History, 1837–1901 (Routledge, 1973), pp. 183–84. ^ F. W. Hirst, Gladstone as Financier and Economist (London: Ernest Benn Limited, 1931), p. 241. ^ Hirst, pp. 242–43. ^ Joseph A. Schumpeter, History of Economic Analysis (George Allen & Unwin Ltd, 1954), pp. 402–05. ^ Eugenio Biagini, "Popular Liberals, Gladstonian finance and the debate on taxation, 1860–1874", in Eugenio Biagini and Alastair Reid (eds.), Currents of Radicalism. Popular Radicalism, Organised Labour and Party Politics in Britain, 1850–1914 (Cambridge University Press, 1991), p. 139. ^ Biagini, "Popular Liberals, Gladstonian finance and the debate on taxation, 1860–1874", pp. 140–41. ^ Biagini, "Popular Liberals, Gladstonian finance and the debate on taxation, 1860–1874", p. 142. ^ Jasper Ridley, Lord Palmerston (Constable, 1970), p. 563. ^ G. I. T. Machin "Gladstone and Nonconformity in the 1860s: The Formation of an Alliance." Historical Journal 17, no. 2 (1974): 347-64. online. ^ Morley, Life of Gladstone: II, p. 82. ^ The Observer (12 October 1862), p. 3. ^ The Times (20 October 1862), p. 7. ^ The New York Times (25 October 1862), p. 4. ^ Quinault, pp 376-377. ^ W.D. Handcock, English Historical Documents, p. 168. ^ Llewellyn Woodward, The Age of Reform, 1815-1870 (1962) p. 182. ^ J. M. Prest, "Gladstone and Russell." Transactions of the Royal Historical Society 16 (1966): 43-63. ^ James Winter, "The Cave of Adullam and parliamentary reform." English Historical Review 81.318 (1966): 38-55. ^ William Evan Williams, The rise of Gladstone to the leadership of the Liberal Party, 1859-1868 (Cambridge UP, 1973. ^ John D. Fair, "The Irish disestablishment conference of 1869." Journal of Ecclesiastical History 26.4 (1975): 379-394. ^ Gladstone's Cabinet of 1868, Lowes Cato Dickinson, ref. NPG 5116, National Portrait Gallery, London, accessed January 2010 ^ Shannon, Richard (1984). Gladstone: 1809-1865 (p.342). p. 580. ISBN 0807815918. Retrieved 30 January 2010. ^ "The Coming Elections". The Times. 2 November 1868. p. 4. Retrieved 22 February 2009. ^ Charles Loch Mowat, The Charity Organisation Society. 1869–1913 (Methuen, 1961), p. 19. ^ Richard Shannon, The Age of Disraeli, 1868–1881: The Rise of Tory Democracy (London: Longman, 1992), pp. 107–10. ^ The Times (24 January 1874), p. 8. ^ E.F. Biagini, Liberty, Retrenchment and Reform. Popular Liberalism in the Age of Gladstone, 1860–1880 (Cambridge University Press, 1992), p. 112. ^ Biagini, Liberty, Retrenchment and Reform, p. 112, n. 177. ^ Biagini, Liberty, Retrenchment and Reform, pp. 113–14. ^ Biagini, Liberty, Retrenchment and Reform, p. 116. ^ H. S. C. Matthew, Gladstone: 1809-1898 (1997) p. 248. ^ David W. Bebbington, William Ewart Gladstone: Faith and Politics in Victorian Britain (1990) p. 226 ^ Gladstone, William Ewart (1874). The Vatican Decrees in their Bearing on Civil Allegiance: A Political Expostulation (1 ed.). London: John Murray. Retrieved 10 June 2016 – via Internet Archive. ^ Gladstone, William Ewart (1875). Vaticanism: an Answer to Reproofs and Replies (1 ed.). London: John Murray. Retrieved 10 June 2016 – via Internet Archive. ^ Philip Magnus, Gladstone: A Biography (London: John Murray, 1963), pp. 235–36. ^ 'Mr. Gladstone On Cottage Gardening', The Times (18 August 1876), p. 9. ^ Lord Kilbracken, Reminiscences of Lord Kilbracken (Macmillan, 1931), pp. 83–84. ^ "[W]illiam [E]wart Gladstone, "Bulgarian Horrors and the Question of the East" (1876) | W.T. Stead Resource Site". attackingthedevil.co.uk. ^ Gladstone, William Ewart (1876). Bulgarian Horrors and the Question of the East (1 ed.). London: John Murray. Retrieved 10 June 2016 – via Internet Archive. ^ "Gladstone, Disraeli and the Bulgarian Horrors | History Today". www.historytoday.com. Retrieved 16 November 2019. ^ Gladstone, William Ewart (1876). Bulgarian Horrors and the Question of the East (1 ed.). London : J. Murray. p. 9. Retrieved 10 June 2016 – via Internet Archive. ^ a b c Alderman, Geoffrey. Modern British Jewry. Oxford: Clarendon, 1992, p. 100 ^ Alderman, Geoffrey. Modern British Jewry. Oxford: Clarendon, 1992, p. 101 ^ W.E. Gladstone, Midlothian Speeches. 1879 (Leicester University Press, 1971), p. 148. ^ Justin H. McCarthy, England under Gladstone, 1880-1885 (1885) pp 6-20.online ^ Ian St John, The Historiography of Gladstone and Disraeli (Anthem Press, 2016) pp. 188-209. ^ Paul Knaplund, Gladstone's foreign policy (1935) is favourable. ^ Paul Hayes, Modern British Foreign Policy: The Twentieth Century: 1880–1939 (1978) p. 1 ^ Shannon, Gladstone 2: 298–307 ^ He adds, "All the rest were maneuvers which left the combatants at the close of the day exactly where they had started. A.J.P. Taylor, "International Relations" in F.H. Hinsley, ed., The New Cambridge Modern History: XI: Material Progress and World-Wide Problems, 1870–98 (1962): 554. ^ Taylor, "International Relations" p. 554 ^ Peter J. Cain and Anthony G. Hopkins, "Gentlemanly capitalism and British expansion overseas II: new imperialism, 1850–1945." Economic History Review 40.1 (1987): 1–26. online ^ Donald Malcolm Reid, "The 'Urabi revolution and the British conquest, 1879–1882", in M.W. Daly, ed., The Cambridge History of Egypt, vol. 2: Modern Egypt, from 1517 to the end of the twentieth century (1998) p. 219. ^ John S. Galbraith and Afaf Lutfi al-Sayyid-Marsot, "The British occupation of Egypt: another view." International Journal of Middle East Studies 9.4 (1978): 471–488. ^ Olson, James; Shadle, Robert (1996). Historical Dictionary of the British Empire. Greenwood. pp. 271–72. ISBN 978-0313293665. ^ Daniel Webster Hollis (2001). The History of Ireland. Greenwood. p. 105. ISBN 978-0313312816. ^ "Fellows of the Royal Society". London: Royal Society. Archived from the original on 16 March 2015. ^ Partridge, Michael (2003). Gladstone. Routledge. p. 178. ISBN 978-1134606382. ^ Morley, Life of Gladstone: III, p. 173. ^ Sneh Mahajan (2003). British Foreign Policy 1874–1914: The Role of India. Routledge. p. 58. ISBN 978-1134510559. ^ Brook Miller, "Our Abdiel: The British Press and the Lionization of 'Chinese' Gordon." Nineteenth-Century Prose 32.2 (2005): 127+ online. ^ Jenkins, 523–532. ^ M. R. D. Foot. "The Hawarden Kite" Journal of Liberal Democrat History 20 (Autumn 1998) pp. 26–32. online ^ Roy Jenkins, Gladstone: A Biography (1997) p. 553 ^ Michael Barker, Gladstone and Radicalism. The Reconstruction of Liberal Policy in Britain. 1885–1894 (The Harvester Press, 1975), p. 92. ^ Barker, p. 92. ^ Barker, pp. 93–94. ^ The Times (12 December 1891), p. 7. ^ "Small Agricultural Holdings Bill – (No. 183.) (Hansard, 24 March 1892)". Hansard.millbanksystems.com. Retrieved 1 May 2010. ^ Barker, p. 198. ^ John Brooke and Mary Sorensen (eds.), The Prime Ministers' Papers: W.E. Gladstone. I: Autobiographica (London: Her Majesty's Stationery Office, 1971), p. 55. ^ David Duncan, The Life and Letters of Herbert Spencer (Methuen, 1908), p. 302. ^ Duncan, p. 302. ^ Kirby, Mark (2000). Sociology in Perspective. google.co.uk. ISBN 9780435331603. ^ "The Unemployed. (Hansard, 1 September 1893)". Hansard.millbanksystems.com. Retrieved 1 May 2010. ^ David Brooks, "Gladstone's Fourth Administration, 1892–1894", in David Bebbington and Roger Swift (eds.), Gladstone Centenary Essays (Liverpool University Press, 2000), p. 239. ^ Anthony Howe, 'Gladstone and Cobden', in David Bebbington and Roger Swift (eds.), Gladstone Centenary Essays (Liverpool University Press, 2000), p. 115. ^ Brooke and Sorensen, pp. 165–66. ^ Daisy Sampson, The Politics Companion (London: Robson Books Ltd, 2004), pp. 80, 91. ^ UK Retail Price Index inflation figures are based on data from Clark, Gregory (2017). "The Annual RPI and Average Earnings for Britain, 1209 to Present (New Series)". MeasuringWorth. Retrieved 2 February 2020. ^ H.C.G. Matthew (1997). Gladstone 1809–1898. Clarendon Press. p. 620. ISBN 978-0191584275. ^ Tollemache, pp. 166–67. ^ Tollemache, p. 123. ^ Howe, p. 114. ^ F.W. Hirst, In the Golden Days (Frederick Muller, 1947), p. 158. ^ Six Oxford Men, Essays in Liberalism (Cassell, 1897), p. x. ^ Shannon, Gladstone: Heroic Minister, 1865–1898, p. 588. ^ published on 5 January 1898 as Personal Recollections of Arthur H. Hallam ^ Sheila Fletcher, 'Gladstone, Helen (1849–1925)', Oxford Dictionary of National Biography, Oxford University Press, 2004; online edn, May 2006 accessed 10 March 2017 ^ Matthew, Gladstone. 1875–1898, p. 382, n. ‡. ^ "CardinalBook History of Peace and War". Cardinalbook.com. 19 March 1998. Archived from the original on 10 May 2010. Retrieved 1 May 2010. ^ M. Partridge, Gladstone (2003) p. 18 ^ Ramm, Agatha (1985). "Gladstone's Religion". The Historical Journal. 28 (2): 327–340. doi:10.1017/S0018246X00003137. JSTOR 2639101. ^ H.C.G. Matthew, Gladstone, 1809–1874 (1986), pp. 42, 62, 66. ^ David Bebbington, William Ewart Gladstone: Faith and Politics in Victorian Britain (1993). ^ Checkland, p. 300. ^ Weyman, Henry T. (1902). "Members of Parliament for Wenlock". Transactions of the Shropshire Archaeological Society, Series 3, Volume II. pp. 353–54. ^ M. Kienholz (2008). Opium Traders and Their Worlds-Volume One: A Revisionist Exposé of the World's Greatest Opium Traders. iUniverse. pp. 190–. ISBN 978-0595910786. ^ https://ancestors.familysearch.org/en/LVSW-21Q/dorothy-mary-catherine-drew-1890-1982 ^ Mance, Henry (5 August 2017). "Tory activists plan Conservative answer to Glastonbury". Financial Times. Retrieved 6 August 2017. Mr Freeman—a descendant of the Liberal prime minister William Gladstone and a former biotechnology investor—said he envisions the Conservative Ideas Festival as a "cross between Hay-on-Wye and the Latitude festival". ^ H.C.G. Matthew, "Gladstone, William Ewart (1809–1898)", Oxford Dictionary of National Biography, Oxford University Press, 2004; online edn, May 2011. Retrieved 28 August 2012. ^ Qalter L. Arnstein, Britain Yesterday and Today: 1832 the Present (6th ed. 1992) p. 125 ^ Herbert Paul (ed.), Letters of Lord Acton to Mary Gladstone (George Allen, 1904), p. 57. ^ Lord Rosebery, The Budget. Its Principles and Scope. A Speech Delivered to the Commercial Community of Glasgow, 10 September 1909 (London: Arthur L. Humphreys, 1909), pp. 30–31. ^ Chris Wrigley, "'Carving the Last Few Columns out of the Gladstonian Quarry': The Liberal Leaders and the Mantle of Gladstone, 1898–1929", in David Bebbington and Roger Swift (eds), Gladstone Centenary Essays (Liverpool University Press, 2000), p. 247. ^ Wrigley, p. 247. ^ F.A. Hayek, The Road to Serfdom (Routledge, 2001), p. 188. ^ Margaret Thatcher, 'Speech to the Conservative Party Conference', 14 October 1983. ^ Margaret Thatcher, 'Keith Joseph Memorial Lecture', 11 January 1996. ^ Nigel Lawson, The View From No. 11: Memoirs of a Tory Radical (Bantam, 1992), p. 279. ^ Michael Partridge (2003). Gladstone. Psychology Press. p. 7. ISBN 978-0415216265. ^ Dick Leonard, The Great Rivalry: Gladstone and Disraeli (2013) is popular, while Richard Aldous, The Lion and The Unicorn: Gladstone and Disraeli (2007) is scholarly. For the historiography see Roland Quinault, "Gladstone and Disraeli: a Reappraisal of their Relationship." History 91#304 (2006): 557–76. ^ Roland Quinault, "The Great Rivalry," History Today (Nov 2013) 63#11 p. 61. ^ Matthew, Gladstone. 1875–1898, p. 300, n. §. ^ "London's Hidden History Bow Church". Modern Gent. Archived from the original on 6 July 2013. Retrieved 1 March 2009. ^ "St John's Garden". Liverpool City Council. Retrieved 7 September 2008. ^ "Statue, W.E. Gladstone Monument". Art and architecture. Retrieved 7 September 2008. ^ Historic England. "Gladstone's Statue, Albert Square (1197823)". National Heritage List for England. Retrieved 19 June 2009. ^ "City of Edinburgh Council". City of Edinburgh Council. Retrieved 23 January 2009. [dead link] ^ Nisbet, Gary. "Sir William Hamo Thornycroft (1850–1925), sculptor, a biography". www.glasgowsculpture.com. Retrieved 15 January 2017. ^ Stephen, Graham (31 May 2010). "Gladstone Rock, Watkin Path, Snowdon". GeoTopoi. Retrieved 31 October 2016. ^ "Old National University of Athens". www.athens-greece.us. Retrieved 26 January 2018. ^ Romig, Walter (1986). Michigan Place Names: The History of the Founding and Naming of More than Five Thousand Past and Present Michigan Communities. Detroit: Wayne State University Press. p. 224. ISBN 978-0814318386. ^ "Gladstone Regional Art Gallery and Museum". Retrieved 26 July 2011. ^ "History of Manitoban Names". Retrieved 21 May 2010. ^ Echo, Liverpool (26 December 2009). "One of Liverpool's most influential sons - William Gladstone". liverpoolecho. Retrieved 4 February 2020. ^ "History of Glenalmond College – Scottish Independent Schools". glenalmondcollege.co.uk. ^ "William Gladstone | Tom Murphy – Liverpool Sculptor". Retrieved 30 January 2019. ^ Scully, R. J. (21 January 2014). "The Origins of William Ewart Gladstone's Nickname, 'The Grand Old Man'". Notes and Queries. 61 (1): 95–100. doi:10.1093/notesj/gjt270. ^ The Secret Agent, by Joseph Conrad, ISBN 978-0141194394, on notes of chapter IX, at p. 256. ^ McGonagall, William (1898). "The Burial of Mr Gladstone – The Great Political Hero". McGonagall Online. ^ Biography of Bediuzzaman Said Nursi, Translator: Şükran Vahide, Sözler Pub. 2000, ISBN 9754320241 p. 48 ^ There are 29 films cited in Denis Gifford, British Film Catalogue (2 vol. 2001). ^ Jeffrey Richards (2014). Visions of Yesterday. Taylor & Francis. p. 223. ISBN 978-1317928607. Further readingEdit BiographiesEdit External video Presentation by Roy Jenkins on Gladstone: A Biography at the Library of Congress, February 10, 1997, C-SPAN Interview with Roy Jenkins on Gladstone: A Biography, March 20, 1997, C-SPAN Bebbington, D.W. William Ewart Gladstone (1993). Biagini, Eugenio F. Gladstone (2000). Brand, Eric. William Gladstone (1986) ISBN 0877545286. Feuchtwanger, E.J. Gladstone (1975). 272 pp. Feuchtwanger, E.J. "Gladstone and the Rise and Fall of Victorian Liberalism" History Review (Dec 1996) v. 26 online; also online Jagger, Peter J., ed. Gladstone (2007), 256 pp. Jenkins, Roy. Gladstone: A Biography (2002) Magnus, Philip M. Gladstone: A biography (1954) online Matthew, H.C.G. "Gladstone, William Ewart (1809–1898)", Oxford Dictionary of National Biography, (2004; online edition, May 2006. Matthew, H.C.G. Gladstone, 1809–1874 (1988); Gladstone, 1875–1898 (1995) online complete Matthew, Gladstone: 1809–1898 (1997) is an unabridged one-volume version. online Morley, John (1903). The Life of William Ewart Gladstone. London & New York: Macmillan and CO. Limited and The Macmillan Company. volume I; volume II, volume III via Internet Archive. Partridge, M. Gladstone (2003) Reid, Sir Wemyss, ed. (1899). The Life of William Ewart Gladstone. London, Paris, New York, Melbourne: Cassell and Company. Limited. Retrieved 13 October 2017. . Russell, George W.E (1891). The Right Honourable William Ewart Gladstone. London: Sampson, Low, Marston & Company. Retrieved 13 October 2017 – via Internet Archive. . Russell, Michael. Gladstone: A Bicentenary Portrait (2009). ISBN 978-0859553179 Shannon, Richard. Gladstone: Peel's Inheritor, 1809–1865 (1985), ISBN 0807815918; Gladstone: Heroic Minister, 1865–1898 (1999), ISBN 0807824860, a scholarly biography vol 1 online Shut, M.L. (2008). "Gladstone, William Ewart (1809–1898)". In Hamowy, Ronald (ed.). The Encyclopedia of Libertarianism. SAGE. pp. 206–07. doi:10.4135/9781412965811.n123. ISBN 978-1412965804. Special studiesEdit Aldous, Richard. The Lion and the Unicorn: Gladstone vs Disraeli (2007). Barker, Michael. Gladstone and Radicalism. The Reconstruction of Liberal Policy in Britain. 1885–1894 (The Harvester Press, 1975). Beales, Derek. From Castlereagh to Gladstone, 1815–1885 (1969), survey of political history online Bebbington, D.W. The Mind of Gladstone: Religion, Homer and Politics (2004). Bebbington, David and Roger Swift (eds.), Gladstone Centenary Essays (Liverpool University Press, 2000). Biagini, E.F. Liberty, Retrenchment and Reform. Popular Liberalism in the Age of Gladstone, 1860–1880 (Cambridge University Press, 1992). Biagini, Eugenio. and Alastair Reid (eds.), Currents of Radicalism. Popular Radicalism, Organised Labour and Party Politics in Britain, 1850–1914 (Cambridge University Press, 1991). Boyce, D. George and Alan O'Day, eds. Gladstone and Ireland: Politics, Religion, and Nationality in the Victorian Age (Palgrave Macmillan; 2011), 307 pp. Bright, J. Franck. A History Of England. Period 4: Growth Of Democracy: Victoria 1837–1880 (1902)online 608pp; highly detailed older political narrative A History of England: Period V. Imperial Reaction, Victoria, 1880‒1901 (1904) online Butler, P. Gladstone, church, state, and Tractarianism: a study of his religious ideas and attitudes, 1809–1859 (1982). Buxton, Sydney. Finance and Politics. An Historical Study. 1783–1885. Volume I (John Murray, 1888) Gopal, S. "Gladstone and the Italian Question." History 41#141 (1956): 113–21. in JSTOR Guedalla, Philip. Queen and Mr. Gladstone (2 vols, 1933) online edition Hirst, F.W. Gladstone as Financier and Economist (1931). Hirst, F.W. In the Golden Days (Frederick Muller, 1947). Isba, Anne. Gladstone and Women (2006), London: Hambledon Continuum, ISBN 1852854715. Hammond, J.L. Gladstone and the Irish nation (1938) online edition. Jenkins, T.A. Gladstone, whiggery and the liberal party, 1874–1886 (1988). Langer, William L. The Diplomacy of Imperialism: 1890–1902 (2nd ed. 1950), a standard diplomatic history of Europe Loughlin, J. Gladstone, home rule and the Ulster question, 1882–1893 (1986). online Machin, G. I. T. "Gladstone and Nonconformity in the 1860s: The Formation of an Alliance." Historical Journal 17, no. 2 (1974): 347–64. online. Parry, J. P. Democracy and religion: Gladstone and the liberal party, 1867–1875 (1986). Quinault, Roland, et al. eds William Gladstone: New Studies and Perspectives (2012). Quinault, Roland. "Chamberlain and Gladstone: An Overview of Their Relationship." in Joseph Chamberlain: International Statesman, National Leader, Local Icon ed. by I. Cawood, C. Upton, (Palgrave Macmillan UK, 2016). 97–115. Quinault, Roland. "Gladstone and slavery." The Historical Journal 52.2 (2009): 363–383. DOI: https://doi.org/10.1017/S0018246X0900750X Schreuder, D. M. Gladstone and Kruger: Liberal government and colonial 'home rule', 1880–85 (1969). Schreuder, D. M. "Gladstone and Italian unification, 1848–70: the making of a Liberal?", The English historical review, (1970) vol. 85 (n. 336), pp. 475–501 . in JSTOR Schumpeter, Joseph A. History of Economic Analysis (George Allen & Unwin Ltd, 1954). Seton-Watson, R.W. Disraeli, Gladstone and the eastern question: a study in diplomacy and party politics (1935). Shannon, Richard. The crisis of imperialism, 1865–1915 (1976), pp. 76–100, 142–98. Shannon, Richard. Gladstone and the Bulgarian agitation, 1876 (1975) online Taylor, Michael. "The British West India interest and its allies, 1823–1833." English Historical Review 133.565 (2018): 1478–1511. https://doi.org/10.1093/ehr/cey336, focus on slavery Vincent, J. Gladstone and Ireland (1978). Vincent, J. The Formation of the Liberal Party, 1857–1868 (1966) online. Midlothian campaignEdit Blair, Kirstie. "The People's William and the People's Poets: William Gladstone and the Midlothian Campaign." The People's Voice (2018) online. Brooks, David. "Gladstone and Midlothian: The Background to the First Campaign," Scottish Historical Review (1985) 64#1 pp 42–67. Fitzsimons, M. A. "Midlothian: the Triumph and Frustration of the British Liberal Party," Review of Politics (1960) 22#2 pp 187–201. in JSTOR Kelley, Robert. "Midlothian: A Study In Politics and Ideas," Victorian Studies (1960) 4#2 pp 119–140. Matthew, H. C. G Gladstone: 1809-1898 (1997) pp 293–313 Whitehead, Cameron Ean Alfred. "The Bulgarian Horrors: culture and the international history of the Great Eastern Crisis, 1876-1878" (PhD. Dissertation, University of British Columbia, 2014) online Yildizeli, Fahriye Begum. "W.E. Gladstone and British Policy Towards the Ottoman Empire." (PhD dissertation, University of Exeter, 2016) online. HistoriographyEdit St. John, Ian. The Historiography of Gladstone and Disraeli (Anthem Press, 2016) 402 pp excerpt Primary sourcesEdit Gladstone, W.E. Midlothian Speeches. 1879 (Leicester University Press, 1971). Gladstone, William E. Midlothian Speeches 1884 with an Introduction by M. R. D. Foot, (New York: Humanities Press, 1971) online Guedalla, Philip, ed. Gladstone and Palmerston: Being the Correspondence of Lord Palmerston with Mr. Gladstone, 1851-1865 (1928) Guedalla, Philip, ed. Queen And Mr. Gladstone (1933) online Lord Kilbracken, Reminiscences of Lord Kilbracken (Macmillan, 1931). Russell, G.W.E. (1911). One Look Back. London: Wells Gardner, Darton and Co., LTD. Retrieved 13 October 2017 – via Internet Archive. . Tollemache, Lionel A. (1898). Talks with Mr. Gladstone (1 ed.). London: Edward Arnold. Retrieved 13 October 2017 – via Internet Archive. . Matthew, H.C.G. and M.R.D. Foot, eds. Gladstone Diaries. With Cabinet Minutes & Prime-Ministerial Correspondence (13 vol; vol 14 is the index; 1968–1994); includes diaries, important selections from cabinet minutes and key political correspondence. online at Questia are vol 1, 4, 6, 7, and 11–14.; vol 14, pp. 1–284 includes brief identification of the 20,000+ people mentioned by Gladstone. Partridge, Michael, and Richard Gaunt, eds. Lives of Victorian Political Figures Part 1: Palmerston, Disraeli and Gladstone (4 vol. Pickering & Chatto. 2006) reprints 27 original pamphlets on Gladstone. Ramm, Agatha, ed. The Political Correspondence of Gladstone and Lord Granville 1876-1886. (2 vol Clarendon, 1962) online Temperley, Harold and L.M. Penson, eds. Foundations of British Foreign Policy: From Pitt (1792) to Salisbury (1902) (1938), primary sources online William Ewart Gladstoneat Wikipedia's sister projects Media from Wikimedia Commons Quotations from Wikiquote Texts from Wikisource Data from Wikidata Portraits of William Ewart Gladstone at the National Portrait Gallery, London Hansard 1803–2005: contributions in Parliament by William Gladstone William Gladstone - Harry Furniss Caricatures - UK Parliament Living Heritage Mr. Gladstone (character sketch by W.T. Stead, in the Review of Reviews, 1892). Works by William Ewart Gladstone at Project Gutenberg Works by or about William Ewart Gladstone at Internet Archive Works by William Ewart Gladstone at LibriVox (public domain audiobooks) More about William Ewart Gladstone on the Downing Street website. William Ewart Gladstone 1809–98 biography from the Liberal Democrat History Group. BBC Radio – Programme Two contains a recording of Gladstone's voice. "Archival material relating to William Ewart Gladstone". UK National Archives. Parliament of the United Kingdom William Farnworth Handley Thomas Wilde Member of Parliament for Newark With: William Farnworth Handley 1832–1835 Thomas Wilde 1835–1841 Lord John Manners 1841–1845 Succeeded by Lord John Manners Thomas Estcourt Sir Robert Inglis Member of Parliament for Oxford University With: Sir Robert Inglis 1847–1854 Sir William Heathcote 1854–1865 Succeeded by Sir William Heathcote Gathorne Hardy Algernon Egerton William Legh Charles Turner Member of Parliament for South Lancashire With: Algernon Egerton Charles Turner Constituency abolished Charles Tilston Bright David Salomons Member of Parliament for Greenwich With: David Salomons 1868–1873 Thomas Boord 1873–1880 Succeeded by Thomas Boord Baron Henry de Worms Earl of Dalkeith Member of Parliament for Midlothian 1880–1895 Succeeded by Sir Thomas Gibson-Carmichael John Stuart-Wortley Under-Secretary of State for War and the Colonies 1835 Succeeded by Sir George Grey Fox Maule Vice-President of the Board of Trade The Earl of Ripon President of the Board of Trade The Lord Stanley Secretary of State for War and the Colonies The Earl Grey Benjamin Disraeli Chancellor of the Exchequer Sir George Lewis Sir John Young Lord High Commissioner of the Ionian Islands Sir Henry Knight Storks The Viscount Palmerston Leader of the House of Commons Benjamin Disraeli Prime Minister of the United Kingdom Robert Lowe Chancellor of the Exchequer Sir Stafford Northcote The Earl of Beaconsfield Prime Minister of the United Kingdom 23 April 1880 – 9 June 1885 Succeeded by Sir Stafford Northcote Chancellor of the Exchequer Leader of the House of Commons Sir Michael Hicks-Beach The Marquess of Salisbury Prime Minister of the United Kingdom 1 February 1886 – 20 July 1886 Succeeded by Sir Michael Hicks-Beach Leader of the House of Commons Lord Randolph Churchill The Earl of Harrowby Lord Privy Seal The Earl Cadogan 15 August 1892 – 2 March 1894 Succeeded by Arthur Balfour Leader of the House of Commons Sir William Harcourt The Earl Cadogan Lord Privy Seal The Lord Tweedmouth Party political offices The Earl Russell Leader of the British Liberal Party The Earl Granville Marquess of Hartington Marquess of Hartington Leader of the British Liberal Party The Viscount Palmerston Liberal Leader in the Commons Marquess of Hartington Liberal Leader in the Commons William Vernon Harcourt Academic offices New institution Rector of the University of Edinburgh The Earl of Beaconsfield Rector of the University of Glasgow John Bright The Earl of Beaconsfield Oldest living British prime minister The Earl Grey Senior Privy Counsellor The Duke of Rutland Spencer Horatio Walpole Professional and academic associations Edward Cust President of the Historic Society of Lancashire and Cheshire 1863–66 Succeeded by Joseph Mayer Retrieved from "https://en.wikipedia.org/w/index.php?title=William_Ewart_Gladstone&oldid=1000379577"
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
1,071
Kenneth Alvin Smith (May 8, 1924 — September 23, 2000) was a Canadian ice hockey winger. Career Smith played 331 games in the National Hockey League for the Boston Bruins between 1944 and 1951. The rest of his career, which lasted from 1944 to 1957, was primarily spent in the minor American Hockey League. His brother, Don, played 11 games with the New York Rangers in 1949–50. Career statistics Regular season and playoffs External links 1924 births 2000 deaths Boston Bruins players Canadian ice hockey left wingers Hershey Bears players Ice hockey people from Saskatchewan Oshawa Generals players Pittsburgh Hornets players Providence Reds players Regina Pats players Sportspeople from Moose Jaw
{ "redpajama_set_name": "RedPajamaWikipedia" }
8,983
Our vessel 'Sousa' is for those wanting an experience like no other...we customize your Outer Great Barrier Reef or Island experience to suit your wishes. Whether it's SCUBA Diving or snorkelling, experienced or not - this is the best way to immerse yourself, challenge yourself or treat yourself here in Mission Beach. 'Sousa' is the indigenous name for Hump Back Dolphin and that's just how she performs, riding the waves with ease! She is a 7m Swift Aluminum RIB designed for comfort, safety and performance. Powered by twin 150hp Yamaha's and being an ex Marine Parks Vessel she is equipped with the latest navigation equipment, radar, sounder, safety equipment and more. You can even rinse off under the fresh water shower!!!! She cruises at a quick 30 knots when it's calm and when it's a bit bumpy she's a fun ride at 22 knots. Only 40 minutes to the reef, you have more time snorkelling and doing...well, whatever you want - IT'S YOUR DAY! We offer Sousa for charter for those who would like a more personalized trip to the Outer Great Barrier Reef. All snorkel charters are fully guided in water by the skipper for an interactive and informative experience.
{ "redpajama_set_name": "RedPajamaC4" }
5,070
{"url":"https:\/\/tspace.library.utoronto.ca\/handle\/1807\/3074","text":"Home\n\nBrowse\nCommunities\n&\u00a0Collections\n\nIssue Date\nAuthor\nTitle\nSubject\n\nSign on to:\n\nMy Account\nauthorized users\n\nEdit Profile\n\nHelp\n Please use this identifier to cite or link to this item: http:\/\/hdl.handle.net\/1807\/3074\n\n Title: Excavations at Kommos (Crete) during 1979 Authors: Shaw, Joseph W. Keywords: Excavations (Archaeology) - Greece - Kommos (Crete) Issue Date: 1980 Publisher: American School of Classical Studies at Athens Citation: Shaw, Joseph W. Excavations at Kommos (Crete) during 1979. Hesperia, Vol. 49, No. 3. (Jul. - Sep., 1980), pp. 207-250. Plates 53 - 67 (pp. 45 - 59.) Abstract: During this fourth season of our excavations at Kommos we completed all major excavation of the Late Minoan (LM) houses on the hilltop as well as the LM house discovered earlier on the hillside. Soundings in the Middle Minoan (MM) levels in both these areas proved to be profitable, especially on the hillside where an intact MM storeroom was found within most informative stratigraphic contexts. In the Greek sanctuary to the south two more, relatively large altars were found within the deep sand. West of them we discovered a Greek temple of which the outer walls are destroyed but the interior is intact. Below the floor of the temple is an unusual shrine of Late Geometric\/Early Archaic date. Further west, along the shore, lies a group of Minoan buildings of a monumental character not hitherto encountered on the Kommos site. Description: 37 p., 7 p. of plates. - This article has been scanned and reformatted by the T-Space Digitization Project Assistant. If a researcher is interested in referencing this work, it is recommended that the citation listed above be consulted, as the page numbers of the PDF file do not match those of the original publication. URI: http:\/\/hdl.handle.net\/1807\/3074 ISBN: 87661-500-0 ISSN: 0018-098X Appears in Collections: Journal articles, conference papers and book chapters\n\nFiles in This Item:\n\nFile Description SizeFormat","date":"2014-03-09 11:37:52","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.44539743661880493, \"perplexity\": 10795.434233581744}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 5, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2014-10\/segments\/1393999677515\/warc\/CC-MAIN-20140305060757-00050-ip-10-183-142-35.ec2.internal.warc.gz\"}"}
null
null
World ignoring 'immense tragedies', Pope Francis says in Christmas message Holly Bancroft Religious leader Pope Francis delivers his traditional Christmas Day Urbi et Orbi from the main balcony of St Peter's Basilica at the Vatican (via REUTERS) The Pope said "immense tragedies are now being passed over in silence", as he urged increased dialogue between people and nations in his annual Christmas message. Pope Francis warned against a growing polarisation among individuals and world leaders – something he said had been exacerbated by the coronavirus pandemic. "We continue to witness a great number of conflicts, crises and disagreements," he said from the central balcony of St Peter's Basilica in Rome. "These never seem to end; by now we hardly even notice them. We have become so used to them that immense tragedies are now being passed over in silence; we risk not hearing the cry of pain and distress of so many of our brothers and sisters." In the "Urbi et Orbi" – "to the city and the world" – message, Pope Francis urged people to talk to each other rather than isolate themselves. "Our capacity for social relationships is sorely tired," he said. "There is a growing tendency to withdraw, to do it all by ourselves, to stop making an effort to encounter others and do things together." He continued: "On the international level, too, there is the risk of avoiding dialogue, the risk that this complex crisis will lead to taking shortcuts rather than setting out on the longer paths of dialogue. Yet only those parts can lead to the resolution of conflicts and to lasting benefit for all." Pope Francis listed conflicts, tensions and crises in Syria, Yemen, Israel, Palestine, Afghanistan, Ukraine, Sudan and South Sudan, as well as others. He asked God to "prevent fresh outbreaks of a long-festering conflict" in Ukraine. The build-up of Russian troops on the Ukrainian border has led to fresh fears of an invasion in January. Pope Francis used the word "dialogue" 11 times in the speech as he spoke before a small crowd in wet and windy conditions. He asked God to "give serenity and unity to families" and added: "Let us ask him for the strength to be open to dialogue. On this festive day, let us implore him to stir up in the hearts of everyone a yearning for reconciliation and fraternity." He also asked people not to be indifferent to the plight of migrants and refugees, as well as political prisoners, and female victims of violence. Pope Francis warned people that they should not hurt God "by despising the poor with our indifference". He added: "That is where Jesus is born: close to them, close to the forgotten ones of the peripheries. "He comes where human dignity is put to the test. He comes to ennoble the excluded and he first reveals himself to them; not to educated and important people, but to poor working people." He also urged leaders to protect the environment for future generations. Ralph Emery, who became known as the dean of country music broadcasters over more than a half-century in both radio and television, has died Right-wing academics feel need to 'self-censor' political beliefs on campus Three in four right-leaning academics say they are having to hide their political views on campus, according to a new report which warns of a higher education "monoculture" in which large numbers of lecturers "openly dislike" those who aren't left wing. Taylor Swift must face 'Shake It Off' copyright trial even if she's 'unhappy', accusers say Singer's lawyers had asked judge to dismiss case
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
2,072
{"url":"https:\/\/math.dartmouth.edu\/~m50f17\/HW3Sol.html","text":"## Question-1\n\nIs maximum-likelihood estimator $$\\tilde{\\sigma}^2$$ of $$\\sigma^2$$ an unbiased estimator ? Verify your answer. Comment on the change of the value of $\\mathbb{E}(\\tilde{\\sigma}^2) - {\\sigma}^2$ as $$n$$ goes to infinity.\n\nWe know that\n\n$\\tilde{\\sigma}^2 = \\frac{ \\sum_{i=1}^{n}(y_i - \\tilde\\beta_0 - \\tilde\\beta_1 x )^2}{n}$ and, moreover $$\\tilde\\beta_0=\\hat\\beta_0$$ and $$\\tilde\\beta_1=\\hat\\beta_1$$ since LSE and MLE has same coefficients estimations.\n\nCombining these yield \\begin{aligned} \\mathbb{E} [\\tilde{\\sigma}^2] & = \\frac{ \\mathbb{E} [ \\sum_{i=1}^{n}(y_i - \\tilde\\beta_0 - \\tilde\\beta_1 x )^2 ] }{n} \\\\ &= \\frac{ \\mathbb{E} [ \\sum_{i=1}^{n}(y_i - \\hat\\beta_0 - \\hat\\beta_1 x )^2 ] }{n} \\\\ &= \\frac{ \\mathbb{E} [ SS_{Res} ] }{n} \\\\ &= \\frac{ \\mathbb{E} [ (n-2) \\hat\\sigma^2 ] }{n} \\\\ \\end{aligned} since $$\\hat\\sigma^2 = \\frac{SS_{Res}}{n-2}$$. We can now see\n\n$\\mathbb{E} [\\tilde{\\sigma}^2] = \\frac{ (n-2) }{n}\\mathbb{E} [ \\hat\\sigma^2 ] = \\frac{ (n-2) }{n} \\sigma^2$\n\nsince $$\\hat\\sigma^2$$ is an unbiased estimator of $$\\sigma^2$$. We conclude that $$\\tilde{\\sigma}^2$$ is a biased estimator with\n\n$\\mathbb{E}(\\tilde{\\sigma}^2) - {\\sigma}^2 = \\left(\\frac{ n-2 }{n} -1 \\right) \\sigma^2 = \\frac{ -2 }{n} \\sigma^2$\n\nwhich goes to $$0$$ as $$n \\rightarrow\\infty$$. Therefore bias is negligible for large $$n$$.\n\n## Question-2\n\nConsider the shear strength vs age relation using the propellant data.\n\n1. Recalculate the coefficients of the fitted linear regression model using the vector equations we obtained.\n\n2. Suppose that the expectation of the initial shear strength is known to be 2400. Write the corresponding model (should involve only one parameter $$\\beta_1$$). Calculate 95% CI on $$\\beta_1$$.\n\n# Computation part of the answer :\n\nshearS<-prop$ShearS age<-prop$Age\n\nX <- cbind(1,age)\nbetaHat <- solve( t(X) %*% X ) %*% t(X) %*% shearS\n\n# part (a)\ncat ( \" Part(a)\nFitted Coefficients = \" , betaHat , \" \\n\\n\") \n## Part(a)\n## Fitted Coefficients = 2627.822 -37.15359\n# part (b)\n# We can use a vertical shift and use the no-intercept model\n# Note that vertical shifting will not change the beta1 and its statistics.\n# Therefore after we shift down by 2400, we simply work on a no-intercept model\n\nshearS_Shifted <- shearS - 2400\n\nbeta1Hat = sum( age * shearS_Shifted) \/ sum(age^2)\nyHat <- beta1Hat * age\n\n# We use CI for no-intercept model\ndof = 19\n\nMSres = sum((yHat - shearS_Shifted)^2) \/ dof\nseBeta1 = sqrt(MSres \/ sum(age^2) )\n\ntQ = qt( .975, dof)\nlowerCI = beta1Hat - tQ * seBeta1\nupperCI = beta1Hat + tQ * seBeta1\n\ncat ( \" Part (b)\nLower and upper bound of CI are : \" , lowerCI , \", \" , upperCI , \"\n\\n Note that these numbers make sense. Since we forced intercept to be 2400 (which is\nlower than the estimate of the intercept-model) the regression analysis response is\nto raise the other end, and therefore increase the slope. \"\n) \n## Part (b)\n## Lower and upper bound of CI are : -28.64285 , -19.63201\n##\n## Note that these numbers make sense. Since we forced intercept to be 2400 (which is\n## lower than the estimate of the intercept-model) the regression analysis response is\n## to raise the other end, and therefore increase the slope.\nfitted = lm(shearS ~ age)\nplot(age, shearS, main=\"Shear Strength vs. Age\", pch=16, xlim=c(0,30), ylim=c(1600,2700))\nabline(fitted$coef, lwd = 2, col = \"blue\") abline( c(2400,beta1Hat), lwd = 2 , col = 'red') ## Example : Phytoplankton Population A scientist is trying to model the relation between phytoplankton population in the city public water supply and concentration of two substances. The sample data is at : https:\/\/math.dartmouth.edu\/~m50f17\/phytoplankton.csv where headers are \u2022 pop : population of phytoplankton ($$y$$) \u2022 subs1 : concentration of substance-1 ($$x_1$$) \u2022 subs2 : concentration of substance-2 ($$x_2$$) Lets consider a guessed model $y = 200 + 10x_1 -15x_2$ Below is the corresponding code to plot the scatter diagram and the above plane. # Note: Run the following in R console if you get errors in plotting or library loading : # install.packages(\"scatterplot3d\") # install.packages(\"plot3D\") library(\"plot3D\") library(\"scatterplot3d\") # Loading data pData <- read.table(\"https:\/\/math.dartmouth.edu\/~m50f17\/phytoplankton.csv\", header=T, sep=\",\") pop <- pData$pop\nsubs1 <- pData$subs1 subs2 <- pData$subs2\n\n# Create a mesh\nmeshP <- mesh( seq(min(subs1),max(subs1),0.03) , seq(min(subs2),max(subs2),0.03) )\nx1Mesh <- meshP$x x2Mesh <- meshP$y\n\nmyModel <- 200 + 10*x1Mesh - 15 *x2Mesh\n\n# Below is the code to plot the scatter diagram with red markers and your model\n# You need to set two variables before calling :\nsc1\\$points3d (x2Mesh,x1Mesh, myModel, cex=.02, col=\"blue\")","date":"2018-01-22 14:24:19","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 2, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.9976863265037537, \"perplexity\": 5115.965739451322}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2018-05\/segments\/1516084891377.59\/warc\/CC-MAIN-20180122133636-20180122153636-00075.warc.gz\"}"}
null
null