\documentclass[main.tex]{subfiles}
\begin{document}

\subsubsection{The transfer equation for scattering}

\marginpar{Sunday\\ 2020-8-16, \\ compiled \\ \today}

If we only account for true emission and absorption the transfer equation looks like
%
\begin{align}
\dv{I_\nu }{s} = - \alpha_{\nu } I_\nu + j_\nu
\,.
\end{align}

For isotropic and conservative scattering we can modify this equation by adding on the scattering absorption and emission terms:
%
\begin{align}
\dv{I_\nu }{s} = - (\alpha_{\nu } + \alpha_{\nu }^{(s)}) I_\nu + j_\nu + \alpha_{\nu }^{(s)} J_\nu
\,.
\end{align}

Now we cannot give a formal solution anymore: the derivative of the intensity now depends not only on the intensity itself but on its average over all solid angles, \(J_\nu  = \expval{I_\nu }_{\Omega }\).
This will typically pose a problem: scattering is often the dominant phenomenon in radiative transfer for astrophysical systems.

In order to solve the equation we can resort to numerical methods: for example we can use an iterative relaxation procedure in which we start off by computing the solution without scattering, calculate the mean intensity and plug it as a fixed value into the next iteration, and keep going.

We can write the transfer equation as
%
\begin{align}
\dv{I_\nu }{ s}
= (\alpha_{\nu } + \alpha_{\nu }^{(s)})
\qty(- I_\nu + \frac{j_\nu + \alpha_{\nu }^{(s)} J_\nu }{\alpha_{\nu } + \alpha_{\nu }^{(s)}})
= (\alpha_{\nu } + \alpha_{\nu }^{(s)})
\qty(-I_\nu  + S_\nu )
\,,
\end{align}
%
where we define a new form for the source function:
%
\begin{align} \label{eq:source-function-with-scattering}
S_\nu = \frac{j_\nu + \alpha_{\nu }^{(s)} J_\nu }{\alpha_{\nu } + \alpha_{\nu }^{(s)}}
\,,
\end{align}
%
where, as long as Kirkhoff's law holds, we can substitute \(j_\nu = \alpha_{\nu } B_\nu \).

The optical depth is derived from the \emph{total} absorption coefficient:
%
\begin{align}
\dd{\tau_{\nu }} = (\alpha_{\nu } + \alpha_{\nu }^{(s)}) \dd{s}
\,.
\end{align}

With these definitions, we can write the transfer equation like before,
%
\begin{align}
\dv{I_\nu }{\tau_{\nu }} = - I_\nu + S_\nu
\,.
\end{align}

If there is scattering this is only apparently simple, the formulation only hides the complexity.

\subsection{Mean free path}

We defined absorption as \(\alpha_{\nu } = n \sigma_{\nu }\): this is just the inverse of the mean free path, so we have (for true absorption):
%
\begin{align}
\ell_{\nu } = \frac{1}{\alpha_{\nu }}
\,,
\end{align}
%
and we can define a mean free path for scattering in the exact same way, with \(\alpha_{\nu }^{(s)}\).
These will be the mean free paths of a photon before it undergoes that specific process, if we want to compute the mean free path of a photon before it undergoes \emph{either one} then we can just take the inverse of \(\alpha_{\nu } + \alpha_{\nu }^{(s)}\), the total absorption coefficient.

Now, consider a medium with scattering, emission and absorption.
Typically, a photon will be emitted, scatter a few times, and then be absorbed. Let us say that between emission and absorption it is scattered \(N\) times, and let us call the spatial intervals it travels between these scatterings \(\vec{r}_i\), where \(i\) goes from 1 to \(N\).
The total distance travelled will look like \(\vec{R} = \sum _{i} \vec{r}_i\).

The average of its square value will be
%
\begin{align}
\expval{R^2} = \sum _{ij} \expval{\vec{r}_i \vec{r}_j}
= \sum _{i} \expval{r_i^2} + 2 \sum _{i<j} \expval{\vec{r}_i \vec{r}_j}
\,.
\end{align}

The mixed averages \(\expval{r_i r_j}\) evaluate to zero, since each scattering is isotropic and independent; on the other hand each of the \(\expval{r_i^2}\) is equal to \(\ell_\nu^2\), the square of the mean free path.
This means that we have \(\expval{R^2} = N \ell_\nu^2\), meaning that the average distance occurring between each scattering is given by \(\ell_{*} = \sqrt{N} \ell_{\nu }\).

Now, let us suppose that the photon is being scattered in a medium whose characteristic length is \(L\). Then typically a photon will need to be scattered \(N\) times before escaping the medium, where \(L = \sqrt{N} \ell_{\nu }\).
This means that
%
\begin{align}
\sqrt{N} = \frac{L}{\ell_{\nu }} = \alpha_{\nu } L \sim \tau_{\nu }
\,,
\end{align}
%
where the last order-of-magnitude relation comes from the fact that the \emph{differential} of the optical path is given by \(\dd{\tau }_{\nu } = \alpha_{\nu } \dd{s}\).

This means that, at least in terms of order of magnitude, \(N \sim \tau_{\nu }^2\). This holds as long as the medium is optically thick, that it, \(\tau_{\nu }\) is larger (ideally much larger) than 1.

What happens instead if the medium is optically thin, with \(\tau_{\nu } < 1\)?
Then, we can neglect emission and scattering emission, and only consider scattering absorption. Then, the transfer equation will read
%
\begin{align}
\dv{I_\nu }{\tau_{\nu }} = - I_\nu
\,,
\end{align}
%
which is solved by \(I_\nu = I_\nu (0) e^{-\tau_{\nu }}\).
This can also be written, by adding \(I_\nu (0)\) to both sides, as
%
\begin{align}
I_\nu (0 ) - I_\nu  &= I_\nu (0) \qty(1 - e^{-\tau_{\nu }}) \\
\frac{I_\nu (0) - I_\nu }{I_\nu } &= 1 - e^{-\tau_{\nu }} \approx \tau_{\nu }
\,.
\end{align}

Now, the average number of scatterings will be less than 1 and will correspond to the average relative intensity lost, \(N = \Delta I_\nu / I_\nu (0)\). Therefore, in this case we will have \(N \sim \tau_{\nu }\).

Putting together these two limiting cases, we can roughly say that we will have
%
\begin{align}
N \approx \max \qty(\tau_{\nu },  \tau_{\nu }^2)
\,.
\end{align}

After a mean free path the photon can be either scattered or absorbed.
The probability that it is absorbed as opposed to being scattered is given by
%
\begin{align}
\epsilon_{\nu } = \frac{\alpha_{\nu }}{\alpha_{\nu } + \alpha_{\nu }^{(s)}}
\,,
\end{align}
%
while the probability that it is scattered is \(1 - \epsilon_{\nu }\), and this last quantity is typically called the \textbf{single scattering albedo}.

The average number of mean free paths travelled before absorption will be\footnote{This can be shown using the identity
%
\begin{align}
\sum _{i=1}^{\infty } i p^{i-1} = \frac{1}{(1-p)^2}
\,,
\end{align}
%
which can be proven by differentiating the geometric series and bringing the derivative into the sum, which converges absolutely.

Then, we can compute the average number of scatterings as
%
\begin{align}
\expval{N} = \sum _{i=1}^{\infty } \epsilon_{\nu } i (1 - \epsilon_{\nu })^{i-1} = \frac{\epsilon_{\nu }}{(1 - (1 - \epsilon_{\nu }))^2} = \frac{1}{\epsilon_{\nu }}
\,.
\end{align}}
%
\begin{align}
N = \frac{1}{\epsilon_{\nu }}
\,,
\end{align}
%
so we can make the following manipulation to find an explicit expression for the mean path between emission and absorption:
%
\begin{align}
\ell_{*}^2 = N \ell_{\nu }^2 = \frac{\ell_{\nu }^2}{\epsilon_{\nu }}
= \frac{1}{(\alpha_{\nu } + \alpha_{\nu }^{(s)} )^2} \frac{\alpha_{\nu }+ \alpha_{\nu }^{(s)}}{\alpha_{\nu }}
= \frac{1}{\alpha_{\nu } (\alpha_{\nu } + \alpha_{\nu }^{(s)})}
\,.
\end{align}

This means that
%
\begin{align}
\ell_{*} = \frac{1}{\sqrt{\alpha_{\nu } (\alpha_{\nu } + \alpha_{\nu }^{(s)})}}
\,.
\end{align}

Now we make use again of the order-of-magnitude relation \(\tau \sim \alpha L\) where \(L\) is the length scale of the medium; if we multiply \(L\) by \(1 / \ell_{*}\), the effective absorption coefficient, we get
%
\begin{align}
\tau \sim \frac{L}{\ell_{*}} = \sqrt{L^2 \alpha_{\nu } (\alpha_{\nu } + \alpha_{\nu }^{(s)})} = \sqrt{\tau_{\nu } (\tau_{\nu } + \tau_{\nu }^{(s)})}
\,,
\end{align}
%
which is larger than \(\tau_{\nu }\) alone would be. This is called the \textbf{effective optical depth}; the fact that this is larger than \(\tau_{\nu }\) means that scattering traps the photon in the region for a longer time than it would remain there with absorption alone.

\section{Radiative diffusion}

This is a way to approximately solve the radiative transfer equation under certain assumptions, the main one being that the medium should be very \textbf{optically thick}.

Another assumption we will make is the \textbf{plane-parallel} approximation: this means that the properties of the medium only vary with respect to one coordinate, which we will call \(z\).
We will further assume that the properties of the radiation also only vary along \(z\).

Now, this is about the \emph{spatial} dependence of the quantities, however certain ones like the radiation intensity \(I_\nu \) are also intrinsically vectors, so they also depend on the direction.
However, we will have cylindrical symmetry for rotations around the \(z\) axis: therefore, the intensity will be a function of \(z\) and of the angle \(\theta \) between the ray and the \(z\) axis.

The differential length travelled by the ray can be expressed in terms of the distance travelled along the \(z\) axis as
%
\begin{align}
\dd{s} = \frac{ \dd{z}}{\cos \theta } = \frac{ \dd{z}}{\mu }
\,,
\end{align}
%
where we define the usual shorthand, \(\mu  = \cos \theta \).

The radiative transfer equation reads
%
\begin{align}
\dv{I_\nu }{s} = \qty(- I_\nu + S_\nu ) \qty(\alpha_{\nu } + \alpha_{\nu }^{(s)})
\,,
\end{align}
%
where we can substitute
%
\begin{align}
\dv{I_\nu }{s} = \mu \pdv{I_\nu }{z}
\,,
\end{align}
%
and using this we can express the radiative transfer equation like
%
\begin{align}
I_\nu (z, \mu ) = S_\nu - \frac{1}{\alpha_{\nu } + \alpha_{\nu }^{(s)}}
\mu \pdv{I_\nu }{z}
\,.
\end{align}

Now we make use of the assumption that the optical depth is large. This means that \(\tau \sim (\alpha_{\nu }+ \alpha_{\nu }^{(s)}) \ell\) is large, where \(\ell\) is the characteristic scale of the system.

