\section{Prioritizing Project Selection to Hedge Against Uncertainty}
\label{sec:StochasticCapitalBudgeting}

One limitation of traditional optimization models for capital budgeting is that
they do not account for risk/uncertainty in profit and cost streams associated
with individual projects, nor do they account for risk in resource availability
in future years. Projects can incur cost overruns, especially when projects are
large, performed infrequently, or when there is risk regarding technical viability,
external contractors, and/or suppliers of requisite parts and materials.
Occasionally, projects are performed ahead of schedule and with savings in cost.
Planned budgets for capital improvements can be cut, and key personnel may be
lost. Or, there may be surprise budgetary windfalls for maintenance activities
due to decreased costs for “unplanned” maintenance. In such cases, how should
we resolve capital budgeting when we have risk forecasts for costs, profits, and
budgets? One approach is to re-solve the models described in the previous
section once refined forecasts for these parameters become available. However,
it is not always practical to fully revise a project portfolio whenever better
forecasts become available.

In order to prioritize the project selection using a risk forecast for these
parameters, the two-stage stochastic optimization model~\cite{PrioritizingProjectSelection}
is employed to provide priority lists to decision-makers to support better
risk-informed decisions.
Its inputs include those described in above sections for different variants of
the capital budgeting problem, except that a probabilistic description of the
uncertain parameters is integrated into the optimization process. The two-stage
stochastic optimization model forms a priority list as its first-stage decision,
then forms a corresponding project portfolio for each scenario as its
second-stage decision. When forming the optimal second-stage project portfolio
under a specific scenario, the stochastic optimization model ensures that the
portfolio is consistent with the first-stage prioritization (i.e., a project can
be selected only if all high-priority projects are also selected.) Thus, the
portfolios of projects corresponding to different scenarios are nested.

The notation and formulation of the risk-informed models are as follows:

\[
\begin{array}{ll}
%%%%%%%%%%%%%% INDICES AND SET %%%%%%%%%%%%%%%%
\multicolumn{2}{l}{\mbox{\em Indices and sets:} } \\
t \in T  & \mbox{time periods (years)} \\
i,i^{'} \in I  & \mbox{candidate projects} \\
j \in J_{i}	& \mbox{options for selecting project $i$} \\
%i^{'},j^{'} \in IJ_{ij} & \mbox{piggybacking situations} \\
k \in K	& \mbox{types of resources} \\
m \in M & \mbox{units of NPP} \\
\omega \in \Omega & \mbox{scenarios}\\
\\
%%%%%%%%%%%%%% DATA %%%%%%%%%%%%%%%%
\multicolumn{2}{l}{\mbox{\em Data:}} \\
a_{i}^{\omega} & \mbox{reward for selecting project $i$ under scenario $\omega$}  \\
a_{ij}^{\omega} & \mbox{reward for selecting project $i$ via option $j$ under scenario $\omega$}  \\
b^{\omega} & \mbox{available budget under scenario $\omega$}\\
b_{k}^{\omega} & \mbox{available budget for a resource of type $k$ under scenario $\omega$}\\
b_{t}^{\omega} & \mbox{available budget in year $t$ under scenario $\omega$}\\
b_{m}^{\omega} & \mbox{available budget for unit $m$ under scenario $\omega$}\\
b_{kt}^{\omega} & \mbox{available budget for a resource of type $k$ in year $t$ under scenario $\omega$}\\
c_{i}^{\omega} & \mbox{cost of investment $i$ under scenario $\omega$} \\
c_{ik}^{\omega} & \mbox{consumption of resource of type $k$} \\
& \mbox{if project $i$ is selected under scenario $\omega$}\\
c_{ijt}^{\omega} & \mbox{consumption of resource in year $t$ } \\
& \mbox{if project $i$ is performed via option $j$ under scenario $\omega$}\\
c_{ijkt}^{\omega} & \mbox{consumption of resource of type $k$ in year $t$ } \\
& \mbox{if project $i$ is performed via option $j$ under scenario $\omega$}\\
q^{\omega} & \mbox{probability of scenario $\omega$}\\
\\
%%%%%%%%%%%%%% DECISION VARS %%%%%%%%%%%%%%%%
\multicolumn{2}{l}{\mbox{\em Decision variables:}}  \\
x_{i}^{\omega} & \mbox{1 if project $i$ is selected under scenario $\omega$; 0 otherwise} \hspace*{4.0in}\\
x_{im}^{\omega} & \mbox{1 if project $i$ is selected for unit $m$ under scenario $\omega$; 0 otherwise} \hspace*{4.0in}\\
x_{ij}^{\omega} & \mbox{1 if project $i$ is selected via option $j$ under scenario $\omega$; 0 otherwise} \hspace*{4.0in}\\
y_{ii^{'}} & \mbox{1 if project $i$ has no lower priority than project $i^{'}$; 0 otherwise} \hspace*{4.0in}\\
\end{array}
\]

\subsection{Risk-Informed Single Knapsack Problem Optimization}
\label{subsec:RIskp}

\subsubsection{Risk-Informed Simple Knapsack Problem}
\vst \noi {\em Formulation:}
\begin{subequations}\label{RISimpleKP}
\begin{eqnarray}
&\dst \max_{x} &  \dst \sum_{\omega\in\Omega} q^\omega \dst \sum_{i \in I} a_{i}^\omega x_{i}^\omega \\
& s. t. & \sum_{i \in I} c_{i}^\omega x_{i}^\omega \leq b^\omega \label{stoc_cona}\\
& & y_{ii'} + y_{i'i} \geq 1, i<i' \label{stoc_conb} \\
& & x_{i}^\omega \geq x_{i'}^\omega + y_{ii'}-1, i\neq i' \label{stoc_conc}
\end{eqnarray}
\end{subequations}
For simplicity in what follows, the variable $y_{ii'}=1$ means that project $i$
is of higher priority than $i'$, even though the variable definition allows for ties
(i.e., projects of the same priority).
Constraint~(\ref{stoc_cona}) requires us to be within budget under each scenario.
Constraint~(\ref{stoc_conb}) indicates that either project $i$ is of higher priority
than project $i'$, or vice versa, or that both are of equal priority (i.e., a tie).
Constraint~(\ref{stoc_conc}) indicates that if project $i$ is of higher priority than
project $i'$ ($y_{ii'}=1$), and we select the lower priority project, then we
must also select the higher priority project; if $y_{ii'}=0$, or if $x_{i'}^\omega=0$,
then the constraint is vacuous.
In order to handle the risk in the capital budgeting problems, the entity
\xmlNode{Uncertainties} (see section~\ref{subsec:Uncertainties}) is used to specify
different scenarios of input parameters.

Example LOGOS input XML:
\begin{lstlisting}[style=XML]
<Logos>
  <Sets>
    <investments>
      1,2,3,4,5,6,7,8,9,10
    </investments>
  </Sets>

  <Parameters>
    <net_present_values index="investments">
      18,20,17,19,25,21,27,23,25,24
    </net_present_values>
    <costs index="investments">
      1,3,7,4,8,9,6,10,2,5
    </costs>
    <available_capitals>
      15
    </available_capitals>
  </Parameters>

  <Uncertainties>
    <available_capitals>
      <totalScenarios>10</totalScenarios>
      <probabilities>
        0.012, 0.019, 0.032, 0.052, 0.086, 0.142, 0.235, 0.188, 0.141, 0.093
      </probabilities>
      <scenarios>
        11, 12, 13, 14, 15, 16, 17, 18, 19, 20
      </scenarios>
    </available_capitals>
    <net_present_values>
      <totalScenarios>2</totalScenarios>
      <probabilities>
        0.3, 0.7
      </probabilities>
      <scenarios>
        18,20,17,19,25,21,27,23,25,24,
        18,20,17,19,25,21,27,23,25,24
      </scenarios>
    </net_present_values>
  </Uncertainties>
  ...
</Logos>
\end{lstlisting}

When running this case, LOGOS would generate a CSV (comma separated values) file
containing solutions for the optimization problem (i.e. values of decision variables
and maximum profit [MaxNPV is used to describe the maximum profit]). The header of
this CSV file contains the indices listed under \xmlNode{investments}
used as indices for decision variable, the objective variable \textbf{MaxNPV},
the scenario name and the associated probability weight.
The data provides the values for both decision variables and the objective variable.

Example LOGOS output CSV:
\begin{lstlisting}[basicstyle=\small,language=python]
1,10,2,3,4,5,6,7,8,9,ScenarioName,ProbabilityWeight,MaxNPV
1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_1,0.0036,70.0
1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_6,0.0224,70.0
1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_5,0.0096,70.0
1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_4,0.0133,70.0
1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_3,0.0057,70.0
1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_2,0.0084,70.0
1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_7,0.0156,94.0
1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_8,0.0364,94.0
1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_9,0.0258,94.0
1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_12,0.0994,94.0
1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_11,0.0426,94.0
1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_10,0.0602,94.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_16,0.1316,114.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_19,0.0279,114.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_15,0.0564,114.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_20,0.0651,114.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_14,0.1645,114.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_13,0.0705,114.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_17,0.0423,114.0
1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,scenario_18,0.0987,114.0
\end{lstlisting}

\subsubsection{Risk-Informed Multi-Dimensional Knapsack Problem}

\vst \noi {\em Formulation:}
\begin{subequations}\label{RISimpleKP}
\begin{eqnarray}
&\dst \max_{x} &  \dst \sum_{\omega\in\Omega} q^\omega \dst \sum_{i \in I} a_{i}^\omega x_{i}^\omega \\
& s. t. & \sum_{i \in I} c_{it}^\omega x_{i}^\omega \leq b_{t}^\omega, t\in T \\
& & y_{ii'} + y_{i'i} \geq 1, i<i'\\
& & x_{i}^\omega \geq x_{i'}^\omega + y_{ii'}-1, i\neq i'
\end{eqnarray}
\end{subequations}

Example LOGOS input XML:
\begin{lstlisting}[style=XML]
<Logos>
  <Sets>
    <investments>
      1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
    </investments>
    <time_periods>
      1,2,3,4,5
    </time_periods>
  </Sets>

  <Parameters>
    <net_present_values index="investments">
      2.315,0.824,22.459,60.589,0.667,5.173,4.003,0.582,0.122,
      -2.870,-0.102,-0.278,-0.322,-3.996,-0.246,-20.155
    </net_present_values>
    <costs index="investments, time_periods">
      0.219,0.257,0.085,0.0,0.0,
      0.0,0.0,0.122,0.103,0.013,
      5.044,1.839,0.0,0.0,0.0,
      6.74,6.134,10.442,0.0,0.0,
      0.425,0.0,0.0,0.0,0.0,
      2.125,2.122,0.0,0.0,0.0,
      2.387,0.19,0.012,2.383,0.192,
      0.0,0.95,0.0,0.0,0.0,
      0.03,0.03,0.688,0.0,0.0,
      0,0.2,0.763,0.739,2.539,
      0.081,0.032,0,0,0,
      0.3,0,0,0,0,
      0.347,0,0,0,0,
      4.025,0.297,0,0,0,
      0.095,0.095,0.095,0,0,
      5.487,5.664,0.5,6.803,6.778
    </costs>
    <available_capitals index="time_periods">
      18,18,18,18,18
    </available_capitals>
  </Parameters>

  <Uncertainties>
    <available_capitals>
      <totalScenarios>10</totalScenarios>
      <probabilities>
        0.012, 0.019, 0.032, 0.052, 0.086, 0.142, 0.235, 0.188, 0.141, 0.093
      </probabilities>
      <!--
        scenarios is ordered by numberScenarios * parametersIndex, the number of
        scenarios is determined by the number of elements in <probabilities>,
        for this case total element in scenarios:
        numberScenarios * time_periods = 10 * 5
      -->
      <scenarios>
        11, 11, 11, 11, 11,
        12, 12, 12, 12, 12,
        13, 13, 13, 13, 13,
        14, 14, 14, 14, 14,
        15, 15, 15, 15, 15,
        16, 16, 16, 16, 16,
        17, 17, 17, 17, 17,
        18, 18, 18, 18, 18,
        19, 19, 19, 19, 19,
        20, 20, 20, 20, 20
      </scenarios>
    </available_capitals>
  </Uncertainties>
  <Settings>
    <mandatory>10,11,12,13,14,15,16</mandatory>
    <solver>cbc</solver>
    <sense>maximize</sense>
  </Settings>
</Logos>
\end{lstlisting}

Example LOGOS output CSV:
\begin{lstlisting}[basicstyle=\tiny,language=python]
1,10,11,12,13,14,15,16,2,3,4,5,6,7,8,9,ScenarioName,ProbabilityWeight,MaxNPV
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,scenario_1,0.012,-23.581
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,scenario_2,0.019,-23.459
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,scenario_3,0.032,-23.459
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,scenario_4,0.052,-23.459
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,scenario_5,0.086,-23.459
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,scenario_6,0.142,-23.459
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,scenario_7,0.235,-23.459
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,scenario_8,0.188,37.130
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,scenario_9,0.141,37.1230
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,scenario_10,0.093,42.303
\end{lstlisting}

\subsection{Risk-Informed Multiple Knapsack Problem Optimization}
\label{subsec:RImkp}

Model formulation:\\

\begin{equation}\label{rimkp_obja}
\mathop{\max}_{x,y} \sum _{ \omega  \in  \Omega }q^{ \omega } \sum _{i \in I} \sum _{m \in M}a_{i}^{ \omega }x_{im}^{ \omega }
\end{equation}

