\documentclass[./main.tex]{subfiles}

\begin{document}

\chapter{Switching regulator implementation details}

Design requirements:
\begin{itemize}
    \item Input voltage range: 3.4V-4.2V
    \item Input voltage (mean): 3.7V
    \item Output voltage: 3.4V
    \item Output current (max): 0.5A
    \item Ratio of ripple current: 0.3
\end{itemize}

\noindent Pre-choosen hardware specification
\begin{itemize}
    \item Switching frequency: 0.55Mhz (LM2734YMK)
    \item Switch ON Resistance: $R_{DS} = 0.3 \si{\ohm}$
    \item Catch Diode $V_F$: $V_{D1} = 0.3V$
    \item Boost Diode $V_F$: $V_{D2} = 1V$
\end{itemize}

\section{Inductor selection}
The Duty Cycle (D) can be approximated quickly using the ratio of output voltage (VO) to the input voltage (VIN):
\begin{equation}
    D = \frac{V_O}{V_{IN}}
\end{equation}

The catch diode (D1) forward voltage drop and the voltage drop across the internal NMOS must be included to calculate a more accurate duty cycle. Calculate D by using the following formula:
\begin{equation}
    D = \frac{V_O + V_{D}}{V_{IN} + V_{D} - V_{SW}}
    % = \frac{3.4V + 0.3V}{3.7V + 0.3V - 1A \times 0.3Ohm}
    = \frac{1.5V + 0.3V}{5V + 0.3V - 1A \times 0.3\si{\ohm}} = 36\%
\end{equation}
$V_{SW}$ can be approximated by:
\begin{equation}
    V_{SW} = I_O \times R_{DS}
\end{equation}
The diode forward drop (VD) can range from 0.3 V to 0.7 V depending on the quality of the diode. The lower $V_D$ is, the higher the operating efficiency of the converter.

The inductor value determines the output ripple current. Lower inductor values decrease the size of the inductor, but increase the output ripple current. An increase in the inductor value will decrease the output ripple current. The ratio of ripple current ($\delta i_L$) to the output current ($I_O$) is optimized when it is set between 0.3 and 0.4 at 1 A. The ratio r is defined as:
\begin{equation}
    r = \frac{\delta i_L}{I_O}
\end{equation}

One must also ensure that the minimum current limit (1.2 A) is not exceeded, so the peak current in the inductor must be calculated. The peak current ($I_{LPK}$) in the inductor is calculated as shown in the following equation:
\begin{equation}
    I_{LPK} = I_O + \frac{\delta i_L}{2}
\end{equation}

If r = 0.5 at an output of 1 A, the peak current in the inductor will be 1.25 A.
Now that the ripple current or ripple ratio is determined, the inductance is calculated as shown in
\begin{equation}
    L = \frac{V_O + V_D}{I_O \times r \times f_s} \times (1-D)
    = \frac{3.4V + 0.3V}{0.5A * 0.3 * 1.6MHz} * (1-0.95) = 0.77uH
\end{equation}
where:
\begin{itemize}
    \item $f_s$ is the switching frequency
    \item $I_O$ is the output current
\end{itemize}
When selecting an physical inductor, make sure that it is capable of supporting the peak output current without saturating.

\end{document}


\section{Post-simulation analysis}
CpHMD simulations allow the user to determine
the protonation states of all titratable sites
at the simulation pH conditions,
the {\pka} values,
or pH- or proton-coupled conformational dynamics.
Below we will discuss these aspects.

\subsection{Determination of protonation states and {\pka} values}
The lambda file contains the time evolution of $\lambda$ (titration state) and $x$ (tautomeric state) coordinates of titratable groups.
These data allow us to determine the protonation
states at specific pH, calculate the
{\pka} values and tautomer states, and
monitor convergence of protonation-state sampling.
As an example, Fig.~\ref{Fig:lambda_time} shows the time evolution of $\lambda$ for Cys481 in the BTK kinase
at different pH conditions.

 %---------------------------------------------
\begin{figure}[htb!]
    \centering
    \includegraphics[width=3.6in]{figs/btk_c481_lambdavstime.pdf}
    \caption{\textbf{Time series of the $\lambda$ value for Cys481 in the BTK kinase.} The data were saved every 20 ps (taken from Ref \cite{Liu_Shen_2021_J.Med.Chem.}). The pH conditions and fractions of mixed states ($0.2 \le \lambda \le 0.8$) are given. The plots show that the protonation-state sampling at all pH conditions converge after $\sim$10 ns.
    }
\label{Fig:lambda_time}
\end{figure}
 %---------------------------------------------