\todo[inline]{Should we not say explicitly that, besides being optically thick, the medium's thickness should be ``slowly varying''?}

This means that the term proportional to \(\pdv*{I_\nu }{z}\) is small compared to the source function, so we can apply perturbation theory.

To zeroth order, assuming thermal equilibrium, we will have
%
\begin{align}
I_\nu^{(0)} \approx S_\nu^{(0)} = B_\nu (T)
\,.
\end{align}

Then, the first-order approximation can be found by inserting the zeroth-order expression into the equation:
%
\begin{align}
I_{\nu }^{(1)} (z, \mu ) = B_\nu - \frac{\mu }{\alpha_{\nu } + \alpha_{\nu }^{(s)}} \pdv{B_\nu }{z}
\,.
\end{align}

An important thing to note is the linear relation between \(I_\nu \) and the cosine \(\mu \) of the angle.

With this first-order result we can compute the flux: if we were to use the zeroth-order one we would get zero, since blackbody radiation is isotropic.
The flux is given by the integral over the solid angle: the contribution to the integral due to the \(B_\nu \) term vanishes, since it is isotropic
%
\begin{align}
F_{\nu }(z) &= \int I_\nu^{(1)} (z, \mu ) \mu \dd{\Omega }
= 2 \pi \int_0^{\pi } I_\nu^{(1)} (z, \mu ) \cos \theta \sin \theta \dd{\theta }  \\
&= - \frac{2 \pi }{\alpha_{\nu } + \alpha_{\nu }^{(s)}} \pdv{B_\nu }{z}
\underbrace{\int_{1}^{-1}  \mu^2  (-1) \dd{\mu }}_{= 2/3}  \\
&= - \frac{4 \pi }{3 (\alpha_{\nu } + \alpha_{\nu }^{(s)})} \pdv{B_\nu }{z}  \\
&= - \frac{4 \pi }{3 (\alpha_{\nu } + \alpha_{\nu }^{(s)})} \pdv{B_\nu }{T} \dv{T}{z}
\,,
\end{align}
%
where we used the fact that the spatial dependence of the \(B_\nu \) only comes through the temperature \(T(z)\). This is useful since, while the derivative of \(B_\nu \) is frequency-dependent, the derivative of the temperature is not: therefore it can be factored out.

The total flux is given by
%
\begin{align}
F &= \int_{0}^{\infty } F_\nu \dd{\nu } =
- \frac{4 \pi }{3} \dv{T}{z} \int_0^{\infty } \frac{1}{\alpha_{\nu } + \alpha_{\nu}^{(s)}} \pdv{B_\nu }{T} \dd{\nu }  \\
&= - \frac{4 \pi }{3} \dv{T}{z}
\frac{\int_0^{\infty } \frac{1}{\alpha_{\nu } + \alpha_{\nu}^{(s)}} \pdv{B_\nu }{T} \dd{\nu }}{
\int_0^{\infty } \pdv{B_\nu }{T} \dd{\nu }
}
\int_0^{\infty } \pdv{B_\nu }{T} \dd{\nu }
\,,
\end{align}
%
which is the \textbf{average value} of the function \(1 / (\alpha_{\nu }+ \alpha_{\nu }^{(s)})\) weighted by the \emph{known} function \(\pdv*{B_\nu }{T}\); the integral at the numerator can be explicitly evaluated:
%
\begin{align}
\int_0^{\infty } \pdv{B_\nu }{T} \dd{\nu }
= \pdv{}{T} \int_{0}^{\infty} B_\nu \dd{\nu }
= \pdv{}{T} \qty( \frac{\sigma}{\pi } T^{4})
= \frac{4 \sigma }{\pi } T^3
\,,
\end{align}
%
which means that the final expression is
%
\begin{align}
F = - \frac{4 \pi }{3} \frac{4 \sigma T^3}{\pi } \dv{T}{z}
\frac{\int_0^{\infty } \frac{1}{\alpha_{\nu } + \alpha_{\nu}^{(s)}} \pdv{B_\nu }{T} \dd{\nu }}{
\int_0^{\infty } \pdv{B_\nu }{T} \dd{\nu }
}
\,,
\end{align}
%
which we can better understand by defining the \textbf{Rosseland mean opacity}
%
\begin{align}
\frac{1}{\alpha_{R}} = \frac{\int_0^{\infty } \frac{1}{\alpha_{\nu } + \alpha_{\nu}^{(s)}} \pdv{B_\nu }{T} \dd{\nu }}{
\int_0^{\infty } \pdv{B_\nu }{T} \dd{\nu }
}
\,,
\end{align}
%
so that the expression reads
%
\begin{align}
F = - \frac{16}{3} \frac{\sigma T^3}{\alpha_{R}} \dv{T}{z}
\,.
\end{align}

This is called the \textbf{Rosseland approximation}. The result is that we can find a net photon flux which is driven by the temperature gradient.
This has many applications, for example in stellar astrophysics.

This equation is very similar to the heat flux equation in one dimension:
%
\begin{align}
q = - k \pdv{T}{z}
\,,
\end{align}
%
which in our case has the constant (thermal conductivity)
%
\begin{align}
k = \frac{16}{3} \frac{\sigma T^3}{\alpha_{R}}
\,.
\end{align}

We have assumed that the medium is optically thick, but we can see that if it becomes very optically thick then the photons have a hard time escaping (\(k\) becomes small).

\section{The Eddington approximation}

In the Rosseland approximation we found the result
%
\begin{align}
I_\nu = B_\nu (T) + \mu \times \text{stuff}
\,,
\end{align}
%
where the ``stuff'' is small. We then expanded in this parameter; without it we are in a perfectly isotropic condition, so we can say that we are ``expanding around isotropy''.

The idea behind the Eddington approximation is similar: we assume that the intensity can be written as
%
\begin{align}
I_\nu (\tau ) = a_\nu (\tau ) + b_\nu (\tau ) \mu
\,,
\end{align}
%
so as before the angular dependence is linear.

Let us compute the moments of the specific intensity: the zeroth moment is the mean intensity,
%
\begin{align}
J_\nu = \frac{1}{4 \pi } \int I_\nu \dd{\Omega }
= \frac{2 \pi }{4 \pi } \int_{-1}^{1} (a_\nu + b_\nu \mu) \dd{\mu }
= a_\nu
\,,
\end{align}
%
while the first moment is equal to
%
\begin{align}
H_\nu = \frac{1}{4 \pi } \int I_\nu \mu \dd{\Omega }
= \frac{2 \pi }{4 \pi } \int_{-1}^{1} \qty(a_\nu \mu + b_\nu \mu^2) \dd{\mu } = \frac{1}{2} \frac{2}{3} b_\nu = \frac{b_\nu }{3}
\,.
\end{align}

The second moment is
%
\begin{align}
K_\nu = \frac{1}{4 \pi } \int I_\nu \mu^2 \dd{\Omega } = \frac{a_\nu }{3}
= \frac{1}{3} J_\nu
\,.
\end{align}

The fact that the second moment of the intensity  is related to the zeroth one as \(K_\nu = J_\nu / 3\) is precisely what the Eddington approximation asks.

The plane-parallel radiative transport equation can be written as
%
\begin{align}
\mu \pdv{I_\nu }{\tau } = I_\nu - S_\nu
\,,
\end{align}
%
since \(\dd{\tau } = -(\alpha_{\nu } + \alpha_{\nu }^{(s)}) \dd{s}\) and \(\dd{z} = \mu \dd{s}\).

\todo[inline]{Why is the optical depth defined with a negative sign here? It is the same in RL \cite[eq.\ 1.115]{rybickiRadiativeProcessesAstrophysics1979}. Is this to be interpreted as the optical depth towards a far-away observer, positioned at large \(z\)?}

In this equation, the source function \(S_\nu \) is assumed to be isotropic. So, if we average over the solid angle (or equivalently in \(\dd{\mu } / 2\)) we get
%
\begin{align}
\frac{1}{2}\int_{-1}^{1} \mu \pdv{I_\nu }{\tau } \dd{\mu } &= \frac{1}{2}\int_{-1}^{1} I_\nu \dd{\mu }
- \frac{1}{2}\int_{-1}^{1} S_\nu \dd{\mu } \\
\pdv{}{\tau } H_\nu  &= J_\nu - S_\nu
\,.
\end{align}

We can also take the first moment of the same equation by multiplying the equation by \(\mu \) before integrating: this yields
%
\begin{align}
\frac{1}{2}\int_{-1}^{1} \mu^2 \pdv{I_\nu }{\tau } \dd{\mu } &= \frac{1}{2}\int_{-1}^{1} I_\nu \mu  \dd{\mu }
- \underbrace{\frac{1}{2}\int_{-1}^{1} S_\nu \mu \dd{\mu }}_{= 0 }  \\
\pdv{K_\nu }{\tau } &= H_\nu
\,.
\end{align}

However, recall that in the Eddington approximation we have \(K_\nu = J_\nu / 3\): this means that we have the system of coupled differential equations
%
\begin{align}
\pdv{H_\nu }{\tau } = J_\nu - S_\nu
\qquad \text{and} \qquad
\frac{1}{3} \pdv{J_\nu }{\tau } = H_\nu
\,,
\end{align}
%
which we can combine into one second order equation by differentiating the second: this yields
%
\begin{align}
\frac{1}{3}\pdv[2]{J_\nu }{\tau } = J_\nu - S_\nu
\,.
\end{align}

Now, the source function can be decomposed in a part depending on \(J_\nu \) and a part depending on \(B_\nu \) according to the single scattering albedo \(\epsilon_{\nu }\) (see equation \eqref{eq:source-function-with-scattering}):
%
\begin{align}
S_\nu = \epsilon_{\nu } B_\nu + (1 - \epsilon_{\nu }) J_\nu
\,.
\end{align}

Substituting this in a term simplifies and we finally find
%
\boxalign{
\begin{align}
\frac{1}{3} \pdv[2]{J_\nu }{\tau } = \epsilon_{\nu } \qty(J_\nu - B_\nu )
\,,
\end{align}}
%
the \textbf{radiative diffusion equation}.
This can be solved relatively simply; however it does not give us the whole intensity, instead we can only find its mean value \(J_\nu \).

If we can calculate \(S_\nu \) using this equation, then we can plug what we have found into the radiative transfer equation
%
\begin{align}
\mu \pdv{I_\nu }{\tau } = I_\nu - S_\nu
\,.
\end{align}

Now that we have discussed the differential equations at length, let us consider for a moment the \textbf{boundary conditions} we need to impose.

A possible way to approach the problem is called the \emph{two stream approximation}: we assume that radiation is only travelling along two angles, whose cosines are \(\mu = \pm 1/ \sqrt{3}\), so \(\theta = \pm \SI{55}{\degree}\).
This choice is less arbitrary than it may seem, there is good reason to suppose that in certain condition this is indeed the angle at which radiation will travel. This will be discussed later.

Let us introduce the quantities
%
\begin{align}
I_\nu^{\pm} (\tau ) = I_\nu (\tau , \pm \frac{1}{\sqrt{3}})
\,.
\end{align}

Then, the average intensity will be given by their average:
%
\begin{align}
J_\nu = \frac{I_\nu^{+} + I_\nu^{-}}{2}
\,.
\end{align}
%
The further moments can also be computed: they will be
%
\begin{align}
H_\nu = \frac{1}{2 \sqrt{3}} \qty(I_\nu^{+} + I_\nu^{-})
\qquad \text{and} \qquad
K_\nu = \frac{I_\nu^{+} + I_\nu^{-}}{6}
\,,
\end{align}
%
consistently with the Eddington approximation. Note that, if we want to use a two-stream approximation, the only way for Eddington to hold is to use the values of \(\mu = \pm 1/\sqrt{3}\).

The explicit expressions of the moments allow us to recover the \(I_\nu^{\pm}\) as
%
\begin{align}
I_\nu^{+} &= J_\nu + \sqrt{3} H_\nu = J_\nu + \frac{1}{\sqrt{3}} \pdv{J_\nu }{\tau } \\
I_\nu^{+} &= J_\nu - \sqrt{3} H_\nu = J_\nu - \frac{1}{\sqrt{3}} \pdv{J_\nu }{\tau }
\,.
\end{align}

Now, let us fix an example for concreteness: a ``slab'' (like, for instance, a stellar atmosphere) extending from \(\tau_0\) to \(\tau =0\).
The point at \(\tau = 0\) is the top of the atmosphere: so, we want to impose the absence of incoming radiation there (supposing that there are no other nearby stars to influence the process): this is implemented as \(I_\nu^{-} (\tau = 0) = 0\).
This is called the \emph{non-illuminated atmosphere} condition.

Also suppose that there is no radiation coming into the bottom of the slab: \(I_\nu^{+} (\tau_0 ) = 0\).

This means that
%
\begin{align}
\eval{J_\nu + \frac{1}{\sqrt{3}} \pdv{J_\nu }{\tau }}_{\tau_0 } = 0
\qquad \text{and} \qquad
\eval{J_\nu - \frac{1}{\sqrt{3}} \pdv{J_\nu }{\tau }}_{0} = 0
\,.
\end{align}

With these boundary conditions, one can solve the equation numerically.

\chapter{Results in classical electromagnetism}

\section{Plane electromagnetic waves}

In a vacuum, Maxwell's equations read
%
\begin{align}
\nabla \cdot E = \nabla \cdot B =0
\,
\end{align}
%
and
%
\begin{align}
\nabla \times E &= - \frac{1}{c} \pdv{B}{t}  \\
\nabla \times B &= \frac{1}{c} \pdv{E}{t}
\,.
\end{align}

Using the identity \(\epsilon_{ijk} \epsilon_{klm} = \delta_{jl} \delta_{km} - \delta_{jm} \delta_{kl}\) we can combine these into a wave equation,
%
\begin{align}
\nabla^2 E - \frac{1}{c^2} \pdv[2]{E}{t} = 0
\,,
\end{align}
%
which is solved by plane monochromatic waves
%
\begin{align}
\vec{E}  =\vec{\epsilon} E_0 \exp(i (\vec{k} \cdot \vec{r} - \omega t))
\,,
\end{align}
%
where the angular frequency and wavevector satisfy \(\omega = c \abs{\vec{k}}\).
These are transverse waves: the scalar product of \(\vec{\epsilon}\) and the wavevector \(\vec{k}\) is zero, there is no longitudinal oscillation along the direction of motion.

These solutions form a basis, generally the radiation we find is not monochromatic.
The electric field will be time-dependent, \(\vec{E} = \vec{E} (t)\).

We want to discuss the frequency decomposition of these waves; we start off by assuming that we are dealing with a pulse, such that \(\vec{E}(t) \rightarrow 0\) as \(t \to \pm \infty \).

The Fourier transform of the electric field in the time domain gives us its frequency decomposition: we choose our conventions so that
%
\begin{align}
\hat{E}(\omega ) = \frac{1}{2 \pi } \int_{- \infty }^{\infty } E(t) e^{i \omega t} \dd{t}
\,.
\end{align}

Since \(E(t)\) is real, we must have \(\hat{E}^{*}(\omega ) = \hat{E} (- \omega )\).
This means that we do not need to worry about negative frequencies.

The fundamental quantity we need to compute is the \textbf{energy spectrum} from the electric field: how is the energy in the EM radiation distributed across the various frequencies?
The Poynting vector is useful in this context, as it quantifies the amount of energy carried per unit area and time: its modulus is given by
%
\begin{align}
S = \frac{ \dd{w}}{ \dd{t} \dd{A}} = \frac{c}{4 \pi } E^2(t)
\,,
\end{align}
%
which we need to integrate if we want to find the total energy carried by the pulse:
%
\begin{align}
\dv{w}{A} = \frac{c}{4 \pi } \int_{- \infty }^{\infty} E^2(t) \dd{t}
\,.
\end{align}

Now, \textbf{Parseval's theorem} is a statement about Fourier transforms, telling us that the energy of the signal is conserved if we Fourier transform, meaning that
%
\begin{align}
\int_{- \infty }^{\infty } E^2(t) \dd{t} = 2 \pi \int_{-\infty}^{\infty} \abs{\hat{E}(\omega )}^2 \dd{\omega}
\,.
\end{align}

Since this square modulus is the same for the conjugate the integrand is symmetric under \(\omega \to - \omega \), so we can compute it from 0 to \(\infty \) and multiply by 2 to get the same result. This yields
%
\begin{align}
\dv{w}{A} = \frac{4 \pi c}{4 \pi } \int_{0}^{\infty }\abs{\hat{E}(\omega )}^2 \dd{\omega}
\,,
\end{align}
%
which can be differentiated with respect to \(\omega \) to find the energy density per unit time and frequency:
%
\begin{align}
\frac{ \dd{w}}{ \dd{A} \dd{\omega }} = c \abs{\hat{E}(\omega )}^2
\,.
\end{align}

This concerns the \emph{total} energy of the pulse: we might want to calculate the energy per unit area, time and frequency!
However, there is an issue in doing this: the uncertainty principle. We cannot sample with arbitrarily small intervals in both \(t\) and \(\omega \), since the inequality \(\Delta \omega \Delta t \geq 1\) must be satisfied.

However, if our pulse repeats over some comparatively long time \(T\) we can formally define
%
\begin{align}
\frac{ \dd{w}}{ \dd{A} \dd{\omega } \dd{t}} = \frac{1}{T} c \abs{\hat{E}(\omega )}^2
\,,
\end{align}
%
so, as long as \(T\) is relatively long we can take the limit:
%
\begin{align}
\frac{ \dd{w}}{ \dd{A} \dd{\omega } \dd{t}} = \lim_{T \to \infty  } \frac{1}{T} c \abs{\hat{E}(\omega )}^2
\,.
\end{align}

\subsection{Polarization}

This is a measurable quantity in astrophysics, it is easier to perform polarization measurements for low frequencies but nowadays we are starting to be able to measure polarizations as far as X-rays.

By definition a monochromatic plane wave is \emph{linearly polarized}: it oscillates along a specific axis.
Consider a superposition of two electric fields at a specific point in space, for simplicity \(\vec{r} = 0 \): the total electric field will be given by
%
\begin{align}
\vec{E} = \underbrace{\qty(\vec{x} E_1 + \vec{y} E_2 )}_{\vec{E}_0 } e^{-i \omega t}
\,,
\end{align}
%
where the amplitudes \(E_{1,2} \) are in general complex: \(E_{1, 2} = \xi_{1, 2} e^{i \phi_{1,2} }\). So, we can write the total electric field
%
\begin{align}
\vec{E} =
\vec{x} \xi_1 e^{i (\phi_1 - \omega t)}
+
\vec{y} \xi_2 e^{i (\phi_2 - \omega t)}
\,.
\end{align}

The physical field along any direction will be given by the real part of the projection of this complex-valued vector along that component:
%
\begin{align}
E_x = \Re \qty{\xi_1 e^{i (\phi_1 - \omega t)}} = \xi_1 \cos(\phi_1 - \omega t)
= \xi_1 \cos \omega t  \cos \phi_1 + \xi_1 \sin \omega t \sin \phi_1
\,,
\end{align}
%
and similarly with \(E_y\), \(\xi_2\) and \(\phi_2 \).

Now, a short aside: an ellipse can be described parametrically from its principal axes with
%
\begin{align}
x' = A \cos \beta \cos \omega t
\qquad \text{and} \qquad
y' = - A \sin \beta \sin \omega t
\,,
\end{align}
%
since these expressions satisfy
%
\begin{align}
\frac{x^{\prime 2} }{A^2 \cos^2\beta }
+\frac{y^{\prime 2} }{A^2 \sin^2\beta }
= 1
\,,
\end{align}
%
so we can parametrize any ellipse with an appropriate choice of \(A \in R^{+}\) and \(\beta \in [- \pi /2, \pi /2]\).

\end{document}


\chapter{The axiom of extensionality}


\subsection{tempPerDay()}

The third graph we created was the second example graph proposed in the instructions file. It shows the mean temperature for each day of the year. It is produced by the member function of tempTrender called "tempPerDay(). It is akin to stacking 365 of the "tempOnDay()" histograms vertically.

\begin{figure}[h]
\centering
\includegraphics[scale=0.3]{graph3.png}
\caption{Histogram showing the mean temperature on each day of the year. Produced by "tempPerDay()". }
\end{figure}


\documentclass{tufte-handout}

\usepackage{amsmath}
\usepackage[utf8]{inputenc}
\usepackage{mathpazo}
\usepackage{booktabs}
\usepackage{microtype}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{width=9cm,compat=1.13}

\title{Foursum Report}
\author{Alice Cooper and Bob Marley}

\begin{document}
\maketitle
\thispagestyle{empty}

  \section{Exhaustive search}

\sidenote{Complete the report by filling
  in your names, filling in the parts marked $[\ldots]$ and changing other parts wherever necessary.
  (For instance, the numbers is the tables are nonsense right now.)
  Remove the sidenotes in your final hand-in.}

Our program [\texttt{Simple.java} / \texttt{simple.py}]\sidenote{Choose one.} solve the Four-sum problem using four nested loops.
The index variables $i$, $j$, $k$, $l$ run from [$\ldots$]\sidenote{Explain. Do you start in $0$? One sentence.}
Thus, we can bound the number of array accesses by $\sim\frac{1}{10}(\cos N)\binom{N}{5}$.\sidenote{Replace by an expression that corresponds to your code.}

  \subsection{Experiments}

The following table summarises the empirical performance data on the input files in the \texttt{data} directory.
We have run each file once, and report the minimum, maximum, and average running time over the files for each input size.

  \bigskip\noindent
{ \small
  \begin{tabular}{cccccccc}
  \toprule
& \multicolumn{3}{c}{Java} & $\quad$ & \multicolumn{3}{c}{Python}  \\\cmidrule{2-4} \cmidrule{6-8}
  $N$     & $\min$     & $\max$ & avg. &
          & $\min$     & $\max$ & avg.   \\\midrule
  $100	$ & 1 sec & 5 days & 23.5 hours \\
  $[\ldots]$ \\
  \bottomrule
  \end{tabular}
}

\medskip
We can plot the maximum running time as a function of input size, as a standard plot and as a log--log plot.\sidenote{Draw both graphs, as two separate figures. Use any software you want, or draw it hand.}
In the latter, note that the points fall nicely on a line of slope [$\dots$]\sidenote{replace by an integer}.
\medskip

\begin{tikzpicture}
	\begin{axis}[
		title={Running time for search, one planted quadruple},
		xlabel={$N$},
                xmode = log,
                log ticks with fixed point,
                ymode = log,
		ylabel={Time (s)},
		xmin=30, xmax=3200,
		ymin=.03, ymax=8,
		xtick={30,50,100,200,400, 800, 1600,3200},
		%ytick={0,40,80,160},
		ytick={.05,.1,.5,1,2},
                legend style={at={(1.1,0)}, anchor=south west},
                % legend pos=north east, %north west,
		%ymajorgrids=true,
		%grid style=dashed,
	]
	\addplot[color=blue, mark=x,error bars/.cd,y dir=both,y explicit ] table [x index=0, y index=1, y error index=2] {Tables_done/Weed1Java.table};
        %	coordinates { (100,32)(200,37.8)(400,44.6)(800,61.8)(1600,83.8)(3200,114) };
	\addplot[ color=red, mark=*,error bars/.cd,y dir=both,y explicit ]	table [x index=0, y index=1, y error index=2] {Tables_done/Weed1PythSimp.table};
        % coordinates { (100,132)(200,72.8)(400,144.6)(800,161.8)(1600,133.8)(3200,224) };
	\addplot[ color=green, mark=o,error bars/.cd,y dir=both,y explicit ] table [x index=0, y index=1, y error index=2] {Tables_done/Weed1JavaHash.table};
	\addplot[ color=brown, mark=x,error bars/.cd,y dir=both,y explicit ] table [x index=0, y index=1, y error index=2] {Tables_done/Weed1PythDict.table};
%        \addplot[color=yellow] expression[domain=8:3200] {.00009*x+.08};
%        \addplot[color=yellow] expression[domain=8:3200] {.0009*x};
%        \addplot[color=yellow] expression[domain=8:3200] {.0002*x*ln(x)};
        \addplot[color=yellow] expression[domain=8:3200] {.0000000041*x*x*x*x};
%        \addplot[color=yellow] expression[domain=8:3200] {.00000000031*x*x*x*x};
        \addplot[color=yellow] expression[domain=8:3200] {.00000038*x*x};
	\legend{Java, Python, Fast Java, Fast Python}
	\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
	\begin{axis}[
		title={Running time for exhaustive search},
		xlabel={$N$},
                xmode = log,
                log ticks with fixed point,
                ymode = log,
		ylabel={Time (s)},
		xmin=30, xmax=3200,
		ymin=.03, ymax=8,
		xtick={30,50,100,200,400, 800, 1600,3200},
		%ytick={0,40,80,160},
		ytick={.05,.1,.5,1,2},
                legend style={at={(1.1,0)}, anchor=south west},
                % legend pos=north east, %north west,
		%ymajorgrids=true,
		%grid style=dashed,
	]
	\addplot[color=blue, mark=x,error bars/.cd,y dir=both,y explicit ] table [x index=0, y index=1, y error index=2] {Tables_done/TripleJava.table};
        %	coordinates { (100,32)(200,37.8)(400,44.6)(800,61.8)(1600,83.8)(3200,114) };
	\addplot[ color=red, mark=*,error bars/.cd,y dir=both,y explicit ]	table [x index=0, y index=1, y error index=2] {Tables_done/TriplePythSimp.table};
        % coordinates { (100,132)(200,72.8)(400,144.6)(800,161.8)(1600,133.8)(3200,224) };
	\addplot[ color=green, mark=o,error bars/.cd,y dir=both,y explicit ] table [x index=0, y index=1, y error index=2] {Tables_done/TripleJavaHash.table};
	\addplot[ color=brown, mark=x,error bars/.cd,y dir=both,y explicit ] table [x index=0, y index=1, y error index=2] {Tables_done/TriplePythDict.table};
%        \addplot[color=yellow] expression[domain=8:3200] {.00009*x+.08};
        \addplot[color=yellow] expression[domain=8:3200] {.02*exp(ln(x)/3)};
        \addplot[color=yellow] expression[domain=8:3200] {.00000018*x*x};
        \addplot[color=yellow] expression[domain=8:3200] {.0000000081*x*x*x*x};
        \addplot[color=yellow] expression[domain=8:3200] {.000000000031*x*x*x*x};
	\legend{Java, Python, Fast Java, Fast Python}
	\end{axis}
\end{tikzpicture}

\begin{tikzpicture}
	\begin{axis}[
		title={Running time for simple search},
		xlabel={$N$},
                xmode = log,
                log ticks with fixed point,
                ymode = log,
                error bars/y dir=both,
		ylabel={Time (s)},
		xmin=30, xmax=850,
		ymin=.04, ymax=1.6,
		xtick={30,50,100,200,400, 800, 1600,3200},
		%ytick={0,40,80,160},
		ytick={.05,.1,.2,.5,1,2},
		legend pos=north west,
		%ymajorgrids=true,
		%grid style=dashed,
	]
	\addplot[ color=blue, mark=x, error bars/.cd,y dir=both,y explicit] table [x index=0, y index=1, y error index=2] {Tables_done/TripleJava.table};
        %	coordinates { (100,32)(200,37.8)(400,44.6)(800,61.8)(1600,83.8)(3200,114) };
	\addplot[ color=red, mark=*,error bars/.cd,y dir=both,y explicit ]	table [x index=0, y index=1, y error index=2] {Tables_done/Weed0Java.table};
        % coordinates { (100,132)(200,72.8)(400,144.6)(800,161.8)(1600,133.8)(3200,224) };
	\addplot[ color=green, mark=o, error bars/.cd,y dir=both,y explicit] table [x index=0, y index=1, y error index=2] {Tables_done/Weed1Java.table};
	\addplot[ color=brown, mark=x,error bars/.cd,y dir=both,y explicit ] table [x index=0, y index=1, y error index=2] {Tables_done/Weed1JavaHash.table};
	\legend{Triple, Weed 0, Weed 1, Weed1JavaHash}
	\end{axis}
\end{tikzpicture}

\subsection{Improvements}

Using the binary search-based idea sketeched in [SW, 1.4] for the Three-sum problem, we can improve our running time to $\sim N^3\log N$. \sidenote{Correct as necessary. If instead you’ve figured out how to do it even faster, rewrite the whole sentence so as to explain what you do.}

The following table reports our maximum running times on the test inputs. [$\cdots$]

The following log--log plot shows these values graphically, note that the points are on a line of slope [$\cdots$].

\end{document}


\section{Intensity}
\subsection{Purpose}
For T2 and T3 data, it is often useful to group records into fixed time bins and count the number of records in each bin. This program does just that, reporting the intensity at each channel for all data in a time-ordered stream.

\subsection{Command-line syntax}
%\input{programs/intensity.usage}

\subsubsection{Input}
T2 and T3 modes accept data of the form produced by \program{picoquant}, as specified in section~\ref{sec:picoquant_output}.

\subsubsection{Output}
The output for both T2 and T3 modes is of the form:
\begin{verbatim}
lower time limit, upper time limit,
  channel 0 intensity, channel 1 intensity, ... \n
\end{verbatim}
For T2 mode, the time bin is defined as a number of picoseconds. For T3 mode, the time bin is a number of pulses.

Passing the flag \texttt{--count-all} will ignore the time bins, and instead count all events on each channel as belonging to one large channel.

The bin limits for the first and last bin are set to the first and last photons seen, unless the flag \texttt{--start-time} or \texttt{--stop-time} is passed. This eliminates dead time at the beginning and end of the measurement, though for some purposes the limits may need to be extended. For such limit modifications, use external analysis code.

\subsection{Examples of usage}
\subsubsection{Bin counts into fixed-width bins}
\begin{verbatim}
> picoquant --file-in data.pt2 --number 100000 |  \
  intensity --mode t2 --channels 2 \
            --bin-width 50000000000
7128264,50000000000,2674,0
50000000000,100000000000,2715,0
100000000000,150000000000,2650,0
150000000000,186537236212,1961,0
\end{verbatim}

\subsubsection{Count all photons}
\begin{verbatim}
> picoquant --file-in data.pt2 --number 100000 |  \
  intensity --mode t2 --channels 2 \
  --count-all
0,186537236212,10000,0
\end{verbatim}

\subsubsection{Count photons in a subset of time}
\begin{verbatim}
> picoquant --file-in data.pt2 --number 100000 | \
  intensity --mode t2 --channels 2 \
  --bin-width 50000000000
  --start-time 100000000000
100000000000,150000000000,2650,0
150000000000,186537236212,1961,0
> picoquant --file-in data.pt2 --number 100000 | \
  intensity --mode t2 --channels 2 \
  -bin-width 50000000000
  --start-time 100000000000
  --stop-time 120000000000
100000000000,120000000000,1040,0
\end{verbatim}

\subsection{Implementation details}
\label{sec:intensity_implementation}
Each channel can be treated independently, so we will focus on how to handle a single stream of records.

Given a set of photons $\photon\in\photons$, our goal is to determine the number of $\photon$ whose arrival times are in a time range $\timewindow$:
\begin{equation}
I(\timewindow) = \abs{\setbuilder{\photon}{\photon\in\photons;~\Time(\photon)\in\timewindow}}
\end{equation}
In our case, we will only be concerned with time intervals $\timewindow$ which are consecutive and collectively span the full integration time:
\begin{align}
\timewindow_{j} &= \left[[\timewindow_{j}\upminus,\timewindow_{j}\upplus\right) \\
\integrationtime &= \bigcup\limits_{j=0}^{m}{\timewindow_{j}}
\end{align}
As such, any photon can belong to exactly one subset $\photons_{\timewindow_{j}}$, and these $\timewindow_{j}$ can each be visited exactly once by iterating through times in the experiment. This can be performed efficiently if we impose the condition that the stream of photons be time-ordered, by iterating over photons and time bins alternately:
\lstset{language=Python}
\begin{lstlisting}
photon = next(photons)
time_bin = next(time_bins)
intensity = 0

while photon and time_bin:
    if photon in time_bin:
        intensity += 1
        photon = next(photon)
    else:
        yield(time_bin, intensity)
        time_bin = next(time_bins)
        intensity = 0

yield(time_bin, intensity)
\end{lstlisting}
As can be seen, this algorithm scales linearly with the number of time bins and photons, i.e. it scales as O(\abs{\photons}). This algorithm requires time-ordered photons and bins which never lag behind the photon stream, which are guaranteed by appropriate initialization of the photon and bin streams.


\documentstyle[11pt,reduce,fancyheadings]{article}
\title{The Weierstrass substitution in REDUCE}

\author{Neil Langmead \\
        Konrad-Zuse-Zentrum f\"ur Informationstechnik (ZIB) \\
        Takustrasse 7  \\
        D- 14195 Berlin Dahlem \\
        Berlin
        Germany}
\date{January 1997}

\def\foottitle{The Weierstrass substitution}
\pagestyle{fancy}
\lhead[]{{\footnotesize\leftmark}{}}
\rhead[]{\thepage}
\lfoot[]{Neil Langmead}
\rfoot[]{}
\addtolength{\oddsidemargin}{-20 mm}
\addtolength{\textwidth}{25 mm}
\pagestyle{fancy}
\setlength{\headrulewidth}{0.6pt}
\setlength{\footrulewidth}{0.6pt}
\setlength{\topmargin}{1 mm}
\setlength{\footskip}{10 mm}
\setlength{\textheight}{220 mm}
\cfoot{}
\rfoot{\small\foottitle}

\def\exprlist   {exp$_{1}$,exp$_{2}$, \ldots ,exp$_{{\tt n}}$}
\def\lineqlist  {lin\_eqn$_{1}$,lin\_eqn$_{2}$, \ldots ,lin\_eqn$_{n}$}
\begin{document}
\maketitle
%\begin{center} \Large The Weirstrass Substitution in REDUCE
%\end{center} }
\pagebreak
\tableofcontents
\pagebreak
\section{Introduction}
This package is an implementation of a new algorithm proposed by D.J. Jeffrey and A.D. Rich ~\cite{Jeff} to remove "spurious" discontinuities from integrals. Their paper focuses on the Weirstrass substitution,$u=\tan(x/2)$, currently used in conjunction with the Risch algorithm in most computer algebra systems to evaluate trigonometric integrals. Expressions obtained using this substitution sometimes contain discontinuities, which limit the domain over which the expression is correct. The algorithm presented finds a better expression, in the sense that it is continous on wider intervals whilst still being an anti derivative of the integrand.

\subsection{Example}
 Consider the following problem:  \\
     \begin{equation} \int \frac{3}{5-4\cos(x)}\,dx  \end{equation}

\small{REDUCE} \normalsize computes an anti derivative to the given function using the Weirstrass substitution $u=tan(\frac{x}{2})$, and then the Risch algorithm is used, returning:
    \begin{equation} \frac{2\arctan(3\tan(\frac{x}{2}))}{3}, \end{equation}
which is discontinuous at all odd multiples of $\pi$. Yet our original function is continuous everywhere on the real line, and so by the Fundamental Theorem of Calculus, any anti-derivative should also be everywhere continuous. The problem arises from the substitution used to transform the given trigonometric function to a rational function: often, the substituted function is discontinuous, and spurious discontinuities are introduced as a result. \\
Jeffery and Richs' algorithm returns the following to the given problem: \\
\[ \int \frac{3}{5-4\cos(x)}\,dx = 2\arctan(3\tan(\frac{x}{2}))+2\pi\lfloor \frac{x-\pi}{2\pi} \rfloor \]
which differs from (2) by the constant 2$\pi$, and this is the correct way of removing the discontinuity.
\pagebreak
\section{Statement of the Algorithm}
We define a Weierstrass substitution to be one that uses a function $u=\Phi(x)$ appearing in the following table: \\

\begin{tabular}{|c|p{1in}|p{0.5in}|p{0.5in}|p{0.5in}|c|c||} \hline
\multicolumn{7}{|l|}{Functions $u=\Phi$ used in the Weirstrass Alg. and their corresponding substitutions} \\ \hline
\multicolumn{1}{|c|}{Choice}
&\multicolumn{1}{|c|}{  $\Phi(x)$  }
&\multicolumn{1}{|c|}{  $\sin(x)$  }
&\multicolumn{1}{|c|}{  $\cos(x)$  }
&\multicolumn{1}{|c|}{  $dx$  }
&\multicolumn{1}{|c|}{  $b$  }
&\multicolumn{1}{|c|}{  $p$  }  \\  \hline
$(a)$  & $\tan(x/2)$ & $\frac{2u}{1+u^{2}}$ & $ \frac{1-u^{2}}{1+u^{2}}$ & $\frac{2du}{1+u^{2}}$ & $\pi$ & $2\pi$ \\ \hline
$(b)$  & $\tan(\frac{x}{2}+\frac{\pi}{4})$ & $\frac{u^{2}-1}{u^{2}+1}$ & $\frac{2u}{u^{2}+1} $ & $\frac{2du}{1+u^{2}}$ & $\frac{\pi}{2}$ & $2\pi$ \\ \hline
$(c)$ & $\cot(x/2)$ & $\frac{2u}{1+u^{2}}$ & $\frac{u^{2}-1}{1+u^{2}}$ & $\frac{-2du}{1+u^{2}}$ & $0$ & $2\pi$ \\ \hline
$(d)$ & $\tan(x)$ & $\frac{u}{\sqrt{1+u^{2}}}$ & $\frac{1}{\sqrt{1+u^{2}}}$ & $\frac{du}{1+u^{2}}$ & $\frac{\pi}{2}$ & $\pi$ \\ \hline
\end{tabular} \vspace{4mm}

There are of course, other trigonometric substitutions, used by \small{REDUCE}, \normalsize such as $\sin$ and $\cos$, but since these are never singular, they cannot lead to problems with discontinuities. \\
Given an integrable function $f(\sin x,\cos x)$ whose indefinite integral is required, select one of the substitutions listed in the table. The choice is based on the following heuristics: choice (a) is used for integrands not containing $\sin x$, choice (b) for integrands not containing $\cos x$; (c) is useful in cases when (a) gives an integral that cannot be evaluated by \small{REDUCE},\normalsize and (d) is good for conditions described in Gradshteyn and Ryzhik (1979, sect 2.50). The integral is then transformed using the entries in the table,; for example, with choice (c), we have:
\[ \int f(\sin x,\cos x)\, dx = \int f(\frac{2u}{1+u^{2}},\frac{u^{2}-1}{1+u^{2}})\,\frac{-2 du}{1+u^{2}} . \]

The integral in $u$ is now evaluated using the standard routines of the system, then $u$ is substituted for. Call the result $\hat{g}(x)$. Next we calculate
 \[ K=\lim_{x \rightarrow b^{-}} \hat{g}(x) - \lim_{x \rightarrow b^{+}} \hat{g}(x), \]
where the point $b$ is given in the table. the corrected integral is then
\[ g(x)=\int f(\sin x,\cos x)\,dx = \hat{g}(x)+K\lfloor \frac{x-b}{p} \rfloor, \]
where the period $p$ is taken from the table, and $\lfloor x \rfloor$ is the floor function.
\pagebreak
\section{REDUCE implementation}
The name of the function used in \small{REDUCE} \normalsize to implement these ideas is trigint, which has the following syntax:
\begin{center}  \bf{trigint(exp,var)}, \end{center}
where exp is the expression to be integrated, and var is the variable of integration.  \\
If trigint is used to calculate the integrals of trigonometric functions for which no substitution is necessary, then non standard results may occur. For example, if we calculate
  \begin{center} \bf{trigint(cos(x),x)}, \end{center}
we obtain \\
\[ \frac{2\tan\frac{x}{2}}{\tan\frac{x}{2}^{2}+1} \]
which, by using simple trigonometric identities, simplifies to: \\
\[  \frac{2\tan\frac{x}{2}}{\tan\frac{x}{2}^{2}+1} \rightarrow \frac{2\tan\frac{x}{2}}{\sec^{2}\frac{x}{2}} \rightarrow 2\sin\frac{x}{2}\cos\frac{x}{2} \rightarrow \sin 2\frac{x}{2} \rightarrow \sin x, \]
which is the answer we would normally expect. In the absence of a normal form for trigonometric functions though, both answers are equally valid, although most would prefer the simpler answer $\sin x.$ Thus, some interesting trigonometric identities could be derived from the program if one so wished.
\subsection{Examples}
Using our example in (1), we compute the corrected result, and show a few other examples as well:
\begin{verbatim}

REDUCE Development Version,  4-Nov-96 ...

1: trigint(3/(5-4*cos(x)),x);

               x              - pi + x
2*(atan(3*tan(---)) + floor(-----------)*pi)
               2               2*pi

\end{verbatim}
\pagebreak
\begin{verbatim}
2: trigint(3/(5+4*sin(x)),x);

                                         2
               pi + 2*x              - pi  + 2*pi*x
2*(atan(3*tan(----------)) + floor(-----------------)*pi
                  4                        4

              - pi + 2*x
    + floor(-------------)*pi)
                4*pi

3: trigint(15/(cos(x)*(5-4*cos(x))),x);

              x                - pi + x                   x
8*atan(3*tan(---)) + 8*floor(-----------)*pi - 3*log(tan(---) - 1)
              2                 2*pi                      2

              x
 + 3*log(tan(---) + 1)
              2

\end{verbatim}
\section{Definite Integration}
The corrected expressions can now be used to calculate some definite integrals, provided the region of integration lies between adjacent singularities. For example, using our earlier function, we can use the corrected primitive to calculate
     \begin{equation} \int_{0}^{4\pi} \frac{1}{2+\cos x}\,dx \end{equation}
trigint returns the answer below to give an indefinite integral, $F(x)$:
\begin{verbatim}

                       x
                  tan(---)
                       2               - pi + x
 2*sqrt(3)*(atan(----------) + floor(-----------)*pi)
                  sqrt(3)               2*pi
------------------------------------------------------                   (*)
                          3

\end{verbatim}
And now, we can apply the Fundamental Theorem of Calculus to give
 \begin{equation} \int_{0}^{4\pi} \frac{1}{2+\cos x}\,dx = F(4\pi)-F(0) \end{equation}
\begin{verbatim}

sub(x=4*pi,F)-sub(x=0,F);

   4*sqrt(3)*pi
-----------------
        3

\end{verbatim}
and this is the correct value of the definite integral.
Note that although the expression in (*) is continuous, the functions value at the points $x=\pi,3\pi$ etc. must be intepreted as a limit, and these values cannot substituted directly into the formula given in (*). Hence care should be taken to ensure that the definite integral is well defined, and that singularities are dealt with appropriately. For more details of this in \small{REDUCE},\normalsize please see the documentation for the $cwi$ addition to the $defint$ package.

\section{Tracing the $trigint$ function}

The package includes a facility to trace in some detail the inner workings of the $ratint$ program. Messages are given at key points of the algorithm, together with the results obtained. These messages are displayed whenever the switch $tracetrig$ is on, which is done in \small{REDUCE} \normalsize with the following command:
\begin{verbatim}
on tracetrig;
\end{verbatim}
This switch is off by default. In particular, the messages inform the user which substitution is being tried, and the result of that substitution. The error message
\begin{verbatim}
cannot integrate after subs
\end{verbatim}
means that \small{REDUCE} \normalsize has tried all four of the Weierstra\ss \hspace{1 mm} substitutions, and the system's standard integrator is unable to integrate after the substitution has been completed.

\section{Bugs, comments, suggestions}
This program was written whilst the author was a placement student at ZIB Berlin. Please refer all suggestions, comments or bugs therefore to Winfried Neun, Symbolik, ZIB, Takustrasse 7, D- 14195 Berlin Dahlem, Germany (e-mail neun@zib.de).

\begin{thebibliography}{99999}

\bibitem[Jeff]{Jeff} Jeffery, D.J. and Rich, A.D.
{\it The Evaluation of Trigonometric Integrals avoiding Spurious Discontinuities
}, ACM Trans. Math Software 20, 1, 1994, pages 124--135, DOI: 10.1145/174603.174409.

\end{thebibliography}
\end{document}


\documentclass[a4paper,12pt]{article}
\usepackage{graphicx}
\usepackage{amsmath,amssymb}             % AMS Math
\usepackage[T1]{fontenc}
%\usepackage[french]{babel}
\usepackage[utf8]{inputenc}
\usepackage{tablefootnote}
\usepackage{a4wide}
\usepackage{enumitem}
\usepackage[font=small,skip=0pt]{caption}
\usepackage{verbatim}
\begin{document}

\centerline
{\bf NLTE implementation in Turbospectrum - Bertrand Plez - 06/01-2020}
\centerline {Revised 07/04-2020}
\bigskip

\section{Equations}
\noindent
From Rutten 2003 (Eq. 2.105) the NLTE line source function is:
\begin{equation}
S_\lambda = \frac{j_\lambda}{\alpha_\lambda} =
\frac{2 h c^2}{\lambda^5} \frac{\psi/\varphi}{\frac{b_l}{b_u}e^{h\nu/kT}-\chi/\varphi}
\end{equation}
and with complete redistribution ($\chi=\varphi=\psi$),
\begin{equation}
 S_\lambda = \frac{2 h c^2}{\lambda^5} \frac{1}{\frac{b_l}{b_u}e^{h\nu/kT}-1} = B_\lambda \frac{e^{h\nu/kT}-1}{\frac{b_l}{b_u}e^{h\nu/kT}-1}
\end{equation}
The bound-bound extinction is then (complete redistribution):
\begin{equation}
\boxed{\alpha_\lambda = \alpha_\lambda^* b_l \frac{1-\frac{b_u}{b_l}e^{-h\nu/kT}}{1-e^{-h\nu/kT}}}\label{eq-bb}
\end{equation}
From which the emissivity:
\begin{equation}
j_\lambda = \alpha_\lambda S_\lambda = \alpha_\lambda^* b_l \frac{1-\frac{b_u}{b_l}e^{-h\nu/kT}}{1-e^{-h\nu/kT}}
B_\lambda \frac{e^{h\nu/kT}-1}{\frac{b_l}{b_u}e^{h\nu/kT}-1}
\end{equation}
\begin{equation}
j_\lambda = \alpha_\lambda^* b_l B_\lambda \frac{1 - \frac{b_u}{b_l} e^{-h\nu/kT}}{\frac{b_l}{b_u} - e^{-h\nu/kT}}
\end{equation}
and finally:
\begin{equation}
\boxed{j_\lambda = \alpha_\lambda^* b_u B_\lambda }\label{eq-jbb}
\end{equation}
The total source function at a given wavelength, if more than one line contributes is:

\begin{equation}
\boxed{S_\lambda=\frac{\sum{j_\lambda}}{\sum{\alpha_\lambda}}}\label{eq-Sbb}
\end{equation}
Similarly for the continuum:
\begin{equation}
\boxed{ \alpha_\lambda^{bf} = \alpha_\lambda^{bf*} b_i \frac{1-\frac{b_c}{b_i}e^{-h\nu/kT}}{1-e^{-h\nu/kT}} } \label{eq-bf}
\end{equation}
\begin{equation}
\boxed{j_\lambda^{bf} = \alpha_\lambda^{bf*} b_c B_\lambda }\label{eq-jbf}
\end{equation}
and
\begin{equation}
\boxed{ \alpha_\lambda^{ff} = \alpha_\lambda^{ff*} b_c} \label{eq-ff}
\end{equation}
\begin{equation}
\boxed{j_\lambda^{ff} = \alpha_\lambda^{ff*} b_c B_\lambda }\label{eq-jff}
\end{equation}
\begin{equation}
S_\lambda^{ff}=B_\lambda
\end{equation}

\section{Philosophy of the implementation in Turbospectrum}
In TS  the implementation can be done as follows:
\begin{itemize}
\item The identification of the upper and lower level is read from the line list, using two more variables at the end of the statement (eqwidt.f version, as bsyn.f does not have the obseqw and eqwerror):

 >> read(lunit,*) xlb,chie,gfelog,fdamp,gu,raddmp,levlo,levup,obseqw,eqwerror

These identifications are those of the model atom.

\item The departure coefficients are read from the MULTI output file with identical level id:s.
\item The absorption coefficient is corrected in bsyn.f (and eqwidt.f, if we plan to use it). Variable is called plez(). See loop: do 111 ...continue.
\item The extinction coefficient is incremented: abso() only. The scattering part absos() is kept to zero.
Warning: abso() is normalized by the standard opacity, and is in cm$^2$/gram of stellar matter. It should either be transformed to $\alpha$ (cm$^{-1}$), or the emissivity should be given in cm$^2$/gram as well.
\item A new array is created and incremented: emissivity().
\item  After all lines have been scanned, and their contribution added in abso() and emissivity(), bsynb.f is called.
\item In bsynb.f the continuum absocont() and absoscont() are computed, as well as the Planck function,
then traneq.f is called to solve the transport equation for the continuum. SOME THINKING NEEDED HERE.
Do we want to do it this way? How do we add the continuum contribution for the NLTE species?
\item Then same thing is done including lines. In MULTI, the continuum scattering part of the source function is treated properly. We should keep it this way in TS, i.e. keep $\sigma_{cont}$ and $\kappa_{cont}$ separate. The source function can then
be iterated as usual in TS. CHECK that this gives the same result as MULTI. The source function for the lines
needs to be changed from bplan() to emissivity/alpha, i.e. emissivity/abso()*ross().
\end{itemize}

\noindent The implementation must keep compatibility with the older line list format, and with LTE calculations. For
this to work a flag NLTE = .true./.false. is implemented (all departure coefficients set to one).\\

\noindent One uncertain issue is the treatment of bf and ff transitions for NLTE species. We do not implement it for the
moment.

\section{Actual implementation}
\subsection{babsma}
Nothing was changed in the babsma.f part (computation of the continuum opacities). This can be changed later if we decide
to implement NLTE corrections for some of the continuous opacities (photoionisation, or hydrogen opacities).

\subsection{bsyn}
In bsyn.f, a new switch is implemented (NLTE = .false. or .true.), implemented in the run-script by, e.g.\footnote{This is
different from the PURE-LTE logical switch which, if set
in both babsma and bsyn, includes all scattering into the absorption coefficient, resulting in a pure planckian source function.}
:
\begin{verbatim}'NLTE :'          '.false.'\end{verbatim}.
If set to .true. this switch results in a special treatment of the line list, the calculation of the line opacity, and the source function. By default it is set to .false., ensuring back compatibility with previous LTE versions.

\subsubsection{line list}
In order for the NLTE information to be read from the line list, a keyword must be included in the free comment line
that is included after the line providing the element, ionisation stage and number of lines in the line list. This comment
just needs to include somewhere the word NLTE.
Then each line is read according to:
\begin{verbatim}
            read(lunit,*) xlb,chie,gfelog,fdamp,gu,raddmp,levlo,levup,
     &                    comment_line,
     &                    ilevlo,ilevup,idlevlo,idlevup
\end{verbatim}
With the last 4 items (2 integers and 2 character*20) being the lower and upper level number, and identifications.
Only the number is used in the following.

\subsubsection{departure coefficients}
If the species is treated in NLTE, the model atom is read, and departure coefficients
are set for all levels (new routines read\_modelatom.f and read\_departure.f). if a species is to be treated in LTE,
the departure coefficients are all set to 1.0.

\subsubsection{line absorption and source function}
For all lines of LTE and NLTE species the absorption coefficient is calculated as in Eq.\,\ref{eq-bb}, and the emissivity
 as in Eq.\,\ref{eq-jbb}. This is done at each wavelength, where the absorption for all
contributing lines is added to the continuum absorption. The same is done for the emissivity.
For the continuum contributions, Eq.\,\ref{eq-bf}, \ref{eq-jbf}, \ref{eq-ff}, and \ref{eq-jff} are used,
with all departure coefficients set to 1.
When all contributions have been added, the source function is calculated using Eq.\,\ref{eq-Sbb}.

\subsection{Solving the radiative transfer equation}
In the subroutine bsynb.f, the continuum radiative transfer problem is solved as usual using the Feautrier method,
and iterating on the starting Planck source function to converge to the final $S = \frac{\kappa B + \sigma J}{\kappa + \sigma}$
at all wavelengths. Then the line + continuum radiative transfer is solved using the NLTE source function.

In case there is a velocity field, the outgoing intensities and flux are then calculated using the same source
function, by a simple integration of S.exp(-tau). This is not strictly correct, as the source
function and the opacities should be Doppler-shifted. {\bf There is no iteration on the source function in that case}.

For the total (line + continuum) opacity, the scheme is similar, except that the absorption coefficient is Doppler-shifted.
{\bf There is no
Doppler-shift implemented so far for the scattering continuum opacities, and the source function is not iterated}.

\section{Tests}
\subsection{Radiative transfer solver, and direct quadrature of source function (used in case of velocity fields)}
This solver (routine Iplus\_calc.f) computes the integral ${\int_0^{\tau_{\rm max}}s(t) exp(-t) dt}$ on the tau scale for each
ray. For optically thick rays it uses the diffusion approximation for the deepest point:
$i^+(\tau_{\rm max}) = S(\tau_{\rm max})+\frac{dS}{d\tau}(\tau_{\rm max})$.
For optically thin rays it uses an approximation of the intensity generated in the layer above $\tau_{\rm min}$:
$i^+ = S(\tau_{\rm min}) * (1-exp(-\tau_{\rm min}))$.

This routine gives slightly different results from the ordinary Feautrier routine (traneq.f). It was therefore tested against
an analytic solution, for a source function of the form $S(tau)=\sum_0^{n_{max}}{a_i \tau^i}$, with $a_i = 1$, as well as against various degree 4 polynomials for the source function, including non-monotonous.
This was tested  for different quadratures (n=1 is the shallowest depth point):
\begin{enumerate}
\item propagation of the intensity from the deepest point out to the surface, using the analytic expression for the integral,
and an average of the source function in the interval:
$$i^+_n=I^+_{n+1} e^{-(\tau_{n+1}-\tau_{n})} + 0.5 (S_{n}+S_{n+1}) e^{-(\tau_{n+1}-\tau_{n})}$$\label{prop}
\item propagation of the intensity, using the trapezoidal rule for the integration within each interval, i.e. approximating $Se^{-\tau}$ by an affine function within each $\tau$ interval:
$$i^+_n=i^+_{n+1} e^{-(\tau_{n+1}-\tau_{n})}+ (S_{n+1} e^{-(\tau_{n+1}-\tau_{n})} + S_n) (\tau_{n+1}+\tau_n)/2.$$\label{proptrap}
\item trapezoidal rule for the whole integral:
$$i^+(1)=\sum_1^{n_{max}}{(S_{n}e^{-\tau_n}+S_{n+1}e^{-\tau_{n+1}})(\tau_{n+1}-\tau_{n})/2}$$\label{trap}
\end{enumerate}
Rectangle rule for the whole integral gave larger errors.
With a sampling of 0.1 in $\tau$, and a range between $10^{-6}$ and $100$, method \ref{proptrap} gave better than 1\% results, with method \ref{trap} always close. Increasing the sampling to 0.2 and 0.3 increases the error to
3.5 and 8\% respectively.
Method \ref{prop} shows errors in excess of 1\% in all cases, increasing above 10 or even 100\% with the lowest sampling.
We adopt method \ref{proptrap}.
Note that the Feautrier plane-parallel and spherical formal solvers do not always agree. Their performances degrade
when the optical depth sampling is coarser. The PP version does not work in the optically thin case.
The spherical version and our adopted method agree within less than a percent most of the time, and occasionally differ a
little more.

\subsection{Test of the NLTE implementation in the static case}

\subsubsection{NLTE case with departure coefficients set to 1}

Using departure coefficients of unity recovers the Planck function for the line source function, and a spectrum identical
to the LTE case within rounding errors.

\subsubsection{Test with a model atom}

The use of a MULTI output for a Ca model atom (106 levels) in a MARCS solar model atmosphere, leads  to
NLTE and LTE line profiles that are identical to the MULTI calculation. The continuum levels are identical as well (MULTI
gives $F_\nu$, while TS calculates $F_\lambda$).

Need to check for a case with strong scattering in the continuum, e.g. Ca\,II H and K lines in a metal-poor star.

\subsection{non-zero velocity NLTE case}
\end{document}


    \filetitle{isstationary}{True if all eigenvalues are within unit circle}{VAR/isstationary}

	\paragraph{Syntax}\label{syntax}

\begin{verbatim}
Flag = isstationary(V)
\end{verbatim}

\paragraph{Input arguments}\label{input-arguments}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{V} {[} VAR {]} - VAR object whose eigenvalues will be tested
  for stationarity.
\end{itemize}

\paragraph{Output arguments}\label{output-arguments}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{Flag} {[} \texttt{true} \textbar{} \texttt{false} {]} - True
  if all eigenvalues are within unit circle.
\end{itemize}

\paragraph{Options}\label{options}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{'tolerance='} {[} numeric \textbar{}
  \emph{\texttt{getrealsmall()}} {]} - Tolerance for the eigenvalue
  test.
\end{itemize}


\documentclass[•]{article}
\usepackage{blindtext}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\usepackage{amsmath}

\begin{document}
\title{Perception and localization}
\author{Matteo Baiguera}
\maketitle

\date{\today}

\section{Introduction}
Perception: detect the object, classify the object, estimate the object's trajectory.\\
The assumed sensor-suite is the following
\begin{center}
\begin{tabular}{c|c|c|}
\hline
				   & Sensor(s)& computing platform\\
\hline
\textbf{Perception}& LiDAR, Camera&\\
\hline
					& Ultrasonic&\\
\hline
					& Event camera&\\
\hline
\hline
\textbf{Navigation}& IMU,GPS&\\
\hline
\end{tabular}
\end{center}

%Therefore sensors are splitted into two main classes
%\begin{itemize}
%\item{\textbf{•}}
%\item{\textbf{•}}
%\end{itemize}

\section{Extended Kalman Filter}

The purpose of extended kalman filter in AD problem is to track objects.\\

The assumed dynamic for all object is the following:
\begin{align*}
\vec{x}_{k+1} &= A_k \vec{x}_k + B_k \vec{u}_k  \\
\vec{x}_{k} &= C_k \vec{z}_k
\end{align*}

For each tracked object is assumed a state ($\vec{x} $) and an observation ($\vec{z} $).\\
\begin{align*}
\vec{x}_{k+1} &= A_k \vec{x}_k + B_k \vec{u}_k  \\
\vec{x}_{k} &= C_k \vec{z}_k
\end{align*}

The object state is defined as:
\begin{align}
    \vec{x} &= \begin{bmatrix}
           	    x  \\
           		y \\
               v_x \\
          	   v_y\\
         \end{bmatrix}
\end{align}

and

The object's motions is assumed to be a \textsl{"random walker"} process, such that:
\begin{align}
   A_k &= \begin{pmatrix}
           	    1 & 0    & \Delta t & 0  \\
           		0 & 1    & 0        & \Delta t \\
                0 & 0    &        1 & 0 \\
          	    0 & 0    & 0       & 1 \\
         \end{pmatrix}
\end{align}
\begin{algorithm}[H]
\caption{Put your caption here}
\begin{algorithmic}[1]

    \For {$o_j \in {o1,o2,...oN}$} \Comment{track all objects}
%    \If{$condition = True$}
%        \State Do this
%        \If{$Condition \geq 1$}
%        \State Do that
%        \ElsIf{$Condition \neq 5$}
%        \State Do another
%        \State Do that as well
%        \Else
%        \State Do otherwise
%        \EndIf
%    \EndIf
 	\State Initialization: $ $
	\State Update Step: $ $
	\State Predict Step: $ $
    \EndFor
    \While{$something \not= 0$}  \Comment{put some comments here}
        \State $var1 \leftarrow var2$  \Comment{another comment}
        \State $var3 \leftarrow var4$
    \EndWhile  \label{roy's loop}
\end{algorithmic}
\end{algorithm}

\section{Particle Filter}
Vehicle ego-localization via particle filter

\end{document}


% This LaTeX was auto-generated from an M-file by MATLAB.
% To make changes, update the M-file and republish this document.

\subsection*{lossT.m}

\begin{par}
\textbf{Summary:} Test derivatives of cost functions. It is assumed that the cost function computes (at least) the mean and the variance of the cost for a Gaussian distributed input $x\sim\mathcal N(m,s)$
\end{par} \vspace{1em}
\begin{verbatim}function [dd dy dh] = lossT(deriv, policy, m, s, delta)\end{verbatim}
\begin{par}
\textbf{Input arguments:}
\end{par} \vspace{1em}
\begin{verbatim}deriv    desired derivative. options:
      (i)   'dMdm' - derivative of the mean of the predicted cost
             wrt the mean of the input distribution
      (ii)  'dMds' - derivative of the mean of the predicted cost
             wrt the variance of the input distribution
      (iii) 'dSdm' - derivative of the variance of the predicted cost
             wrt the mean of the input distribution
      (iv)  'dSds' - derivative of the variance of the predicted cost
             wrt the variance of the input distribution
      (v)   'dCdm' - derivative of inv(s)*(covariance of the input and the
             predicted cost) wrt the mean of the input distribution
      (vi)  'dCds' - derivative of inv(s)*(covariance of the input and the
             predicted cost) wrt the variance of the input distribution
cost     cost structure
  .fcn   function handle to cost
  .\ensuremath{<}\ensuremath{>}    other fields that are passed on to the cost
m        mean of the input distribution
s        covariance of the input distribution
delta    (optional) finite difference parameter. Default: 1e-4\end{verbatim}
\begin{par}
\textbf{Output arguments:}
\end{par} \vspace{1em}
\begin{verbatim}dd         relative error of analytical vs. finite difference gradient
dy         analytical gradient
dh         finite difference gradient\end{verbatim}
\begin{par}
Copyright (C) 2008-2013 by Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen.
\end{par} \vspace{1em}
\begin{par}
Last modified: 2013-05-30
\end{par} \vspace{1em}

\begin{lstlisting}
function [d dy dh] = lossT(deriv, cost, m, S, delta)
\end{lstlisting}

\subsection*{Code}

\begin{lstlisting}
% create a default test if no input arguments are given
if nargin == 0;
  D = 4;
  m = randn(4,1);
  S = randn(4); S = S*S';
  cost.z = randn(4,1);
  W = randn(4); W = W*W';
  cost.W = W;
  cost.fcn = @lossQuad;
  deriv = 'dLdm';
end
D = length(m); if nargout < 5; delta = 1e-4; end

% check derivatives
switch deriv
  case {'dLdm', 'dMdm'}
    [d dy dh] = checkgrad(@losstest01, m, delta, cost, S);

  case {'dLds', 'dMds'}
    [d dy dh] = checkgrad(@losstest02, S(tril(ones(D))==1), delta, cost, m);

  case 'dSdm'
    [d dy dh] = checkgrad(@losstest03, m, delta, cost, S);

  case 'dSds'
    [d dy dh] = checkgrad(@losstest04, S(tril(ones(D))==1), delta, cost, m);

  case {'dCdm', 'dVdm'}
    [d dy dh] = checkgrad(@losstest05, m, delta, cost, S);

  case {'dCds', 'dVds'}
    [d dy dh] = checkgrad(@losstest06, S(tril(ones(D))==1), delta, cost, m);
end
\end{lstlisting}

\begin{lstlisting}
function [f, df] = losstest01(m, cost, S)                   % dLdm

[L dLdm] = cost.fcn(cost, m, S);

f = L; df = dLdm;

function [f, df] = losstest02(s, cost, m)                   % dLds

d = length(m);
ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss));

[L dLdm dLds] = cost.fcn(cost, m, ss);

f = L; df = dLds; df = 2*df-diag(diag(df)); df = df(tril(ones(d))==1);

function [f, df] = losstest03(m, cost, S)                   % dSdm

[L dLdm dLds S dSdm] = cost.fcn(cost, m, S);

f = S; df = dSdm;

function [f, df] = losstest04(s, cost, m)                   % dSds

d = length(m);
ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss));