\begin{equation}\label{rimkp_objb}
~~~~~~~~~~~~s.t.~~~~~y_{ii^{'}}+y_{i^{'}i} \geq 1,~ i<i^{'}\text{, i, }i^{'} \in I
\end{equation}

\begin{equation}\label{rimkp_objc}
~~~~~~~~\sum_{m=1}^{M} x_{im}^\omega \geq \sum_{m=1}^{M} x_{i'm}^\omega + y_{ii'} -1,~ i \neq i^{'}\text{, i, }i^{'} \in I,  \omega  \in  \Omega
\end{equation}

Constraint~(\ref{rimkp_objb}) indicates that either project $i$  is of higher priority
than project  $i^{'}$, or vice versa, or that both are of equal priority (i.e., a tie).
Constraint~(\ref{rimkp_objc}) indicates that if project  $i$  is higher priority than
project  $i^{'}$ ($y_{ii^{'}}=1$), and we select the lower priority project
\textit{for some unit}, then we must also select the higher priority project;
if  $y_{ii^{'}}=0$, or if $\sum_{m=1}^{M} x_{i'm}^\omega=0$  then the constraint is vacuous.\par

\begin{equation}\label{rimkp_objd}
 \sum _{i \in I}^{} c_{i}^{ \omega }x_{im}^{ \omega }~  \leq  b_{m}^{ \omega },~ m \in M,  \omega  \in  \Omega
\end{equation}

Constraint~(\ref{rimkp_objd}) requires that we be within budget
for each unit under each scenario.

\begin{equation}\label{rimkp_obje}
\sum_{m\in M} x_{im}^{ \omega } \leq 1,~ i \in I, \omega  \in  \Omega
\end{equation}

Constraint~(\ref{rimkp_obje}) simultaneously ensures that we select project $i$
only for one unit.

Example LOGOS input XML:
\begin{lstlisting}[style=XML]
  <Sets>
    <investments>
      1,2,3,4,5,6,7,8,9,10
    </investments>
    <capitals>
      unit_1, unit_2
    </capitals>
  </Sets>

  <Parameters>
    <net_present_values index="investments">
      78, 35, 89, 36, 94, 75, 74, 79, 80, 16
    </net_present_values>
    <costs index="investments">
      18, 9, 23, 20, 59, 61, 70, 75, 76, 30
    </costs>
    <available_capitals index="capitals">
      103, 156
    </available_capitals>
  </Parameters>

  <Uncertainties>
    <available_capitals>
      <totalScenarios>2</totalScenarios>
      <probabilities>
        0.3 0.7
      </probabilities>
      <scenarios>
        103, 156,
        103, 156
      </scenarios>
    </available_capitals>
    <net_present_values>
      <totalScenarios>2</totalScenarios>
      <probabilities>
        0.3, 0.7
      </probabilities>
      <scenarios>
        78, 35, 89, 36, 94, 75, 74, 79, 80, 16,
        78, 35, 89, 36, 94, 75, 74, 79, 80, 16
      </scenarios>
    </net_present_values>
  </Uncertainties>

  <Settings>
    <solver>glpk</solver>
    <sense>maximize</sense>
    <problem_type>MultipleKnapsack</problem_type>
  </Settings>
</Logos>
\end{lstlisting}

Example LOGOS output CSV:
\begin{lstlisting}[basicstyle=\tiny,language=python]
"('1', 'unit_1')","('1', 'unit_2')","('10', 'unit_1')","('10', 'unit_2')","('2', 'unit_1')","('2', 'unit_2')","('3', 'unit_1')",
"('3', 'unit_2')","('4', 'unit_1')","('4', 'unit_2')","('5', 'unit_1')","('5', 'unit_2')","('6', 'unit_1')","('6', 'unit_2')",
"('7', 'unit_1')","('7', 'unit_2')","('8', 'unit_1')","('8', 'unit_2')","('9', 'unit_1')","('9', 'unit_2')",
ScenarioName,ProbabilityWeight,MaxNPV
1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,scenario_1,0.09,452.0
1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,scenario_2,0.21,452.0
1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,scenario_3,0.21,452.0
0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,scenario_4,0.49,452.0
\end{lstlisting}

\subsection{Risk-Informed Multiple-Choice Multi-Dimensional Knapsack Problem Optimization}
\label{subsec:RImckp}

Model formulation:\\

\begin{equation}\label{stoc_obja}
\mathop{\max}_{x,y} \sum _{ \omega  \in  \Omega }^{}q^{ \omega } \sum _{i \in I}^{} \sum _{j \in J_{i}}^{}a_{ij}^{ \omega }x_{ij}^{ \omega }
\end{equation}

\begin{equation}\label{stoc_objb}
~~~~~~~~~~~~s.t.~~~~~y_{ii^{'}}+y_{i^{'}i} \geq 1,~ i<i^{'}\text{, i, }i^{'} \in I
\end{equation}

\begin{equation}\label{stoc_objc}
~~~~~~~~\sum_{j=1}^{J_i} x_{ij}^\omega \geq \sum_{j=1}^{J_i} x_{i'j}^\omega + y_{ii'} -1,~ i \neq i^{'}\text{, i, }i^{'} \in I,  \omega  \in  \Omega
\end{equation}

Constraint~(\ref{stoc_objb}) indicates that either project $i$ is of higher priority
than project  $i^{'}$, or vice versa, or that both are of equal priority (i.e., a tie).
Constraint~(\ref{stoc_objc}) indicates that if project  $i$  is higher priority than
project  $i^{'}$  $y_{ii^{'}}=1$, and we select the lower priority project
\textit{under some option}, then we must also select the higher priority project;
if  $y_{ii^{'}}=0$,  or if  $\sum_{j=1}^{J_i} x_{i'j}^\omega=0$,  then the constraint is vacuous.\par

\begin{equation}\label{stoc_objd}
 \sum _{i \in I}^{} \sum _{j \in J_{i}}^{}\text{~ c}_{ijkt}^{ \omega }x_{ij}^{ \omega }~  \leq  b_{kt}^{ \omega },~ k \in K, t \in T,  \omega  \in  \Omega
\end{equation}

Constraint~(\ref{stoc_objd}) requires that we be within budget in each time period,
for each resource type, and under each scenario.

\begin{equation}\label{stoc_obje}
\sum_{j\in J_i} x_{ij}^{ \omega } \leq 1,~ i \in I, \omega  \in  \Omega
\end{equation}

Constraint~(\ref{stoc_obje}) simultaneously ensures that we select project  $i$
via, at most, one option. Note that this illustrates a situation in which we
must include the {\it DoNothing}  option among the alternatives to optional projects.\par

Example LOGOS input XML:
\begin{lstlisting}[style=XML]
<Logos>
  <Sets>
    <investments>
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17
    </investments>
    <options index='investments'>
      1;
      1;
      1;
      1,2,3;
      1,2,3,4;
      1,2,3,4,5,6,7;
      1;
      1;
      1;
      1;
      1;
      1;
      1;
      1;
      1;
      1;
      1
    </options>
  </Sets>

  <Parameters>
    <net_present_values index='options'>
      2.046
      2.679
      2.489
      2.61
      2.313
      1.02
      3.013
      2.55
      3.351
      3.423
      3.781
      2.525
      2.169
      2.267
      2.747
      4.309
      6.452
      2.849
      7.945
      2.538
      1.761
      3.002
      3.449
      2.865
      3.999
      2.283
      0.9
      8.608
    </net_present_values>
    <costs index='options'>
      36538462
      83849038
      4615385
      2788461538
      2692307692
      5480769231
      1634615385
      2981730768
      7211538462
      9038461538
      649038462
      650000000
      216346154
      212500000
      3076923077
      3942307692
      1144230769
      675721154
      1442307692
      99711538
      4807692
      123076923
      138461538
      86538462
      108653846
      75092404
      6413462
      147932692
    </costs>
    <available_capitals>
      15E9
    </available_capitals>
  </Parameters>

  <Uncertainties>
    <available_capitals>
      <totalScenarios>3</totalScenarios>
      <probabilities>
        0.2,0.6,0.2
      </probabilities>
      <scenarios>
        5E9,10E9,15E9
      </scenarios>
    </available_capitals>
  </Uncertainties>

  <Settings>
    <solver>cbc</solver>
    <solverOptions>
      <threads>1</threads>
      <StochSolver>EF</StochSolver>
    </solverOptions>
    <sense>maximize</sense>
    <problem_type>mckp</problem_type>
  </Settings>
</Logos>
\end{lstlisting}

Example LOGOS output CSV:
\begin{lstlisting}[basicstyle=\tiny,language=python]
"('1', '1')","('10', '1')","('11', '1')","('12', '1')","('13', '1')","('14', '1')","('15', '1')","('16', '1')",
"('17', '1')","('2', '1')","('3', '1')","('4', '1')","('4', '2')","('4', '3')","('5', '1')","('5', '2')","('5', '3')",
"('5', '4')","('6', '1')","('6', '2')","('6', '3')","('6', '4')","('6', '5')","('6', '6')","('6', '7')","('7', '1')",
"('8', '1')","('9', '1')",ScenarioName,ProbabilityWeight,MaxNPV
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,scenario_1,0.2,53.865
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,scenario_2,0.6,59.488
1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,scenario_3,0.2,59.826
\end{lstlisting}


%-------------------------------------------------------------------------------
%\subsubsection{Balancing Units}
%-------------------------------------------------------------------------------
Ensuring that units are balanced and correct requires care.
Take the system of linear equations that arises from the finite volume discretisation, specified in \eq{eq:ode_linsys} and \eq{eq:rhs_linsys}
\begin{equation}
    \label{eq:linsys_FV}
    \left[
        \frac{\sigma_i \cmi}{\Delta t} + \sum_{j\in\mathcal{N}_i} {\alpha_{ij}}
    \right]
    V_i^{k+1} - \sum_{j\in\mathcal{N}_i} { \alpha_{ij} V_j^{k+1}}
        =
    \frac{\sigma_i \cmi}{\Delta t} V_i^k -  \sigma_i(i_m^{k} - i_e).
\end{equation}

The choice of units for a parameter, e.g. $\mu m^2$ or $m^2$ for the area $\sigma_{ij}$, introduces a constant of proportionality wherever it is used ($10^{-12}$ in the case of $\mu m^2 \rightarrow m^2$).
Wherever terms are added in \eq{eq:linsys_FV} the units must be checked, and constants of proportionality balanced.

First, appropriate units for each of the parameters and variables are chosen in~\tbl{tbl:units}.
We try to use the same units as NEURON, except for the specific membrane capacitance $c_m$, for which $F\cdot m^{-2}$ is used in place of $nF\cdot mm^{-2}$.

\begin{table}[hp!]
\begin{tabular}{lllr}
    \hline
    term                      &   units                 &  normalized units                         & NEURON \\
    \hline
    $t$                       &   $ms$                  &  $10^{-3} \cdot s$                        & yes    \\
    $V$                       &   $mV$                  &  $10^{-3} \cdot V$                        & yes    \\
    $a,~\Delta x$             &   $\mu m$               &  $10^{-6} \cdot m$                        & yes    \\
    $\sigma_{i},~\sigma_{ij}$ &   $\mu m^2$             &  $10^{-12} \cdot m^2$                     & yes    \\
    $c_m$                     &   $F\cdot m^{-2}$       &  $s\cdot A\cdot V^{-1}\cdot m^{-2}$       & no     \\
    $r_L$                     &   $\Omega\cdot cm$      &  $10^{-2} \cdot A^{-1}\cdot V\cdot m$     & yes    \\
    $\overline{g}$            &   $S\cdot cm^{-2}$      &  $10^{4} \cdot A\cdot V^{-1}\cdot m^{-2}$ & yes    \\
    $g_s$                     &   $\mu S$               &  $10^{-6} \cdot A\cdot V^{-1}$            & yes    \\
    $I_e$                     &   $nA$                  &  $10^{-9} \cdot A$                        & yes    \\
    \hline
\end{tabular}
\caption{The units chosen for parameters and variables in Arbor. The NEURON column indicates whether the same units have been used as NEURON.}
\label{tbl:units}
\end{table}

\subsection{Left Hand Side}
First, we calculate the units for the term $\frac{\sigma_i \cmi}{\Delta t}$, as follows
\begin{align}
    \left[ \frac{\sigma_i \cmi}{\Delta t} \right]
        &=
    \frac{10^{-12}\cdot m^2 \cdot s\cdot A\cdot V^{-1}\cdot m^{-2} } {10^{-3}\cdot s}
            \nonumber \\
        &=
    10^{-9} \cdot A \cdot V^{-1}. \label{eq:units_lhs_diag}
\end{align}
The units of $\alpha_{i,j}$ are:
\begin{align}
    \left[ \alpha_{i,j} \right]
        &=
    \left[ \frac{\sigma_{ij}}{ r_L \Delta x_{ij}} \right] \nonumber \\
        &=
    \frac{10^{-12}\cdot m^2}{ 10^{-2} \cdot A^{-1}\cdot V\cdot m \cdot 10^{-6}\cdot m}
        \nonumber \\
        &=
    10^{-4}\cdot A \cdot V^{-1}, \label{eq:units_lhs_lu}
\end{align}
which can be scaled by $10^{5}$ to have the same scale as in \eq{eq:units_lhs_diag}.

Thus, the RHS with scaling for units is:
\begin{equation}
    \label{eq:linsys_LHS_scaled}
    \left[
        \frac{\sigma_i \cmi}{\Delta t} + \sum_{j\in\mathcal{N}_i} {10^5\cdot\alpha_{ij}}
    \right]
    V_i^{k+1} - \sum_{j\in\mathcal{N}_i} { 10^5\cdot\alpha_{ij} V_j^{k+1}}.
\end{equation}
The implementation folds the $10^5$ factor into the $\alpha_{ij}$ terms when they are used to calculate the invariant component of the matrix during the initialization phase.

After this scaling, the units of the LHS are
\begin{align}
    \text{units on LHS}
        &= (10^{-9} \cdot A \cdot V^{-1})( 10^{-3} \cdot V) \nonumber \\
        &= 10^{-12} \cdot A. \label{eq:balanced_units}
\end{align}

\subsection{Right Hand Side}
The first term on the RHS has the same scaling factor as the LHS, so does not need to be changed.

Density channels and point processes describe the membrane current differently in NMODL;
as current densities ($10\cdot A\cdot m^{-2}$) and currents ($10^{-9}\cdot A$) respectively.
The current term can be written as follows:
\begin{equation}
    \sigma_i (i_m - i_e) \equiv \sigma_i \bar{i}_m + I_m - I_e,
\end{equation}
where $\bar{i}_m$ is the current density contribution from ion channels, $I_m$ is the current contribution from synapses, and $I_e$ is current contribution from electrodes.

The units of the current density as calculated via NMODL are
\begin{equation}
    \label{eq:im_unit}
    \unit{ \bar{i}_m } =  \unit{ \overline{g} } \unit{ V }
                       =  10 \cdot A \cdot m^{-2},
\end{equation}
so the units of the current from density channels are
\begin{equation}
    \unit{\sigma_i \bar{i}_m} = 10^{-12}\cdot{m}^2 \cdot 10 \cdot A \cdot m^{-2} = 10^{-11}\cdot A.
\end{equation}
Hence, the $\sigma_i \bar{i}_m$ term must be scaled by 10 to match units.

Likewise the units of synapse and electrode current
\begin{equation}
    \label{eq:Im_unit}
    \unit{ I_e } = \unit{ I_m } = \unit{ g_s } \unit{ V }
                 = 10^{-9}\cdot A,
\end{equation}
which must be scaled by $10^3$ to match units.

The properly scaled RHS is
\begin{equation}
    \label{eq:linsys_RHS_scaled}
    \frac{\sigma_i \cmi}{\Delta t} V_i^k -
        (10\cdot\sigma_i \bar{i}_m + 10^3(I_m - I_e)).
\end{equation}

\subsection{Putting It Together}
From \eq{eq:linsys_LHS_scaled} and \eq{eq:linsys_RHS_scaled} the full scaled linear system is
\begin{align}
    &
    \left[
        \frac{\sigma_i \cmi}{\Delta t} + \sum_{j\in\mathcal{N}_i} {10^5\cdot\alpha_{ij}}
    \right]
    V_i^{k+1} - \sum_{j\in\mathcal{N}_i} { 10^5\cdot\alpha_{ij} V_j^{k+1}} \nonumber \\
       & =
    \frac{\sigma_i \cmi}{\Delta t} V_i^k -
        (10\cdot\sigma_i \bar{i}_m + 10^3(I_m - I_e)),
\end{align}
where the units on both sides have been scaled from $pA$ to $nA$, i.e. by a factor of $10^3$.
This can be expressed more generally in terms of weights
\begin{align}
    &
    \left[
        g_i + \sum_{j\in\mathcal{N}_i} {g_{ij}}
    \right]
    V_i^{k+1} - \sum_{j\in\mathcal{N}_i} { g_{ij} V_j^{k+1}} \nonumber \\
       & =
    g_i V_i^k -
        (w_i^d \bar{i}_m + w_i^p(I_m - I_e)),
\end{align}
which can be expressed more compactly as
\begin{equation}
    Gv=i,
\end{equation}
where $G\in\mathbb{R}^{n\times n}$ is the conductance matrix, and $v, i \in \mathbb{R}^{n}$ are voltage and current vectors respectively.

In Arbor the weights are chosen such that the conductance has units $\mu S$, voltage has units $mV$ and current has units $nA$.

    \begin{center}

    \begin{tabular}{llll}
        \hline
        weight & value & units  & SI \\
        \hline
        $g_i$    & $10^{-3}\frac{\sigma_i \cmi}{\Delta t}$ & $\mu S$ & $10^{-6} \cdot A\cdot V^{-1}$ \\
        $g_{ij}$ & $10^2\alpha_{ij}$                       & $\mu S$ & $10^{-6} \cdot A\cdot V^{-1}$ \\
        $w_i^d$  & $10^{-2}\cdot\sigma_i$                  & $10^2\mu m^{-2}$ & $10^{-10}m^2$ \\
        $w_i^p$  & $1$                                     & $1$     & $1$ \\
        \hline
    \end{tabular}

    \end{center}
%------------------------------------------
\subsection{Supplementary Unit Information}
%------------------------------------------
Here is some information about units scraped from Wikipedia for convenience.

\begin{table*}[htp!]
    \begin{center}

    \begin{tabular}{llll}
        \hline
        quality & symbol & unit  & notes \\
        \hline
        energy     & $J$ & joule   $j$  & work to push 1 $N$ through 1 $m$ \\
        charge     & $q$ & coulomb $C$  & $6.25\cdot10^{18}$ electrons, $[A\cdot s]$ \\
        current    & $I$ & ampere  $A$  & $[C\cdot s^{-1}]$, $A$ is SI base unit\\
        voltage    & $V$ & volt    $V$  & potential work per unit charge \\
        resistance & $R$ & ohm $\Omega$ & recall Ohm's law $V=IR$ \\
        capacitance& $C$ & farad   $F$  & $C=\frac{q}{V}$, $[J\cdot C^{2}]$\\
        conductance& $g$ & siemens $S$  & $g=1/R$ i.e. inverse of resistance \\
        \hline
    \end{tabular}

    \vspace{20pt}

    \begin{tabular}{llll}
        \hline
        symbol & unit & equivalents & SI base \\
        \hline
        $J$    & $j$      &  $J\cdot s^{-1}$, $V\cdot A$ &
            $kg\cdot m^{2}\cdot s^{-2}$ \\

        $q$    & $C$      & $s\cdot A$ &
            $s\cdot A$ \\

        $I$    & $A$  & $C\cdot s^{-1}$ &
            $A$ \\

        $V$    & $V$      & $W\cdot A$ &
            $kg\cdot m^{2}\cdot s^{-3}\cdot A^{-1}$ \\

        $R$    & $\Omega$ & $V\cdot A^{-1}$ &
            $kg\cdot m^{2}\cdot s^{-3}\cdot A^{-2}$ \\

        $C$    & $F$      & $C\cdot V^{-1}$  &
            $kg^{-1}\cdot m^{-2}\cdot s^{4}\cdot A^{2}$ \\
        $g$    & $S$      & $A\cdot V^{-1}$  &
            $kg^{-1}\cdot m^{-2}\cdot s^3\cdot A^2$ \\
        \hline
    \end{tabular}

    \end{center}
    \caption{Symbols and quantities.}
\end{table*}


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

\marginpar{Wednesday\\ 2020-4-29, \\ compiled \\ \today}

So, we can write out the \textbf{general solution} for the Dirac equation: the spinor and its conjugate are
%
\begin{subequations}
\begin{align}
\psi (x) &=
\frac{1}{(2 \pi )^{3/2}}
\int \frac{ \dd[3]{k}}{\sqrt{2 \omega_{k}}}
\sum _{r=1}^{2} \qty[
    c_r(k) u_r(k) e^{-ikx}
    + d^{*}_{r} (k) v_r(k) e^{ikx}
]_{\omega_{k} = k^{0}}
\\
\overline{\psi} (x) &=
\frac{1}{(2 \pi )^{3/2}}
\int \frac{ \dd[3]{k}}{\sqrt{2 \omega_{k}}}
\sum _{r=1}^{2} \qty[
    d_r(k) \overline{v}_r(k) e^{-ikx}
    + c^{*}_{r} (k) \overline{u}_r(k) e^{ikx}
]_{\omega_{k} = k^{0}}
\,.
\end{align}
\end{subequations}

The functions \(c_r\) and \(d_r\) represent the two degrees of freedom of the positive and negative energy solution respectively.

The important thing to recall is
%
\begin{align}
\psi_{+} \sim cu \qquad \text{and} \qquad
\psi_{-} \sim d ^* v
\,.
\end{align}

Note that \(c_r\) and \(d_r\) are scalar functions, while \(u_r\) and \(v_r\) are 4D spinors.

\subsection{Energy projectors}

We wish to distinguish positive and negative energy solutions: so, we define the projector onto the positive and negative energy subspaces,
%
\begin{align}
\Lambda_{\pm } (k) = \frac{\pm \slashed{k} + M}{2M}
\,.
\end{align}

These two are an incomplete set of orthogonal projectors.

\begin{claim}
They satisfy
%
\begin{subequations}
\begin{align}
\Lambda_{\pm}^2 (k) &= \Lambda_{\pm} (k)  \\
\Lambda_{+} (k) + \Lambda_{-} (k) &= \mathbb{1}  \\
\Lambda_{+} (k) \Lambda_{-} (k) &= 0  \\
\Tr[\Lambda_{\pm} (k)] &= 2
\,.
\end{align}
\end{subequations}
\end{claim}

\begin{proof}
Let us first establish what \(\slashed{k}^2\) is equal to:
%
\begin{align}
\slashed{k}^2 =
\gamma^{\mu } k_{\mu } \gamma^{\nu } k_{\nu }
= \frac{1}{2} \qty{\gamma^{\mu }, \gamma^{\nu }}k_{\mu } k_{\nu }
= \eta^{\mu \nu } k_{\mu } k_{\nu }
= k^2 \mathbb{1}_{4}
\,.
\end{align}

So, we can compute
%
\begin{subequations}
\begin{align}
\Lambda_{\pm}^2 (k) &= \frac{1}{4 M^2}\qty[\slashed{k}^2 + M^2 \mathbb{1} \pm 2 \slashed{k} M]  \\
&= \frac{1}{4 M^2} \qty[2 M \mathbb{1} \pm 2 \slashed{k}M] = \frac{\pm \slashed{k} + M}{2M}
\,.
\end{align}
\end{subequations}

For the second property, we get
%
\begin{align}
\Lambda_{+} + \Lambda_{-} = \frac{+ \slashed{k} + M - \slashed{k} + M}{2M} = \frac{2M}{2M} = \mathbb{1}
\,.
\end{align}

For the third expression, we find
%
\begin{align}
\Lambda_{+} \Lambda_{-} \propto \qty(\slashed{k} + M) \qty(\slashed{k} - M) = \slashed{k}^2 - M^2 = 0
\,.
\end{align}

For the fourth expression, instead, we find that since \(\slashed{k}\) is traceless the trace is equal to that of \((M / 2 M)  \mathbb{1}\), which is equal to \(2\) since spinorial matrices are 4-dimensional.
\end{proof}

We can apply these projectors to the solutions we know how to write from the general expression \eqref{eq:dirac-equation-solutions}:
%
\begin{subequations}
\begin{align}
\Lambda_{+} u_r (k) &= \frac{C}{2M} (\slashed{k} + M)^2 u_r(M) = C(\slashed{k} + M) u_r (M) = u_r(k) \\
\Lambda_{-} u_r (k) &= \frac{C}{2M} (-\slashed{k} + M) (\slashed{k} + M) u_r(M) = 0 \\
\Lambda_{+} v_r (k) &= \frac{C}{2M} (\slashed{k} + M) (\slashed{k} - M) u_r(M) = 0 \\
\Lambda_{-} v_r (k) &= \frac{C}{2M} (-\slashed{k} + M) (-\slashed{k} + M) u_r(M) = v_r(k)
\,.
\end{align}
\end{subequations}

These projectors can also be obtained from the vectors themselves: if a vector \(v\) is normalized to 1, the matrix \(v v ^{\top}\) is a projector onto the subspace of the vector.

We can add projectors together in order to get projectors onto larger subspaces.

\begin{claim}
We can recover the projectors \(\Lambda_{\pm }\) by the expressions:
%
\begin{subequations} \label{eq:energy-projectors-spinor}
\begin{align}
\Lambda_{+} (k) &= \sum_{r} \frac{u_r(k) \overline{u}_{r} (k)}{2M} \\
\Lambda_{-} (k) &= - \sum_{r} \frac{v_r(k) \overline{v}_{r} (k)}{2M}
\,.
\end{align}
\end{subequations}
\end{claim}

\begin{proof}
The calculation yields
%
\begin{subequations}
\begin{align}
u_r(k) \overline{u}_{r}(k) &=
\left[\begin{array}{c}
\xi_{r}\sqrt{\omega_{k} + M} \\
\displaystyle
\frac{\vec{k} \cdot \vec{\sigma}}{\sqrt{\omega_{k} + M}}
\xi_{r}
\end{array}\right]
\left[\begin{array}{cc}
\xi_{r}^{\top} \sqrt{\omega_{k} + M}, &
\displaystyle
- \xi_{r}^{\top} \frac{\vec{k} \cdot \vec{\sigma}}{\sqrt{\omega_{k} + M}}
\end{array}\right]  \\
&= \left[\begin{array}{cc}
\xi_{r} \xi_{r}^{\top} (\omega_{k} + M) & - \xi_{r} \xi_{r}^{\top} (\vec{k} \cdot \vec{\sigma}) \\
(\vec{k} \cdot \vec{\sigma}) \xi_{r} \xi_{r}^{\top} &
- \frac{ (\vec{k}\cdot \vec{\sigma}) \xi_{r} \xi_{r}^{\top} (\vec{k} \cdot \vec{\sigma})}{\omega_{k} + M}
\end{array}\right]
\,,
\end{align}
\end{subequations}
%
and now we notice the fact that \(\sum _{r} \xi_{r} \xi_{r} ^{\top} = \mathbb{1}_{2}\), so if we sum over \(r\) we get
%
\begin{subequations}
\begin{align}
\sum _{r} u_r (k) \overline{u}_{r}(k) &=
\left[\begin{array}{cc}
\omega_{k} + M & - \vec{k} \cdot \vec{\sigma} \\
\vec{k} \cdot \vec{\sigma} & - \frac{\abs{k}^2}{\omega_{k} + M}
\end{array}\right]  \\
&= \left[\begin{array}{cc}
\omega_{k} + M & - \vec{k} \cdot \vec{\sigma} \\
\vec{k} \cdot \vec{\sigma} & - \omega_{k} + M
\end{array}\right]  \\
&= \slashed{k} + M
\,.
\end{align}
\end{subequations}

If we divide by \(2M\) we get our result.
The computation for \(v_{r}\) is similar.
\end{proof}

\subsection{Spin operators}

Recall, the spinorial representation of the Lorentz group is generated by the matrices \(\Sigma^{\mu \nu }\), which can be calculated by
%
\begin{align}
\Sigma^{\mu \nu } = \frac{i}{4} \qty[\gamma^{\mu }, \gamma^{\nu }]
\,.
\end{align}

We can use these to define, in the Dirac representation, the generators of boosts:
%
\begin{subequations}
\begin{align}
K_{i} = \Sigma^{i0} = -\frac{i}{2} \left[\begin{array}{cc}
0 & \sigma_{i} \\
\sigma_{i} & 0
\end{array}\right]
\,,
\end{align}
\end{subequations}
%
and of rotations:
%
\begin{subequations}
\begin{align} \label{eq:rotation-spin-generator-definition}
\Sigma_{i} = \frac{1}{2} \epsilon_{ijk} \Sigma^{jk}
= \frac{1}{2} \left[\begin{array}{cc}
\sigma_{i} & 0 \\
0 & \sigma_{i}
\end{array}\right]
\,.
\end{align}
\end{subequations}

We can exponentiate these to get the representations of general boosts and rotations: a boost will be written as
%
\begin{align}
S(\Lambda) = \exp( - \frac{i}{2} \omega_{0i} K_{i} )
\,,
\end{align}
%
while a rotation will be written as
%
\begin{align}
S(\Lambda ) = \exp( - \frac{i}{2} \theta_{k} \Sigma_{k})
\,,
\end{align}
%
where we used the angle \(\theta_{k} = \epsilon_{ijk} \omega^{ij}\).
These \(\Sigma_{k}\) are called the spin operators. They result in an \emph{internal rotation} of the spinor corresponding to a rotation of our coordinates.

In the rest frame of the particle, the basis states we chose are the eigenstates of \(\Sigma_{3}\): We have
%
\begin{subequations}
\begin{align}
\Sigma_{3} u_r (M) = \frac{1}{2} \left[\begin{array}{cc}
\sigma_3  & 0 \\
0 & \sigma_3
\end{array}\right]
\sqrt{2M}
\left[\begin{array}{c}
\xi_{r} \\
0
\end{array}\right]
= \pm \frac{1}{2} u_R (M)
\,,
\end{align}
\end{subequations}
%
where we have either \(+\) or \(-\) depending on whether \(r=1\) or \(2\), respectively.

Also, the negative energy solutions are basis states: we get
%
\begin{subequations}
\begin{align}
\Sigma_{3} v_r (M) = \frac{1}{2}
\left[\begin{array}{cc}
\sigma_3  & 0 \\
0 & \sigma_3
\end{array}\right]
\sqrt{2M}
\left[\begin{array}{c}
0   \\
\xi_{r}
\end{array}\right]
= \pm \frac{1}{2} v_r(M)
\,.
\end{align}
\end{subequations}

So, our particles have spin \(1/2\). We can have the \(z\) component of the spin to be \(\pm 1 /2 \), and positive and negative energy: in the end, these are 4 degrees of freedom.

Note that we have eigenstates of \(\Sigma_3 \) specifically because of the way we chose \(\xi_{r}\): we can have other equivalent choices.

\subsection{The helicity operator}

\begin{claim}
The spin projection along a given axis is not a good quantum number: it does not commute with the Hamiltonian, \(\qty[H , \Sigma_3 ] \neq 0\).
\end{claim}

\begin{proof}
What is the Dirac Hamiltonian?
Recall that we started the whole discussion by requiring that the Dirac equation should have the form
%
\begin{align}
i \partial_{t} \psi = H_D \psi
\,,
\end{align}
%
and the ansatz we used was
%
\begin{align}
H_D = \alpha \cdot \vec{p} + \beta M
\,,
\end{align}
%
and we found that for a massive particle we can write \(\alpha_{i}\) and \(\beta \) as 4-dimensional matrices, which in the Dirac representation are
%
\begin{subequations}
\begin{align}
\alpha_{i} = \left[\begin{array}{cc}
0 & \sigma_{i} \\
\sigma_{i} & 0
\end{array}\right]
\qquad \text{and} \qquad
\beta = \left[\begin{array}{cc}
\mathbb{1} & 0 \\
0 & -\mathbb{1}
\end{array}\right]
\,.
\end{align}
\end{subequations}

So, the Hamiltonian is a 4-dimensional matrix, which looks like
%
\begin{subequations}
\begin{align}
H_D = \left[\begin{array}{cc}
M & \vec{\sigma} \cdot \vec{p}\\
 \vec{\sigma} \cdot \vec{p} & -M
\end{array}\right]
\,.
\end{align}
\end{subequations}

So, let us compute the commutator: we get
%
\begin{align}
\qty[\vec{\alpha} \cdot \vec{p} + \beta M, \Sigma_3 ]
= \qty[\vec{\alpha}, \Sigma_{3}] \cdot \vec{p} + M \qty[\beta, \Sigma_3 ]
\,.
\end{align}

We can just compute the two matrix commutators, since the momentum and the mass are fixed. We find, for each component:
%
\begin{subequations}
\begin{align}
\qty[\alpha_{i}, \Sigma_{3}] =
\frac{1}{2}
\left[\begin{array}{cc}
0 & \sigma_{i} \\
\sigma_{i} & 0
\end{array}\right]
\left[\begin{array}{cc}
\sigma_3  & 0 \\
0 & \sigma_3
\end{array}\right]
- \frac{1}{2}
\left[\begin{array}{cc}
\sigma_3  & 0 \\
0 & \sigma_3
\end{array}\right]
\left[\begin{array}{cc}
0 & \sigma_{i} \\
\sigma_{i} & 0
\end{array}\right]
=  \frac{1}{2}
\left[\begin{array}{cc}
0 & \qty[\sigma_3, \sigma_{i}] \\
\qty[\sigma_3, \sigma_{i}] & 0
\end{array}\right]
\,,
\end{align}
\end{subequations}
%
and we know that this is given by\footnote{A more elegent way to deal with these computations is to intrpret them in terms of tensor products of Pauli matrices: we have, for instance, \(\alpha_{i} = \sigma_{x} \otimes \sigma_{i}\), and there are explicit formulas for products in the form \((\sigma_{a } \otimes \sigma_{b})(\sigma_{c } \otimes \sigma_{d}) \) \cite[]{agartthaCommutatorsTensorProduct2018}.}
%
\begin{align}
\qty[\sigma_{3}, \sigma_{i}] = 2i \epsilon_{3ik} \sigma_{k}
\,,
\end{align}
%
so in the full expression we find
%
\begin{align}(\sigma_{a } \otimes \sigma_{b})
\qty[\alpha_{i}, \Sigma_3]
=
i \epsilon_{3ik} \alpha_{k}
\,,
\end{align}
%
while \(\beta \) and \(\Sigma_3 \) are both diagonal, and therefore they commute. So, we can finally say that
%
\begin{align} \label{eq:spin-conservation-dirac}
\qty[H_D, \Sigma_3 ] = i \epsilon_{3jk} p_{j} \alpha_{k}
\,,
\end{align}
%
which is not zero \emph{unless} \(\vec{p}\) is oriented along the \(z\) axis.
This, however, is not a covariant condition.
\end{proof}

So, we define the \textbf{helicity} as the projection of the spin along the direction of motion:
%
\begin{align}
\Sigma_{p} = \frac{\vec{\Sigma} \cdot \vec{p}}{\abs{p}} = \vec{\Sigma} \cdot \hat{p}
\,.
\end{align}

The helicity is a good quantum number. It commutes with the Dirac Hamiltonian, whereas \(\Sigma_3 \) does not.
So, the eigenvalue of \(\Sigma_{p}\) is conserved: this makes it a good quantum number, since it provides a reliable description of the state.

From the result we found before we can see that what we are basically doing here is calculating \(\Sigma_{p}\) along the momentum, which is equivalent (after a rotation of the axes) to setting \(\vec{p} = \abs{p} \hat{z}\).
Then, from equation \eqref{eq:spin-conservation-dirac} we can see that \(\Sigma_{p}\) will commute with the Hamiltonian.

\todo[inline]{This is much simpler than the solution proposed in the professor's notes, but just as valid, I think: after all, we can choose the coordinates in which we perform the calculation as we wish since in the end we get a covariant result.}

\subsection{Pauli-Lubanski vector and helicity}

We define the following pseudovector:\footnote{Pseudovector means that it is even under parity transformations \(P : \vec{x} \to - \vec{x}\).

More formally, we can say that it transforms under spatial rotations like a vector density: if \(R \in O(3)\), a regular vector transforms like \(v' = R v\), but a pseudovector transforms like \(w' = (\det R) Rw \). So, while a vector is flipped by a parity: \(Pv = - v\) a pseudovector is not: \(P w = w\).

We can obtain pseudovectors by taking the cross product of regular vectors. The magnetic field \(\vec{B}\) is an example of a pseudovector.
}
%
\begin{align}
\omega^{\mu } = \frac{1}{2} \epsilon^{\mu \nu \rho \sigma } J_{\nu \rho } p_{\sigma }
\,,
\end{align}
%
where \(J_{\nu \rho }\) is the total angular momentum tensor, which includes both an angular and spin component:
%
\begin{align}
J_{\nu \rho } = L_{\nu \rho } + \Sigma_{\nu \rho }
\qquad \text{where} \qquad
L_{\nu \rho } = 2 x_{[\nu } p_{\rho  ]}
\,.
\end{align}

There are two terms in the expression for \(\omega^{\mu }\), but the angular momentum one vanishes: we have
%
\begin{align}
\frac{1}{2} \epsilon^{\mu \nu \rho \sigma }L_{\nu \rho } p_{\sigma }
=
\frac{1}{2} \epsilon^{\mu \nu \rho \sigma } \qty(x_{\nu }p_{\rho } - x_{\rho } p_{\nu }) p_{\sigma } =0
\,,
\end{align}
%
since in both cases we have the contraction of two copies of the momentum, which are symmetric in their indices, with the antisymmetric tensor.

Now, let us move to the rest frame of the particle, so that \(p^{\mu } = (M, \vec{0})\).
Then, we will have
%
\begin{align}
\omega^{\mu } = \frac{M}{2} \epsilon^{\mu \nu \rho 0} \Sigma_{\nu \rho }
\,.
\end{align}

Therefore, this vector is purely spatial since setting \(\mu =0\) means the RHS vanishes: so, \(\omega^{0} = 0\). On the other hand, we have
%
\begin{align}
\omega^{i} = - \frac{M}{2} \epsilon^{0i \nu \rho } \Sigma_{\nu \rho } = - \frac{M}{2} \epsilon^{i j k } \Sigma_{j k } = - M \Sigma^{i}
\,,
\end{align}
%
where we applied the definition of the spin generator \(\Sigma^{i}\) \eqref{eq:rotation-spin-generator-definition}, and we moved from the four-dimensional Kronecker symbol to the three-dimensional one: we are allowed to move to three-vector indices since the case in which they are equal to zero is excluded by the first index being zero.

\todo[inline]{There is an extra minus sign due to the odd permutation of indices in the Levi-Civita symbol (thanks Andrea!): this does not change the observable \(\abs{\Sigma }^2\), but it is reported incorrectly in the professor's notes. See \cite[eqs 9.121 to 9.124]{dauriaSpecialRelativityFeynman2011}.}

So, we can take the square modulus of \(\omega^{\mu }\) in the rest frame, and normalize it by \(M^2\). Since this is a 4-vector this will be a covariant quantity:
%
\begin{subequations}
\begin{align}
\eval{\frac{\omega_{\mu } \omega^{\mu }}{M^2}}_{\text{rest frame}}
= \Sigma^{i} \Sigma_{i} = - \Sigma^{i} \Sigma^{i} = -\frac{1}{4} \left[\begin{array}{cc}
\sigma_{i} \sigma_{i} & 0 \\
0 & \sigma_{i } \sigma_{i}
\end{array}\right]
= - \frac{3}{4} \mathbb{1}
\,. \marginnote{Factor \(3\) since there is a sum over \(i\).}
\end{align}
\end{subequations}

This is consistent with the expression we know from quantum mechanics, that is, the eigenvalue of \(s^2\) being \(s (s+1)\) with \(s = 1/2\).
The negative sign has no particular physical meaning: it is due to the fact that our metric signature gives spacelike vectors negative norms.

So, the PL vector gives us a way to define the spin of a particle in a relativistic manner.

We can use a unit vector \(n^{\mu }\) which is orthogonal to the momentum of the particle, that is, such that \(n^{\mu } p_{\mu }=0\) and \(n^{\mu } n_{\mu }=-1\), to define a spin in a generic direction:
%
\begin{align}
\eval{\frac{\omega^{\mu }n_{\mu }}{M}}_{\text{rest frame}} = - \vec{\Sigma} \cdot \vec{n}
\,.
\end{align}

We can also define the helicity in this frame work, using the vector
%
\begin{subequations}
\begin{align}
n^{\mu }_{p} = \frac{1}{M} \left[\begin{array}{c}
\abs{p} \\
\omega_{p} \hat{p}
\end{array}\right]
\,,
\end{align}
\end{subequations}
%
which has square modulus \((\abs{p}^2 - \omega_{p}^2) / M^2 = -1\), and is orthogonal to the momentum: their product is \(\propto \abs{p} \omega_{p}  - \omega_{p} \abs{p} = 0\).

For some geometrical intuition: if we trace out a 2D spacetime diagram with the directions of time and \(\hat{p}\), the momentum will be some timelike vector, while this \(n^{\mu }_{p}\) will be its reflection with respect to the light-like axis.

With this, we recover
%
\begin{align}
\eval{\frac{\omega^{\mu }n_{\mu , p}}{M}}_{\text{rest frame}}
= - \Sigma_{p} = - \vec{\Sigma} \cdot \hat{p}
\,.
\end{align}
%
\subsection{Chirality}

We can define another matrix beyond the \(\gamma^{\mu }\): it is
%
\begin{align} \label{eq:gamma5-definition}
\gamma_{5} = - \frac{i}{4} \epsilon_{\mu \nu \rho \sigma } \gamma^{\mu } \gamma^{\nu } \gamma^{\rho } \gamma^{\sigma } = + i \gamma^{0} \gamma^{1} \gamma^{2} \gamma^{3}
\,.
\end{align}

Note the sign convention: we choose \(\epsilon^{0123} = +1 \), which means that we get \(\epsilon_{0123} = -1\), since we must lower an odd amount of spacelike indices.

\begin{claim}
The \(\gamma^{5}\) matrix is self adjoint:
%
\begin{align}
\gamma_{5} = \qty(\gamma_{5})^\dag
\,,
\end{align}
%
it squares to the identity:
%
\begin{align}
\qty(\gamma_5 )^2 = \mathbb{1}
\,,
\end{align}
%
and it anticommutes with the other gamma matrices:
%
\begin{align}
\qty{\gamma^{\mu } , \gamma_5 } = 0
\,.
\end{align}
\end{claim}

\begin{proof}
We will need to move a few matrices around, so first let us establish that, since
%
\begin{align}
\frac{1}{2} \qty{\gamma^{\mu }, \gamma^{\nu }} = \eta^{\mu \nu }
\,,
\end{align}
%
we have that the square of \(\gamma^{0} \) is \(\mathbb{1}\), while the square of \(\gamma^{i} \) is \(- \mathbb{1}\).

On the other hand, we can switch the places of two different \(\gamma \) matrices as long as we switch the global sign. So, first of all let us show that the square of the \(\gamma_5 \) matrix is the identity: we write a number in place of the \(\gamma \), for clarity.
%
\begin{subequations}
\begin{align}
\qty(\gamma_{5})^2 &= i^2 01230123 = - 01230123  \\
&= (-)^{4} 00123123 = (-)^{6} 00112323 = (-)^{7} 00112233  \\
&= - \mathbb{1} (-\mathbb{1})^3 = \mathbb{1}
\,.
\end{align}
\end{subequations}

For the self-adjointness, we have
%
\begin{subequations}
\begin{align}
\gamma_5 ^\dag &= + \frac{i}{4} \epsilon_{\mu \nu \rho \sigma }
\gamma^{\sigma \dag} \gamma^{\rho \dag} \gamma^{\nu \dag} \gamma^{\mu \dag} \\
&= \frac{i}{4} \epsilon_{\mu \nu \rho \sigma } \gamma^{\sigma } \gamma^{\rho } \gamma^{\nu } \gamma^{\mu }  \\
&= \frac{i}{4} \epsilon_{\mu \nu \rho \sigma }
\gamma^{\mu } \gamma^{\nu } \gamma^{\rho } \gamma^{\sigma }
\,.
\end{align}
\end{subequations}

Here we used the fact that the Dirac matrices are self-adjoint, and that we can get from the configuration \(\mu \nu \rho \sigma \) to \(\sigma \rho \nu \mu \) in an even number of ``hops''. At each hop we can exchange the matrices by changing sign, like before, so there is no issue. The matrices we are exchanging are surely different since they are multiplied by the Kronecker symbol.

For the anticommutation: say we have the expression \(\gamma^{\mu } \gamma_5 \) for some \(\mu \) and we want to bring the \(\gamma^{\mu } \) to the other side. We can commute it with the Kronecker symbol and itself, and we need to anticommute it with three matrices different from itself. This gives us three minus signs, so the result has an opposite sign to what we started with: \(\gamma^{\mu } \gamma_5 = - \gamma_5 \gamma^{\mu }\), what we wanted to prove.
\end{proof}

In the Dirac representation,
%
\begin{subequations}
\begin{align}
\gamma_5 = \left[\begin{array}{cc}
0 & \mathbb{1} \\
\mathbb{1} & 0
\end{array}\right]
\,.
\end{align}
\end{subequations}
%

\begin{claim}
The \(\gamma_{5}\) matrix commutes with the spin tensor \(\Sigma^{\mu \nu }\).
\end{claim}

\begin{proof}
Recall that \(\Sigma^{\mu \nu} \propto \qty[\gamma^{\mu}, \gamma^{\nu }]\). Then, as before writing the indices without the \(\gamma \)s:
%
\begin{subequations}
\begin{align}
\qty[\gamma_5, \Sigma^{\mu \nu }] &\propto 5 \mu \nu - 5 \nu \mu - \mu \nu 5 + \nu \mu 5   \\
&= -\mu 5 \nu + \nu 5 \mu + \mu 5 \nu - \nu 5 \mu  =0
\,,
\end{align}
\end{subequations}
%
where we anticommuted \(\gamma_5 \) with \(\gamma^{\mu }\) and \(\gamma^{\nu }\).
\end{proof}

The fact that these commute means that they can be simultaneously diagonalized.

This allows us to classify the eigenvectors by the eigenvalue f \(\gamma_5 \) instead of the spin.

The \(N=4\) spinorial representation is reducible: it is the sum of 2 2-dimensional representations.

The \(\gamma_5 \) matrix is called the \textbf{chirality} operator, using it we can define the projectors
%
\begin{align} \label{eq:chirality-projection-operators}
P_{R, L} = \frac{\mathbb{1} \pm \gamma_5 }{2}
\,,
\end{align}
%
where the minus corresponds to the left projector, while the plus corresponds to the right.

\begin{claim}
These are indeed a complete set of orthogonal projectors: they are idempotent, orthogonal and they sum to the identity.

Also, they are self adjoint.
\end{claim}

\begin{proof}
First, let us show idempotence; we denote either of \(L\) or \(R\) by \(x\).

\begin{align}
P_x^2 = \frac{1}{4} \qty(1 \pm 2 \gamma_5  + \gamma_5^2)
= \frac{1}{4} \qty(2 \mathbb{1} \pm 2 \gamma_5 ) = P_x
\,.
\end{align}

Then, to see orthogonality:
%
\begin{align}
P_L P_R = \frac{1}{4} \qty(\mathbb{1} - \gamma_5 ) \qty(\mathbb{1} + \gamma_5 ) = \frac{1}{4} \qty(\mathbb{1}^2 - \gamma_5^2) = 0
\,.
\end{align}

Finally, they sum to the identity:
%
\begin{align}
P_L + P_R = \frac{1}{2} \qty(\mathbb{1} - \gamma_5 ) + \frac{1}{2} \qty(1 + \gamma_5) = \mathbb{1}
\,.
\end{align}

They are self-adjoint because \(\mathbb{1}\) and \(\gamma_5 \) are.
\end{proof}

We can then project any Dirac spinor into the left or right chiral subspaces by applying these matrices.

The projections onto the right-chiral subspace will have a \(+1 \) eigenvalue for \(\gamma_5 \), the projections onto the left-chiral subspace will have eigenvalue \(-1\).

These chiral spinors are the irreducible \(N=2\) representations which constitute the full spinor.

For the massless case we could also have used a \(N=2\) representation for the full space, the Weyl spinor. This would have behaved like a left or right chiral spinor.

Finally, we can define the \textbf{conjugate chiral spinors}:
%
\begin{subequations}
\begin{align}
\overline{\psi}_{L} &= \qty(\psi_{L} ^\dag) \gamma^{0}
= \psi ^\dag P_L \gamma^{0} = \overline{\psi} P_R \\
\overline{\psi}_{R} &= \qty(\psi_{R} ^\dag) \gamma^{0}
= \psi ^\dag P_R \gamma^{0} = \overline{\psi} P_L
\,,
\end{align}
\end{subequations}
%
where we used the fact that
%
\begin{align}
\gamma^{0} \qty(1 \pm \gamma_5 )
= \qty(1 \mp \gamma_5 ) \gamma^{0}
\,,
\end{align}
%
since the identity commutes with \(\gamma^{0}\), while \(\gamma^{5}\) anticommutes with it.
\end{document}


% Copyright (c) 2012-2020, Yegor Bugayenko
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions
% are met: 1) Redistributions of source code must retain the above
% copyright notice, this list of conditions and the following
% disclaimer. 2) Redistributions in binary form must reproduce the above
% copyright notice, this list of conditions and the following
% disclaimer in the documentation and/or other materials provided
% with the distribution. 3) Neither the name of Yegor Bugayenko nor
% the names of other contributors may be used to endorse or promote
% products derived from this software without specific prior written
% permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
% NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
% THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
% INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
% SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
% HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
% STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
% OF THE POSSIBILITY OF SUCH DAMAGE.
%
\documentclass[12pt]{article}
\usepackage{amsmath}
\begin{document}
\title{Source Code Volatility (SCV)\\to Spot Dead Code}
\author{Yegor Bugayenko}
\maketitle

\section{Introduction}

Volatility of source code is an experimental metric that
shows how big is the difference between actively and rarely changed (possibly dead)
code. It is assumed that a big percentage of dead code is
an indicator of maintainability problems in the project.

\section{Details}

First, by looking at Git history,
it is observed how many times every source code file out of $N$ was touched
during the lifetime of the repository (excluding the files that don't exist
in the repository anymore):

\begin{eqnarray}
T = [t_1, t_2, \dots, t_N]
\end{eqnarray}

Then, the entire interval between $\check{T}$ (the maximum value)
and $\hat{T}$ (the minimum value) is divided to $Z$ equivalent groups:

\begin{align}
G &= [g_1, g_2, \dots, g_{Z}] \\
\delta &= ( \check{T} - \hat{T} ) / Z \\
g_j &= \sum_{i=1}^N [ j(\delta-1) < t_i < j\delta ]
\end{align}

Then, the mean $\mu$ is calculated as:

\begin{eqnarray}
\mu = \frac{1}{Z}\sum_{j=1}^{Z}{g_j}
\end{eqnarray}

Finally, the variance is calculated as:

\begin{eqnarray}
Var(g) = \frac{1}{Z}\sum_{j=1}^{Z}{|g_j - \mu|^2}
\end{eqnarray}

The variance $Var(g)$ is the volatility of the source code. The smaller
the volatility the more cohesive is the repository and the smaller
the amount of the dead code inside it.

\end{document}


\documentclass[11pt]{amsbook}

\usepackage{../HBSuerDemir}	% ------------------------

\setcounter{tocdepth}{3}

\usepackage{fancyhdr} % Header/Footer
\pagestyle{fancy}
\thispagestyle{fancy}
\fancyfoot{}
\fancyfoot[L]{\footnotesize
	Freshman Calculus by Suer \& Demir  \textbf{DRAFT} \\
	\LaTeX ~by Haluk Bingol
	\href{http://www.cmpe.boun.edu.tr/~bingol}
	{http://www.cmpe.boun.edu.tr/bingol}
	%\large
	%\footnotesize
	\today}
\fancyfoot[R]{{\thepage} of \pageref{LastPage}}

\begin{document}

% ++++++++++++++++++++++++++++++++++++++
\hPage{b1p1/3}
% ++++++++++++++++++++++++++++++++++++++

\centerline{\thepage}
\bigskip

\begin{hEnumerateRoman}

	\item
	$r_{1}+r_{2}
	\hPairingParan{\dfrac{p_{1}}{q_{1}}
		+ \dfrac{p_{2}}{q_{2}}
		= \dfrac{p_{1} q_{2} + p_{2} q_{1}}
		{q_{1} q_{2}}}$,

	\item
	$r_{1}-r_{2}
	\hPairingParan{\dfrac{p_{1}}{q_{1}}
		- \dfrac{p_{2}}{q_{2}}
		= \dfrac{p_{1} q_{2} - p_{2} q_{1}}
		{q_{1} q_{2}}}$,

	\item
	$r_{1} \cdot r_{2}
	\hPairingParan{\dfrac{p_{1}}{q_{1}}
		\cdot \dfrac{p_{2}}{q_{2}}
		= \dfrac{p_{1} p_{2}}
		{q_{1} q_{2}}}$,

	\item
	$r_{1}:r_{2}
	\hPairingParan{\dfrac{p_{1}}{q_{1}}
		: \dfrac{p_{2}}{q_{2}}
		= \dfrac{p_{1} q_{2}}
		{q_{1} p_{2}}}$
	\\
	\\
\end{hEnumerateRoman}
are all rational.
\\

\begin{cor}
Between any two distinct rational numbers
there exists at least one rational number,
hence infinitely many.
\\

\begin{proof}\renewcommand{\qedsymbol}{}
	Let the given rational numbers be $r_{1}$ and $r_{2}$ :
	$r_{1} + r_{2}$ rational
	$\Longrightarrow$
	$\dfrac{1}{2}(r_{1} + r_{2})$ is rational.
	(why this arithmetic mean is between $r_{1}$ and $r_{2}$?)
	\\
	This process can be continued indefinitely.
	\\
\end{proof}
\end{cor}

% -------------------------------------------------------------------
\subsection{Irrational numbers}
\label{subsec:IrrationalNumbers}

A number which is not rational is called an
\hDefined{irrational number}.
Since any cyclic decimal expansion is a rational number,
then non cyclic ones represent irrational numbers:
\\
\begin{align*}
0,81881888188881\cdots
&\text{ (Number of 8's increases by 1 in each step)} \\ \bigskip
4,303003000300003\cdots \\
&
\end{align*}

The existence of irrational numbers may also be shown
by the following theorem:

% =======================================================
\end{document}


% !TeX root = constructions.tex

\chapter{How to (Almost) Square a Circle}\label{c.squaring}

\section{Approximations to $\pi$}\label{s.square-intro}

To square a circle the length $\sqrt{\pi}$ must be constructed, however, $\pi$ is \emph{transcendental}, meaning that it is not the solution of any algebraic equation.

This chapter brings three constructions of approximations to $\pi$. The following table shows the formulas of the lengths that are constructed, their approximate values, the difference between these values and the value of $\pi$, and the error in meters that results if the approximation is used to compute the circumference of the earth given that its radius is $6378$ km.
\[
\renewcommand{\arraystretch}{2.2}
\begin{array}{|l|c|c|c|c|}
\hline
\textrm{Construction} & \textrm{Formula} &\textrm{Value} & \textrm{Difference} & \textrm{Error (m)}\\\hline
\pi & & 3.14159265359 & - & -\\\hline
\textrm{Kochansky} & \sqrt{\disfrac{40}{3}-2\sqrt{3}}&
  3.14153338705 & 5.932 \times 10^{-5} & 756\\\hline
\textrm{Ramanujan}\; 1 & \disfrac{355}{113} &
  3.14159292035 &2.667  \times 10^{-7}&3.4\\\hline
\textrm{Ramanujan}\; 2 &\left(9^2+\disfrac{19^2}{22}\right)^{1/4}&
  3.14159265258 & 1.007 \times 10^{-9}& 0.013\\\hline
\end{array}
\]
Kochansky's construction from $1685$ can be found in \cite{bold}.

Ramanujan's constructions from $1913$ can be found in \cite{ramanujan1,ramanujan2}.

In the constructions in this chapter we need to divide a line segment into three parts; here we show how the division of two lengths can be constructed. Given a line segment of length $1$ and line segments of lengths $a,b$, by similar triangles:
\[
\disfrac{1}{b}=\disfrac{\overline{OD}}{a}\,,
\]
so $\overline{OD}=\disfrac{a}{b}$.

\begin{center}
\begin{tikzpicture}[scale=1.1]
%\clip (-.6,-1) rectangle (4,3);
\draw[name path=horz] (0,0) coordinate (o) -- (7,0);
\fill (o) circle(1.5pt) node[left] {$O$};
\fill (6,0) circle(1.5pt) coordinate (a) node[below] {$A$};
\draw (0,0) -- (30:5.5);
\fill (30:3) circle(1.5pt) coordinate (c) node[above] {$C$};
\fill (30:5) circle(1.5pt) coordinate (b) node[above] {$B$};
\draw (a) -- (b);
\path[name path=par] (c) -- +($(a)-(b)$);
\path[name intersections={of=par and horz,by=d}];
\fill (d) circle(1.5pt) node[below] {$D$};
\draw (c) -- (d);
\draw[<->] (-.4,.5) -- node[fill=white] {$b$} +(30:5.2);
\path (o) -- node[above] {$1$} (c);
\draw[<->] (0,-.8) -- node[fill=white] {$a$} +(6,0);
\path (o) -- node[below] {$a/b$} (d);
\end{tikzpicture}
\end{center}

\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Kochansky's construction}

\subsection{The construction}

Construct three circles:
\begin{enumerate}
\item Construct a unit circle centered at $O$, let $\overline{AB}$ be a diameter and construct a tangent to the circle at $A$.
\item Construct a unit circle centered at $A$. Its intersection with the first circle is $C$.\footnote{For the second and third circles, the diagram only shows the arc that intersects the previous circle.}
\item Construct a unit circle centered at $C$. Its intersection with the second circle is $D$.
\end{enumerate}
Construct $\overline{OD}$ and denote its intersection with the tangent by $E$.

From $E$ construct $F,G,H$, each at distance $1$ from the previous point; then $\overline{AH}=3-\overline{EA}$.

Construct $\overline{BH}$.

Claim: $\overline{BH}=\sqrt{\disfrac{40}{3}-2\sqrt{3}}\approx \pi$.
\begin{center}
\begin{tikzpicture}[scale=.9]
% Scale at 4

% Coordinates of circle
\coordinate (O) at (0,0);
\coordinate (A) at (0,-4);
\coordinate (B) at (0,4);
\fill (O) circle(2pt) node[above right] {$O$};
\fill (A) circle(2pt) node[below right] {$A$};
\fill (B) circle(2pt) node[above right] {$B$};
\draw (A) rectangle +(12pt,12pt);

% Draw circle and diameter
\node [draw,circle through=(A),name path=circle] at (O) {};
\draw (A) --  node[right] {$1$} (O) -- node[right] {$1$} (B);

% Draw tangent at A
\draw[name path=tangent] ($(A)+(-4.5,0)$) -- ($(A)+(10.5,0)$);

% Draw arc centered at A which intersects circle at C
\draw[name path=Aarc] (O)
   arc [start angle=90,end angle=220,radius=4];
\path[name intersections={of=circle and Aarc,by=C}];
\fill (C) circle(2pt) node[left,xshift=-4pt] {$C$};

% Draw arc centered at C which intersects the first arc at D
\draw[name path=Carc] ($(C)+(260:4)$)
   arc [start angle=260,end angle=280,radius=4];
\path[name intersections={of=Carc and Aarc,by=D}];
\fill (D) circle(2pt) node[below left] {$D$};

% Draw O--D which intersects the tangent at E
\draw[name path=OD] (O) -- (D);
\path[name intersections={of=tangent and OD,by=E}];
\fill (E) circle(2pt) node[above left] {$E$};

% Find point H at length 3 from E
\coordinate (F) at ($(E)+(4,0)$);
\fill (F) circle(2pt) node[above right,xshift=4pt] {$F$};
\coordinate (G) at ($(F)+(4,0)$);
\fill (G) circle(2pt) node[above] {$G$};
\coordinate (H) at ($(G)+(4,0)$);
\fill (H) circle(2pt) node[above] {$H$};

% Draw BH of length approximately pi
\draw (B) -- (H);

\draw[<->] ($(E)+(0,-.8)$) -- node[fill=white] {$1$} ($(F)+(0,-.8)$);
\draw[<->] ($(F)+(0,-.8)$) -- node[fill=white] {$1$} ($(G)+(0,-.8)$);
\draw[<->] ($(G)+(0,-.8)$) -- node[fill=white] {$1$} ($(H)+(0,-.8)$);

\end{tikzpicture}
\end{center}

\newpage

\subsection{The proof}

Extract the following diagram from the first one. Dashed line segments have been added. Since all the circles are unit circles, it is easy to see that the length of each dashed line segment is $1$. It follows that  $\overline{AOCD}$ is a rhombus so its diagonals are perpendicular to and bisect each other at $K$ and $\overline{AK}=\frac{1}{2}$.
\begin{center}
\begin{tikzpicture}[scale=1.25]
% Scale at 4

\clip (-4.5,-6.5) rectangle +(5,7);
% Coordinates of circle
\coordinate (O) at (0,0);
\coordinate (A) at (0,-4);
\coordinate (B) at (0,4);

% Draw circle
\node [circle through=(A),name path=circle] at (O) {};
\draw ($(O)+(200:4)$) arc [start angle=200,end angle=280,radius=4];

% Draw tangent at A
\draw[name path=tangent] ($(A)+(-4.5,0)$) -- ($(A)+(10.5,0)$);
\draw (A) rectangle +(6pt,6pt);

% Draw arc centered at O which intersects circle at C
\draw[name path=Aarc] (O)
   arc [start angle=90,end angle=220,radius=4];
\path[name intersections={of=circle and Aarc,by=C}];

% Draw arc centered at C which intersects the first arc at D
\draw[name path=Carc] ($(C)+(260:4)$)
   arc [start angle=260,end angle=280,radius=4];
\path[name intersections={of=Carc and Aarc,by=D}];

% Draw O--D which intersects the tangent at E
\draw[name path=OD] (O) -- (D);
\path[name intersections={of=tangent and OD,by=E}];

% Find point H at length 3 from E
\coordinate (F) at ($(E)+(4,0)$);
\coordinate (G) at ($(F)+(4,0)$);
\coordinate (H) at ($(G)+(4,0)$);

% Draw BH of length approximately pi
\draw (B) -- (H);

\draw[very thick,dashed] (A) -- (O) -- (C) -- (D) -- cycle;
\draw[very thick,dashed,name path=AC] (A) -- (C);

\node[above left,yshift=10pt,xshift=2pt] at (A) {$60^\circ$};
\node[left,yshift=10pt,xshift=-20pt] at (A) {$30^\circ$};

\path[name intersections={of=AC and OD,by=K}];
\draw[rotate=-30] (K) rectangle +(6pt,6pt);

\path (A) -- node[above,xshift=2pt,yshift=2pt] {$1/2$} (K);
\path (A) -- node[below,xshift=-10pt] {$1/\sqrt{3}$} (E);

\fill (O) circle(1.25pt) node[above right] {$O$};
\fill (A) circle(1.25pt) node[below right] {$A$};
\fill (B) circle(1.25pt) node[above right] {$B$};
\fill (C) circle(1.25pt) node[left,xshift=-4pt] {$C$};
\fill (D) circle(1.25pt) node[below left] {$D$};
\fill (E) circle(1.25pt) node[above left] {$E$};
\fill (F) circle(1.25pt) node[above right,xshift=4pt] {$F$};
\fill (G) circle(1.25pt) node[above] {$G$};
\fill (H) circle(1.25pt) node[above] {$H$};
\fill (K) circle(1.25pt) node[above,yshift=4pt] {$K$};
\end{tikzpicture}
\end{center}
The diagonal $\overline{AC}$ forms two equilateral triangles $\triangle OAC, \triangle DAC$ so $\angle OAC=60^\circ$. Since tangent forms a right angle with the radius $\overline{OA}$, $\angle KAE=30^\circ$. Now:
\begin{displaymath}
\renewcommand{\arraystretch}{1.5}
\begin{array}{lcl}
\disfrac{1/2}{\overline{EA}}&=&
\cos 30^\circ=\disfrac{\sqrt{3}}{2}\\
\overline{EA}&=&\disfrac{1}{\sqrt{3}}\\
\overline{AH}&=&3-\overline{EA}=\left(3-\disfrac{1}{\sqrt{3}}\right)
=\disfrac{3\sqrt{3}-1}{\sqrt{3}}\\
\end{array}
\end{displaymath}

Returning to the first diagram, we see that $\triangle ABH$ is a right triangle:
\begin{displaymath}
\renewcommand{\arraystretch}{2}
\begin{array}{lcl}
\overline{BH}^2&=&\overline{OB}^2+\overline{AH}^2\\
&=&4+\disfrac{9\cdot 3 -6\sqrt{3}+1}{3}=\disfrac{40}{3}-2\sqrt{3}\\
\overline{BH}&=&\sqrt{\disfrac{40}{3}-2\sqrt{3}}\approx 3.141533387\approx \pi\,.
\end{array}
\end{displaymath}

\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Ramanujan's first construction}

\subsection{The construction}

Construct a unit circle centered at $O$ and let $\overline{PR}$ be a diameter.

$H$ bisects $\overline{PO}$ and $T$ trisects $\overline{RO}$.

Construct a perpendicular at $T$ that intersects the circle at $Q$.

Construct a chord $\overline{RS}=\overline{QT}$.

Construct $\overline{PS}$.

Construct a line parallel to $\overline{RS}$ from $T$ that intersects $\overline{PS}$ at $N$.

Construct a line parallel to $\overline{RS}$ from $O$ that intersects $\overline{PS}$ at $M$.

Construct the chord $\overline{PK}=\overline{PM}$.

Construct the tangent at $P$ of length $\overline{PL}=\overline{MN}$.

Connect the points $K,L,R$.

Find point $C$ such that $\overline{RC}$ is equal to $\overline{RH}$.

Construct $\overline{CD}$ parallel to $\overline{KL}$ that intersects $\overline{LR}$ at $D$.

Claim: $\overline{RD}^2=\disfrac{355}{113}\approx \pi$.

\begin{center}
\begin{tikzpicture}[scale=1.1,align=left]
\clip (-6,-5.1) rectangle +(11.5,10.2);
% Draw circle and horizontal diameter
\draw[name path=circle] (0,0)  coordinate (o) node[below] {$O$} circle[radius=5cm];
\draw (-5,0) coordinate (p) node[left] {$P$} -- (5,0) coordinate (r) node[right] {$R$};
\fill (o) circle (1pt);
\fill (p) circle (1pt);
\fill (r) circle (1pt);
\fill (-2.5,0) coordinate (h) node[below] {$H$} circle (1pt);
\fill (10/3,0) coordinate (t) node[below left] {$T$} circle (1pt);
\path (p) -- node[above,xshift=10pt] {$1/2$} (h) -- node[above] {$1/2$} (o) -- node[above] {$2/3$} (t) -- node[above] {$1/3$} (r);

% Draw perpendicular TQ
\path[name path=tq] (t) -- +(0,5);
\path[name intersections={of=tq and circle,by=q}];
\draw (t) -- node[left] {$a$} (q) node[above] {$Q$};
\fill (q) circle (1pt);

% Draw chord RS and line PS
\path[name path=tq] (t) -- +(0,5);
\path[name intersections={of=tq and circle,by=q}];
\path[name path=rcirc] (r) let \p1 = ($ (t) - (q) $) in circle ({veclen(\x1,\y1)});
\path[name intersections={of=rcirc and circle,by=s}];
\draw (r) -- node[right] {$a$} (s);
\fill (s) node[above right] {$S$} circle (1pt);
\draw[name path=ps] (p) -- (s);

% Draw TN
\path[name path=tn] (t) -- +($(s)-(r)$);
\path[name intersections={of=ps and tn,by=n}];
\draw (t) -- (n);
\fill (n) node[above] {$N$} circle (1pt);

% Draw OM
\path[name path=om] (o) -- +($(s)-(r)$);
\path[name intersections={of=ps and om,by=m}];
\draw (o) -- (m);
\fill (m) node[above left] {$M$} circle (1pt);
\path (p) -- (m);
\path (m) -- (n);

% Draw chord PK
\draw (p) -- +(-62.3:4.64) coordinate (k) node[below left] {$K$};

% Draw tangent PL
\draw let \p1 = ($ (m) - (n) $), \n1 = {veclen(\x1,\y1)} in (p) -- (-5,-\n1) coordinate (l) node[left] {$L$};

% Connect L and K to R
\draw (r) -- (l) -- (k) -- cycle;

% Find point C on RK
\coordinate (c) at ($(r)!7.5cm!(k)$);
\path (r) -- (c);
\fill (c) node[below] {$C$} circle (1pt);

% Draw CD
\path[name path=cd] (c) -- +($(l)-(k)$);
\path[name path=lr] (l) -- (r);
\path[name intersections={of=cd and lr,by=d}];
\draw (c) -- (d);
\fill (d) node[above,xshift=2pt] {$D$} circle (1pt);
\path (r) -- (d);

\draw[rotate=90] (t) rectangle +(8pt,8pt);
\draw[rotate=-160] (s) rectangle +(8pt,8pt);
\draw[rotate=28] (k) rectangle +(8pt,8pt);
\end{tikzpicture}
\end{center}

\newpage

\subsection{The proof}

By Pythagoras' theorem on $\triangle QOT$:
\[
\overline{QT} = \sqrt{1^2-\left(\frac{2}{3}\right)^2}=\frac{\sqrt{5}}{3}\,.
\]
$\triangle PSR$ is a right triangle because it subtends a diameter. By Pythagoras theorem:
\[
\overline{PS} = \sqrt{2^2-\left(\frac{\sqrt{5}}{3}\right)^2}=\sqrt{4-\frac{5}{9}}=\frac{\sqrt{31}}{3}\,.
\]
$\triangle MPO\sim \triangle SPR$ so:
\begin{form}{2.2}
\disfrac{\overline{PM}}{\overline{PO}}&=&\disfrac{\overline{PS}}{\overline{PR}}\\
\disfrac{\overline{PM}}{1}&=&\disfrac{\sqrt{31}/3}{2}\\
\overline{PM}&=&\disfrac{\sqrt{31}}{6}\\
\overline{PK}&=&\overline{PM}=\disfrac{\sqrt{31}}{6}\,.
\end{form}
$\triangle NPT\sim \triangle SPR$ so:

\begin{form}{2.2}
\disfrac{\overline{PN}}{\overline{PT}}&=&\disfrac{\overline{PS}}{\overline{PR}}\\
\disfrac{\overline{PN}}{5/3}&=&\disfrac{\sqrt{31}/3}{2}\\
\overline{PN}&=&\disfrac{5\sqrt{31}}{18}\\
\overline{MN}&=&\overline{PN}-\overline{PM}=\sqrt{31}\left(\disfrac{5}{18}-\disfrac{1}{6}\right) = \disfrac{\sqrt{31}}{9}\\
\overline{PL}&=&\overline{MN}=\disfrac{\sqrt{31}}{9}\,.
\end{form}

$\triangle PKR$ is a right triangle because it subtends a diameter. By Pythagoras's theorem:
\[
\overline{RK}=\sqrt{2^2-\left(\frac{\sqrt{31}}{6}\right)^2} = \frac{\sqrt{113}}{6}\,.
\]

$\triangle PLR$ is a right triangle because it $\overline{PL}$ is a tangent. By Pythagoras's theorem:
\[
\overline{RL}=\sqrt{2^2+\left(\frac{\sqrt{31}}{9}\right)^2} = \frac{\sqrt{355}}{9}\,.
\]

\newpage

$\overline{RC}=\overline{RH}=\displaystyle\frac{1}{3}+\frac{2}{3}+\frac{1}{2}=\frac{3}{2}$. Since $\overline{CD}$ is parallel to $\overline{LK}$, by similar triangles:
\begin{form}{2.2}
\disfrac{\overline{RD}}{\overline{RC}}&=&\disfrac{\overline{RL}}{\overline{RK}}\\
\disfrac{\overline{RD}}{3/2}&=&\disfrac{\sqrt{355}/9}{\sqrt{113}/6}\\
\overline{RD}&=&\sqrt{\disfrac{355}{113}}\,.
\end{form}

Here is the construction with line segments labeled with their lengths:

\begin{center}
\begin{tikzpicture}[scale=1.1,align=left]
\clip (-6,-5.1) rectangle +(11.5,10.2);
% Draw circle and horizontal diameter
\draw[name path=circle] (0,0)  coordinate (o) node[below] {$O$} circle[radius=5cm];
\draw (-5,0) coordinate (p) node[left] {$P$} -- (5,0) coordinate (r) node[right] {$R$};
\fill (o) circle (1pt);
\fill (p) circle (1pt);
\fill (r) circle (1pt);
\fill (-2.5,0) coordinate (h) node[below] {$H$} circle (1pt);
\fill (10/3,0) coordinate (t) node[below] {$T$} circle (1pt);
\path (p) -- node[above,xshift=10pt] {$1/2$} (h) -- node[above] {$1/2$} (o) -- node[above] {$2/3$} (t) -- node[above] {$1/3$} (r);
% Draw chord RS and line PS
\path[name path=tq] (t) -- +(0,5);
\path[name intersections={of=tq and circle,by=q}];
\path[name path=rcirc] (r) let \p1 = ($ (t) - (q) $) in circle ({veclen(\x1,\y1)});
\path[name intersections={of=rcirc and circle,by=s}];
\draw (r) -- node[left] {$\sqrt{5}/3$} (s);
\fill (s) node[above right] {$S$} circle (1pt);
\draw[name path=ps] (p) -- node[above right,yshift=16pt] {$\sqrt{31}/3$} (s);
% Draw TN
\path[name path=tn] (t) -- +($(s)-(r)$);
\path[name intersections={of=ps and tn,by=n}];
\draw (t) -- (n);
\fill (n) node[above] {$N$} circle (1pt);
% Draw OM
\path[name path=om] (o) -- +($(s)-(r)$);
\path[name intersections={of=ps and om,by=m}];
\draw (o) -- (m);
\fill (m) node[above left] {$M$} circle (1pt);
\path (p) -- node[below,xshift=32pt,yshift=12pt] {$\sqrt{31}/6$} (m);
\path (m) -- node[below,xshift=8pt,yshift=-6pt] {$\sqrt{31}/9$} (n);
% Draw chord PK
\draw (p) -- node[right,xshift=-2pt,yshift=10pt] {$\sqrt{31}/6$} +(-62.3:4.64) coordinate (k) node[below left] {$K$};
% Draw tangent PL
\draw let \p1 = ($ (m) - (n) $), \n1 = {veclen(\x1,\y1)} in (p) -- node[left] {$\disfrac{\sqrt{31}}{9}$} (-5,-\n1) coordinate (l) node[left] {$L$};
% Connect L and K to R
\draw (r) -- (l) -- (k) -- cycle;
% Find point C on RK
\coordinate (c) at ($(r)!7.5cm!(k)$);
%\path (r) -- node[below,yshift=-16pt] {$RC=3/2$\\$RK=\sqrt{113}/6$} (c);
\path (r) -- node[below,xshift=16pt,yshift=-2pt] {$\overline{RC}=3/2$} (c);
\path (r) -- node[below,xshift=-4pt,yshift=-20pt] {$\overline{RK}=\sqrt{113}/6$} (k);
\fill (c) node[below] {$C$} circle (1pt);
% Draw CD
\path[name path=cd] (c) -- +($(l)-(k)$);
\path[name path=lr] (l) -- (r);
\path[name intersections={of=cd and lr,by=d}];
\draw (c) -- (d);
\fill (d) node[above,xshift=2pt] {$D$} circle (1pt);
%\path (r) -- node[above,xshift=-40pt,yshift=-8pt] {$RD=\sqrt{355/113}$\\$RL=\sqrt{355}/9$} (d);
\path (r) -- node[above,xshift=-40pt,yshift=-4pt] {$\overline{RD}=\sqrt{355/113}$} (d);
\path (r) -- node[below,xshift=-28pt,yshift=-15pt] {$\overline{RL}=\sqrt{355}/9$} (l);
\draw[rotate=28] (k) rectangle +(8pt,8pt);
\draw[rotate=-160] (s) rectangle +(8pt,8pt);
\end{tikzpicture}
\end{center}

\bigskip

The value $\disfrac{355}{113}$ could be constructed by constructing two line segments of length $355$ and $113$ and then using the division construction shown in Section~\ref{s.square-intro}, but that is rather tedious!

\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Ramanujan's second approximation}

\subsection{The construction}

Construct a unit circle centered at $O$ with diameter $\overline{AB}$, and let $C$ be the intersection of the perpendicular at $O$ with the circle.

Trisect $\overline{AO}$ so that $\overline{AT}=1/3$ and $\overline{TO}=2/3$.

Construct $\overline{BC}$ and find points $M,N$ such that $\overline{CM}=\overline{MN}=\overline{AT}=1/3$.

Construct $\overline{AM}$ and $\overline{AN}$ and let $P$ be the point on $\overline{AN}$ such that $\overline{AP}=\overline{AM}$.

From $P$ construct a line parallel to $\overline{MN}$ that intersects $\overline{AM}$ at $Q$.

Construct $\overline{OQ}$ and then from $T$ construct a line parallel to $\overline{OQ}$ that intersects $\overline{AM}$ at $R$.

Construct a line segment $\overline{AS}$ tangent to $A$ of length $\overline{AR}$.

Construct $\overline{SO}$.

Claim: $3\sqrt{\overline{SO}}=\left(9^2+\disfrac{19^2}{22}\right)^{\frac{1}{4}}\approx \pi$.

\begin{center}
\begin{tikzpicture}[scale=1.4]
\clip (-4.4,-4.2) rectangle +(8.8,8.6);
% Scale at 4

% Coordinates of circle
\coordinate (O) at (0,0);
\coordinate (A) at (-4,0);
\coordinate (B) at (4,0);
\coordinate (C) at (0,4);

% Draw circle and diameter
\node [thick,draw,circle through=(A),name path=circle] at (O) {};
\draw [thick] (A) -- (B);
\draw [thick,dashed] (C) -- (O);
\draw (O) rectangle +(8pt,8pt);
\draw[rotate=-90] (A) rectangle +(8pt,8pt);

\coordinate (T) at (-2.667,0);
\path (A) -- node[below] {$1/3$} (T);
\path (T) -- node[below] {$2/3$} (O);
\path (O) -- node[below] {$1$} (B);

\draw (C) -- node[right] {$1/3$} +(-45:1.333) coordinate (M);
\draw (M) -- node[right] {$1/3$} +(-45:1.333) coordinate (N);
\draw (N) -- node[near start,right] {$\sqrt{2}\!-\!2/3$}(B);

\draw[name path=AM] (A) -- (M);
\draw[name path=AN] (A) -- (N);

\node [circle through=(M),name path=AMcircle] at (A) {};

\path[name intersections={of=AMcircle and AN,by=P}];

\path[name path=PQ] (P) -- +(135:2);
\path[name intersections={of=PQ and AM,by=Q}];
\draw (P) -- (Q) -- (O);

\path[name path=QT] (T) -- ($(Q)+(-2.667,0)$) -- (Q);
\path[name intersections={of=QT and AM,by=R}];
\draw (T) -- (R);

\node [circle through=(R),name path=ARcircle] at (A) {};
\path[name path=AS] (A) -- ($(A)+(0,-2.5)$);
\path[name intersections={of=ARcircle and AS,by=S}];
\draw (A) -- (S);

\draw (S) -- (O);

\fill (O) circle(1.2pt) node[below right] {$O$};
\fill (A) circle(1.2pt) node[left] {$A$};
\fill (B) circle(1.2pt) node[right] {$B$} node[above left,xshift=-8pt] {$45^\circ$};
\fill (C) circle(1.2pt) node[above] {$C$};
\fill (T) circle(1.2pt) node[below] {$T$};
\fill (M) circle(1.2pt) node[right] {$M$};
\fill (N) circle(1.2pt) node[right] {$N$};
\fill (P) circle(1.2pt) node[below] {$P$};
\fill (Q) circle(1.2pt) node[above left] {$Q$};
\fill (R) circle(1.2pt) node[above left] {$R$};
\fill (S) circle(1.2pt) node[above left] {$S$};

\end{tikzpicture}
\end{center}

\newpage

\subsection{The proof}

$\triangle COB$ is a right triangle, $\overline{OB}=\overline{OC}=1$, 	so by Pythagoras' theorem $\overline{CB}=\sqrt{2}$ and $\overline{NB}=\sqrt{2}-2/3$. The triangle is isoceles so $\angle NBA =\angle MBA=45^\circ$.

We use the law of cosines on $\triangle NBA$ to compute $\overline{AN}$:
\begin{form}{2}
\overline{AN}^2&=&\overline{BA}^2 + \overline{BN}^2-2\cdot\overline{BA}\cdot\overline{BN}\cdot\cos \angle NBA\\
&=&2^2+\left(\sqrt{2}-\disfrac{2}{3}\right)^2-2\cdot 2 \cdot \left(\sqrt{2}-\disfrac{2}{3}\right)\cdot \disfrac{\sqrt{2}}{2}\\
&=&\left(4+2+\disfrac{4}{9}-4\right) + \sqrt{2}\cdot \left(-\disfrac{4}{3}+\disfrac{4}{3}\right)=\disfrac{22}{9}\\
\overline{AN}&=&\sqrt{\disfrac{22}{9}}\,.
\end{form}

Similarly, we use the law of cosines on $\triangle MBA$ to compute $\overline{AM}$:
\begin{form}{2}
\overline{AM}^2&=&\overline{BA}^2 + \overline{BM}^2-2\cdot\overline{BA}\cdot\overline{BM}\cdot\cos \angle MBA\\
&=&2^2+\left(\sqrt{2}-\disfrac{1}{3}\right)^2-2\cdot 2 \cdot \left(\sqrt{2}-\disfrac{1}{3}\right)\cdot \disfrac{\sqrt{2}}{2}\\
&=&\left(4+2+\disfrac{1}{9}-4\right) + \sqrt{2}\cdot \left(-\disfrac{2}{3}+\disfrac{2}{3}\right)=\disfrac{19}{9}\\
\overline{AM}&=&\sqrt{\disfrac{19}{9}}\,.
\end{form}

By construction $\overline{QP}\| \overline{MN}$ so
$\triangle MAN\sim \triangle QAP$, and by construction $\overline{AP}=\overline{AM}$ giving:
\begin{form}{2.4}
\disfrac{\overline{AQ}}{\overline{AM}}&=&\disfrac{\overline{AP}}{\overline{AN}}=\disfrac{\overline{AM}}{\overline{AN}}\\
\overline{AQ}&=&\disfrac{\overline{AM}^2}{\overline{AN}}=\disfrac{19/9}{\sqrt{22/9}}=\disfrac{19}{3\sqrt{22}}\,.
\end{form}

By construction $\overline{TR}\| \overline{OQ}$ so
$\triangle RAT\sim \triangle QAO$ giving:
\begin{form}{2.4}
\disfrac{\overline{AR}}{\overline{AQ}}&=&\disfrac{\overline{AT}}{\overline{AO}}\\
\overline{AR}&=&\overline{AQ}\cdot\disfrac{\overline{AT}}{\overline{AO}}=\disfrac{19}{3\sqrt{22}}\cdot\disfrac{1/3}{1}=\disfrac{19}{9\sqrt{22}}\,.
\end{form}

\newpage

By construction $\overline{AS}=\overline{AR}$ and $\triangle OAS$ is a right triangle. By Pythagoras' theorem:
\begin{form}{3}
\overline{SO}&=&\sqrt{1^2+\left(\disfrac{19}{9\sqrt{22}}\right)^2}\\
3\sqrt{\overline{SO}}&=&3\left(1+\disfrac{19^2}{9^2\cdot 22}\right)^\frac{1}{4}\\
&=&\left(3^4+\disfrac{3^4\cdot 19^2}{9^2\cdot 22}\right)^\frac{1}{4}\\
&=&\left(9^2+\disfrac{19^2}{22}\right)^\frac{1}{4}\approx 3.14159265262\approx \pi\,.
\end{form}

Here is the construction with line segments labeled with their lengths:

\begin{center}
\begin{tikzpicture}[scale=1.4]
\clip (-5,-4.2) rectangle +(10,8.5);
% Scale at 4

% Coordinates of circle
\coordinate (O) at (0,0);
\coordinate (A) at (-4,0);
\coordinate (B) at (4,0);
\coordinate (C) at (0,4);

% Draw circle and diameter
\node [thick,draw,circle through=(A),name path=circle] at (O) {};
\draw [thick] (A) -- (B);
\draw [thick,dashed] (C) -- (O);
\draw (O) rectangle +(8pt,8pt);
\draw[rotate=-90] (A) rectangle +(8pt,8pt);

\coordinate (T) at (-2.667,0);
\path (A) -- node[below] {$1/3$} (T);
\path (T) -- node[below] {$2/3$} (O);
\path (O) -- node[below] {$1$} (B);

\draw (C) -- node[right] {$1/3$} +(-45:1.333) coordinate (M);
\draw (M) -- node[right] {$1/3$} +(-45:1.333) coordinate (N);
\draw (N) -- node[near start,right] {$\sqrt{2}\!-\!2/3$}(B);

\draw[name path=AM] (A) -- node[above,xshift=15pt,yshift=24pt] {$\overline{AM}=\sqrt{19/9}$} (M);
\draw[name path=AN] (A) -- node[below,yshift=-10pt] {$\overline{AN}=\sqrt{22/9}$} (N);

\node [circle through=(M),name path=AMcircle] at (A) {};

\path[name intersections={of=AMcircle and AN,by=P}];

\path[name path=PQ] (P) -- +(135:2);
\path[name intersections={of=PQ and AM,by=Q}];
\draw (P) -- (Q) -- (O);
\path (A) -- node[above,xshift=-14pt,yshift=10pt] {$\overline{AQ}=19/3\sqrt{22}$} (Q);

\path[name path=QT] (T) -- ($(Q)+(-2.667,0)$) -- (Q);
\path[name intersections={of=QT and AM,by=R}];
\draw (T) -- (R);
\path (A) -- node[above,xshift=-32pt,yshift=6pt] {$\overline{AR}=19/9\sqrt{22}$} (R);

\node [circle through=(R),name path=ARcircle] at (A) {};
\path[name path=AS] (A) -- ($(A)+(0,-2.5)$);
\path[name intersections={of=ARcircle and AS,by=S}];
\draw (A) -- node[xshift=10pt,yshift=6pt] {$\overline{AS}=\,19/9\sqrt{22}$} (S);

\draw (S) -- node[right,xshift=-2pt,yshift=-10pt] {$\overline{SO}=\sqrt{1+
  \left(\disfrac{19^2}{9^2\cdot 22}\right)}$} (O);

\fill (O) circle(1.2pt) node[below right] {$O$};
\fill (A) circle(1.2pt) node[left] {$A$};
\fill (B) circle(1.2pt) node[right] {$B$} node[above left,xshift=-8pt] {$45^\circ$};
\fill (C) circle(1.2pt) node[above] {$C$};
\fill (T) circle(1.2pt) node[below] {$T$};
\fill (M) circle(1.2pt) node[right] {$M$};
\fill (N) circle(1.2pt) node[right] {$N$};
\fill (P) circle(1.2pt) node[below] {$P$};
\fill (Q) circle(1.2pt) node[above left] {$Q$};
\fill (R) circle(1.2pt) node[above left] {$R$};
\fill (S) circle(1.2pt) node[above left] {$S$};

\end{tikzpicture}
\end{center}


%*******************************************
% Lab 04: ALU
%*******************************************
\chapter{Arithmetic Logic Unit (ALU)}\label{lab04}

\section{Purpose}

In this lab you will build an \acf{ALU}. An \ac{ALU} is an important digital logic device used to perform all sorts of arithmetic and logic functions in a circuit. The commercial 74181 \ac{ALU} has two four-bit data inputs along with a one-bit mode (M) and a four-bit select input. Depending on those settings, the device will complete one of the functions listed in Table \ref{tab0301}.

\begin{table}[H]
	\sffamily
	\newcommand{\head}[1]{\textcolor{white}{\textbf{#1}}}
	\begin{center}
		\rowcolors{2}{gray!10}{white} % Color every other line a light gray
		\begin{tabular}{ccc}
			\rowcolor{black!75}
			\head{Select} & \head{Logic (M=1)} &\head{Arithmetic (M=0)} \\
			0000 & A' & A \\
			0001 & (A + B)' & A + B \\
			0010 & A'B & A + B' \\
			0011 & Logical 0 & minus 1 (2's Comp) \\
			0100 & (AB)' & A + AB' \\
			0101 & B' & (A + B) plus AB' \\
			0110 & A XOR B & A minus B minus 1 \\
			0111 & AB' & AB' minus 1 \\
			1000 & A' + B & A plus AB \\
			1001 & (A XOR B)' & A plus B \\
			1010 & B & (A + B') plus AB \\
			1011 & AB & AB minus 1 \\
			1100 & Logical 1 & A plus A \\
			1101 & A + B' & (A + B) plus A \\
			1110 & A + B & (A + B') plus A \\
			1111 & A & A minus 1
		\end{tabular}
	\end{center}
	\caption{Function Table for 74181 ALU}
	\label{tab0301}
\end{table}

Notes: in the ``Arithmetic'' column, the + sign indicates logic \textit{OR} while the words \textit{plus} and \textit{minus} indicate arithmetic add and subtract operations. The value of \textit{A plus A} is the same as shifting the bits left to the next most significant position.

The \ac{ALU} built in this lab is not as complex as a 74181 \ac{IC}, however it demonstrates the basic functions of an \ac{ALU}.

\section{Procedure}

\marginpar{This is a rather complex circuit so several completed subcircuits are provided.}Load the \ac{ALU} starter circuit in \textit{Logisim-evolution}. That starter circuit already has the \lstinline[columns=fixed]|main|, \lstinline[columns=fixed]|ALU|, and \lstinline[columns=fixed]|Arithmetic| subcircuits completed.

\subsection{main}

The \lstinline[columns=fixed]|main| circuit does nothing more than provide a human-friendly interface for the rest of the \ac{ALU}. That interface include two four-bit inputs (labeled \textit{InA} and \textit{InB}), a three-bit select, a one-bit mode, a carry-in and carry-out bit (so the \ac{ALU} could be chained to another to create an eight-bit device), a \textit{compare} output (TRUE if the two inputs are equal), and a four-bit output (labeled \textit{ALUOut}). In operation, numbers are entered on \textit{InA} and \textit{InB}, the mode and select are set, and then the result is read on \textit{ALUOut}.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/04-01}
	\caption{ALU main}
	\label{fig:04-01}
\end{figure}

\subsection{ALU}

The \lstinline[columns=fixed]|ALU| subcircuit contains the logic that routes \textit{InA}, \textit{InB}, and \textit{Sel} to two other subcircuits, \lstinline[columns=fixed]|Arithmetic| or \lstinline[columns=fixed]|Logic|. It then uses a multiplexer to route the output of one of those subcircuits to an output port depending on the setting of the \textit{Mode} bit. Note that the inputs are sent to both subcircuits but only the output specified by the \textit{Mode} is returned to the user. This type of logic is also used in the \lstinline[columns=fixed]|Arithmetic| circuit.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/04-02}
	\caption{ALU Subcircuit}
	\label{fig:04-02}
\end{figure}

\subsection{Arithmetic}

This subcircuit contains numerous devices from the \textit{Arithmetic} library and they are all wired appropriately for whatever operation is selected. The concept for this subcircuit is rather simple but routing the wiring to all of the devices is challenging.

Notice that two multiplexers are necessary since the circuit provides two different outputs. The top multiplexer routes the four-bit solution and the bottom multiplexer routes the carry-out bit. The \textit{compare} output is always active since it is comparing the input signals and does not rely on the function that is selected.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/04-03}
	\caption{Arithmetic Subcircuit}
	\label{fig:04-03}
\end{figure}

\subsection{Challenge}

In the starter circuit, the \lstinline[columns=fixed]|Logic| subcircuit is only a shell with three inputs and one output.

\begin{figure}[H]
	\centering
	\includegraphics[width=\maxwidth{.95\linewidth}]{gfx/04-04}
	\caption{Logic Subcircuit}
	\label{fig:04-04}
\end{figure}

Complete that subcircuit by adding the necessary logic gates and wiring, similar to the \lstinline[columns=fixed]|Arithmetic| subcircuit. This subcircuit is much simpler than the \lstinline[columns=fixed]|Arithmetic| subcircuit since there are no carry-in, carry-out, or compare bits. When completed, the subcircuit only needs eight logic gates and a multiplexer added to the starter.

\subsection{Testing the Circuit}

The \lstinline[columns=fixed]|ALU| should be tested by entering several values on \textit{InA} and \textit{InB} and then select all possible arithmetic and logic operations. The outputs for each check should be accurate.

\section{Deliverable}

To receive a grade for this lab, complete the Challenge. Be sure the standard identifying information is at the top left of the \textit{main} circuit, similar to this:

\bigskip
% The minipage environment keeps the three lines together - no page break.
\begin{minipage}{\linewidth}
	\begin{verbatim}
	George Self
	Lab 04: ALU
	February 18, 2018
	\end{verbatim}
\end{minipage}
\bigskip

Save the file with this name: \emph{\texttt{Lab04\_ALU}} and submit that file for grading.