To facilitate analysis of the lambda files, we developed a Python tool \href{https://gitlab.com/shenlab-amber-cphmd/cphmd-analysis}{cphmd\_anal.py}.
This tool returns plots of the time series of unprotonated fractions and fitting of the unprotonated fractions to obtain {\pka's} (see discussion below).
For a trajectory at a specific pH,
we can count the number of frames where a titratable residue $i$ is
in the protonated or unprotonated state, which is defined
as $\lambda_i < 0.2$ or $\lambda_i > 0.8$, respectively.
The unprotonated fraction of the residue ($S_i$)
is calculated as
\begin{equation}
S_i = \frac{N_i^{\rm Unprot}}{N_i^{\rm Prot} + N_i^{\rm Unprot}},
\end{equation}
where $N_i^{\rm Prot}$ and $N_i^{\rm Unprot}$ are
the number of protonated and unprotonated frames,
respectively.
Plotting the time series of the $S_i$ value informs
convergence of the protonation state sampling (Fig.~\ref{fig:intro}, step 5).
Once convergence is reached, the {\pka} of residue $i$
can be obtained by fitting the $S_i$
values at all simulation pH to
the generalized Henderson-Hasselbalch equation,
\begin{equation}
S_i = \frac{1}{1+10^{n(\rm pK_{a,i} - pH)}},
\end{equation}
where $n$ is the Hill coefficient.
The resulting best fit is referred to as the titration curve (Fig.~\ref{fig:intro}, step 5).
A significant deviation of $n$ from 1 indicates cooperativity
($n>1$)
or anti-cooperativity ($n<1$) with a neighboring residue.
We note, in the past, $\lambda_i < 0.1$ and $\lambda_i > 0.9$ were used for
defining the protonated and unprotonated states \cite{Khandogin_Brooks_2005_Biophys.J.,Khandogin_Brooks_2006_Biochemistry}; however, our extensive studies (based on more than 100 proteins) showed that the calculated {\pka} value is not sensitive to the cutoff.

\subsection{Analysis of proton-coupled conformational dynamics and rationalization of the calculated {\pka} values}
A major application of
CpHMD simulations is
elucidation of pH-dependent or proton-coupled conformational dynamics, which
in turn rationalizes the calculated {\pka} values.
This practice can be best explained using an example.
The pH replica-exchange GBNeck2-CpHMD simulations
of the BTK kinase
\cite{Liu_Shen_2021_J.Med.Chem.}
gave a {\pka} of about 7.5 for Cys481,
which is one unit lower than the
model {\pka} of cysteine -- the {\pka} value of an isolated cysteine fully exposed to solvent.
Analysis of the pH replicas (i.e., trajectories at different pH conditions) revealed that Cys481 accepts hydrogen bonds (h-bond) from
Asn481 and Thr410 when it is in the deprotonated
thiolate state (Fig.~\ref{Fig:analysis}a).
Note, these h-bonds are absent in the crystal structure (PDB 3pj3).
Following this observation, we plotted the deprotonated fractions of Cys481 at different pH conditions (Fig.~\ref{Fig:analysis}b)
and the occupancies of the h-bond formation
between Cys481 and Asn484 or Thr410
(Fig.~\ref{Fig:analysis}c).
A comparison between the pH-dependent deprotonation
and h-bond formation demonstrates that the two are correlated, i.e., deprotonation of Cys481 is coupled to the h-bond formation.
It also suggests that the {\pka} downshift of Cys481 relative to the model value
can be attributed to the stabilization of the deprotonated thiolate state by the h-bond formation with Asn484 and Thr410.
We note, while implicit-solvent based CpHMD simulations have been successfully applied to {\pka} predictions and rationalization, hybrid-solvent and all-atom CpHMD simulations offer more accurate description of conformational dynamics.
We refer the user to the studies listed in Table~\ref{Table:applications} as examples.

 %---------------------------------------------
\begin{figure}[htb!]
    \centering
    \includegraphics[width=3.3in]{figs/analysis_example.pdf}
    \caption{\textbf{An example analysis of proton titration of a cysteine and coupling with conformational dynamics.}
    (a) A zoomed-in view of the structural environment of Cys481 in the BTK kinase taken from the trajectory at pH 9.
    The h-bonds with Asn484$\cdots$Cys481 and Thr410$\cdots$Cys481 are shown.
    The pH 9 replica is used.
    (b) The unprotonated fractions of Cys481 at different pH conditions. The titration curve represents the best fit to the Henderson-Hasselbalch equation.
    (c) Occupancy of the h-bond formation between Cys481 thiolate and Asn484 or Thr410
    at different pH conditions.
  Reprinted with permission from Liu, Zhan et al.\cite{Liu_Shen_2021_J.Med.Chem.}
    Copyright {2021} American Chemical Society.
    }
\label{Fig:analysis}
\end{figure}
 %---------------------------------------------


\documentclass[11pt]{article}

\usepackage{times}

%% Page layout
\oddsidemargin 0pt
\evensidemargin 0pt
\textheight 600pt
\textwidth 469pt
\setlength{\parindent}{0em}
\setlength{\parskip}{1ex}

\begin{document}

\title{15-213, Fall 20xx\\
Data Lab: Manipulating Bits\\
Assigned: Aug.~30, Due: Wed., Sept.~12, 11:59PM
}

\author{}
\date{}

\maketitle

Harry Bovik ({\tt bovik@cs.cmu.edu}) is the lead person for
this assignment.

\section{Introduction}
The purpose of this assignment is to become more familiar with
bit-level representations of integers and floating point numbers.
You'll do this by solving a series of programming ``puzzles.'' Many of
these puzzles are quite artificial, but you'll find yourself thinking
much more about bits in working your way through them.

\section{Logistics}

This is an individual project. All handins are electronic.
Clarifications and corrections will be posted on the course Web page.

\section{Handout Instructions}

\begin{quote}
\bf SITE-SPECIFIC: Insert a paragraph here that explains how the
instructor will hand out the {\tt datalab-handout.tar} file to the
students.
\end{quote}

Start by copying {\tt datalab-handout.tar} to a (protected) directory
on a Linux machine in which you plan to do your work.  Then give the
command
\begin{verbatim}
  unix> tar xvf datalab-handout.tar.
\end{verbatim}
This will cause a number of files to be unpacked in the directory.
The only file you will be modifying and turning in is {\tt bits.c}.

The {\tt bits.c} file contains a skeleton for each of the 15
programming puzzles.  Your assignment is to complete each function
skeleton using only {\em straightline} code for the integer puzzles
(i.e., no loops or conditionals) and a limited number of C arithmetic
and logical operators. Specifically, you are {\em only} allowed to use
the following eight operators:
\begin{verbatim}
 ! ~ & ^ | + << >>
\end{verbatim}
A few of the functions further restrict this list.  Also, you are not
allowed to use any constants longer than 8 bits.  See the comments in
{\tt bits.c} for detailed rules and a discussion of the desired coding
style.

\section{The Puzzles}

This section describes the puzzles that you will be solving in {\tt bits.c}.

\subsection{Bit Manipulations}

Table \ref{bit-tab} describes a set of functions that manipulate and
test sets of bits.  The ``Rating'' field gives the difficulty rating
(the number of points) for the puzzle, and the ``Max ops'' field gives
the maximum number of operators you are allowed to use to implement
each function.  See the comments in {\tt bits.c} for more details on
the desired behavior of the functions.  You may also refer to the test
functions in {\tt tests.c}.  These are used as reference functions to
express the correct behavior of your functions, although they don't
satisfy the coding rules for your functions.

\begin{table}[htbp]
\begin{center}
\begin{tabular}{|l|l|c|c|}
\hline
Name & Description & Rating & Max Ops\\
\hline
{\tt bitAnd(x,y)} & \verb@x & y@ using only \verb@|@ and \verb@~@  &1&8\\
{\tt getByte(x,n)} & Get byte \verb@n@ from \verb@x@.  &2&6\\
{\tt logicalShift(x,n)} & Shift right logical. &3&20\\
{\tt bitCount(x)} & Count the number of 1's in \verb@x@.  &4&40\\
{\tt bang(x)} & Compute \verb@!n@ without using \verb@!@ operator.  &4&12\\
\hline
\end{tabular}
\end{center}
\caption{Bit-Level Manipulation Functions.}
\label{bit-tab}
\end{table}

\subsection{Two's Complement Arithmetic}

Table \ref{two-tab} describes a set of functions that make use of the
two's complement representation of integers.  Again, refer to the
comments in {\tt bits.c} and the reference versions in {\tt tests.c}
for more information.

\begin{table}[htbp]
\begin{center}
\begin{tabular}{|l|l|c|c|}
\hline
Name & Description & Rating & Max Ops\\
\hline
{\tt tmin()} & Most negative two's complement integer & 1 &4\\
{\tt fitsBits(x,n)} & Does \verb@x@ fit in \verb@n@ bits?  &2&15\\
{\tt divpwr2(x,n)} & Compute $\texttt{x}/2^{\texttt{n}}$ & 2 & 15\\
{\tt negate(x)} & \verb@-x@ without negation & 2 & 5 \\
{\tt isPositive(x)} & {\tt x > 0}? & 3 & 8\\
{\tt isLessOrEqual(x,y)} & {\tt x <= y}? & 3 & 24\\
{\tt ilog2(x)} & Compute $\lfloor \log_2 (\texttt{x}) \rfloor$ & 4 & 90 \\
\hline
\end{tabular}
\end{center}
\caption{Arithmetic Functions}
\label{two-tab}
\end{table}

\subsection{Floating-Point Operations}

For this part of the assignment, you will implement some common
single-precision floating-point operations.  In this section, you are
allowed to use standard control structures (conditionals, loops), and
you may use both {\tt int} and {\tt unsigned} data types, including
arbitrary unsigned and integer constants.  You may not use any unions,
structs, or arrays.  Most significantly, you may not use any floating
point data types, operations, or constants.  Instead, any
floating-point operand will be passed to the function as having type
{\tt unsigned}, and any returned floating-point value will be of type
{\tt unsigned}.  Your code should perform the bit manipulations that
implement the specified floating point operations.

Table \ref{fp-tab} describes a set of functions that
operate on the bit-level representations of floating-point numbers.
Refer to the
comments in {\tt bits.c} and the reference versions in {\tt tests.c}
for more information.

\begin{table}[htbp]
\begin{center}
\begin{tabular}{|l|l|c|c|}
\hline
Name & Description & Rating & Max Ops\\
\hline
{\verb@float_neg(uf)@} & Compute \verb@-f@ & 2 & 10\\
{\verb@float_i2f(x)@} & Compute \verb@(float) x@ & 4 & 30\\
{\verb@float_twice(uf)@} & Computer \verb@2*f@ & 4 & 30\\
\hline
\end{tabular}
\end{center}
\caption{Floating-Point Functions.  Value \texttt{f} is the floating-point number having the
same bit representation as the unsigned integer \texttt{uf}.}
\label{fp-tab}
\end{table}

Functions \verb@float_neg@ and \verb@float_twice@ must handle the full
range of possible argument values, including not-a-number (NaN) and
infinity.  The IEEE standard does not specify precisely how to handle
NaN's, and the IA32 behavior is a bit obscure.  We will follow a
convention that for any function returning a NaN value, it will return
the one with bit representation \verb@0x7FC00000@.

The included program \texttt{fshow} helps you understand the structure
of floating point numbers. To compile \texttt{fshow}, switch to the
handout directory and type:
\begin{verbatim}
  unix> make
\end{verbatim}
You can use \texttt{fshow} to see what an arbitrary pattern
represents as a floating-point number:
\begin{verbatim}
  unix> ./fshow 2080374784

  Floating point value 2.658455992e+36
  Bit Representation 0x7c000000, sign = 0, exponent = f8, fraction = 000000
  Normalized.  1.0000000000 X 2^(121)
\end{verbatim}
You can also give \texttt{fshow} hexadecimal and floating point
values, and it will decipher their bit structure.

\section{Evaluation}

Your score will be computed out of a maximum of 76 points based on the
following distribution:
\begin{description}
\item[41] Correctness points.
\item[30] Performance points.
\item[5] Style points.
\end{description}

{\em Correctness points.} The 15 puzzles you must solve have been given a
difficulty rating between 1 and 4, such that their weighted sum totals
to 41.  We will evaluate your functions using the \texttt{btest}
program, which is described in the next section.  You will get full
credit for a puzzle if it passes all of the tests performed by
\texttt{btest}, and no credit otherwise.

{\em Performance points.}  Our main concern at this point in the course is
that you can get the right answer.  However, we want to instill in you
a sense of keeping things as short and simple as you can.
Furthermore, some of the puzzles can be solved by brute force, but we
want you to be more clever.  Thus, for each function we've established
a maximum number of operators that you are allowed to use for each
function. This limit is very generous and is designed only to catch
egregiously inefficient solutions.  You will receive two points for
each correct function that satisfies the operator limit.

{\em Style points.} Finally, we've reserved 5 points for a subjective
evaluation of the style of your solutions and your commenting.  Your
solutions should be as clean and straightforward as possible.  Your
comments should be informative, but they need not be extensive.

\section*{Autograding your work}

We have included some autograding tools in the handout directory ---
\texttt{btest}, \texttt{dlc}, and \texttt{driver.pl} --- to help you
check the correctness of your work.

\begin{itemize}
\item {\bf \texttt{btest:}} This program checks the functional correctness of
  the functions in {\tt bits.c}. To build and use it, type the
  following two commands:
\begin{verbatim}
  unix> make
  unix> ./btest
\end{verbatim}
Notice that you must rebuild \texttt{btest} each time you modify your {\tt
  bits.c} file.

You'll find it helpful to work through the functions one at a time,
testing each one as you go.  You can use the {\tt -f} flag to instruct
\texttt{btest} to test only a single function:
\begin{verbatim}
  unix> ./btest -f bitAnd
\end{verbatim}
You can feed it specific function arguments
using the option flags {\tt -1}, {\tt -2}, and {\tt -3}:
\begin{verbatim}
  unix> ./btest -f bitAnd -1 7 -2 0xf
\end{verbatim}
Check the file {\tt README} for documentation on running the {\texttt
  btest} program.

\item {\bf \texttt{dlc}:} This is a modified version of an ANSI C compiler from
the MIT CILK group that you can use to check for compliance with the
coding rules for each puzzle. The typical usage is:
\begin{verbatim}
  unix> ./dlc bits.c
\end{verbatim}
The program runs silently unless it detects a problem, such as an
illegal operator, too many operators, or non-straightline code in the
integer puzzles.  Running with the \texttt{-e} switch:
\begin{verbatim}
  unix> ./dlc -e bits.c
\end{verbatim}
causes \texttt{dlc} to print counts of the number of operators used by
each function. Type {\tt ./dlc -help} for a list of command line options.

\item {\bf \texttt{driver.pl}:} This is a driver program that uses \texttt{btest}
and \texttt{dlc} to compute the correctness and performance points for
your solution. It takes no arguments:
\begin{verbatim}
  unix> ./driver.pl
\end{verbatim}
Your instructors will use \texttt{driver.pl} to evaluate your
solution.

\end{itemize}

\section{Handin Instructions}

\begin{quote}
\bf SITE-SPECIFIC: Insert text here that tells each student how to
hand in their {\tt bits.c} solution file at your school.
\end{quote}

\section{Advice}

\begin{itemize}

\item Don't include the \verb:<stdio.h>: header file in your {\tt
bits.c} file, as it confuses \texttt{dlc} and results in some
non-intuitive error messages. You will still be able to use {\tt
printf} in your {\tt bits.c} file for debugging without including the
\verb:<stdio.h>: header, although \texttt{gcc} will print a warning that
you can ignore.

\item The \texttt{dlc} program enforces a stricter form of C declarations
than is the case for C++ or that is enforced by \texttt{gcc}.  In
particular, any declaration must appear in a block (what you enclose
in curly braces) before any statement that is not a declaration.  For
example, it will complain about the following code:
\begin{verbatim}
  int foo(int x)
  {
    int a = x;
    a *= 3;     /* Statement that is not a declaration */
    int b = a;  /* ERROR: Declaration not allowed here */
  }
\end{verbatim}

\end{itemize}

\section{The ``Beat the Prof'' Contest}

For fun, we're offering an optional ``Beat the Prof'' contest that
allows you to compete with other students and the instructor to
develop the most efficient puzzles. The goal is to solve each Data Lab
puzzle using the fewest number of operators. Students who match or
beat the instructor's operator count for each puzzle are winners!

To submit your entry to the contest, type:
\begin{verbatim}
    unix> ./driver.pl -u ``Your Nickname''
\end{verbatim}
Nicknames are limited to 35 characters and can contain alphanumerics,
apostrophes, commas, periods, dashes, underscores, and ampersands.
You can submit as often as you like. Your most recent submission will
appear on a real-time scoreboard, identified only by your nickname.
You can view the scoreboard by pointing your browser at
\begin{verbatim}
    http://$SERVER_NAME:$REQUESTD_PORT
\end{verbatim}

\begin{quote}
\bf SITE-SPECIFIC: Replace \verb:$SERVER_NAME: and \verb:$REQUESTD_PORT:
with the values you set in the \verb:./contest/Contest.pm: file.
\end{quote}

\end{document}


\documentclass[class=report, float=false, crop=false]{standalone}
\usepackage[subpreambles=true]{standalone}

\input{preamble}

\graphicspath{{figures/images/}}

% \begin{cbunit}

\begin{document}

\chapter{Euler's equation}
\label{appendix:euler}

In this appendix we mean to remind the definitions of the rotation vector, the angular momentum, the tensor of moments of inertia and the establishment of the Euler's equation describing the rotation of a rigid body. All demonstrations are based on \cite{landau1972mechanics}.

\section{Rotation vector}

Consider a vector $\vec{u}$ on which we apply an infinitesimal rotation of angle $d\theta$ around the axis $\vec{e_z}$ (figure \ref{inf_rotation_fig}).\\

\begin{figure}[h!]
\centering
\includestandalone{figures/tikz/infinitesimal_rotation}
\caption{}
\label{inf_rotation_fig}
\end{figure}

We then have $\vec{u'} = \vec{u} + \vec{du}$ with $|\vec{du}| = |\vec{u} ~\theta \sin\phi|$ and the direction of $\vec{du}$ being perpendicular to the plane formed by $\vec{e_z}$ and $\vec{u}$, which gives us
\begin{equation}
\vec{du} = d\theta \vec{e_z} \times \vec{u} = \vec{d\theta} \times \vec{u}
\label{inf_rotation}
\end{equation}
therefore, if the rotation angle is a function of time $\theta(t)$ we have, by consideration that $d\theta(t) = \dot{\theta}(t)dt$, that
\begin{equation}
\frac{\vec{du}}{dt} = \dot{\theta}\vec{e_z} \times \vec{u}
\end{equation}
We can sum infinitesimal rotations therefore, in the general case -- with $\frac{d}{dt}|\vec{u}| = 0$ -- we can always define a vector $\vec{\omega}$ such that $\dot{\vec{u}} = \vec{\omega} \times \vec{u}$.\\

A rigid body $\mathcal{O}$ is in rotation if we can define such a vector $\vec{\omega}$ which will be the same for all the points of the body. Therefore, whatever origin we may choose, if $\vec{p}$ and $\vec{q}$ point to two points $A$ and $B$ of the body -- which induces that $\frac{d}{dt} |\vec{p} - \vec{q}| = 0$ -- we will have that
\begin{equation}
\frac{d}{dt} \left( \vec{p} - \vec{q} \right) = \vec{\omega} \times \left( \vec{p} - \vec{q} \right)
\end{equation}
which is equivalent to
\begin{equation}
\forall A,B \in \mathcal{O}, \vec{v_B} = \vec{v_A} + \vec{\omega} \times \vec{AB}
\label{comp_vitesse}
\end{equation}
where $\vec{v_A}$ and $\vec{v_B}$ are the velocities of the points $A$ and $B$.

\section{Angular momentum}

The mechanical properties of a closed system do not vary when it is rotated as a whole in any manner in space. Therefore, the Lagrangian of a rigid body $L(\vec{r_i},\vec{v_i},t)$ has to be unchanged by any infinitesimal rotation $\vec{d\theta}$.\\

One can first notice that the equation $\ref{inf_rotation}$ can be applied on any vector of our space, therefore both the positions and velocities are affected by the rotation.\\

We then have that
\begin{align*}
\forall \vec{d\theta},~ \delta L = L(\vec{r_i} + \vec{dr_i},\vec{v_i} + \vec{dv_i},t) - L(\vec{r_i},\vec{v_i},t) &= 0\\
\Leftrightarrow \sum_i \left( \underbrace{\frac{\partial}{\partial\vec{r_i}} L}_{\dot{\vec{p_i}}} \cdot \underbrace{\vec{dr_i}}_{\vec{d\theta} \times \vec{r_i}} + \underbrace{\frac{\partial}{\partial\vec{v_i}} L}_{\vec{p_i}} \cdot \underbrace{\vec{dv_i}}_{\vec{d\theta} \times \vec{v_i}} \right) &= 0\\
\Leftrightarrow \sum_i \left(\dot{\vec{p_i}} \cdot \vec{d\theta} \times \vec{r_i} + \vec{p_i} \cdot \vec{d\theta} \times \vec{v_i} \right) &= 0\\
\Leftrightarrow \vec{d\theta} \cdot \sum_i \left(\vec{r_i}\times\dot{\vec{p_i}} + \vec{v_i}\times\vec{p_i}\right) &= 0\\
\Leftrightarrow \vec{d\theta} \cdot \frac{d}{dt} \underbrace{\sum_i \vec{r_i}\times\vec{p_i}}_{\vec{A}} &= 0
\end{align*}
therefore the vector
\begin{equation}
\boxed{\vec{A} \equiv \sum_i \vec{r_i}\times\vec{p_i}}
\label{ang_momentum}
\end{equation}
which we will call \textit{angular momentum}, is conserved for a closed system.\\

We can give a relation between the angular momentum of the same rigid body in the frame of reference $F$ and the inertial frame of the body $F_O$ -- where the centre of mass $O$ is at rest --, the latter moving with velocity $\vec{V}$ relative to the former.\\

We have to first notice that the velocities of the same point $a$ in these frames are linked by
\begin{align*}
\vec{v_a} = \vec{v_{a,O}} + \vec{V}
\end{align*}
from we can infer that
\begin{align*}
\vec{A} = \sum_i \vec{r_i} \times \vec{p_i} &= \sum_i \left(\vec{r_O} + \left(\vec{r_i} - \vec{r_O}\right)\right) \times \vec{p_i}\\
&= \vec{r_O} \times \underbrace{\sum_i \vec{p_i}}_{\vec{P}} + \sum_i \left(\vec{r_i} - \vec{r_O}\right) \times \vec{p_i}\\
&= \vec{r_O} \times \vec{P} + \sum_i m_i \left(\vec{r_i} - \vec{r_O}\right) \times \left(\vec{v_{i,O}} + \vec{V}\right)\\
&= \vec{r_O} \times \vec{P} + \underbrace{\sum_i \left(\vec{r_i} - \vec{r_O}\right) \times \vec{v_{i,O}}}_{\vec{A_O}} + \cancelto{0}{\sum_i m_i \left(\vec{r_i} - \vec{r_O}\right)}~~\times\vec{V}
\end{align*}
where $\vec{P}$ is the total momentum of the rigid body.\\

Therefore we have the following relation
\begin{equation}
\boxed{\vec{A} = \vec{r_O} \times \vec{P} + \vec{A_O}}
\label{body_to_ref}
\end{equation}

\section{Tensor of moments of inertia}

The angular momentum in equation \ref{ang_momentum} is more easily expressed in the inertial frame of the body where the centre of mass of the body is at rest. We can then infer the angular momentum in the frame of reference with the mean of equation \ref{body_to_ref}.\\

Consider $\vec{\omega}$ the rotation vector of the rigid body, in the inertial frame of the body we then have that the momentum of any point $i$ is
\begin{align*}
\forall i, \vec{p_i} = m\vec{v_i} = m\vec{\omega}\times\vec{r_i}
\end{align*}
therefore, the angular momentum $\vec{A_O}$ is
\begin{align*}
\vec{A_O} &= \sum_i \vec{r_i}\times\vec{p_i} = \sum_i m_i \vec{r_i}\times\left(\vec{\omega}\times\vec{r_i}\right)\\
&= \sum_i m_i \left(\vec{r_i}^2 \vec{\omega} - \vec{r_i} \left(\vec{r_i} \cdot \vec{\omega}\right)\right)\\
&= \sum_k \vec{e_k} \left( \sum_i m_i \left(\vec{r_i}^2\omega_k - r_{i,k}\sum_l r_{i,l}\omega_l\right) \right)\\
&= \sum_k \vec{e_k} \left( \sum_l \left(\sum_i m_i \left(\vec{r_i}^2 \delta_{k,l} - r_{i,k}r_{i,l}\right)\right)\omega_l\right)\\
\end{align*}
We can denote the following symmetric matrix
\begin{equation}
\boxed{\forall k,l \in \llbracket1,3\rrbracket, \bar{\bar{I}}_{k,l} \equiv \sum_i m_i \left(\vec{r_i}^2 \delta_{k,l} - r_{i,k}r_{i,l}\right)}
\label{tensor_inertia}
\end{equation}
the \textit{tensor of moments of inertia}, which then enables us to write
\begin{equation}
\boxed{\vec{A} = \bar{\bar{I}} \vec{\omega}}
\label{ang_momentum_inertia}
\end{equation}
which remains true if the body is regarded as continuous.\\

According to the spectral theorem, there exists an orthonormal base of space $(\vec{u_1},\vec{u_2},\vec{u_3})$ in which $\bar{\bar{I}}$ is diagonal with
\begin{equation}
\forall k,l \in \llbracket1,3\rrbracket, \bar{\bar{I}}_{k,l} = \delta_{k,l}I_k
\label{tensor_inertia_diag}
\end{equation}
these axes are then called the \textit{principal axes of inertia} of the body.

\section{Conservation of the angular momentum}

From equation \ref{ang_momentum} we can write that
\begin{align*}
\frac{d}{dt}\vec{A} = \frac{d}{dt} \sum_i \vec{r_i}\times\vec{p_i} = \sum_i \Big(\cancelto{0}{\underbrace{\dot{\vec{r_i}}}_{\vec{v_i}}\times\vec{p_i}} + \vec{r_i}\times\underbrace{\dot{\vec{p_i}}}_{\vec{F_i}}\Big) = \sum_i \vec{r_i}\times\vec{F_i}
\end{align*}
where $\vec{F_i}$ is the total force exerted on the point $i$ of the rigid body.\\

We will denote
\begin{equation}
\vec{M} = \sum_i \vec{r_i}\times\vec{F_i}
\end{equation}
the total \textit{torque} exerted on the rigid body, then the following equation
\begin{equation}
\boxed{\frac{d}{dt} \vec{A} = \vec{M}}
\label{TMC}
\end{equation}
formulates the conservation of the angular momentum.

\section{Euler's equation}

We have that the angular momentum $\vec{A}$ in equation \ref{TMC} is hard to express in any frame of reference -- see equations \ref{tensor_inertia} and \ref{ang_momentum_inertia}.\\

For a given rigid body $\mathcal{O}$, we then choose to write the conservation of the angular momentum in the system of coordinates corresponding to the principal axes of inertia $(\vec{u_1},\vec{u_2},\vec{u_3})$ of $\mathcal{O}$, where the tensor of moments of inertia is diagonal. In this frame, the derivative of the angular momentum relatively to the fixed frame of reference can be decomposed in a first part
\begin{align*}
\frac{d'}{dt} \vec{A} = \sum_k \frac{d}{dt}\Big(\underbrace{\vec{A}\cdot\vec{u_k}}_{A_k}\Big)\vec{u_k}
\end{align*}
corresponding to the rate of change of $\vec{A}$ relatively to the rotating frame and a second part
\begin{align*}
\vec{\omega} \times \vec{A}
\end{align*}
corresponding to the change of $\vec{A}$ due only to the rotation of the frame.\\

We can infer from equations \ref{ang_momentum_inertia} and \ref{tensor_inertia_diag} that
\begin{align*}
\forall k \in \llbracket1,3\rrbracket, A_k = I_k \omega_k
\end{align*}
with all the $I_k$ being constant, therefore, with $\vec{M} = \sum_k M_k \vec{u_k}$ the total torque exerted on $\mathcal{O}$, we can finally write the following Euler's equation
\begin{equation}
\boxed{\forall k \in \llbracket1,3\rrbracket,~ I_k \dot{\omega_k} + \varepsilon_{k,l,m}\omega_lI_m\omega_m = M_k}
\label{euler_rot}
\end{equation}
which rules the rotation of a rigid body.\\

We can note that the tensor of moments of inertia of a spherically symmetric body is a scalar matrix, therefore the equation \ref{TMC} can be directly solved without the considerations of this part.

% \input{references/biblio}

\end{document}

% \end{cbunit}


%!TEX root = ../Thesis.tex
\chapter{Fission Source Convergence \label{ch:AdvancedArnoldi}}
Monte Carlo criticality calculations have come a long way since their beginning in the 1950s.  Along with the increase in the speed and complexity of computers the problems for which Monte Carlo techniques have been used have increased.  Problems that were prohibitively expensive in the past have now become routine.  Some problems still remain, however,  with Monte Carlo criticality calculations.  Two of those problems are fission source convergence and the underestimation of the variance of the mean eigenvalue \citep[see][]{Brown:2009A-Rev-0}.  In this chapter we will discuss how a Monte Carlo application of Arnoldi's method improves the source convergence as compared with the traditional power method.

\section{Shannon Entropy and Fission Source Convergence \label{sec:Entropy} }
In \Fref{sec:PowerMethod} it was observed that a Monte Carlo code must discard initial iterations as the eigenvalue estimate converges to the fundamental eigenmode.  The number of iterations required for convergence of the power method to the fundamental depends on the dominance ratio ($\lambda_1/\lambda_0$) for the problem.  Also of concern is the convergence of the fission source.  To obtain good estimates of the fission source---or eigenfunction of the fission-transport operator---the fission source should be converged before tallying begins.

Knowing how many cycles to discard can be a challenge.  One could monitor the eigenvalue estimates to see if they have converged and begin active cycles once convergence has been achieved.  \citet{Brown:2009A-Rev-0} suggests that when the dominance ratio is close to 1, the fundamental eigenvalue will converge sooner than the fission source distribution.  We must, therefore, monitor \emph{both} the convergence of the eigenvalue as well as the convergence of the fission source.  It is clear that convergence in fewer iterations is desired because fewer iterations will have to be discarded and tallying can begin sooner.

One problem for which source convergence in the power method is problematic is a geometry with multiplying regions separated by large region of a highly-absorbing material.  This is because of the particles born in one multiplying region only a few, rare, neutrons would ever transport through the absorbing region to cause fission in the other multiplying region.  In the power method, the only way in which particles can move from the initial source to a new location is through the scattering that occurs in the application of the fission-transport operator.  The fission source for the next iteration contains only the points at which neutrons induced fission in the previous iteration.

When restarting, Arnoldi's method uses all of the available information about the operator applied to a source to estimate an eigenvector; the power method only uses information from the latest application of the operator to estimate the fundamental eigenvector.  Using all available information makes it possible for the fission source to be converged more quickly.

To monitor the convergence of the fission source \citet{Ueki:2003Infor-0} have used information theory to calculate the Shannon entropy, $H$, of the fission source.   The Shannon entropy of a spatially discretized fission source $S(x)$ is defined as
\begin{equation}
    H(S(x)) \equiv -\sum_{b=1}^B S_b\log(S_b),
    \label{eq:ShannonEntropy}
\end{equation}
where $B$ is the number of spatial bins and $S_b$ is the number of fission neutrons in bin $b$.  As the calculation proceeds, the Shannon entropy will converge to some value.  The actual value of the Shannon entropy is not important in determining the fission source convergence.  What is important is that it converges to some value.

To calculate the Shannon entropy when using the power method the fission source must be discretized.  This discretization is most easily performed using a first order---or histogram---approximation as described in Equations \eqref{eq:ApproximatedSource}, \eqref{eq:FirstOrderApproximation} and \eqref{eq:ConstantSpaceArnoldiVector}.  The discretization of the fission source will not bias the estimate of the eigenvalue in the power method as it does for Arnoldi's method.  The power method samples from the non-discretized source and only uses the discretized fission source for tallying bins and calculating the Shannon entropy.

In Arnoldi's method, we can't calculate the Shannon entropy of the Arnoldi vectors.  We must, therefore, calculate the Ritz vectors of \A{} and use the fundamental Ritz vector as $S(x)$ in \Fref{eq:ShannonEntropy}.  With the first order approximation to the fission source
\begin{equation}
	S_b = \int_{x_b}^{x_{b+1}} \left|\Px\right| \dd x.
	\label{eq:SbFirstOrder}
\end{equation}
This is equivalent to calculating the Shannon entropy for the Power method.  When using a second order approximation,
\begin{equation}
	S_b = \int_{x_b}^{x_{b+1}} \left|\Lx\right| \dd x.
	\label{eq:SbSecondOrder}
\end{equation}
In both \Fref{eq:SbFirstOrder} and \Fref{eq:SbSecondOrder} $S_b$ is the number of neutrons that have tallied in bin $b$.

\section{Numerical Results}
\subsubsection{Homogeneous Slab}
To demonstrate the eigenvalue and fission source convergence both the power method and Arnoldi's method have been run on a homogeneous slab, 50 mfp thick with \mbox{$\nu\Sigma_f = 1.0$}, \mbox{$\Sigma_a = 0.2$}, and \mbox{$\Sigma_s = 0.8$}; \mbox{$\Sigma_t = 1.0$}.  This geometry is the same as in \Fref{ch:RelaxedArnoldi}.  Arnoldi's method has 25 iterations per restart and both methods track 5E5 particles per iteration.  The dominance ratio for this problem as estimated by Arnoldi's method is 0.992201.  For this problem I have used a second order approximation to the fission source as described in \Fref{ch:SpatialDiscretization}.

In \Fref{fig:50mfpPower} I show the eigenvalue estimates (red) and Shannon entropy convergence (blue) from the power method.  The solid black line shows the reference value of 0.997520 from a deterministic S$32$ code with 200 equally-spaced regions. The dashed black line shows the entropy at the end of the simulation.  \Fref{fig:50mfpArnoldi} shows the eigenvalue estimate and Shannon entropy convergence as calculated by Arnoldi's method.  In this figure, the dashed black line is the mean value of the Shannon entropy.

From \Fref{fig:50mfpPower} and \Fref{fig:50mfpArnoldi}, we see that Arnoldi's method converges immediately for both the eigenvalue estimate and the fission source.  The power method, however, requires approximately 250 iterations to converge.  We do see something different in these figures that we did not see before.  In Figures \ref{fig:SymmetricPower}--\ref{fig:AsymmetricArnoldi}, it appears that the spread in the eigenvalue estimates was approximately the same between Arnoldi's method and the power method.  For the homogeneous slab, however, the spread in the eigenvalue estimates from the power method is 0.00052 while the spread from Arnoldi's method is approximately 0.0012---the eigenvalue estimates from Arnoldi's method are less noisy than the estimates from the power method.

Thus we see that Arnoldi's method is superior to the power method for eigenvalue and fission source convergence, both converge immediately.  The eigenvalue estimates from Arnoldi's method are also less noisy that those from the power method.

\begin{figure}[p]\centering
    \subfloat[Power method.]{\label{fig:50mfpPower}\input{EntropyandVariance/Data/50mfpPower} }

    \subfloat[Arnoldi's method.]{\label{fig:50mfpArnoldi}\input{EntropyandVariance/Data/50mfpArnoldi} }
    \caption{Convergence of eigenvalue estimate and Shannon entropy for 50mfp thick, homogeneous slab.  Solid black line is the S$_{\mathrm{N}}$ eigenvalue solution for the fundamental eigenvalue ($\lambda_0 = 0.997520$).}
\end{figure}

\subsubsection{Heterogeneous Slab}
We now turn to a heterogeneous geometry used in \citet{Kornreich:2002Semi--0} and \citet{Ueki:2005Stati-0}.  Two problems are studied in these papers.  The first problem is a symmetrical, five-region slab with vacuum boundary conditions.  The slab widths (left-to-right) are 1.0, 1.0, 5.0,1.0, 1.0 cm thick.  The second problem is identical except the right most fuel slab has a width of 1.01 cm.  The materials are of three types (left-to-right): fuel, scatterer, absorber, scatterer, fuel.   The cross sections for these materials are
\begin{description}
    \item[Fuel] $\Sigma_t = 1.0$, $\Sigma_s = 0.8$, $\Sigma_{\gamma} = 0.1$, $\Sigma_f = 0.1$, $\nu = 3.0$,
    \item[Scatterer] $\Sigma_t = 1.0$, $\Sigma_s = 0.8$, $\Sigma_a = 0.2$,
    \item[Absorber] $\Sigma_t = 1.0$, $\Sigma_s = 0.1$, $\Sigma_a = 0.9$.
\end{description}
A graphical description of this geometry is shown in \Fref{fig:HeteroGeometry}.

\begin{figure}[ht]\centering
    \includegraphics{EntropyandVariance/Data/MultimediaCartoon}
    \caption{Diagram of heterogeneous slab geometry.}
    \label{fig:HeteroGeometry}
\end{figure}

This geometry is particularly difficult for source convergence.  The initial source for this problem lies entirely in the leftmost bin.  With a large highly absorbing slab in the center, it is difficult to move particles from the left to the right side and therefore it will take many histories for the fission source to converge.  The dominance ratio for the symmetric problem is 0.999566 and it is 0.992504 for the asymmetric problem.  For these simulations, 1E5 particles are tracked in each iteration; Arnoldi's method uses 10 iterations per restart and calculated 2 eigenvalues.

The results for the asymmetric problem will be shown first; with a smaller dominance ratio it should be easier to converge the fission source and eigenvalue.  \Fref{fig:AsymmetricPower} shows the convergence of the eigenvalue estimates and fission source as calculated by the power method.  In \Fref{fig:AsymmetricArnoldi} are shown the eigenvalue estimates and fission source convergence for Arnoldi's method.  The solid black line again shows the reference eigenvalue from \citet{Kornreich:2002Semi--0} which is 0.427425.  The dashed line shows the Shannon entropy at the end of the simulation for the power method and the mean of the Shannon entropy for Arnoldi's method.

The differences in convergence between Arnoldi's method and the power method are easy to see by comparing \Fref{fig:AsymmetricPower} and \Fref{fig:AsymmetricArnoldi}.  We see that Arnoldi's method has converged both the eigenvalue and fission source almost immediately, just like with the homogeneous slab.  The power method however requires 800--900 iterations before the eigenvalue estimates have converged and approximately 1200 iterations before the fission source converges.

\begin{figure}[p]\centering
    \subfloat[Power method.]{\label{fig:AsymmetricPower}\input{EntropyandVariance/Data/AsymmetricPower}}

    \subfloat[Arnoldi's method.]{\label{fig:AsymmetricArnoldi}\input{EntropyandVariance/Data/AsymmetricArnoldi}}
    \caption{Convergence of eigenvalue estimate and Shannon entropy for asymmetric geometry.  Solid black line is the fundamental eigenvalue ($\lambda_0 = 0.427425$ \cite{Kornreich:2002Semi--0}); dashed black line is the entropy at the end of the simulation for the power method and mean entropy for Arnoldi's method.}
\end{figure}

The symmetric problem shows a different convergence for the power method as displayed in \Fref{fig:SymmetricPower}.  \Fref{fig:SymmetricArnoldi} shows convergence of the eigenvalue estimates and fission source as calculated by Arnoldi's method.  The solid black lines show the published eigenvalue \cite{Kornreich:2002Semi--0}, 0.424316.  The dashed black line for the power method shows the final value of the Shannon entropy.  The dashed black line for Arnoldi's method shows the mean value of the Shannon entropy.

In the power method we see that the eigenvalue estimate has converged almost immediately, but the fission source takes much longer to converge.  The power method ran for an extra 2000 iterations and it looks like the fission source might be converged after 4500 iterations, but it looks like the Shannon entropy may still be trending upwards and therefore still has not converged.  In Arnoldi's method both the eigenvalue estimate and the fission source from Arnoldi's method have converged almost immediately.

\begin{figure}[p]\centering
    \subfloat[Power Method]{\label{fig:SymmetricPower}\input{EntropyandVariance/Data/SymmetricPower}}

    \subfloat[Arnoldi's Method]{\label{fig:SymmetricArnoldi}\input{EntropyandVariance/Data/SymmetricArnoldi}}
    \caption{Convergence of eigenvalue estimate and Shannon entropy for symmetric geometry.  Solid black line is the fundamental eigenvalue ($\lambda_0 = 0.424316$ \cite{Kornreich:2002Semi--0}); dashed black line is the entropy at the end of the simulation for the power method and mean entropy for Arnoldi's method.}
\end{figure}

In \Fref{fig:SymmetricVectors} is shown the fundamental eigenvector estimates of the symmetric, heterogeneous problem from the power method and Arnoldi's method.  These eigenvectors are the mean of the last 1250 power iterations or 125 Arnoldi restarts.  We can see that height of the eigenvector in the fuel regions is not the same, but we know that they must be because the slab is symmetric.  Not enough particles are being transported into the right fuel region causing the eigenvector estimate to be smaller in that region.

In \Fref{fig:SymmetricVector1E7} is shown the fundamental eigenvector for the same symmetric, heterogeneous problem, but this time 1E7 particles were tracked in each iteration.  The results for the previous problem are included for comparison.  We can see that when more particles are used, more particles reach the right fuel region and the eigenvector estimate becomes larger.  We expect that if enough particles are tracked, the eigenvector will become symmetric.

\begin{sidewaysfigure} \centering
    \input{EntropyandVariance/Data/SymmetricVectors}
    \caption{Fundamental eigenvector estimates for the symmetric, heterogeneous problem from the power method and Arnoldi's method.}
    \label{fig:SymmetricVectors}
\end{sidewaysfigure}

\begin{sidewaysfigure} \centering
    \input{EntropyandVariance/Data/SymmetricVectors1E7}
    \caption{Fundamental eigenvector estimates for the symmetric, heterogeneous problem from Arnoldi's method using 1E6 and 1E7 particles per iteration.}
    \label{fig:SymmetricVector1E7}
\end{sidewaysfigure}

\section{Summary}
When doing Monte Carlo particle transport, it is important that the eigenvalue estimates and fission source have converged before we begin tallying.  If convergence has not been achieved then estimates of the eigenvalue (or some other tally) which are wrong will be used thus affecting the final result.  Using the Shannon entropy of the fission source, it is easy to monitor the convergence of both the eigenvalue estimate and fission source.  \citet{Brown:2009A-Rev-0} suggests that the number of inactive iterations can be estimated by running the simulation with a small number of particles tracked in an iteration and see how many iterations are required for convergence.

Regardless of how the number of necessary inactive iterations is determined, the inactive iterations must still be performed; for Arnoldi's method only one inactive restart is required.  Because of its rapid convergence, Arnoldi's method can save computational expense because it does not require the many hundreds of inactive iterations to converge like the power method.    Arnoldi's method converges immediately for the three problems shown in this chapter and does not appear to need any inactive iterations.


% This is part of the TFTB Reference Manual.
% Copyright (C) 1996 CNRS (France) and Rice University (US).
% See the file refguide.tex for copying conditions.

\markright{ridges}
\section*{\hspace*{-1.6cm} ridges}

\vspace*{-.4cm}
\hspace*{-1.6cm}\rule[0in]{16.5cm}{.02cm}
\vspace*{.2cm}

{\bf \large \sf Purpose}\\
\hspace*{1.5cm}
\begin{minipage}[t]{13.5cm}
Extraction of ridges from a reassigned TF representation.
\end{minipage}
\vspace*{.5cm}

{\bf \large \sf Synopsis}\\
\hspace*{1.5cm}
\begin{minipage}[t]{13.5cm}
\begin{verbatim}
[ptt,ptf] = ridges(tfr,hat,t,method)
[ptt,ptf] = ridges(tfr,hat,t,method,trace)
\end{verbatim}
\end{minipage}
\vspace*{.5cm}

{\bf \large \sf Description}\\
\hspace*{1.5cm}
\begin{minipage}[t]{13.5cm}
        {\ty ridges} extracts the ridges of a time-frequency
        distribution. These ridges are some particular sets of curves
        deduced from the stationary points of their reassignment
        operators.\\

\hspace*{-.5cm}\begin{tabular*}{14cm}{p{1.5cm} p{8.5cm} c}
Name & Description & Default value\\
\hline
        {\ty tfr}    & time-frequency representation\\
        {\ty hat }   & complex matrix of the reassignment vectors\\
        {\ty t    }  & the time instant(s)\\
        {\ty method} & the chosen representation \\
        {\ty trace } & if nonzero, the progression of the algorithm is shown
                                           & {\ty 0}\\
\hline  {\ty ptt, ptf} & two vectors for the time and frequency
        coordinates of the stationary points of the reassignment.
        Therefore, {\ty plot(ptt,ptf,'.')} shows the squeleton of the
        representation\\

\hline
\end{tabular*}
\vspace*{.2cm}

When called without output arguments, {\ty ridges} runs {\ty
plot(ptt,ptf,'.')}.
\end{minipage}
\vspace*{.5cm}

{\bf \large \sf Example}\\
\hspace*{1.5cm}
\begin{minipage}[t]{13.5cm}
Consider the ridges of the smoothed-pseudo WVD of a linear chirp signal :
\begin{verbatim}
         sig=fmlin(128,0.1,0.4); t=1:2:127;
         [tfr,rtfr,hat]=tfrrspwv(sig,t,128);
         ridges(tfr,hat,t,'tfrrspwv',1);
\end{verbatim}
The points obtained are almost perfectly localized on the instantaneous
frequency law of the signal.
\end{minipage}
\vspace*{.5cm}

{\bf \large \sf See Also}\\
\hspace*{1.5cm}
\begin{minipage}[t]{13.5cm}
\begin{verbatim}
friedman.
\end{verbatim}
\end{minipage}


\section{Calculation of Sea Level Pressure}

Over land, surface pressure is dominated by the land surface elevation rather than the position of low pressure centers, fronts, etc. In order to see these features, surface pressure must be converted to sea level pressure, also known as the pressure at sea level (PSL, denoted here by $p_s$), which is the surface pressure we would have if the landmass was not there. There's no single accepted set of assumptions for how this ``subterranean atmosphere'' should behave. What is its lapse rate? How much moisture does it contain? Because PSL is just a diagnostic output for EAMxx, our current implementation just copies what EAMf90 did, which was inherited from an early version of the Community Atmosphere Model. This approach is outlined in Section 3.1B of \cite{Trenberth_et93} but that document isn't very clear so we describe the approach below.
%Trenberth, K. E., Berry, J. C., & Buja, L. E. (1993). Vertical Interpolation and Truncation of Model-coordinate Data (No. NCAR/TN-396+STR). University Corporation for Atmospheric Research. doi:10.5065/D6HX19NH

%================================
\subsection{Formulation}
%================================

The basic idea is to assume the subterranean atmosphere is free of moisture and has a lapse rate $\Gamma = 6.5$ K km$^{-1}$ unless the atmosphere is too warm or too cold, in which case the lapse rate and the ground temperature are empirically modified to provide more reasonable results (as described later). The hydrostatic equation $\partial p/\partial z = -\rho_\mathrm{air} g$ is integrated from a height of zero (sea level) to the height of the ground to compute sea level pressure. Because the model stores geopotential $\Phi$ rather than geopotential height $z$, we rewrite the hydrostatic equation using $\Phi = gz$ (where $g$ is the gravitational constant). We also use the ideal gas law $\rho_\mathrm{air} = p/(R_d T)$ (where $R_d$ is the gas constant for dry air) to write density in terms of pressure and temperature. Thus our hydrostatic equation is
%-------------------------------------
\begin{equation}
  \frac{\partial p}{\partial \Phi} = \frac{-p}{R_d T}
\label{eq:hydrostat}
\end{equation}
%-------------------------------------
Because lapse rate is assumed linear, the temperature at any $\Phi$ is
%-------------------------------------
\begin{equation}
  T = T_\mathrm{g} + \frac{\Gamma}{g}\left(\Phi_g - \Phi \right)
  \label{eq:T}
\end{equation}
%-------------------------------------
where the subscript $g$ refers to the value of the atmosphere at ground level (i.e. the bottom interface of the lowest atmosphere grid cell). Note that $\Gamma$ is positive in this formulation. For our subterranean atmosphere, $\Phi$ varies between 0 (sea level) and $\Phi_g$, which should be positive except in a few rare depressions like Death Valley. As a result, we expect $T$ to be warmer than $T_g$ most but not all of the time.

Integrating (\ref{eq:hydrostat}) over the vertical after substituting (\ref{eq:T}) yields:
%-------------------------------------
\begin{equation}
  \int_{p_s}^{p_g} \frac{\partial p}{p} = \int_0^{\Phi_g} \frac{-\partial \Phi}{R_d \left[T_\mathrm{g} + \frac{\Gamma}{g}\left(\Phi_g - \Phi\right)\right]}.
  \label{eq:integral}
\end{equation}
%-------------------------------------
For $\Gamma \ne 0$, this equation can be solved exactly by making the substitution $x = R_d (T_\mathrm{g} + \Gamma/g \left(\Phi_g - \Phi\right) )$, which yields
%-------------------------------------
\begin{equation}
  p_s = p_g \left[ 1+\frac{\Gamma \Phi_g}{g T_g} \right]^{g/(R_d \Gamma)}.
  \label{eq:exact_soln}
\end{equation}
%-------------------------------------
If $\Gamma=0$, the exact solution is
%-------------------------------------
\begin{equation}
  p_s = p_g \exp\left\{\frac{\Phi_g}{R_d T_g}\right\}.
  \label{eq:exact_0gamma}
\end{equation}
%-------------------------------------
Because we will set $\Gamma$ to zero when $_g$ gets too warm, using exact solutions would require conditional execution which is inefficient on GPUs. Also, computing non-integer exponents is expensive. Thus we note that the integrand on the right-hand side of (\ref{eq:integral}) can be written as $A \cdot 1/(1-y) = A \sum_{k=0}^\infty y^k$ for $A=1/(R_d T_g)$ and $y=\Gamma/(g T_g)(\Phi - \Phi_g)$. Because $y$ is always much less than 1, accurate approximations can be made from just the first 3 summands. This leads to
%-------------------------------------
\begin{equation}
  p_s \approx p_g \exp\left\{\beta \left[1 - \frac{\alpha \beta}{2} + \frac{(\alpha \beta)^2}{3} \right] \right\}
  \label{eq:approx_soln}
\end{equation}
%-------------------------------------
for $\alpha=\Gamma R_d/g$ and $\beta=\Phi_g/(R_d T_g)$.

If $T_g<255$ K, (\ref{eq:approx_soln}) is applied with $T_g$ modified according to $\widetilde{T_g} = (255 - T_g)/2$. If $T_g>290.5$ K, a trial sea-level temperature $\widetilde{T_s}$ is computed using (\ref{eq:T}) with $\Phi = 0$ and $\Gamma = 6.5$ K km$^{-1}$. If $\widetilde{T_s}$ is also greater than 290.5 K, $\Gamma$ is set to zero (to prevent temperatures near sea levels from getting even warmer) and $\widetilde{T_g} = (290.5 - T_g)/2$ is used in (\ref{eq:approx_soln}). If $T_g>290.5$ K but $\widetilde{T_s}<290.5$ K, excessive temperatures are prevented by choosing $\Gamma$ such that sea-level temperature just reaches 290.5 K. Note that these crude hacks accomplish their intended goal of avoiding extreme temperatures in a smooth way when $\Phi_g>0$, but may not be appropriate when $\Phi_g<0$. We didn't bother to improve this treatment because accurate $p_s$ isn't a major goal for us and  the current treatment survived without complaint for the last 28 yrs.

%================================
\subsection{Validation}
%================================

Fig. \ref{fig:exactVSapprox} compares the exact solutions from (\ref{eq:exact_soln}) and (\ref{eq:exact_0gamma}) against the 2nd order Taylor series we use in our calculations and the cruder 1st order approximation. Both approximations agree very well with the exact solutions. In fact, the first-order approximation is probably sufficient for our uses - it is at most 1 mb worse than the 2nd order result in even the most extreme cases. For the $\Gamma=0$ case, both approximations are off by as much as 6 mb, but the 1st order approach isn't any worse than the 2nd order version.
%----------------------------------------------
\begin{figure}[ht]
\noindent
\centering
\rotatebox{0}{
\includegraphics[keepaspectratio=true, width = 4.5in]
{psl_exactVSapprox.pdf}}
\caption{Tests of exact versus approximate $p_s$ calculations. Left panels are warm enough that $\Gamma=0$ ($T_g=292$ K) while right panels use $\Gamma=6.5$ K km$^{-1}$ ($T_g=280$ K). Top panels show actual $p_s$ and bottom panels show bias. Sea level pressures are much too high because $p_g=1000$ mb, but this should be fine for testing purposes. Note that the lowest elevation sampled is -100 m to test behavior when terrain is below sea level.}
\label{fig:exactVSapprox}
%EXPLANATION:
%/g/g11/caldwep/py/scream/v1/calc_psl.py
\end{figure}
%----------------------------------------------

Fig. \ref{fig:psl_vs_v0} compares $p_s$ from an old F90 simulation against values calculated using our approximate formula. As expected, results look very similar despite using midpoint $T$ as an approximation for $T_g$. Using a first-order rather than 2nd order Taylor series once again has an insignificant effect.
%----------------------------------------------
\begin{figure}[ht]
\noindent
\centering
\rotatebox{0}{
\includegraphics[keepaspectratio=true, width = 5in]
{psl_vs_v0.pdf}}
\caption{Comparison of $p_s$ from an old ne4 F90 model simulation (top left) versus calculation of the same quantity using (\ref{eq:approx_soln}). Panels on the left show $p_s$ and right-hand panels show differences between simulations. Calculated $p_s$ used midpoint rather than surface temperature because the latter wasn't available; this likely accounts for most of the F90 vs new calculation differences we see; despite this imperfection, biases are still acceptably low.}
\label{fig:psl_vs_v0}
%EXPLANATION:
%/g/g11/caldwep/py/scream/v1/calc_psl.py
\end{figure}
%----------------------------------------------

%================================
\subsection{Unit Tests}
%================================

\begin{enumerate}
\item Is C++ value close to exact solution for very warm conditions where $\Gamma$ should be zero?
\item Is C++ value close to exact solution for normal conditions where $\Gamma$ should be 6.5 K km$^{-1}$?
\item Is $p_s<p_g$ when $\Phi_ground>0$ (for very cold, moderate, and very warm $T_g$ and a variety of $p_g$ values)?
\item Is $p_s>p_g$ when $\Phi_ground<0$ (for very cold, moderate, and very warm $T_g$ and a variety of $p_g$ values)?
\item Test that modified $T_g$ values for very cold and very warm conditions are applied correctly. Not sure how to do this - should computation of $\widetilde{T_g}$ be its own unit? Or should modified $T_g$ be computed in the unit test itself and stuffed into the exact solution to provide an independent calculation of the expected solution? Or is this too dumb to test?
\end{enumerate}


%% BOUNDED CONSTRAINT PROBS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Preliminaries}
\label{sec:preliminaries}

\newcommand{\indices}[1]{\{\,1\ldots,#1\}}

Throughout this section we use bold capital letter symbols such as
$\mat{A}$ to denote matrices,
bold lower case letters such as $\v{x}$ to denote vectors,
and undecorated lower case letters to denote scalars.  The components of a
vector $\v{x} \in \RR^n$ are denoted by $\v{x}_i$ with $i \in \{1,\ldots,n\}$.
%
We use Greek letters such as $\theta$ to denote functions that assign values
to only some of the coordinates (e.g.,~the function $\theta : Y \to \ZZ$ with
$Y \subseteq \indices{n}$ only assigns values to indices in $Y$).
%
A vectors $\v{x}$ is then just an assignment where all the indices have
been assigned.

\paragraph{Lattices.} A \emph{lattice} is a discrete additive subgroup of a
Euclidean space. A subset $\La \subset \RR^n$ is a lattice if and only if
there is a collection of linearly independent vectors $\v{v}_1, \ldots,
\v{v}_n \in \RR^n$ such that
$\La = \left\{ \sum_{i=1}^n c_i \v{v}_i \, \mid \, c_i \in \ZZ \right\}$.
%
Such a collection is called a \emph{basis} of
$\La$ and the number $n$ is called the \emph{rank}.
%
A lattice generally has many different bases.
%, but when a basis
%$\{\v{v}_1, \ldots, \v{v}_n\}$ is fixed, each point $\v{x} \in \La$
%can be decomposed into a weighted integral
%sum $\v{x} = \Sum_{i=1}^n \v{v}_i \v{u}_i$ of the vectors.
%
\emph{Lattice reduction} is a term used to describe
algorithms for producing a basis that is ``short'' and ``nearly orthogonal'',
a property that is extremely useful in practice~\cite{Lenstra}.

%JHx
Given a fixed basis $\{\v{v}_1, \ldots, \v{v}_n\}$ of $\La$ and a partial
assignment $\theta : Y \to \ZZ$ with $Y \subseteq \indices{n}$,
we define the set of lattice elements $\La_\theta \subseteq \La$ as follows:
%
\begin{equation}
     \label{eq:lat-sublayer}
     \La_\theta := \left\{ \sum_{i=1}^n c_i \v{v}_i \mid c_i \in \ZZ, \,
         i \in \fn{dom}(\theta) \Rightarrow c_i = \theta(i) \right\}.
\end{equation}
%
We call $\La_\theta$ a \emph{sublayer} of $\La$.  The set $\La_\theta$ should be thought
of as the subset of lattice elements which remain after a partial assignment
of coefficients is made.

Our algorithm for finding \emph{integer} solutions will rely on an
underlying solver for systems of \emph{real} solutions.  To model this,
we define the real-affine linear space $\La^\RR_\theta$ containing
$\La_\theta$:
%
\begin{equation}
     \La^\RR_\theta := \left\{ \sum_{i=1}^n c_i \v{v}_i \mid c_i \in \RR, \,
        i \in \fn{dom}(\theta) \Rightarrow c_i = \theta(i) \right\}.
\end{equation}
%
A fundamental problem in the theory of lattices is the \emph{closest vector
problem} (CVP)~\cite{Lenstra}. We introduce it here because it is very
closely related to our approach for solving bounded ILP. CVP has the following
form: given a lattice $\La \subset \RR^n$ and a point $\v{q} \in \RR^n$, find
a vector $\v{z} \in \La$ that is \emph{closest} to $\v{q}$; i.e. a vector for
which $\norm{\v{z}-\v{q}}$ is minimal.
%
Such a closest vector must exist, but it may be difficult to compute and may
not be unique.
%
The problem of deciding whether such a vector exists within a given bound
is known to be NP-hard~\cite{Boas}, though polynomial-time algorithms are
known if the rank of $\La$ is fixed~\cite{Schnorr-hierarchy}.
%
\paragraph{$\linf$ Metric.} In our decision procedure, we work in $\RR^n$
with a different metric than the usual Euclidean metric. The $\linf$ norm is
defined by $\norminf{\v{x}} := \max \{ \abs{x_i} \mid i=1,\ldots,n \}$. It
determines a metric via $d_\infty(\v{x}, \v{y}) := \norminf{\v{x}-\v{y}}$.

With $\linf$, the set of points whose distance from a given point $\v{p}$
is at most $r$ (i.e. the closed ball of radius $r$ around $\v{p}$) is a
hypercube (the $n$-dimensional analogue of a square) each of whose faces
is orthogonal to a coordinate axis. Explicitly,
%
\begin{equation}
    \label{eq:linf-sphere}
    \left\{ \v{x} \in \RR^n \mid d_\infty(\v{x}, \v{p}) \le r \right\} =
    \left\{ (x_1, \ldots, x_n) \mid p_i-r \le x_i \le p_i+r \right\}.
\end{equation}
%
The distance metric can be extended to subsets of $\RR^n$ by taking it to be the
minimum distance between any two points in the subsets, i.e.,
for $X, Y \subseteq \RR^n$,
\begin{equation}
 d_\infty(X, Y) := \min_{(\v{x},\v{y}) \in X{}\times{}Y} d_\infty(\v{x},\v{y})
\end{equation}
%
We remark that when the sets $X$ and $Y$ can be defined by systems of linear
equality and inequality constraints over rational coefficients, then the
$\linf$ distance can be calculated using linear programming techniques by
observing that:
%
\begin{align}
d_\infty(X, Y)
    &= \min \left\{\ d_\infty(\v{x}, \v{y})   \mid \v{x} \in X,\, \v{y} \in Y\ \right\} \\
    &= \min \left\{\ \max_i\{\abs{x_i-y_i}\}  \mid \v{x} \in X,\, \v{y} \in Y\ \right\} \\
    &= \min \left\{\ t \mid \abs{x_i-y_i} \le t,\, \v{x} \in X,\, \v{y} \in Y\ \right\} \\
    &= \min \left\{\ t \mid x_i-y_i \le t,\, -(x_i-y_i) \le t,\, \v{x} \in X\,
      \v{y} \in Y\ \right\}
\label{eq:set_distance}
\end{align}
%
The last line is a real linear optimization problem over the free
variables in the systems of equations used to define $X$ and $Y$.


\problemname{Rainbow Road Race}

Marcy is attending Pride Fest and has signed up to participate in the
Rainbow Road Race. On each street, there are volunteers who have
colored chalk powder. As contestants walk along a street, volunteers
throw chalk onto the contestants. The chalk thrown on each street is one of
the seven colors of the rainbow (Red, Orange, Yellow, Green, Blue,
Indigo, Violet).  Once a person starts walking along a street, they
must walk to the end of that street.

The race starts at the \textit{Festival Tent}. The goal of the race is
to get covered by chalk of every color and come back to the tent. Help
Marcy determine the shortest distance she has to travel to get every
color and make it back to the tent.

\begin{figure}[h]
\begin{center}
 \includegraphics[width=0.7\textwidth]{rrr.pdf}
 \caption{The left picture illustrates Sample Input 1 and the right picture illustrates Sample Input 2. The triangle is the Festival Tent.}
\end{center}
\end{figure}

\section*{Input}

The first line of input contains two integers $n$~($7 \leq n \leq 7^3$),
which is the number of fun locations at the festival, and $m$~($7 \leq m
\leq 7^4$), which is the number of streets connecting the fun
locations. The fun locations are numbered $1, \dots , n$ and the
Festival Tent is location $1$.

The next $m$ lines describe the streets. Each of these lines contains
three integers $\ell_1$, $\ell_2$~($1 \leq \ell_1 < \ell_2 \leq n$) and
$d$~($1 \leq d \leq 7^5$), followed by a single character
$c$~($c$ is one of \texttt{R}, \texttt{O}, \texttt{Y}, \texttt{G},
\texttt{B}, \texttt{I}, \texttt{V}). This specifies that this street
connects locations $\ell_1$ and $\ell_2$, is $d$ meters long and the
chalk thrown is color $c$.

It is always possible to travel between any pair of fun locations. There
is at most one street between any two pairs of locations and each color
appears at least once.

\section*{Output}

Display the shortest distance Marcy has to travel to get every color
and make it back to the Festival Tent.


\section{Analytic Geometry}\label{sec:AnalyticGeometry}

\input{1-review/1-2-new-cartesian-coordinate-plane}

Suppose we have two points $A$ and $B$ in the $(x,y)$-plane.
We often want to know the change in $x$-coordinate (also called the
``horizontal distance'') in going from $A$ to $B$.  This is often
written $\Delta x$, where the meaning of $\Delta$ (a capital delta in
the Greek alphabet) is ``change in''. Thus, $\Delta x$ can be read as
``change in $x$'' although it usually is read as ``delta $x$''. The
point is that $\Delta x$ denotes a single number, and should not be
interpreted as ``delta times $x$''. Similarly, the ``change in $y$'' is written $\Delta y$
and represents the difference between the $y$-coordinates of the
two points. It is the vertical distance you have to move in going from $A$ to $B$.

\begin{example}{Change in $x$ and $y$}{ChangeIn}\label{ChangeIn}
	If $A=(2,1)$ and $B=(3,3)$ the change in $x$ is
	$$\Delta x=3-2=1$$
	while the change in $y$ is
	$$\Delta y= 3-1=2$$
	\vspace{-0.5cm}
\end{example}

The general formulas for the change in $x$ and the change in $y$
between a point $(x_1,y_1)$ and a point $(x_2,y_2)$ are:
$$
\Delta x=x_2-x_1,\qquad\qquad\Delta y=y_2-y_1.
$$
Note that either or both of these might be negative.\\

%%%%%%%%%% APPLICATION
%%%%%%%%%%%%%%%%%%%%%
%In applications, often letters other than $x$ and $y$ are used, and
%often different scales are chosen in the horizontal and vertical
%directions.
%
%\pagebreak
%\begin{example}{Data Plot}{DataPlot}
%	Suppose you drop a coin from a window, and you want to study how
%	its height above the ground changes from second to second.
%	It is natural to let the letter $t$ denote the time
%	(the number of seconds since the object was released) and to let the
%	letter $h$ denote the height.  For each $t$ (say, at one-second
%	intervals) you have a corresponding height $h$.  This information can
%	be tabulated, and then plotted on the $(t,h)$ coordinate plane, as
%	shown in Figure~\ref{fig:data plot}.
%\end{example}
%\begin{solution}
%
%\hspace{1cm}	\begin{tabular}{c|c}
%	Time, $t$ & Height, $h$  \\ \hline
%	0 & 80 \\
%	1 & 75.1 \\
%	2 & 60.4 \\
%	3 & 35.9 \\
%	4 & 1.6 \\
%	\end{tabular}
%
%	\vspace{-2cm}
%
%	\figure[h]
%		\hspace{70mm}	\beginpicture
%			\normalgraphs
%			%\ninepoint
%			\setcoordinatesystem units <2truecm,0.5truemm>
%			\setplotarea x from 0 to 4.2, y from 0 to 90
%			\axis left shiftedto x=0 ticks numbered from 20 to 80 by 20 /
%			\axis bottom shiftedto y=0 ticks numbered from 0 to 4 by 1 /
%		%	\put {$t$} [l] <3pt,0pt> at 4.2 0
%		%	\put {$h$} [l] <3pt,0pt> at 0 90
%			\setquadratic
%			\plot 0 80 1 75.1 2 60.4 3 35.9 4 1.6 /
%			\multiput {$\bullet$} at 0 80 1 75.1 2 60.4 3 35.9 4 1.6 /
%			\endpicture
%
%
%
%\vspace{-4.4cm} \hspace{63mm} \rotatebox{90}{\textcolor{black}{Height, $h$ (meters)}}
%
%\vspace{8.6mm} \hspace{95mm} Time, $t$(seconds) \\
%
%\caption{A data plot, height versus time. \label{fig:data plot}}
%\endfigure
%\end{solution}

% Input each subsection
\input{1-review/1-2-new-relations}
\input{1-review/1-2-1-lines}
\input{1-review/1-2-2-distances-and-midpoints}
\input{1-review/1-2-3-conics}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\Opensolutionfile{solutions}[ex]
\section*{Exercises for \ref{sec:AnalyticGeometry}}

\begin{enumialphparenastyle}

\begin{multicols}{2}
%%%%%%%%%%
\begin{ex}
Find the equation of the line in the form $y=mx+b$:
\begin{enumerate}
	\item	through $(1,1)$ and $(-5, -3)$
	\item	through $(-1,2)$ with slope $-2$
	\item	through $(-1,1)$ and $(5, -3)$
	\item	through $(2,5)$ and parallel to the line $3x+9y+6=0$
	\item	with $x$-intercept 5 and perpendicular to the line $y=2x+4$
\end{enumerate}
\begin{sol}
\begin{enumerate}
	\item	$(2/3)x+(1/3)$
	\item	$y=-2x$
	\item	$y=(-2/3)x+(1/3)$
	\item	$y=-x/3+17/3$
	\item	$y=-1/2x+5/2$
\end{enumerate}
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
Change the following equations to the form $y=mx+b$, graph the
line, and find the $y$-intercept and $x$-intercept.
\begin{enumerate}
	\item	$y-2x=2$
	\item	$x+y=6$
	\item	$x=2y-1$
	\item	$3=2y$
	\item	$2x+3y+6=0$
\end{enumerate}
\begin{sol}
\begin{enumerate}
	\item	$y=2x+2$, $2$, $-1$
	\item	$y=-x+6$, $6$, $6$
	\item	$y=x/2+1/2$, $1/2$, $-1$
	\item	$y=3/2$, $y$-intercept: $3/2$, no $x$-intercept
	\item	$y=(-2/3)x-2$, $-2$, $-3$
\end{enumerate}
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
Determine whether the lines $3x+6y=7$ and $2x+4y=5$ are parallel.
\begin{sol}
Yes, the lines are parallel as they have the same slope of $-1/2$
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
Suppose a triangle in the $(x,y)$-plane has vertices $(-1,0)$,
$(1,0)$ and $(0,2)$.  Find the equations of the three lines that lie along
 the sides of the triangle in $y=mx+b$ form.
\begin{sol}
$y=0$, $y=-2x+2$, $y=2x+2$
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
Let $x$ stand for temperature in degrees Celsius (centigrade), and let
$y$ stand for temperature in degrees Fahrenheit.  A temperature of $0^\circ$C
corresponds to $32^\circ$F, and a temperature of
$100^\circ$C corresponds to $212^\circ$F.  Find the
equation of the line that relates temperature Fahrenheit $y$ to
temperature Celsius $x$ in the form $y=mx+b$.
Graph the line, and find the point at which this line intersects $y=x$.
What is the practical meaning of this point?
\begin{sol}
$y=(9/5)x+32$, $(-40,-40)$
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
A car rental firm has the following charges for a certain type of car:
\$25 per day with 100 free miles included, \$0.15 per mile for more than
100 miles.  Suppose you want to rent a car for one day, and you know you'll
use it for more than 100 miles.  What is the equation relating the cost
$y$ to the number of miles $x$ that you drive the car?
\begin{sol}
$y=0.15x+10$
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
A photocopy store advertises the following prices: 5c~per
copy for the first 20 copies, 4c~per copy for the 21st through
100th copy, and 3c~per copy after the 100th copy.  Let $x$ be the
number of copies, and let $y$ be the total cost of photocopying.  (a)
Graph the cost as $x$ goes from 0 to 200 copies.  (b) Find the
equation in the form $y=mx+b$ that tells you the cost of making $x$
copies when $x$ is more than 100.
\begin{sol}
$0.03x+1.2$
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
Market research tells you that if you set the price of an item at
\$1.50, you will be able to sell 5000 items; and for every 10 cents you
lower the price below \$1.50 you will be able to sell another 1000 items.
Let $x$ be the number of items you can sell, and let $P$ be the price of
an item.  (a)~Express $P$ linearly in terms of $x$, in other words,
express $P$ in the form $P=mx+b$.  (b)~Express $x$
linearly in terms of $P$.
\begin{sol}
(a) $P=-0.0001x+2$\\
(b) $x=-10000P+20000$
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
An instructor gives a 100-point final exam, and decides that a score
90 or above will be a grade of 4.0, a score of 40 or below will be a grade
of 0.0, and between 40 and 90 the grading will be linear.  Let $x$ be
the exam score, and let $y$ be the corresponding grade.  Find a formula
of the form $y=mx+b$ which applies to scores $x$ between 40 and 90.
\begin{sol}
$(2/25)x-(16/5)$
\end{sol}
\end{ex}

%%%%%%%%%%%
%\begin{ex}
%Find the distance between the pairs of points:
%\begin{enumerate}
%	\item	$(-1,1)$ and $(1,1)$.
%	\item	$(5,3)$ and $(-7,-2)$.
%	\item	$(1,1)$ and the origin.
%\end{enumerate}
%\begin{sol}
%\begin{enumerate}
%	\item	$2$
%	\item	$\sqrt{2}$
%	\item	$\sqrt{2}$
%\end{enumerate}
%\end{sol}
%\end{ex}
%
%%%%%%%%%%%
%\begin{ex}
%Find the midpoint of the line segment joining the point $(20,-10)$ to the origin.
%\end{ex}

%%%%%%%%%%%%%%%%%%%%
\begin{ex}
Find the distance $d$ between the points and the midpoint $M$ of the line segment which connects them.\\
\begin{enumerate}
 \item \hspace{2mm} $(1,2)$, $(-3,5)$ \\
 \item  \hspace{2mm} $(3, -10)$, $(-1, 2)$ \\
 \item 	\hspace{2mm} $\left( \dfrac{1}{2}, 4\right)$, $\left(\dfrac{3}{2}, -1\right)$ \\
 \item  \hspace{2mm}	 $\left(- \dfrac{2}{3}, \dfrac{3}{2} \right)$, $\left(\dfrac{7}{3}, 2\right)$ \\
 \item  \hspace{2mm} $\left( \dfrac{24}{5}, \dfrac{6}{5} \right)$, $\left( -\dfrac{11}{5}, -\dfrac{19}{5} \right)$ \\
 \item  \hspace{2mm}	 $\left(\sqrt{2}, \sqrt{3}\right)$, $\left(-\sqrt{8}, -\sqrt{12}\right)$ \vphantom{$\left( \dfrac{6}{5} \right)$} \\
 \item  \hspace{2mm} $\left(2 \sqrt{45}, \sqrt{12} \right)$, $\left(\sqrt{20}, \sqrt{27} \right)$\\
 \item  \hspace{2mm} $(0, 0)$, $(x, y)$ \\
\end{enumerate}
\begin{sol}
	\begin{enumerate}
\item $d = 5$, $M = \left(-1, \frac{7}{2} \right)$
\item $d = 4 \sqrt{10}$, $M = \left(1, -4 \right)$
\item $d = \sqrt{26}$, $M = \left(1, \frac{3}{2} \right)$
\item $d= \frac{\sqrt{37}}{2}$, $M = \left(\frac{5}{6}, \frac{7}{4} \right)$
\item  $d = \sqrt{74}$, $M = \left(\frac{13}{10}, -\frac{13}{10} \right)$ \vphantom{$\left( \frac{\sqrt{3}}{2} \right)$}
\item $d= 3\sqrt{5}$, $M = \left(-\frac{\sqrt{2}}{2}, -\frac{\sqrt{3}}{2} \right)$
\item  $d = \sqrt{83}$, $M = \left(4 \sqrt{5}, \frac{5 \sqrt{3}}{2} \right)$
\item $d = \sqrt{x^2 + y^2}$, $M = \left( \frac{x}{2}, \frac{y}{2}\right)$ \vphantom{$\left( \frac{\sqrt{3}}{2} \right)$}
\end{enumerate}
\end{sol}
\end{ex}

\begin{ex}
Find all of the points of the form $(x, -1)$ which are $4$ units from the point $(3,2)$.
\begin{sol}
$(3 + \sqrt{7}, -1)$, $(3-\sqrt{7}, -1)$
\end{sol}
\end{ex}

\begin{ex}
Find all of the points on the $y$-axis which are $5$ units from the point $(-5,3)$.
\begin{sol}
	$(0,3)$
\end{sol}
\end{ex}

\begin{ex}
Find all of the points on the $x$-axis which are $2$ units from the point $(-1,1)$.
\begin{sol}
$(-1+\sqrt{3},0)$, $(-1-\sqrt{3},0)$ \vphantom{$\left( \frac{\sqrt{3}}{2} \right)$}
\end{sol}
\end{ex}

\begin{ex}
Find all of the points of the form $(x,-x)$ which are $1$ unit from the origin.
\begin{sol}
	$\left(\frac{\sqrt{2}}{2},-\frac{\sqrt{2}}{2} \right)$, $\left(-\frac{\sqrt{2}}{2},\frac{\sqrt{2}}{2}\right)$
\end{sol}
\end{ex}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{ex}
 Let's assume for a moment that we are standing at the origin and the positive $y$-axis points due North while the positive $x$-axis points due East.  Our Sasquatch-o-meter tells us that Sasquatch is 3 km West and 4 km South of our current position.  What are the coordinates of his position?  How far away is he from us?  If he runs 7 km due East what would his new position be?
 \begin{sol}
 	$(-3,-4), \, 5 \,\, km, \,\, (4, -4)$
 \end{sol}
 \end{ex}

 %%%%%%%%%%%%%%%%%%%%%%%%%
\begin{ex}
Verify the Distance Formula  for the cases when:

\begin{enumerate}

 	\item The points are arranged vertically.  (Hint: Use $P(a, y_{\mbox{\tiny$0$}})$ and $Q(a, y_{\mbox{\tiny$1$}})$.)
 	\item The points are arranged horizontally. (Hint: Use $P(x_{\mbox{\tiny$0$}}, b)$ and $Q(x_{\mbox{\tiny$1$}}, b)$.)
 	\item The points are actually the same point.

 \end{enumerate}
\begin{sol}

\end{sol}
\end{ex}

%%%%%%%%%%%%%%%%%%%
\begin{ex}
Verify the Midpoint Formula by showing the distance between $P(x_{\mbox{\tiny$1$}}, y_{\mbox{\tiny$1$}})$ and $M$ and the distance between $M$ and $Q(x_{\mbox{\tiny$2$}}, y_{\mbox{\tiny$2$}})$ are both half of the distance between $P$ and $Q$.
\begin{sol}

\end{sol}
\end{ex}

%%%%%%%%%%%%%%%%%%%%
\begin{ex}
Show that the points $A$, $\;B$ and $C$ below are the vertices of a right triangle.
\begin{enumerate}

	\item  $A(-3,2)$, $\;B(-6,4)$, and $C(1,8)$

	\item   $A(-3, 1)$, $\;B(4, 0)$ and $C(0, -3)$

\end{enumerate}
\begin{sol}
	(a) The distance from $A$ to $B$ is $|AB| = \sqrt{13}$, the distance from $A$ to $C$ is $|AC| = \sqrt{52}$, and the distance from $B$ to $C$ is $|BC| = \sqrt{65}$.  Since $\left(\sqrt{13}\right)^2 + \left( \sqrt{52} \right)^2 = \left( \sqrt{65} \right)^2$, we are guaranteed by the \href{http://en.wikipedia.org/wiki/Pythagorean_theorem#Converse}{\underline{converse of the Pythagorean Theorem}} that the triangle is a right triangle.\\
	(b) Show that $|AC|^{2} + |BC|^{2} = |AB|^{2}$.
\end{sol}
\end{ex}

%%%%%%%%%%%%%%%%%%%
\begin{ex}
Find a point $D(x, y)$ such that the points $A(-3, 1)$, $\;B(4, 0)$, $\;C(0, -3)$ and $D$ are the corners of a square.  Justify your answer.
\begin{sol}

\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
Find the equation of the circle of radius 3 centered at:
\begin{multicols}{2}
\begin{enumerate}
	\item	$(0,0)$
	\item	$(5,6)$
	\item	$(-5,-6)$
	\item	$(0,3)$
	\item	$(0,-3)$
	\item	$(3,0)$
\end{enumerate}
\end{multicols}
\begin{sol}
\begin{enumerate}
	\item	$x^2+y^2=9$
	\item	$(x-5)^2+(y-6)^2=9$
	\item	$(x+5)^2+(y+6)^2=9$
\end{enumerate}
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
For each pair of points $A(x_1,y_1)$ and $B(x_2,y_2)$ find an equation of
the circle with center at $A$ that goes through $B$.
\begin{multicols}{2}
\begin{enumerate}
	\item	$A(2,0)$, $B(4,3)$
	\item	$A(-2,3)$, $B(4,3)$
\end{enumerate}
\end{multicols}
\end{ex}

%%%%%%%%%%
\begin{ex}
Determine the type of conic section and sketch it.
\begin{enumerate}
	\item	$x^2+y^2+10y=0$
	\item	$9x^2-90x+y^2+81=0$
	\item	$6x+y^2-8y=0$
\end{enumerate}
\begin{sol}
\begin{enumerate}
	\item	circle
	\item	ellipse
	\item	horizontal parabola
\end{enumerate}
\end{sol}
\end{ex}

%%%%%%%%%%
\begin{ex}
Find the standard equation of the circle passing through $(-2,1)$
 and tangent to the line $3x-2y =6$ at the point $(4,3)$.  Sketch.
 (Hint: The line through the center of the circle and the point of tangency
 is perpendicular to the tangent line.)
\begin{sol}
$(x+2/7)^2+(y-41/7)^2=1300/49$
\end{sol}
\end{ex}

\end{multicols}

\end{enumialphparenastyle}