[L dLdm dLds S dSdm dSds] = cost.fcn(cost, m, ss);

f = S; df = dSds; df = 2*df-diag(diag(df)); df = df(tril(ones(d))==1);

function [f, df] = losstest05(m, cost, S)                   % dCdm

[L dLdm dLds S dSdm dSds C dCdm] = cost.fcn(cost, m, S);

f = C; df = dCdm;

function [f, df] = losstest06(s, cost, m)                   % dCds

d = length(m);
ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss));

[L dLdm dLds S dSdm dSds C dCdm dCds] = cost.fcn(cost, m, ss);

f = C;
dCds = reshape(dCds,d,d,d); df = zeros(d,d*(d+1)/2);
for i=1:d;
  dCdsi = squeeze(dCds(i,:,:)); dCdsi = dCdsi+dCdsi'-diag(diag(dCdsi));
  df(i,:) = dCdsi(tril(ones(d))==1);
end;
\end{lstlisting}


  % -*- root: 00-main.tex -*-
\section{Results}
\label{sec:regseg-results}

\subsection{Verification and validation using digital phantoms}
\label{sec:regseg-results_phantom}

The results summarized in \autoref{fig:regseg-phantom} demonstrated that the accuracy was
  high and below the image resolution.
Panel B on \autoref{fig:regseg-phantom} shows the violin plots for each model type corresponding
  to the two sets of resolutions for the generated phantoms.
In order to relate the average misregistration error to the resolution of the moving image,
  we proceeded as follows.
First, we confirmed that the vertex-wise error distributions were skewed by using Shapiro-Wilk's test of
  normality.
All of the distributions of errors in the tests (four phantom types $\times$ two resolutions) were
  nonnormal with $p<$ 0.001.
Consequently, we used the nonparametric Wilcoxon signed-rank test with the Bonferroni
  correction for multiple comparisons ($N$=150, for each phantom type).
The average errors were significantly lower than the voxel size with $p <$ (0.001 / 150)
  in all tests (four phantom types $\times$ two resolutions).
Statistical tests might not be sufficiently conclusive, so we also computed the confidence intervals,
  as shown in \autoref{tab:ci_phantom}.

\begin{figure*}[!h]
  \centering
  \includestandalone[width=\linewidth]{figure05}
  \caption{A. Visual assessment of the results obtained on the digital phantoms.
    The panel shows three coronal slices (indices indicated on the lower left corner) of each phantom
    volume at low resolution:
    ``gyrus'' (top left), ``L'' (top right), ``ball'' (bottom left),
    and ``box'' at (bottom right).
  The contours recovered after registration are represented in yellow.
  \Regseg{} achieved high accuracy because it determined the almost exact locations of the registered
    contours with respect to their ground truth positions (shown in green).
  The partial volume effect makes segmentation of the sulci a challenging problem with voxel-wise
    clustering methods, but they were successfully segmented with \regseg{}.
  B. Quantitative evaluation: the violin plot shows the variability across experiments
    of the average Hausdorff distance measured in each vertex of the corresponding surface, for the
    low (left) and high (right) resolutions.
    Error averages were consistently below the size of the voxel.
    }\label{fig:regseg-phantom}
\end{figure*}
\begin{figure*}[!h]
  \centering
  \includestandalone[width=\linewidth]{figure06}
  \caption{A. Example of a visual assessment report, which was automatically generated by the evaluation tool.
    Each view shows one component of the input image (in this case, the \gls*{fa} map), the ground-truth locations
    of the surfaces (green contours), and the resulting surfaces obtained with the test method (yellow contours).
  The first two rows show axial slices for \regseg{} and the \acrfull*{t2b} method, while the last two rows
    show the corresponding sagittal views.
  The coronal view is omitted because it was the least informative due to the directional property
    of the distortions.
  Specific regions where \regseg{} outperformed \gls*{t2b} are enlarged.
  B. Violin plots of the error distributions for each surface across the 16 subjects, which show the
    voxel size of the \gls*{dmri} images (1.25 mm), thereby supporting the improved results obtained
    by \regseg{} with the proposed settings.
  }\label{fig:regseg-results_real}
\end{figure*}

\subsection{Evaluation using real datasets and cross-comparison}\label{sec:regseg-results_hcp}
Finally, we compared the performance of \regseg{} with that of the standard \gls*{t2b}
  method.
Summary reports for visual assessment of the 16 cases are included in the
  \citetalias[section S5]{esteban_useful_2016}.
In \autoref{fig:regseg-results_real}, box A, the visual report is shown for one subject.
We computed the \gls*{swindex} \eqref{eq:regseg-swindex} of every surface after registration
  using both the \regseg{} and \gls*{t2b} methods.
Finally, to compare the results, we performed Kruskal-Wallis H-tests
  (a nonparametric alternative to ANOVA) on the warping indices for the three surfaces of
  interest selected in \autoref{sec:regseg-experiments_evaluation}
  ($\Gamma_\text{VdGM}$, $\Gamma_\text{WM}$, $\Gamma_\text{pial}$).
All of the statistical tests showed that the error distributions obtained with \regseg{} and
  \gls*{t2b} were significantly different, and the violin plots in box B of
  \autoref{fig:regseg-results_real} demonstrate that the errors were always larger with \gls*{t2b}.
We also show the 95\% CIs of the \gls*{swindex} for these surfaces
  (\autoref{tab:results_real}).
The aggregate CI for \regseg{} was 0.56--0.66 [mm], whereas the \gls*{t2b} method
  yielded an aggregate CI of 2.05--2.39 [mm].
The results of the statistical tests and the CIs are summarized in \autoref{tab:results_real}.

\begin{table}
\centering
\footnotesize
\tabcolsep=0.1cm
\begin{minipage}{.48\textwidth}
    \vskip-4.7ex
    \begin{tabular}{lccccc}
    Res.   & ``gyrus'' & ``ball''  & ``box''   & ``L''     & Aggreg.    \\\hline
    1.0mm  & 0.18--0.38 & 0.31--0.45 & 0.34--0.42 & 0.34--0.40 & 0.34--0.38  \\
    2.0mm  & 0.59--0.60 & 0.65--0.76 & 0.68--0.71 & 0.67--0.77 & 0.64--0.66  \\
    \hline
    \end{tabular}
    \caption{The distributions of vertex-wise Hausdorff distances between the ground-truth surfaces and their
    corresponding estimates obtained with \regseg{} presented a 95\% CI below the half-voxel size for all of
    the phantom types.
    The CIs were computed by bootstrapping using 10$^\text{4}$ samples, with the median as the location statistic.}\label{tab:ci_phantom}
\end{minipage}
\hfill
\begin{minipage}{.48\textwidth}
    \begin{tabular}{cccccc}
    & & $\Gamma_\text{VdGM}$  & $\Gamma_\text{WM}$ & $\Gamma_\text{pial}$ & Aggreg. \\
    \hline
    \multirow{2}{*}{CI}
       & \regseg{} & 0.50--0.78 & 0.50--0.55 & 0.66--0.73 & 0.56--0.66 \\
       & T2B       & 1.78--2.58 & 1.94--2.36 & 2.16--2.58 & 2.05--2.39 \\
    \hline
    \multirow{2}{*}{H-tests}
       & p-value  & 4.1\e{-6} & 2.3\e{-6} & 2.3\e{-6} & 1.8\e{-16} \\
       & H-stat   & 21.20 & 22.31 & 22.31 & 67.85 \\
    \hline
    \end{tabular}
    \caption{Statistical analysis of results obtained using 16 real datasets from
    the \gls*{hcp}, which show that \regseg{} performed better than the alternative \acrfull{t2b} method.
    The distribution of the errors computed for the surfaces of interest ($\Gamma_\text{VdGM}$, $\Gamma_\text{WM}$, $\Gamma_\text{pial}$)
      and the aggregate of all surfaces (Aggreg. column) had lower 95\% CIs with \regseg{}.
   The CIs in this table were computed by bootstrapping using the mean as the location statistic and with 10$^\text{4}$ samples.
    The Kruskal-Wallis H-tests indicated that there was a significant difference between the results obtained using \regseg{} and
      the \gls*{t2b} method.
    }\label{tab:results_real}
\end{minipage}
\end{table}


\paragraph{Influence of Sakoe-Chiba Band Size} \label{influence_of_sakoe-chiba_band_size}
The positive influence of the Sakoe-Chiba band size for the performance of a simulation in the experiment is verified by
table \ref{tab:result}. The most dominating configurations are using a band size with 36\% of the input time series.
It appears not to be effective to compare all different tested band sizes on a huge subset as done above. Therefore, the
influence of the Sakoe-Chiba band size will be demonstrated by changing the band size on the best performing simulation
without a filter. This configuration can be found in row two of table \ref{tab:result}. Figure
\ref{fig:sakoe-chiba_band_result} illustrates the influence of the Sakoe-Chiba band size on the $F_{1}score_{\mu}$ for
the best performing simulation without filter. There is a maximum at 36\% band size.

\begin{figure}[H]
    \begin{center}
        \resizebox {\textwidth} {!} {
            \begin{tabular}{cc}
                \resizebox {!} {\height} {
                    \begin{tikzpicture}
                        \begin{axis}[
                            xmin=0,
                            ymin=0.65,
                            xmax=80,
                            xlabel=band size in \% depending on input time series,
                            ylabel=$F_{1}score_{\mu}$,
                            width=\axisdefaultwidth,
                            height=0.7*\axisdefaultheight]
                            \addplot[blue, ultra thick] table {../data/fig/sakoe-chiba_band_result/scb.dat};
                        \end{axis}
                    \end{tikzpicture}
                } &
                \resizebox {!} {\height} {
                    \begin{tikzpicture}
                        \begin{axis}[
                            xmin=0,
                            xmax=200,
                            ymin=0,
                            ymax=1,
                            xlabel=band size in \% depending on input time series,
                            ylabel=$F_{1}score_{\mu}$,
                            width=\axisdefaultwidth,
                            height=0.7*\axisdefaultheight]
                            \addplot[blue, ultra thick] table {../data/fig/sakoe-chiba_band_result/scb.dat};
                        \end{axis}
                    \end{tikzpicture}
                }
            \end{tabular}
        }
    \end{center}
    \caption{The $F_{1}score_{\mu}$ depending on the size of the Sakoe-Chiba band. The left plot is a zoomed and scaled
    version of the right plot.}
    \label{fig:sakoe-chiba_band_result}
\end{figure}


%General Suggestion: Ideally, the documentation of a style checker should
%be around one page.
\section{[No Reference] Computational Functions}

This analysis computes the amount of floating point, integer, floating point pointer and
integer pointer operations within each function. If the value is larger than
specified, than a warning is triggered. The analysis helps to identify functions
with high computatuional value.

\subsection{Non-Compliant Code Examples}
\begin{verbatim}
void fail() {
  int x=4;
  int y=x+5+7;
  int *z = &x;
  y = *z+*z+6+8+9;
}
\end{verbatim}

\subsection{Compliant Solution}
\begin{verbatim}
void pass() {
  int x= 4;
  int y = x+5+7;
}
\end{verbatim}

\subsection{Parameter Requirements}

computationalFunctions.maxIntOps defines the maximum of integer operations permitted.
computationalFunctions.maxFloatOps defines the maximum of floating point operations permitted.

\subsection{Implementation}

%Details of the implementation go here.
The implementation checks for the following direct types:
\begin{itemize}
\item SgAddOp
\item SgSubtractOp
\item SgDivideOp
\item SgMultiplyOp
\end{itemize}

The implementation checks for the following indirect types:
\begin{itemize}
\item SgCastExp - operations hidden behind cast
\item SgVarRefExp - variable operations
\item SgPointerDerefExp - pointer operations
\item SgPntrArrRefExp - array operations
\end{itemize}

\subsection{References}


\subsection{Peephole LTSM}


\documentclass[11pt]{article}
\usepackage{amsmath,amssymb}
\usepackage{lmodern}
\usepackage{cite}
\usepackage{listings}

\title{py-dimensional-analysis}
\date{}

\begin{document}
\maketitle

\section{py-dimensional-analysis}
This Python package addresses physical dimensional analysis. In particular, \texttt{py-dimensional-analysis} calculates from a given system of (dimensional) variables those products that yield a desired target dimension.

% \begin{equation}
%     y = A^aB^bC_c
% \end{equation}

The following example illustrates how the variables mass, force, time and pressure must relate to each other in order to produce the dimension length*time.

\begin{lstlisting}[language=Python]
import danalysis as da

si = da.standard_systems.SI         # predefined standard units
s = da.Solver(
    {
        'a' : si.M,                 # [a] is mass
        'b' : si.L*si.M*si.T**-2,   # [b] is force (alt. si.F)
        'c' : si.T,                 # [c] is time
        'd' : si.Pressure           # [d] is pressure
    },
    si.L*si.T                       # target dimension
)
\end{lstlisting}
Which prints
\begin{lstlisting}
Found 2 variable products of variables
{
        a:Q(M),
        b:Q(L*M*T**-2),
        c:Q(T),
        d:Q(L**-1*M*T**-2)
}, each of dimension L*T:
        1: [a*c**-1*d**-1] = L*T
        2: [b**0.5*c*d**-0.5] = L*T
\end{lstlisting}

This library is based on \cite{szirtes2007applied}, and also incorporates ideas and examples from \cite{santiago2019first, sonin2001dimensional}.

\subsection{References}
\bibliographystyle{alpha}
\begingroup
\renewcommand{\section}[2]{}%
\bibliography{biblio.bib}
\endgroup

\end{document}

%pandoc --citeproc -s README.tex -o README.md --to markdown_strict


\documentclass[12pt]{article}
\usepackage[margin=2cm]{geometry}
\usepackage{fancyvrb,amsmath,amssymb,graphicx}
\usepackage{tikz}
\usepackage{xcolor}

\title{Eigenmath Manual}
\date{June 9, 2021}
\author{}

\begin{document}

\maketitle

\tableofcontents

\newpage

\input{nabokov}

\input{syntax}

\subsection{Testing for equality}
The infix operator \verb$==$ is used to test for equality of operands.
The operator evaluates to 1 if the operands are equal and 0 if the operands are not equal.

\begin{Verbatim}[formatcom=\color{blue}]
exp(i pi) == -1
\end{Verbatim}

\noindent
1

\bigskip
\noindent
Note: Equality tests involving floating point numbers
can be problematic due to roundoff error.

\input{arithmetic}

\input{exponents}

\input{symbols}

\input{scripting}

\input{draw}

\input{complex}

\input{linear-algebra}

\subsection{Component arithmetic}

\noindent
Tensor plus scalar adds the scalar to each component of the tensor.

{\color{blue}\begin{verbatim}
(x,y,z) + 10
\end{verbatim}}

\noindent
$\begin{bmatrix}x+10\\y+10\\z+10\end{bmatrix}$

\bigskip
\noindent
The product of two tensors is the Hadamard product.

{\color{blue}\begin{verbatim}
A = ((1,2),(3,4))
B = ((a,b),(c,d))
A B
\end{verbatim}}

\noindent
$\begin{bmatrix}a&2b\\3c&4d\end{bmatrix}$

\bigskip
\noindent
Tensor raised to a power raises each component to the power.

{\color{blue}\begin{verbatim}
(x,y,z)^2
\end{verbatim}}

\noindent
$\begin{bmatrix}x^2\\y^2\\z^2\end{bmatrix}$

\newpage

\input{derivative}

\input{integrals}

\input{integral-trick}

\input{fund-thm-of-calculus}

\input{line-integral}

\input{surface-area}

\input{surface-integral}

\input{greens-theorem}

\input{stokes-theorem}

\newpage

\section{Quantum Computing}

\input{quantum-computing}

\newpage

\input{help}

\newpage

\input{tricks}

\end{document}


\section{Conclusion}
\label{sec:conclusion}

\subsection{Summary}

So far it is unknown whether a domain rank can be predicted using methods of ML, in particular CNNs and GNs. In this work we have defined the novel task of vision-based page rank estimation, where a model has to output the rank of a web domain based on screenshots of its web pages and graph information of the hyperlinks connecting them. Our concrete formulation was a pairwise comparison: In the beginning of our study it was unknown to us whether, and if so to what extent, the task could be solved. We consider our work a feasibility study, seeking to find a potential correlation between domain rank and web page look.

We have created a comprehensive data set and collected data for 87,629 of the top 100,000 most popular global websites, according to Open PageRank. Each sample of the dataset corresponds to one domain, represented by a graph of up to eight web pages, attributed with screenshots in mobile and desktop format. For each hyperlink one edge is added to the graph. The total number of images is around one million. To crawl such a huge amount of web pages within a reasonable amount of time, we have developed a scalable data crawler relying on the Chromium web browser. We support future research in the area of page rank estimation by open-sourcing the data set.

Our best performing model achieves an accuracy of 62.68\% on the pairwise web page ranking task. The significant deviation from the trivial baseline of random guessing (50\%) indicates the existence of a correlation between rank and visual appearance. This is the main finding of our work. The model has super-human performance in that it exceeds the human benchmark by an absolute 4.88 percentage points.

We have achieved the scores by combining CNNs for image feature extraction with GNs for graph data processing. The latter handle the heterogenous, graph-like structure of data set samples gracefully. The combination of CNN and GN has proven to be a powerful way of dealing with feature rich, graph-like data.

\subsection{Future Work}

While carrying out the research and experiments of this project, we have touched several aspects qualifying as topics for future work. They are listed in the following.

Our model did not overfit on the training samples of the dataset. It is therefore likely that it was not able to extract all fine-grained features that correlate with page ranks. The use of \textbf{higher capacity models} might help improve the accuracy on the task even more.

Besides model capacity, the \textbf{model architecture} was not subject of extensive empirical evaluation in this work. We started off by building a variant of the CNN proposed by \cite{beltramelli:pix2code} and altered it only slightly to work well with the resolution of our images. Different architectures might achieve better results on the task.

Due to GPU memory limitations and the implementation of our GN library, we were not able to train end-to-end with a batch size greater than two. \textbf{Increasing the batch size}, however, would lead to better estimations of the true gradient of the overall objective. Instead of training the [woft] + GN configuration, the model could then be trained end-to-end [e2e] which would likely improve the accuracy even more.

Our \textbf{dataset} is a rich resource which could be used for other tasks as well. For instance a GAN \cite{goodfellow2014generative} could be trained to generate realistic websites.

The page rank estimation tasks could be extended such that the model has access to \textbf{information other than screenshots and links}. The GN framework seems particularly appealing for such as an extension because it is naturally capable of dealing with text of variable length or HTML source code as well. The text could be embedded into a vector representation (e.g. using GloVe word embeddings \cite{pennington2014:glove}) and would simply extend the graph nodes by another attribute.

The \textbf{pairwise loss term and the accuracy metric} do not regard the difficulty of a particular pairwise comparison. More sophisticated versions of Equations~\ref{eq:loss} and \ref{eq:acc} could e.g. ignore all samples within a certain range around a given sample. A wrong estimation of the samples \#40,000 and \#40,001 would not be penalized any longer, which seems intuitively reasonable.

Section~\ref{sec:gnlibfuturefeatures} mentions future work related to the \textbf{GraphNets library}.


\chapter{The proposed system}

To be able to locate an object in 3D with no previous knowledge of the object (such
as its size, color and so on), two views of the same object are needed. The
views can be obtained by one moving camera or by multiple cameras. In this
thesis, we take a closer look at the second approach.

We propose a system with two cameras, connected to a computer via USB.
Two cameras provide enough information for object localization and make the
project usable also on low-budget. The placement of the cameras is important,
but no precise alignment is required. The cameras should share a significant part
of the view (see an example of the setup in the Figure \ref{fig:camera-setup}).

\begin{figure}
	\includegraphics[width=\linewidth]{img/camera-positions.jpg}
	\caption{Example of camera setup}
	\label{fig:camera-setup}
\end{figure}

The program will be able to calibrate cameras to get their parameters. This
calibration will be based on showing a specific pattern to both cameras. From
this calibration, we obtain information for both cameras, but also their
distance to each other and the rotation between them.

After this calibration, the user marks the objects in both views of the
cameras. At this point, the tracker will start to estimate an object position
in camera view based on the images. We provide several trackers, so the user
can choose one to work with.

When we obtain information from calibration and the object position from both
images, we will estimate the object position in 3D space by simple linear
triangulation.

Each described step is crucial to get a system, which will be able to
localize a point in 3D space. Each step is discussed separately in the following
chapter.

Now we provide a short insight into used tools and the notations, which are
used to describe our solution to the problem.

\section{Tools}

For the computer vision task, we use an \emph{OpenCV} library. OpenCV is an open
source computer vision library with many algorithms implemented (for example
calibration, triangulation, and so on). We use trackers which are now available
only in the \emph{contribute} version. For more information and examples of usage
visit their webpage\footnote{\url{https://opencv.org/}}.

To provide a comparison of trackers, we also include one tracker from
\emph{Dlib}\footnote{\url{http://dlib.net/}} library. It is also open source
and an interface for Python is provided.  Since this library focus is on
machine learning, it does not contain as many functions for computer vision
as the OpenCV library yet.

\section{Notations}

The following section describes some procedures using mathematical notion. To
avoid ambiguity we provide the overview of the used notation here.

\subsubsection*{Vector}
A word \emph{vector} denotes a column vector in a shape of $n\times1$.

\subsubsection*{Block matrix}
A matrix operation $W = (A|B)$, where $A$ is a matrix $m \times n$ and B is a
matrix $m \times p$, creates matrix $W$, where the first $n$ columns are the entries from
matrix $A$ and the last $p$ columns consist of the columns of matrix $B$.
Example:

\[
A = \begin{pmatrix}
        1 & 2 \\
        3 & 4
\end{pmatrix},
B = \begin{pmatrix}
5 \\
6
\end{pmatrix},
(A|B) = \begin{pmatrix}
        1 & 2 & 5 \\
        3 & 4 & 6
\end{pmatrix}
\]

\subsubsection*{Homogeneous coordinates}

In computer vision, homogeneous coordinates are used frequently instead of
Cartesian coordinates. Cartesian coordinates are the most common coordinate
system.  Homogeneous coordinates have one element added. This element is a
scaling factor. As an example, vector $(2x, 2y, 2z, 2)^T$ represents same point
as $(x, y, z, 1)^T$ in homogeneous coordinates. The same point is equal to $(x,
y, z)^T$ in Cartesian coordinates. Unlike the Cartesian coordinates, a single
point can be represented by infinitely many homogeneous coordinates.

Similarly it works for coordinates in any n-dimensional space. In conversion
from Cartesian to homogeneous coordinates we simply add a new element at the end
equal to one. In the opposite direction, we divide first $n-1$ values by the
$n$th.

In homogeneous coordinates the origin is left out. Homogeneous coordinates provide
us also a way how to represent a point in the infinity by finite coordinates.
These points in the infinity are represented with the scale factor equal to 0.

This coordinates representation is tightly bounded to a projective plane, on
which the mathematical theory behind is based. For us, it is just important to
know how to convert them to Cartesian coordinates and that algorithms for
computer vision often use them.


\section{Data}
\label{sec:data}

The age structure in the economy is not modelled directly, but as a consequence of birth rates and mortality rates. Demographic change is then induced by changing these rates. I apply an add-hoc adjustment that does not primarily aim for a realistic representation of the actual mechanisms governing fertility, migration and mortality, but instead seeks to replicate the qualitative features of population dynamics central to the analyses in \cite{LudwigSchelkleVogel2012} while keeping computation as simple as possible.

As the paper aims at analyzing both stationary equilibria as well as the transition dynamics that accompany the change in age structure in the population, individual mortality rates for all time indices are modelled. Initial mortality rates are taken from the Human Mortality Database (HMD). Mortality prior to entering the model is abstracted from (by implicitly setting conditional year-to-year mortality rates to zero for real ages prior to model entry). Furthermore, the conditional probability to survive beyond maximum model age is set to zero, irrespective of the time index. Changes in the age structure of the economy are then induced by iteratively adjusting mortality rates by age and time index.

The adjustment factors are chosen to reproduce the key features of population dynamics present required for analysis, namely an increase in old-age dependency ratio and stationarity prior and post transition. The latter requires that the changes in mortality rates are "sufficiently far away in time" from initial and final state such that the initial state is not affected (too much) through anticipated future changes in survival prospects and the final state is stationary again (i.e. population dynamics "have settled down"). Finally, to simplify interpretation of the results, fertility rates are set such that population size remains constant over time.

Through basic experimentation, the following adjustment has been found that meets the above requirements reasonably well. For time indices zero to ten, survival rates remain constant. For time indices five to 29, conditional year-to-year mortality rates are reduced every year by 5\%. For time indices 30 to 55, mortality rates remain constant again at their respective time 30 levels. Table \ref{tab:life_expectancy} summarizes the resulting simulated life expectancies at different points in the transition.

\begin{table}[ht]
    \caption{Simulated life expectancy and average HH age}
    \label{tab:life_expectancy}
    \centering
    \begin{tabular}{l c c c}
        \hline \hline
        & at birth & at retirement & average age \\
        \hline
        \csvreader[head to column names]{../../out/tables/life_expectancy.csv}{}
        {\\\csvcoli&\csvcolii&\csvcoliii&\csvcoliv}
        \\
        \hline \hline \\
    \end{tabular}
\end{table}

Naturally, the adjustment of the population age structure, indicated by average household age is lagging the shift in mortality rates: while the change in mortality rates is completed by period 30, the transition of the population continous throughout the model horizon. The observation that average household age decreases towards the end of the transition period is an artifact of the way population dynamics are modelled, namely the assumption of stationary population size, which results in an initial decrease of the fertility rate, followed by a subsequent rise in fertility, before settling at the new stationary rate. This secondary rise in fertility triggers a decrease in the average age of a household.

The simulated OADR exhibits the core qualitative features of \citet{LudwigSchelkleVogel2012}: The ratio is initially relatively flat, then increases sharply for about 20 years and then begins to settles at a new level, with a very slight decrease at the end of the model horizon. The magnitude of the change in both the original paper and this paper is roughly 17 percentage points. Note that the scale of the OADR differs from this term paper to the original paper by \citet{LudwigSchelkleVogel2012}: while the ratio ranges between slightly below 20\% and ca. 37\% in the original paper, the OADR of the population used in this paper ranges between 28\% and 45\%. This mostly stems from the fact, that, in this paper, fertility rates are not estimated from data, but instead chosen such that the total mass of the population remains constant. While the level clearly plays a central role for quantitative treatments, it should play a minor role in qualitative assessments such as this. Figure \ref{fig:OADR} depicts the OADR resulting from the population dynamics simulated as described above.


%!TEX root =  ../main.tex

\mychapters{Infinities}{infinity}{\chapdir/pics/amazing-736875_1280}

In all of calculus, one number is unique, containing an infinite exponent in a finite number.
$e$ is hard to appreciate until you start considering rates of change,
accumulated distance, or continuous growth.

But what does infinity even mean?  Nothing in our world has even gone on without limit,
except perhaps black holes.  Aristotle said there are two kinds of infinities: potential and
actual.  But Georg Cantor said a physical potential infinity presupposes an actual infinity
in our minds, the mental construct we are saying would come into existence, if were to
continue.

Amazingly, all this heady talk of math and philosophy has real-life implications.  The infinite
sum of all the natural numbers appears on page 22 of Joseph Polchinski's classic,
\textit{String Theory}.  Calculus itself --- with all its myriad applications in our lives today
--- is the based on the assumption that a line is subdivided into a infinite number of
indivisible units.  Whether or not they exist in nature, infinities are useful mathematical
constructs.

\newpage
\chapterminitoc

%								8 - 1
\newpage
\invisiblesection{e}
\marginlessinput{\chapdir/0801p}
\newpage
\input{ch08/0801}
\newpage
\subsection{Exercises}
Kuta and
Read chapter one --- ``Big Numbers'' --- of George Gamow's
\textit{One, Two, Three ... Infinity} .

%								8 - 2
\newpage
\invisiblesection{Infinities}
\marginlessinput{\chapdir/0802p}
\newpage
\input{ch08/0802}
\newpage
\input{\chapdir/0802x}

%								8 - 3
\newpage
\invisiblesection{Logarithmic Derivatives}
\marginlessinput{\chapdir/0803p}
\newpage
\input{ch08/0803}
\newpage
\subsection{Exercises}
Kuta

%								8 - 4
\newpage
\invisiblesection{Dominance}
\marginlessinput{\chapdir/0804p}
\newpage
\input{ch08/0804}
\newpage
\subsection{Exercises}
in Kuta

%								8 - 5
\newpage
\invisiblesection{Analyses}
\marginlessinput{\chapdir/0805p}
\newpage
\input{ch08/0805}
\newpage
\subsection{Exercises}
In kuta

%								8 - 6
\newpage
\section{Review}
\subsection{Chapter Review}
\subsection{Chapter Test}
\subsection{Cumulative Review}
This unit has been a diverse whirlwind.  We united almost everything we had ever seen
before in math where $x$ had an exponent on it under the heading ``Power Function''.
Next we added such things together to get polynomials.  Then we divided those by each
other and got rational functions.  Then we swapped where $x$ was and put it in the
exponent.  This produced functions which ``transcended'' algebra, where ordinary inputs
could produce amazingly irrational answers.  The inverses of these functions were called
logs.

This transcendental leap allowed us to get a perspective on mathematics itself.  What
are we doing here?  Are all these abstract things just in our minds?  If so, why do they
works so well in the world?  It is surprisingly easy to imagine some things that
seemingly do not exist: namely infinities.  Some are countable, some are not.  Such
crazy ideas were necessary to continue finding derivatives to everything kind of function
we might need in the world, but they produce some logical conundrums.   But they
are the very foundation of all the calculus we have been doing!

in the world
\subsection{Cumulative Test}