% Preamble
\documentclass[11pt]{PyRollDocs}
\usepackage{textcomp}

\addbibresource{refs.bib}

% Document
\begin{document}

    \title{The Wusatowski Spreading PyRoll Plugin}
    \author{Max Weiner}
    \date{\today}

    \maketitle

    This plugin provides a spreading modelling approach with Wusatowski's formula for flat rolling, adapted on groove rolling by an equivalent rectangle approach.

    \section{Model approach}\label{sec:model-approach}

    \subsection{Wusatowski's spread equation}\label{subsec:wusatowski's-spread-equation}

    \textcite{Wusatowski1969} proposed \autoref{eq:wusatowski} for estimation of spreading in flat rolling,
    where $\gamma = \frac{h_1}{h_0}$ is the compression. $h$ and $b$ are height and width of the workpiece with the indices
    0 and 1 denoting the incoming respectively the outgoing profile. $a$, $c$, $d$ and $f$ are correction
    coefficients for temperature, velocity, material and friction, respectively.

    \begin{equation}
        \beta = \frac{b_1}{b_0} = a \times c \times d \times f \times \gamma^{-w}
        \label{eq:wusatowski}
    \end{equation}

    \noindent The velocity coefficient $c$ can be assumed as below in dependence on the velocity $v$.

    \begin{equation}
        c = \left(-0.002958 + 0.00341 \gamma \right) v + 1.07168 - 0.10431 \gamma
        \label{eq:velocity-coefficient}
    \end{equation}

    $w$ is the spread exponent, many different expressions were given by various authors for its value.
    The original expression by \textcite{Wusatowski1969} is given in \autoref{eq:exponent}, where $R$ is the roll radius.

    \begin{equation}
        w = 10^{ \num{-1.269} \left( \frac{h_0}{2 R} \right)^{\num{0.56}} \frac{b_0}{h_0} }
        \label{eq:exponent}
    \end{equation}

    \subsection{Equivalent rectangle approach}\label{subsec:equivalent-rectangle-approach}

    Wusatowskis spreading model~\cite{Wusatowski1969} was originally built for flat rolling.
    A common approach for groove rolling is to calculate some equivalent rectangular profile to be able to use flat rolling models~\cite{Hensel1978, Spittel1984}.
    \autoref{fig:equivalent_rectangle} shows 3 variants of calculating an equivalent rectangle of a profile.

    \begin{figure}
        \centering
        \includegraphics[width=\linewidth]{equivalent_rectangle}
        \caption{Three methods of defining an equivalent rectangle of an oval groove}
        \label{fig:equivalent_rectangle}
    \end{figure}

    The first variant is to keep the width constant and calculate the height $h'$ so that the cross section $A$ is
    equal:

    \[
        h' = \frac{A}{b}
    \]

    The second variant is to keep the height constant and calculate the width $b'$ so that the cross section $A$ is
    equal:

    \[
        b' = \frac{A}{h}
    \]

    Both represent the geometry of the profile poorly.
    A better way is to keep the aspect ratio equal as propose by \textcite{Spittel1984}:

    \[
        h'' = \sqrt{\frac{A h}{b}}
    \]

    \[
        b'' = \sqrt{\frac{A b}{h}}
    \]

    This variant is used in the current implementation.
    So $h$ and $b$ in Wusatowski's model are replaced with $h''$ and $b''$.
    In the end, $b_1$ can be obtained from $b_1''$ by:

    \[
        b_1 = \frac{b_1'' h_1}{h_1''}
    \]

    \section{Usage instructions}\label{sec:usage-instructions}

    The plugin can be loaded under the name \texttt{pyroll\_wusatowski\_spreading}.

    An implementation of the \lstinline{spread} hook on \lstinline{RollPass} is provided,
    calculating the spread using the equivalent rectangle approach and Wusatowski's model.

    Several additional hooks on \lstinline{RollPass} are defined, which are used in spread calculation, as listed in \autoref{tab:hookspecs}.
    Base implementations of them are provided, so it should work out of the box.
    For \lstinline{wusatowski_exponent} and \lstinline{wusatowski_velocity_coefficient} the equations~\ref{eq:exponent} and~\ref{eq:velocity-coefficient} are implemented.
    The others default to \num{1}.
    Provide your own hook implementations or set attributes on the \lstinline{RollPass} instances to alter the spreading behavior.

    \begin{table}
        \centering
        \caption{Hooks specified by this plugin. Symbols as in \autoref{eq:wusatowski}.}
        \label{tab:hookspecs}
        \begin{tabular}{ll}
            \toprule
            Hook name                                     & Meaning                                \\
            \midrule
            \texttt{wusatowski\_temperature\_coefficient} & temperature correction coefficient $a$ \\
            \texttt{wusatowski\_velocity\_coefficient}    & velocity correction coefficient $c$    \\
            \texttt{wusatowski\_material\_coefficient}    & material correction coefficient $d$    \\
            \texttt{wusatowski\_friction\_coefficient}    & friction correction coefficient $f$    \\
            \texttt{wusatowski\_exponent}                 & spread exponent $w$                    \\
            \bottomrule
        \end{tabular}
    \end{table}

    \printbibliography

\end{document}


\section{Grammar as Network of FSA}

Given a EBNF grammar where every nonterminal has a unique rule. Any transition labelled with a nonterminal $B$ is a call to the automaton $M_B$.

\begin{description}
    \item[Machine] The FSA of a nonterminal
    \item[Automaton] the PDA that accepts $L(G)$
    \item[Net] the set of all machines
\end{description}

The machine $M_A$ must be \emph{normalized}, initial state $0_A$ must have no entering arcs.

\subsection{Followers of nonterminal}
Given a final state of a machine, the \emph{set of followers} if the set of all the terminal characters that can follow exiting the machine (including $\dashv$). Given a state $q_A$:
\[
    Ini(q_A) = Ini(L(q_A)) = \{ a \in \Sigma | a\Sigma^* \cap L(q_A) \ne \emptyset \}
\]

\textbf{Note}: $Ini$ cannot contain $\epsilon$, it is empty iff $L(q_A)=\{\epsilon\}$.
Terminal $a$ is in $Ini(q_A)$ iff:
\begin{align*}
    & \exists \text{ arc } q_A \xrightarrow{a} r_A \\
    & \exists \text{ arc } q_A \xrightarrow{B} r_A \land a \in Ini(0_B) \\
    & \exists \text{ arc } q_A \xrightarrow{B} r_A \land B \text{ is nullable } \land a \in Ini(r_A)
\end{align*}


\chapter{Units and Conversions}

At this point, you are working with a lot of units: grams for weight,
joules for energy, newtons for force, meters for distance, seconds for
time, etc. For each type of measurement, there are several different
units; for example, distance can be measured in feet, miles,
and light-years.

\begin{mdframed}[style=important, frametitle={Some Equalencies}]

\begin{tabular}{r | l}
  \hline
  \multicolumn{2}{c}{\textbf{Distance}}\\
  1 mile & 1.6093 kilometers \\
  1 foot & 0.3048 meters \\
  1 inch & 2.54 centimeters \\
  1 light-year & $9.461 \times 10^{12}$ kilometers\\
  \hline
  \multicolumn{2}{c}{\textbf{Volume}}\\
  1 milliliter & 1 cubic centimeter \\
  1 quart & 0.9461 liters \\
  1 gallon & 3.7854 liters \\
  1 fluid ounce & 29.6 milliliters \\
  \hline
  \multicolumn{2}{c}{\textbf{Mass}}\\
  1 pound & 0.4535924 kilograms\\
  1 ounce & 0.4535924 grams\\
  1 metric ton & 1000 kilograms \\
  \hline
  \multicolumn{2}{c}{\textbf{Force}}\\
  1 newton & 1 kilogram meter per sec$^2$\\
  \hline
  \multicolumn{2}{c}{\textbf{Pressure}}\\
  1 pascal & 1 newton per square meter \\
  1 bar & 0.98692 atmosphere \\
  1 pound per square inch & 6897 pascals \\
  \hline
  \multicolumn{2}{c}{\textbf{Energy}}\\
  1 joule & 1 newton meter \\
  1 calorie & 4.184 joules \\
  1 kilowatt-hour & $3.6 \times 10^{6}$ joules  \\
\end{tabular}\index{units table}

(You don't need to memorize these! Just remember that this page is here.)

\end{mdframed}

In the metric system, prefixes are often used to express a multiple. Here are the common prefixes:\index{metric system!prefixes}

\begin{mdframed}[style=important, frametitle={Common Prefixes for Metric Units}]

\begin{tabular}{r | l}
giga  & $\times 10^{9}$\\
mega  & $\times 10^{6}$\\
kilo  & $\times 10^{3}$\\
milli  & $\div 10^{3}$\\
micro  & $\div 10^{6}$\\
nano  & $\div 10^{9}$\\
\end{tabular}

(These are worth memorizing.)

\end{mdframed}

\section{Conversion Factors}

Here is a really handy trick to remembering how to do conversions
between units.\index{conversion factors}

Often, you will a table like the one above, and someone will ask you
``How many miles are in 0.23 light-years?''  You know that 1 mile = 1.6093
kilometers and that 1 light-year is $9.461 \times 10^{12}$ kilometers.
How do you do the conversion?

The trick is to treat the two parts of the equality as a fraction that equals 1.  That is, you think:

$$\frac{1 \text{ miles}}{1.6093 \text{ km}} = \frac{1.6093 \text{ km}}{1 \text{ miles}} = 1$$

and

$$\frac{1 \text{ light-years}}{9.461 \times 10^{12} \text{ km}} = \frac{9.461 \times 10^{12} \text{ km}}{1 \text{ light-years}} = 1$$

We call these fractions \textit{conversion factors}.

Now, your problem is

$$0.23 \text{ light-years} \times \textit{ Some conversion factors} = ? \text{ miles}$$

Note that when you multiply fractions together, things in the numerators can cancel with things in the denominator:

$$\left( \frac{31\pi}{47} \right) \left( \frac{11}{37\pi}\right) = \left(\frac{31\cancel{\pi}}{47}\right) \left( \frac{11}{37\cancel{\pi}}\right) = \left(\frac{31}{47} \right) \left( \frac{11}{37} \right)$$

When working with conversion factors, you will do the same with the units:

\begin{multline*}
  0.23 \text{ light-years} \left( \frac{9.461 \times 10^{12} \text{ km}}{1 \text{ light-years}} \right) \left( \frac{1 \text{ miles}}{1.6093 \text{ km}} \right) = \\
  0.23 \text{ \cancel{light-years}} \left( \times \frac{9.461 \times 10^{12} \text{ \cancel{km}}}{1 \text{ \cancel{light-years}}} \right) \left( \frac{1 \text{ miles}}{1.6093 \text{ \cancel{km}}}\right) = \frac{(0.23)(9.461 \times 10^{12})}{1.6093} \text{ miles}$$
\end{multline*}

\begin{Exercise}[title={Simple Conversion Factors}, label=simple_conversion_factors]

  How many calories are in 4.5 killowatt-hours?

\end{Exercise}
\begin{Answer}[ref=simple_conversion_factors]

  $$4.5 \text{ \cancel{kWh}} \left( \frac{3.6 \times 10^{6} \text{ \cancel{joules}}}{1 \text{ \cancel{kWh}}} \right) \left( \frac{1 \text{ calories}}{4.184 \text{ \cancel{joules}}}\right) = \frac{(4.5)(3.6 \times 10^6)}{4.184} = 1.08 \times 10^6 \text {calories}$$

\end{Answer}

\section{Conversion Factors and Ratios}

Conversion factors also work on ratios.  For example, if you are told
that a bug is moving 0.5 feet every 120 milliseconds. What is that in
meters per second?

The problem, then is

$$\frac{0.5 \text{ feet}}{120 \text{ milliseconds}} = \frac{\text{? m}}{second}$$

So you will need conversion factors to replace the ``feet'' with ``meters'' and to replace ``milliseconds'' with ``seconds'':

\begin{multline*}
\left(\frac{0.5 \text{ \cancel{feet}}}{120 \text{ \cancel{milliseconds}}}\right) \left( \frac{0.3048 \text{ meters}}{1 \text{ \cancel{feet}}} \right) \left( \frac{ 1000 \text{ \cancel{milliseconds}}} {1 \text{ second}}\right) = \frac{(0.5)(0.3048)(1000)}{120}\text{ m/second}
\end{multline*}

\begin{Exercise}[title={Conversion Factors}, label=conversion_factors]

The hole in the bottom of the boat lets in 0.1 gallons every 2 minutes.  How many milliliters per second is that?

\end{Exercise}
\begin{Answer}[ref=onversion_factors]

  \begin{multline*}
    \frac{0.1 \text{ \cancel{gallons}}}{2 \text{ \cancel{minutes}}}
  \left( \frac{3.7854 \text{ \cancel{liters}}}{1 \text{ \cancel{gallons}}} \right)
  \left( \frac{1000 \text{ milliliters}}{1\text{ \cancel{liters}}}\right)
  \left( \frac{1 \text{ \cancel{minutes}}}{60 \text{ seconds}} \right) = \\
  \frac{(0.1)(3.7854)(1000)}{(2)(60)} \text{ ml/second} = 3.1545 \text{ ml/second}
  \end{multline*}

\end{Answer}

\section{When Conversion Factors Don't Work}

Conversion factors only work when the units being converted are
proportional to each other. Gallons and liters, for example are
proportional to each other: If you have $n$ gallons, you have $n
\times 3.7854$ liters.

Degrees celsius and degrees farenheit are \textit{not} proportional to
each other.  If your food is $n$ degrees celsius, it is $n \times
\frac{9}{5} + 32$ degrees farenheit.  You can't use conversion factors
to convert celsius to farenheit.


\documentclass[twocolumn]{article}
\usepackage{amsmath}

\begin{document}

\section*{Proof of extremum}
\davidsays{I think this section should probably move to supplementary information, if we're going to send to Nature.  It suddenly gets way more mathematical here, and we start introducing Fourier space, etc.}

To show that a uniform potential gives the highest deliverable capacity, we consider a potential of interaction between guest and substrate $\V(\vec r)$ that varies with space.  In this proof we will actually make use of the Fourier transform of this potential:
\begin{align}
    \Vk \equiv \iiint \V(\vec r) e^{-i\vec k\cdot \vec r} d\vec r
\end{align}
The Fourier transform of a uniform potential is a Dirac delta function $\tilde{\V}(\vec k)\propto\delta(\vec k)$. Therefore, to show that a uniform potential extremizes the deliverable capacity, we must show that the functional derivative of the deliverable capacity with respect to $\Vk$ is zero for \emph{nonzero} values of $\vec k$, i.e.
\begin{align}
    \frac{\delta D}{\delta \Vk} &= 0, \text{ if } \vec k\ne 0.
\end{align}
We note that this functional derivative may be non-zero for $\vec k=0$ because we separately maximize with respect to the particular uniform potential $\V$.
This means that
\begin{align}
    \frac{\delta N_H}{\delta \V(\vec k)} &= -\frac{\delta N_L}{\delta \Vk}
\end{align}
where $N_H$ and $N_L$ are the number of particles at the low and high pressure.

Because the chemical potential $\mu$ varies monotonically with $N$ at fixed temperature, we can consider how the chemical potential varies as we change $\Vk$ with the number of molecules held fixed.  We demonstrate this using the cyclic chain rule, which shows us that
\begin{align}
    \left(\frac{\delta N}{\delta \Vk}\right)_{\mu} &=
    -\left(\frac{\delta \mu}{\delta \V(\vec k)}\right)_{N}
    \left(\frac{\partial N}{\partial \mu}\right)_{\Vk}.
\end{align}
Since changing the chemical potential changes the number of molecules in the general case, if we can show that $\left(\frac{\delta \mu}{\delta \V(\vec k)}\right)_{N}=0$ then we will have shown that $\left(\frac{\delta N}{\delta \V(\vec k)}\right)_{\mu}=0$.  Thus we consider
\begin{align}
    \left(\frac{\delta \mu}{\delta \tilde\V(\vec k)}\right)_N
    &= \left(\frac{\delta \left(\frac{\partial F}{\partial N}\right)_{\volume}}{\delta \Vk}\right)_N
    \\
    &= \left(\frac{\partial \left(\frac{\delta F}{\delta \Vk}\right)_{\volume}}{\partial N}\right)_{\volume}
    \label{eq:dmudpot}
\end{align}
where we have made use of the derivative relationship between $\mu$ and the Helmholtz free energy $F$, and have then reorderd the functional and partial derivatives.
Let us consider the interior derivative first.  The derivative of the Helmholtz free energy with respect to the external potential $\Vk$ just gives the number density:
\begin{align}
    \frac{\delta F}{\delta \Vk} &= \rho(\vec k)
\end{align}
The number density is itself homogeneous for any system that is stable in a fluid state at this density (i.e. does not spontaneously crystallize), and thus has a Fourier transform that is proportional to a Dirac $\delta$-function.  Thus the functional derivative $\frac{\delta F}{\delta \V(\vec r)}$ is actually a uniform function.
We can insert this expression into Eq.~\ref{eq:dmudpot} to find that
\begin{align}
    \frac{\delta \mu}{\delta \Vk} &\propto \delta(\vec k) \\
    \frac{\delta N}{\delta \Vk} &\propto \delta(\vec k)
\end{align}
Thus the functional derivative of both the chemical potential and $N$ with regard to $\V(\vec r)$ are itself homogeneous.  Since we already maximize $D$ with respect to the homogeneous component of the potential (i.e. $\vec k=0$), the derivative of $D$ with respect to any change of potential is zero.

This demonstrates that a homogeneous potential leads to an extremum value of the deliverable capacity.  This proof is insufficient, however, to show that it must be a true maximum.

\end{document}


In this section, the governing equations of general dynamic problems in elastic-plastic solids are first written with a tensorial formalism based on the fourth-order stiffness tensor.
This framework leads on the one hand to the same characteristic structure as in \cite{Raniecki,mandel_book}, so that well known results can be used.
On the other hand, it allows easy specialization to problems involving less than three space dimensions, such as the one-dimensional ones already treated in the literature.
% This framework is more generic than the works mentioned in the introduction, which are formulated in matrix form based on the elastoplastic compliances, since it can be easily specialized to problems already treated in the literature.
%
Second, the spectral analysis of the hyperbolic system written in an arbitrary direction is performed, which is motivated by the solution of Riemann problems in one space dimension in numerical schemes such as the Finite Volume Method (FVM) \cite{Leveque,Toro}.
That approach furthermore avoids the seeking of bi-characteristics as proposed by \textsc{Clifton} in order to build elastoplastic finite difference schemes \cite{Clifton_thesis}.
It must be emphasized that the present work aims at highlighting a sufficient amount of information so as to enable numerical schemes to mimic the analytical behavior, and does not require the complete bi-characteristic structure.

\subsection{Governing equations}
We consider the isothermal deformation of a solid body of mass density $\rho$ in the linearized geometrical framework.
The balance equation of linear momentum with neglected body forces, and the geometrical balance equations \cite{Plohr,Gil_HE} are:
\begin{equation}
  \label{eq:balance_equations}
  %\left\lbrace
    \begin{aligned}
    & \rho \dot{\vect{v}} - \nablav \cdot \tens{\sigma} = \vect{0} \\
    &  \dot{\tens{\eps}} - \nablav \cdot \(\frac{\vect{v}\otimes \tens{I} + \tens{I} \boxtimes \vect{v}}{2}\) = \vect{0}
  \end{aligned}
%\right.
\end{equation}
where the operator $ \boxtimes $ refers to the transpose on second and third indices of the classical tensor product, namely: $\tens{I} \boxtimes \vect{v} = \delta_{ik} v_j\vect{e}_i \otimes \vect{e}_j \otimes \vect{e}_k$.
%
Furthermore, $\tens{I}$, $\vect{v}$, $\tens{\sigma}$ and $\tens{\eps}$ denote respectively the second-order identity tensor, the velocity vector, the Cauchy stress tensor and the linearized strain tensor.
The latter additively decomposes into an elastic strain $\tens{\eps}^e$ and a plastic strain $\tens{\eps}^p$ in the small strain case.
Assuming Cartesian coordinates, system \eqref{eq:balance_equations} can be written as:
\begin{equation}
  \label{eq:conservative_form}
  \drond{\Ucb}{t} + \drond{\Fcb\cdot \vect{e}_i}{x_i}=\tens{0}
\end{equation}
with the vector of conserved quantities $\Ucb$ and the flux vectors $\Fcb_i=\Fcb\cdot \vect{e}_i$:
\begin{equation}
  \label{eq:vectors}
  \Ucb =\matrice{\rho\vect{v} \\ \tens{\eps}} \quad ; \quad \Fcb_i = \matrice{-\tens{\sigma}\cdot\vect{e}_i\\-\frac{\vect{v}\otimes\vect{e}_i +\vect{e}_i \otimes\vect{v} }{2} }
\end{equation}
Alternatively, the introduction of an auxiliary vector of conserved quantities $\Qcb$ allows rewriting equation \eqref{eq:conservative_form} as a quasi-linear form by means of the chain rule \cite{Trangenstein91}:
\begin{equation}
  \label{eq:quasi-linear_form}
  \drond{\Qcb}{t} + \Absf^i \drond{\Qcb}{x_i}=\tens{0}
\end{equation}
In particular, by setting $\Qcb=\matrice{\vect{v} \\ \tens{\sigma}}$, one writes:
\begin{equation}
  \label{eq:matrix-quasi}
  \Absf^i = \(\drond{\Ucb}{\Qcb}\)^{-1}\drond{\Fcb_i}{\Qcb} = -\matrice{\tens{0}^2 & \frac{1}{\rho}\(\frac{\tens{I}\otimes\vect{e}_i + \vect{e}_i\otimes \tens{I}}{2}\)\\ \Hbb\cdot \vect{e}_i & \tens{0}^4},
\end{equation}
$\tens{0}^q$ being a $q$th-order zero tensor and $\Hbb=\drond{\tens{\sigma}}{\tens{\eps}}$ the fourth-order tangent modulus tensor.
It then appears that the characteristic structure of the hyperbolic problem, which is driven by the matrices $\Absf^i$, depends on the nature of the deformation (\textit{i.e. elastic or elastic-plastic}) through the tangent modulus.

% On the other hand, following the Generalized Standard Material framework \cite{GSM} a Helmholtz free-energy $\psi$ depending on $\tens{\eps}$ and the set of additional internal variables $\Vcb$ is assumed to  govern the evolution of the microstructure.
Following the Generalized Standard Material framework \cite{GSM}, the elastic-plastic constitutive response is described by a Helmholtz free-energy $\psi$, convex with respect to $\tens{\eps}$ and the set of additional internal variables $\Vcb$, and a yield surface $f$ in the case of associative plasticity.
Assuming elastic isotropy, reversible evolutions are governed by the elastic law derived from Helmholtz's free energy:
\begin{equation}
  \label{eq:elastic_law}
  \tens{\sigma} = \Cbb: \tens{\eps}^e = 2\mu \tens{\eps}^e + \lambda \tr \tens{\eps}^e \: \tens{I}
\end{equation}
in which $(\lambda,\mu)$ are Lam{\'e}'s parameters.
The inverse constitutive law can also be written based on Young's modulus and Poisson's ratio $(E,\nu)$:
\begin{equation}
  \label{eq:elastic_inverse}
  \tens{\eps}^e = \Cbb^{-1}:\tens{\sigma} = \frac{1+\nu}{E} \tens{\sigma} - \frac{\nu}{E} \tr \tens{\sigma}  \: \tens{I}
\end{equation}

Next, restricting ourselves to isotropic hardening, the set $\Vcb$ consists of the cumulated plastic strain $p$.
%
In addition, the von-Mises yield surface is considered:
\begin{equation}
  \label{eq:von-Mises_yield}
  f\(\tens{\sigma},R \)= \sqrt{\frac{3}{2}}\norm{\tens{s}} - \(R(p)+\sigma^y\) \leq 0 \\
\end{equation}
where $\tens{s}$ denotes the deviatoric part of the Cauchy stress tensor, $\sigma^y$ is the yield stress in tension, and $-R(p)$ is the thermodynamical force conjugate to the cumulated plastic strain through some hardening law.
% The evolution of the cumulated plastic strain follows from the consistency condition:
% \begin{equation}
%   %\label{eq:consistance}
%   \dot{f}=0 \quad \Leftrightarrow  \quad  \drond{f}{\tens{\sigma}}:\tens{\dot{\sigma}} - \drond{f}{R}\:\dot{R} =0
% \end{equation}
% so that one writes:
% \begin{equation}
%   \label{eq:consistance}
%   \dot{R}=\sqrt{\frac{3}{2}}\:\frac{\tens{s}:\tens{\dot{\sigma}}}{\norm{\tens{s}}}
% \end{equation}
% Then, the plastic flow rule:
% \begin{equation}
%   \label{eq:plastic_flow_rule}
%   \tens{\dot{\eps}}^p = \dot{p}\drond{f}{\tens{\sigma}}
% \end{equation}
The evolution of the plastic strain tensor and the cumulated plastic strain are governed by the following flow rule and hardening law respectively:
\begin{align}
  \label{eq:plastic_flow_rule}
  & \tens{\dot{\eps}}^p = \lambda \drond{f}{\tens{\sigma}} \\
  \label{eq:hardening_rule}
  & \dot{p} = -\lambda \drond{f}{R} %= \lambda
\end{align}
where the plastic multiplier $\lambda$ and the yield surface obey the Kuhn-Tucker complementarity conditions:
\begin{equation}
  \label{eq:Kuhn-Tucker}
  \lambda \geq 0 \quad ;\quad f \leq 0 \quad ; \quad \lambda f =0
\end{equation}
along with the consistency condition:
\begin{equation}
  \label{eq:consistency}
  \lambda \dot{f}=0 %\quad \Leftrightarrow  \quad  \drond{f}{\tens{\sigma}}:\tens{\dot{\sigma}} - \drond{f}{R}\:\dot{R} =0
\end{equation}
% From the above conditions, one deduces:
% \begin{equation}
%   %\label{eq:consistance}
%   \dot{f}=0 \quad \Leftrightarrow  \quad  \drond{f}{\tens{\sigma}}:\tens{\dot{\sigma}} - \drond{f}{R}\:\dot{R} =0
% \end{equation}
% in such a way that:
% \begin{equation}
%   \label{eq:consistance}
%   \dot{R}=\sqrt{\frac{3}{2}}\:\frac{\tens{s}:\tens{\dot{\sigma}}}{\norm{\tens{s}}}
% \end{equation}
Therefore, combining equations \eqref{eq:plastic_flow_rule} and \eqref{eq:hardening_rule}, the flow rule can be rewritten as:
\begin{equation}
  \label{eq:plastic_strain_rate}
  \tens{\dot{\eps}}^p = \dot{p}\:\sqrt{\frac{3}{2}}\frac{\tens{s}}{\norm{\tens{s}}}
\end{equation}

Given this description of internal processes, the thermodynamical framework then leads to the elastic-plastic constitutive equations during irreversible deformations by combining the elastic law \eqref{eq:elastic_law}, the additive decomposition of the strain tensor and the plastic flow rule \eqref{eq:plastic_strain_rate} \cite{Simo}:
\begin{align}
  \label{eq:elastoplastic_tangent}
  & \tens{\dot{\sigma}} = \Cbb^{ep}:\tens{\dot{\eps}}=\(\Cbb - \beta\:\tens{s}\otimes\tens{s} \):\tens{\dot{\eps}} \\
  \label{eq:plastic_flow}
  % & \beta = \frac{6\mu^2}{3\mu +C}\times\frac{1}{\tens{s}:\tens{s}}
  & \beta = \frac{6\mu^2}{3\mu +R'}\times\frac{1}{\tens{s}:\tens{s}}
\end{align}
where the elastoplastic tangent modulus $\Cbb^{ep}$ can be decomposed into the elasticity tensor $\Cbb$ and another part depending on the direction of the plastic flow.
Therefore, plastic evolutions involve $\Hbb \equiv \Cbb^{ep}$ while elastic ones involve $\Hbb\equiv\Cbb$.
%$
% \begin{remark}
%   In what follows, only linear isotropic hardening is considered by setting $R(p)=C p$ so that $R'=C$, with $C$ the hardening modulus.
% \end{remark}

% Given this description of the internal processes, the thermodynamical framework then leads to the elastic-plastic constitutive equations for the components of the Cauchy stress tensor during irreversible deformations \cite{Simo}:
% \begin{align}
%   \label{eq:elastoplastic_tangent}
%   & \tens{\dot{\sigma}} = \Cbb^{ep}:\tens{\dot{\eps}}=\(\Cbb - \beta\:\tens{s}\otimes\tens{s} \):\tens{\dot{\eps}} \\
%   \label{eq:plastic_flow}
%   % & \beta = \frac{6\mu^2}{3\mu +C}\times\frac{1}{\tens{s}:\tens{s}}
%   & \beta = \frac{6\mu^2}{3\mu +R'}\times\frac{1}{\tens{s}:\tens{s}}
% \end{align}
% where the elastoplastic tangent modulus $\Cbb^{ep}$ can be decomposed into the elasticity tensor $\Cbb$ and another part depending on the direction of the plastic flow.
% In addition, the evolution of the cumulated plastic strain follows from the consistency condition:
% \begin{equation}
%   %\label{eq:consistance}
%   \dot{f}=0 \quad \Leftrightarrow  \quad  \drond{f}{\tens{\sigma}}:\tens{\dot{\sigma}} - \drond{f}{R}\:\dot{R} =0
% \end{equation}
% so that one writes:
% \begin{equation}
%   \label{eq:consistance}
%   C\dot{p}=\sqrt{\frac{3}{2}}\:\frac{\tens{s}:\tens{\dot{\sigma}}}{\norm{\tens{s}}}
% \end{equation}
% %Then, assuming  the existence of a dissipation pseudo-potential $\phi(\tens{\sigma},-R(p))$, the plastic flow rule:
% Then, the plastic flow rule:
% \begin{equation}
%   \label{eq:plastic_flow_rule}
%   \tens{\dot{\eps}}^p = \dot{p}\drond{f}{\tens{\sigma}}
% \end{equation}
% finally leads to the evolution of the plastic part of the strain tensor:
% \begin{equation}
%   \label{eq:plastic_strain_rate}
%   \tens{\dot{\eps}}^p = \dot{p}\:\sqrt{\frac{3}{2}}\frac{\tens{s}}{\norm{\tens{s}}}
% \end{equation}

% On the other hand, reversible evolutions are governed by the elastic law:
% \begin{equation}
%     \label{eq:elastic_law}
%     \tens{\sigma} = \Cbb: \tens{\eps}^e = 2\mu \tens{\eps}^e + \lambda \tr \tens{\eps}^e \: \tens{I}
% \end{equation}
% in which $(\lambda,\mu)$ are Lam{\'e}'s parameters.
% The inverse constitutive law also can be written based on Young's modulus and Poisson's ratio $(E,\nu)$:
% \begin{equation}
%   \label{eq:elastic_inverse}
%   \tens{\eps}^e = \Cbb^{-1}:\tens{\sigma} = \frac{1+\nu}{E} \tens{\sigma} - \frac{\nu}{E} \tr \tens{\sigma}  \: \tens{I}
% \end{equation}
% Therefore, plastic evolutions involve $\Hbb \equiv \Cbb^{ep}$ while elastic ones involve $\Hbb\equiv\Cbb$.

\subsection{Spectral analysis}
\label{sec:spectral-analysis}

Considering an arbitrary direction of space $\vect{n}$, the quasi-linear form \eqref{eq:quasi-linear_form} reads:
% The quasi-linear form of the sets of equations \eqref{eq:balance_equations} and \eqref{eq:plasticity_equations} in a Cartesian coordinate system and an arbitrary direction $\vect{n}$ is:
\begin{equation}
  \label{eq:quasilinear_normal}
  \drond{\Qcb}{t} + \Jbsf \drond{\Qcb}{x_n} = \vect{0}
\end{equation}
where $x_n=\vect{x}\cdot\vect{n}$ and $\Jbsf=n_i\Absf^i$ is the Jacobian matrix.
Simple waves are solutions for which the vector $\Qcb$ is constant along each curve of the one-parameter family $\eta^K(x_n,t)=\text{const}$.
For such \textit{self-similar} solutions, system \eqref{eq:quasilinear_normal} reads:
\begin{equation}
  \label{eq:simple_system}
  \(\Jbsf -  c_K \Ibsf \vphantom{\Qcb'(\eta^K)}\)\Qcb'(\eta^K)  = \vect{0}
\end{equation}
where $\Ibsf$ is the $9\times 9$ identity matrix and $c_K = -\drond{\eta^K}{t} / \drond{\eta^K}{x_n}$ appears to be the $K$th eigenvalue of the Jacobian matrix.
The problem therefore admits nontrivial solutions if $\Jbsf$ has real eigenvalues and distinct left eigenvectors $\Lcb^K= \[ \vect{v}^K \: , \: \tens{\sigma}^K \]$ satisfying:
\begin{equation}
  \label{eq:eigen_system}
  \vect{\Lc}^K \(\Jbsf - c_K \Ibsf\) = \vect{0} \qquad K=1,\cdots,9
\end{equation}
%The characteristic structure of the problem is given by the eigenvalues $c_K$ and the associated left eigenvectors $\Lcb^K= \[ \vect{v}^K \: , \: \tens{\sigma}^K \]$ of the Jacobian matrix satisfying:
% \begin{equation}
%   \label{eq:eigen_system}
%   \vect{\Lc}^K \(\Jbsf - c_K \Ibsf\) = \vect{0} \qquad K=1,\cdots,9
% \end{equation}
%with $\Ibsf$, the $9\times 9$ identity matrix.
Thus, for non-zero eigenvalues one gets:
\begin{align}
  \label{eq:eigen_left_stress}
  & -\tens{\sigma}^K:\(\Hbb\cdot  \vect{n}\) - c_K  \vect{v}^K =\vect{0} \\
  \label{eq:eigen_left_velo}
  & -\frac{1}{\rho}\vect{v}^K\otimes\vect{n} - c_K \tens{\sigma}^K = \tens{0}
\end{align}
Substitution of $\tens{\sigma}^K$ obtained from \eqref{eq:eigen_left_velo} in \eqref{eq:eigen_left_stress} leads to:
\begin{equation}
  \label{eq:acoustic_eigen}
 (\vect{v}^K\otimes\vect{n}):\(\Hbb\cdot  \vect{n}\) - \rho c_K^2 \vect{v}^K = \tens{0}
\end{equation}
which is the left eigensystem of the acoustic tensor $A_{ij}=n_k H_{ik j l}  n_l$.
Due to the symmetry of $\tens{A}$, system \eqref{eq:acoustic_eigen} is equivalent to the right eigensystem:
\begin{equation}
  \label{eq:acoustic_eigen_system_lambda}
  \(  n_k H_{ik j l}  n_l - \rho c_K^2 \delta_{ij} \) v_j^K =0
\end{equation}
or alternatively, with the eigenvalues $\omega_p$ and associated left eigenvectors of the acoustic tensor $\vect{l}^q\: \: (q=1,2,3)$:
\begin{equation}
  \label{eq:acoustic_eigen_system}
  \vect{l}^q \cdot \( \tens{A} - \omega_q \tens{I} \)   = \vect{0}
\end{equation}
The condition for system \eqref{eq:quasilinear_normal} to be hyperbolic (real eigenvalues and independent eigenvectors) is thus ensured by the positive definiteness of the acoustic tensor, also known as the \textit{strong ellipticity} condition \cite{Foundation_of_elasticity}:
\begin{equation}
  \label{eq:strong_ellipticity}
  (\vect{m}\otimes \vect{n}): \Hbb: (\vect{n}\otimes \vect{m}) > 0 \quad \forall \vect{n},\vect{m} \in \Rbb^3 \: ; \: \vect{n},\vect{m} \ne \vect{0}
\end{equation}
If the condition holds, the acoustic tensor admits $3$ couples of eigenvalue--eigenvector $\{\omega_q,\vect{l}^q\}$ leading to $6$ couples $\{c_K,\Lcb^K\}$ for the Jacobian matrix, the $3$ other eigenvalues being null \cite{Kluth}.
The couples $\{c_K,\Lcb^K\}$ are referred to as the \textit{left characteristic fields}.
Notice that since the elastic stiffness tensor $\Cbb$ or the elastoplastic tangent modulus $\Cbb^{ep}$ may be involved in equation \eqref{eq:quasi-linear_form}, three left characteristic fields are obviously associated with elastic and elastic-plastic evolutions respectively.
The left eigenvectors related to the non-zero eigenvalues of the Jacobian matrix are obtained by using equation \eqref{eq:eigen_left_velo} so that the following $6$ eigenfields of the quasi-linear form \eqref{eq:quasilinear_normal} can be defined:
\begin{equation}
  \label{eq:left_eigenfields}
    \left\lbrace \pm \sqrt{\frac{\omega_q}{\rho_0}} ; \: \[ \pm \rho_0\sqrt{\frac{\omega_q}{\rho_0}} \vect{l}^q , -\vect{l}^q\otimes \vect{n} \]  \right\rbrace ,\: q=1,2,3
\end{equation}
At last, three independent left eigenvectors associated with the null eigenvalue of multiplicity $3$ can be found by solving equation \eqref{eq:eigen_left_stress} for the null eigenvalue:
\begin{equation}
  \label{eq:left_null_eigenvectors}
  \tens{\sigma}^K:\(\Hbb\cdot  \vect{n}\) =\vect{0},\quad K=1,...,3
\end{equation}

Since the above formulation is based on the elastoplastic stiffnesses rather than compliances, it differs from those of \textsc{Bleich} \cite{Bleich}, \textsc{Clifton} \cite{Clifton}, and hence from these of \textsc{Ting} and \textsc{Nan} \cite{Ting68} and \textsc{Ting} \cite{Ting69}.
%
The use of the tangent modulus $\Hbb$ enables the specialization of equations \eqref{eq:left_eigenfields} and \eqref{eq:left_null_eigenvectors} to the plane strain and the plane stress cases, as we shall see in section \ref{sec:2dproblem}.

\subsection{Known properties of the plastic waves}
\label{sec:plastic_speeds}

Let us now recall some of the important results of \textsc{Mandel} \cite{Mandel62,Mandel69_thermoWaves} for which proofs can also be found in \cite{mandel_book}.
% eq (6.13)
Denoting the elastic acoustic tensor as $\tens{A}^e = \vect{n} \cdot \Cbb \cdot \vect{n}$, the eigenvalue problem \eqref{eq:acoustic_eigen_system} can be rewritten as:
\begin{equation}
  \label{eq:mod_eigen_acoustic}
  \vect{l}^q \cdot \( \tens{B} - \beta \vect{a}\otimes\vect{a} \)   = \vect{0}
\end{equation}
in which $\tens{B}=\tens{A}^e- \omega_q \tens{I}$ and $\vect{a}=\tens{s}\cdot\vect{n}$.
Then, assuming that the coordinate axes coincide with the eigenbasis of $\tens{A}^e$, the determinant of system \eqref{eq:mod_eigen_acoustic} reads:
\begin{equation}
  \label{eq:polynomial_principal}
  F(\omega_q)=(A^e_1-\omega_q)(A^e_2-\omega_q)(A^e_3-\omega_q) - \beta\[ (A^e_2-\omega_q)(A^e_3-\omega_q){a}^2_1 + (A^e_1-\omega_q)(A^e_3-\omega_q){a}^2_2 + (A^e_1-\omega_q)(A^e_2-\omega_q){a}^2_3 \] =0
\end{equation}
With $\beta>0$ and the eigenvalues of $\tens{A^e}$ satisfying $A^e_1 \geq A^e_2 \geq A^e_3$, it comes out that:
\begin{equation}
  \label{eq:polynomial_property}
  F\(A^e_1\) \leq 0\quad ; \quad F\(A^e_2\) \geq 0 \quad ;\quad F(A^e_3)\leq 0 \quad ; \quad F(\infty) < 0
\end{equation}
from which the following conclusion is drawn.
\begin{property}[First Mandel's inequality]
  \label{pr:mandel_inequality}
  For a unit normal vector $\vect{n}$, the speeds of plastic waves $c_I^p\geq c_{II}^p \geq c_{III}^p$ are bounded by the elastic speeds $c_I^e\geq c_{II}^e \geq c_{III}^e$ according to:
  \begin{equation}
    \label{eq:Mandels_inequality}
    c_I^e\geq c_I^p\geq c_{II}^e\geq c_{II}^p \geq c_{III}^e \geq c_{III}^p
  \end{equation}
\end{property}

Consider now equation \eqref{eq:simple_system}, from which one gets for plastic evolutions:
\begin{align}
  \label{eq:right_eigen1}
  & \tens{\sigma}' = -\frac{1}{c_K} \Hbb : \( \vect{n}\otimes \vect{v}' \) \\
  \label{eq:right_eigen2}
  & \( \tens{A}^{ep}  - \rho c_K^2 \tens{I} \) \vect{v}'  = \vect{0}
\end{align}
If one of the plastic speed is equal to an elastic speed, the expansion of equation \eqref{eq:right_eigen2} leads to:
\begin{equation}
  \label{eq:zero_dot_prod}
  \beta \vect{a}\cdot \vect{v}' =0
\end{equation}
Then, the projection of the variation $\tens{\sigma}'$ from equation \eqref{eq:right_eigen1} onto the normal to the yield surface is:
\begin{equation}
  \label{eq:nutral_wave}
  % \drond{f}{\tens{\sigma}}:\tens{\sigma}' = -\frac{1}{c_K}\sqrt{\frac{3}{2}} \frac{\tens{s}}{\norm{\tens{s}}} :  \Hbb : \( \vect{n}\otimes \vect{v}' \) = \frac{1}{c_K}\sqrt{\frac{3}{2}} \frac{\mu - \beta \norm{\tens{s}}}{\norm{\tens{s}}} \vect{a}\cdot\vect{v}' = 0
  \drond{f}{\tens{\sigma}}:\tens{\sigma}'= \frac{1}{c_K}\sqrt{\frac{3}{2}} \frac{\mu - \beta \norm{\tens{s}}}{\norm{\tens{s}}} \vect{a}\cdot\vect{v}' = 0
\end{equation}
Hence, if condition \eqref{eq:zero_dot_prod} is satisfied, the stress increment is tangent to the yield surface.
% Neutral waves
\begin{property}
  \label{pr:neutral_wave}
  A plastic wave traveling with the speed of an elastic wave results in a stress path that is tangent to the yield surface in the stress space.
  Such a wave is called a \textit{neutral wave}.
\end{property}

%In what follows, the above equations are specified to plane strain and plane stress cases.

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "manuscript"
%%% End:


\chapter{Tree}

\section{Binary Tree}
\subsection{Introductions}
\runinhead{Get parent ref.} To get a parent reference (implicitly), \textit{return the Node} of the current recursion function to its parent to maintain the path. Sample code:
\begin{java}
Node deleteMin(Node x) {
    if (x.left == null) return x.right;
    x.left = deleteMin(x.left);
    // x.count = 1+size(x.left)+size(x.right);
    return x;
}
\end{java}
\runinhead{Construct path from root to target.} To search a node in binary tree (not necessarily BST), use dfs:
\begin{python}
def dfs(self, root, t, path, found):
    # post-call check
    if not root: return
    if found[0]: return

    path.append(root)
    if root == t:
        found[0] = True

    self.dfs(root.left, t, path, found)
    self.dfs(root.right, t, path, found)
    if not found[0]:
        path.pop()  # 1 pop() corresponds to 1 append()
\end{python}
The `found` is a wrapper for boolean to keep it referenced by all calling stack.

\runinhead{Lowest common ancestor.} In BST, the searching is straightforward. In normal binary tree, construct the path from root to $node_1$ and $node_2$ respectively, and \textbf{diff} the two paths.

\runinhead{Find all paths.} Find all paths from root to leafs. For every currently visiting node, add itself to path; search left, search right and pop itself. Record current result when reaching the leaf.
\begin{python}
def dfs_path(self, cur, path, ret):
    if not cur: return

    path.append(cur)
    if not cur.left and not cur.right:
        ret.append("->".join(map(lambda x: str(x.val), path)))

    self.dfs_path(cur.left, path, ret)
    self.dfs_path(cur.right, path, ret)
    path.pop()
\end{python}
\subsection{Morris Traversal}
Traversal with O(1) space. \footnote{\href{http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html}{ref}}

Time complexity $O(3n).$ - find \pyinline{pre} twice, \pyinline{cur} traverse once. \begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=0.9in]{morris_time}}
\caption{Morris traversal time complexity}
\label{fig:morrisTime}
\end{figure}

\subsubsection{Inoder}
Assign the current node's in-order predecessor's right child to itself (threading). Two ptr \pyinline{cur}, \pyinline{pre}.

Process:
\begin{enumerate}
\item If no left, \textit{consume} \pyinline{cur}, go right
\item If left, find in-order predecessor \pyinline{pre}
\begin{enumerate}
\item If no thread (i.e. no \pyinline{pre} right child), assign it to \pyinline{cur}; go left
\item If thread, \textit{consume} \pyinline{cur}, go right. ($\equiv$ no left).
\end{enumerate}
\end{enumerate}

\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=1.6in]{morris_inorder}}
\caption{Morris inorder traversal}
\label{fig:morrisInorder}
\end{figure}
\newpage
Code:
\begin{python}
def morris_inorder(self, root):
    cur = root
    while cur:
        if not cur.left:
            self.consume(cur)
            cur = cur.right
        else:
            pre = cur.left
            while pre.right and pre.right != cur:
                pre = pre.right

            if not pre.right:
                pre.right = cur
                cur = cur.left
            else:
                pre.right = None
                self.consume(cur)
                cur = cur.right
\end{python}
\subsubsection{Preoder}
Similar to inorder.

Process:
\begin{enumerate}
\item If no left, \textit{consume} \pyinline{cur}, go right
\item If left, find in-order predecessor \pyinline{pre}
\begin{enumerate}
\item If no thread (i.e. no \pyinline{pre} right child), assign it to \pyinline{cur}; \textit{consume} \pyinline{cur}, go left
\item If thread, go right. ($\equiv$ no left, but no \textit{consume}, since consume before).
\end{enumerate}
\end{enumerate}

\subsubsection{Postorder}
More tedious.
\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=1.6in]{morris_postorder}}
\caption{Morris inorder traversal}
\label{fig:morrisInorder}
\end{figure}

TODO

\section{Binary Search Tree (BST)}
\runinhead{Array and BST.}Given either the \textbf{preorder} or \textbf{postorder} (but not inorder) traversal of a BST containing N distinct keys, it is possible to reconstruct the shape of the BST.
\subsection{Rank}
\runinhead{Calculates rank.}
\begin{enumerate}
\item When inserting:
  \begin{enumerate}
  \item insert to an existing node: \pyinline{node.cnt_this += 1}
  \item insert to left subtree: \pyinline{node.cnt_left += 1}
  \item insert to right subtree: do nothing.
\end{enumerate}
\item When querying rank:
  \begin{enumerate}
  \item query equals current node: \pyinline{return node.cnt_left}
  \item query goes to \textbf{left} node: \pyinline{return rank(node.left, val)};
  \item query goes to \textbf{right} node: \pyinline{return node.cnt_left} \pyinline{+ node.cnt_this + rank(node.right, val)}
  \end{enumerate}
Notice that the \pyinline{rank} calculates a val's rank in a subtree.
\end{enumerate}

\runinhead{Count of smaller number before itself.} Given an array $A$. For each element $A_i$ in the array, count the number of element before this element $A_i$ is smaller than it and return count number array. Average $O(n \log n)$
\\
Clues:
\begin{enumerate}
\item Put $A[:i+1]$ into a BST; so as to count the rank of $A[i]$ in the BST
\end{enumerate}
Codes:
\begin{python}
class Node(object):
  def __init__(self, val):
    """Records the left subtree size"""
    self.val = val
    self.cnt_left = 0
    self.cnt_this = 0
    self.left, self.right = None, None

class BST(object):
  def __init__(self):
    self.root = None

  def insert(self, root, val):
    """
    :return: subtree's root after insertion
    """
    if not root:
      root = Node(val)

    if root.val == val:
      root.cnt_this += 1
    elif val < root.val:
      root.cnt_left += 1
      root.left = self.insert(root.left, val)
    else:
      root.right = self.insert(root.right, val)

    return root

  def rank(self, root, val):
    """
    Rank in the root's subtree
    :return: number of items smaller than val
    """
    if not root:
      return 0
    if root.val < val:
      return (root.cnt_this+root.cnt_left+
              self.rank(root.right, val))
    elif root.val == val:
      return root.cnt_left
    else:
      return self.rank(root.left, val)

class Solution(object):
  def countOfSmallerNumberII(self, A):
    tree = BST()
    ret = []
    for a in A:
      tree.root = tree.insert(tree.root, a)
      ret.append(tree.rank(tree.root, a))

    return ret
\end{python}
Notice: if worst case $O(n \log n)$ is required, need to use Red-Back Tree - Section \ref{rbtree}. However, there is a more elegant way using Segment Tree - Section \ref{segmentTreeInversionCount}.

\subsection{Range search}
\runinhead{1-d range count}
\begin{java}
int size(Key lo, Key hi) {
    if (contains(hi)) return rank(hi)-rank(lo)+1;
    else              return rank(hi)-rank(lo);
}
\end{java}

\runinhead{Closest value} Find the value in BST that is closet to the \pyinline{target}.
\\
Clues:
\begin{enumerate}
\item Find the value just $\leq$ the target.
\item Find the value just $\geq$ the target.
\end{enumerate}
\
\\
Code for finding either the lower value or higher value:
\begin{python}
def find(self, root, target, ret, lower=True):
  """ret: result container"""
  if not root: return

  if root.val == target:
    ret[0] = root.val
    return

  if root.val < target:
    if lower:
      ret[0] = max(ret[0], root.val)

    self.find(root.right, target, ret, lower)
  else:
    if not lower:
      ret[0] = min(ret[0], root.val)

    self.find(root.left, target, ret, lower)
\end{python}

\runinhead{Closet values} Find $k$ values in BST that are closet to the \pyinline{target}.
\\\\
Clues:
\begin{enumerate}
\item Find the predecessors $\triangleq \{node | node.value \leq target\}$. Store in the stack.
\item Find the successors $\triangleq \{node | node.value \geq target\}$. Store in the stack.
\item Merge the predecessors and successors as in merge in MergeSort to get he $k$ values.
\end{enumerate}
\
\\
Code for finding the predecessors:
\begin{python}
def predecessors(self, root, target, stk):
  if not root: return

  self.predecessors(root.left, target, stk)
  if root.val <= target:
    stk.append(root.val)
    self.predecessors(root.right, target, stk)
\end{python}

\section{Binary Index Tree (BIT)}\label{BIT}
\subsection{Introduction}
Compared to Segment Tree \ref{section:segmentTree}, BIT is shorter and more elegant. BIT can do most of things that Segment Tree can do and it is easier to code. BIT updates and queries $$i\rightarrow prefixSum$$ in $O(\log n)$ time; however, BIT CANNOT query $$prefixSum \rightarrow i$$
\subsection{Implementation}
Given an array $A$ of length $n $ starting from $1$. prefix sum $s[i]\triangleq A_1+...+A_i$. BIT uses binary to maintain the array of prefix sum for querying and updating. For $i$-th node in the BIT,
$$
N[i]=A_{j+1}+...+A_i
$$
, where $j=i-lowbit(i)$, i.e. set $i$'s lowest bit 1 to 0. $lowbit(i)$ can be defined as \pyinline{return i & -i}, using 2's complement. Notice that the summation ends with $A_i$ since easier to \pyinline{set}.

For the range, we use $(j, i]$ here instead of $[j, i)$ since more elegant for \pyinline{get(i)} and \pyinline{set(i)}
\\\\
Clues:
\begin{enumerate}
\item Binary
\item Low bit
\item BIT uses array index starting from \textbf{1}, because 0 doesn't have $lowbit$.
\end{enumerate}
\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=1.1in]{BITget}}
\caption{Binary Indexed Tree \textit{get} Operation}
\label{fig:LABEL}
\end{figure}

\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[height=1.05in]{BIT}}
\caption{Binary Indexed Tree \textit{set} Operation}
\label{fig:LABEL}
\end{figure}

Time complexity, longest update is along the leftmost branch, which takes $O(\log_2 n)$ (e.g. 1, 10, 100, 1000, 10000); longest query is along a branch starting with node with all 1's (e.g. 1111, 1110, 1100, 1000), which also takes $O(\log_2 n)$.
\newpage
Code:
\begin{python}
class BIT(object):
    def __init__(self, n):
        """BIT uses index starting from 1"""
        self.N = [0 for _ in xrange(n+1)]

    def lowbit(self, i):
        return i & -i

    def get(self, i):
        ret = 0
        while i > 0:
            ret += self.N[i]
            i -= self.lowbit(i)

        return ret

    def set(self, i, val):
        while i < len(self.N):
            self.N[i] += val
            i += self.lowbit(i)
\end{python}

\section{Segment Tree}\label{section:segmentTree}
\subsection{Introduction}
Segment Tree is specially built for \textit{range queries}.

The structure of Segment Tree is a binary tree which each node has two attributes start and end denote an segment/interval.

Notice that by practice, the interval is normally $[start, end)$ but sometimes it can be $[start, end]$, which depends on the question definition.

Structure:
\begin{lstlisting}[columns=flexible]
# a Count Segment Tree
                     [0, 4, count=3]
                     /             \
          [0,2,count=1]             [2,4,count=2]
          /         \               /            \
   [0,1,count=1] [1,2,count=0] [2,3,count=1], [3,4,count=1]
\end{lstlisting}
Variants:
\begin{enumerate}
\item Sum Segment Tree.
\item Min/Max Segment Tree.
\item Count Segment Tree.
\end{enumerate}

For a Maximum Segment Tree, which each node has an extra value max to store the maximum value in this node's interval.

\subsection{Operations}
Segment Tree does a decent job for range queries.
\\
Components in Segment Tree operations:
\begin{enumerate}
\item Build
\item Query
\item Modify
\item Search
\end{enumerate}
Notice:
\begin{enumerate}
\item Only build need to change the start and end recursively.
\item Pre-check is preferred in recursive calls.
\end{enumerate}
Code: Notice the code has abstracted out segment tree functions of sum, min/max or count, by abstracting the subtree combine function to \pyinline{lambda}.
\begin{python}
DEFAULT = 0
f = lambda x, y: x+y

class Node(object):
    def __init__(self, start, end, m):
        self.start, self.end, self.m = start, end, m
        self.left, self.right = None, None

class SegmentTree(object):
    def __init__(self, A):
        self.A = A
        self.root = self.build_tree(0, len(self.A))

    def build_tree(self, s, e):
        """
        segment: [s, e)
        Either check s+1==e or have root.right
        only if have root.left
        """
        if s >= e: return None
        if s+1 == e: return Node(s, e, self.A[s])

        left = self.build_tree(s, (s+e)/2)
        right = self.build_tree((s+e)/2, e)

        val = DEFAULT
        if left: val = f(val, left.m)
        if right: val = f(val, right.m)
        root = Node(s, e, val)
        root.left = left
        root.right = right

        return root

    def query(self, root, s, e):
        """
        :type root: Node
        """
        if not root:
            return DEFAULT

        if s <= root.start and e >= root.end:
            return root.m

        if s >= root.end or e <= root.start:
            return DEFAULT

        l = self.query(root.left, s, e)
        r = self.query(root.right, s, e)
        return f(l, r)

    def modify(self, root, idx, val):
        """
        :type root: Node
        """
        if not root or idx >= root.end or idx < root.start:
            return

        if idx == root.start and idx == root.end-1:
            root.m = val
            self.A[idx] = val
            return

        self.modify(root.left, idx, val)
        self.modify(root.right, idx, val)

        val = DEFAULT
        if root.left:  val = f(val, root.left.m)
        if root.right: val = f(val, root.right.m)

        root.m = val
\end{python}
Concrete example - Count Segment Tree \ref{inversionReconstruct}.

\newpage
\section{Trie}
\subsection{Basic}
Trie is aka radix tree, prefix tree.
\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[scale=.30]{trie.jpg}}
\caption{Trie}
\label{fig:trie}
\end{figure}
\runinhead{Notice:}
\begin{enumerate}
\item Children are stored in HashMap rather than ArrayList.
\item self.word to stores the word and indicates whether a word ends at the current
node.
\end{enumerate}
Codes:
\begin{python}
class TrieNode(object):
    def __init__(self, char):
        self.char = char
        self.word = None
        self.children = {}  # map from char to TrieNode

class Trie(object):
    def __init__(self):
        self.root = TrieNode(None)

    def add(self, word):
        word = word.lower()
        cur = self.root
        for c in word:
            if c not in cur.children:
                cur.children[c] = TrieNode(c)
            cur = cur.children[c]
        cur.word = word
\end{python}

\subsection{Advanced}
Implicit storage of word in TrieNode:
\begin{enumerate}
\item Implicitly stores the current word.
\item Implicitly stores the current char.
\item When insert new word, do not override the existing TrieNode. A flag to indicate
whether there is a word ending here.
\end{enumerate}
\newpage
Code:
\begin{python}
class TrieNode:
    def __init__(self):
        """Implicit storage"""
        self.ended = False
        self.children = {}

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        cur = self.root
        for w in word:
            if w not in cur.children:   # not override
                cur.children[w] = TrieNode()
            cur = cur.children[w]

        cur.ended = True

    def search(self, word):
        cur = self.root
        for w in word:
            if w in cur.children:
                cur = cur.children[w]
            else:
                return False

        if not cur.ended:  # not ended here
            return False

        return True

    def startsWith(self, prefix):
        cur = self.root
        for w in prefix:
            if w in cur.children:
                cur = cur.children[w]
            else:
                return False

        return True
\end{python}
\subsection{Applications}
\begin{enumerate}
\item Word search in matrix.
\item Word look up in dictionary.
\end{enumerate}


\section{The Whitney sum formula}
%Let me just repeat what I was rushing through at the end on Wednesday.
%I wrote slightly incorrect things.
%Let's look at $\cc^n$.
%Of course, $U(n)$ acts on this, and preserves the inner product.
%Recall that $Fr(\cc^n)$ is the space of orthonormal bases of $\cc^n$.
%Thus there's an action of $U(n)$ on this, and this is simply transitive, i.e., it's free and transitive.
%Some would say that this is a ``torsor for $U(n)$''.
%There's a basepoint in here, namely the standard basis, but you may forget about that.
%
%Now I can make various constructions.
%For instance, think about $\Fl(\cc^n)$, which is the space of ordered orthonormal sets of $n$ lines in $\cc^n$.
%There's lots of isotropy now.
%The isotropy group of the $U(n)$ action on the lines through the standard basis is now $T_n=U(1)^n$, i.e., diagonal matrices with roots of unity on the diagonal.
%This is called the \emph{(complete) flag manifold}.
%
%Another thing you could do as well -- you can forget the ordering.
%This doesn't really have a name, I guess, but what I'm doing is considering $\Fl(\cc^n)/\Sigma_n$, which is the space of unordered orthonormal lines in $\cc^n$.
%This is a homogeneous space, too, and it's $U(n)$ quotiented by permutation matrices where $1$ is any complex number of norm $1$.
%For instance, if $N_{U(n)}(T^n) = \Sigma_n\cdot T^n$ is the normalizer, then $\Fl(\cc^n)/\Sigma_n = U(n)/N(T^n)$.
%I can consider the cofiber sequence $T^n\hookrightarrow \Sigma_n\cdot T^n \to W_n$, and the $W_n$ is called the Weyl group.
%Something nice here is that
%\begin{equation*}
%    \xymatrix{
%	T^n\ar@{^(->}[r] & \Sigma_n\cdot T^n\ar[r] & W_n\\
%	& \Sigma_n\ar@{^(->}[u]\ar[ur]^\simeq &
%    }
%\end{equation*}
%To get projective space I consider the space of splittings of $\cc^n$ into a line and its orthogonal complement -- but that's just giving a line because the metric determines the orthogonal complement.
%
%Consider a complex $n$-plane bundle $\xi^n\downarrow X$, with a metric.
%Then $\Fr(\xi^n)\to X$ is a principal $U(n)$-bundle over $X$.
%I can form $E(\xi) = \Fr(\xi)\times_{U(n)}\cc^n$, and $\PP(\xi) = \Fr(\xi)\times_{U(n)} U(n)/(U(1)\times U(n-1))$.
%Note that $U(n)/(U(1)\times U(n-1)) = \CP^{n-1}$.
%I can also consider $\Fl(\xi) = \Fr(\xi)\times_{U(n} U(n)/T^n$.
%
%We found that $H^\ast(X) \hookrightarrow H^\ast(\Fl(\xi))$.
%This is the splitting principle.
%
%Let's look at the universal case $\xi_n\downarrow BU(n)$.
%So, $\Fl(\xi_n) = EU(n)\times_{U(n)} U(n)/T^n$, so this is $BT^n$.
%It maps down to $BU(n)$, and the map is the one induced by the inclusion $T^n\hookrightarrow U(n)$.
%So, for any ring, we find that $H^\ast(BU(n))\hookrightarrow H^\ast(BT^n)$.
%We know that
%$$
%H^\ast(BT^n) = \Z[t_1,\cdots,t_n]
%$$
%where $t_i = e(\lambda_i)$ and $|t_i| = 2$, where $\lambda_i = pr_i^\ast\lambda$ and $\lambda\downarrow \CP^\infty$ is the universal line bundle.
As we saw in the previous section, there is an injection
$H^\ast(BU(n))\hookrightarrow H^\ast(BT^n)$. What is the image of this map?

The symmetric group sits inside of $U(n)$, so it acts by conjugation on $U(n)$.
This action stabilizes this subgroup $T^n$. By naturality, $\Sigma_n$ acts on
the classifying space $BT^n$. Since $\Sigma_n$ acts by conjugation on $U(n)$,
it acts on $BU(n)$ in a way that is homotopic to the identity (Lemma
\ref{conjugation-homotopic}). However, each element $\sigma\in \Sigma_n$ simply
permutes the factors in $BT^n = (\CP^\infty)^n$; we conclude that
$H^\ast(BU(n);R)$ actually sits inside the invariants
$H^\ast(BT^n;R)^{\Sigma_n}$.

Recall the following theorem from algebra:
\begin{theorem}
    Let $\Sigma_n$ act on the polynomial algebra $R[t_1,\cdots,t_n]$ by
    permuting the generators. Then
    $$R[t_1,\cdots,t_n]^{\Sigma_n} = R[\sigma_1^{(n)},\cdots,\sigma_n^{(n)}],$$
    where the $\sigma_i$ are the {elementary symmetric polynomials}, defined
    via
    $$\prod^n_{i=1}(x-t_i) = \sum^n_{j=0} \sigma_i^{(n)}x^{n-i}.$$
\end{theorem}
For instance,
$$\sigma_1^{(n)} = -\sum t_i,\ \sigma_n^{(n)} = (-1)^n\prod t_i.$$
If we impose a grading on $R[t_1,\cdots,t_n]$ such that $|t_i| = 2$, then
$|\sigma_i^{(n)}| = 2i$. It follows from our discussion in \S
\ref{homology-bun} that the ring $H^\ast(BT^n)^{\Sigma_n}$ has the same size as
$H^\ast(BU(n))$.
%they the same Poincar\'{e} series. You could imagine that maybe it embeds as a
%lattice inside the integers?

Consider an injection of finitely generated abelian groups $M\hookrightarrow
N$, with quotient $Q$. Suppose that, after tensoring with any field, the map
$M\to N$ an isomorphism. If $Q\otimes k = 0$, then $Q = 0$.
Indeed, if $Q\otimes \QQ = 0$ then $Q$ is torsion. Similarly, if $Q\otimes
\FF_p = 0$, then $Q$ has no $p$-component. In particular, $M\simeq N$. Applying
this to the map $H^\ast(BU(n)\to H^\ast(BT^n)^{\Sigma_n}$, we find that
$$
H^\ast(BU(n);R) \xrightarrow{\simeq} H^\ast(BT^n;R)^{\Sigma_n} =
R[\sigma_1^{(n)},\cdots,\sigma_n^{(n)}].
$$
What happens as $n$ varies? There is a map $R[t_1,\cdots,t_n] \to
R[t_1,\cdots,t_{n-1}]$ given by sending $t_n\mapsto 0$ and $t_i\mapsto t_i$ for
$i\neq n$. Of course, we cannot say that this map is equivariant with respect
to the action of $\Sigma_n$. However, it \emph{is} equivariant with respect to
the action of $\Sigma_{n-1}$ on $R[t_1,\cdots,t_n]$ via the inclusion of
$\Sigma_{n-1}\hookrightarrow \Sigma_n$ as the stabilizer of
$n\in\{1,\cdots,n\}$. Therefore, the $\Sigma_n$-invariants sit inside the
$\Sigma_{n-1}$-invariants, giving a map
$$
R[t_1,\cdots,t_n]^{\Sigma_n} \to R[t_1,\cdots,t_n]^{\Sigma_{n-1}} \to
R[t_1,\cdots,t_{n-1}]^{\Sigma_{n-1}}.
$$
We also find that for $i<n$, we have $\sigma_i^{(n)} \mapsto \sigma_i^{(n-1)}$
and $\sigma_n^{(n)} \mapsto 0$.
\subsection{Where do the Chern classes go?}\label{euler-multiplicativity}
To answer this question, we will need to understand the multiplicativity of the
Chern class. We begin with a discussion about the Euler class. Suppose $\xi^p\downarrow X,\eta^q\downarrow Y$ are oriented real
vector bundles; then, we can consider the bundle $\xi\times\eta\downarrow X\times Y$, which is
another oriented real vector bundle. The orientation is given by picking
oriented bases for $\xi$ and $\eta$.
%There are lot of choices, but I'll put the first one first and the second one
%second.
We claim that
$$e(\xi\times\eta) = e(\xi)\times e(\eta) \in H^{p+q}(X\times Y).$$
Since $D(\xi\times\eta)$ is homeomorphic to $D(\xi)\times D(\eta)$, and
$S(\xi\times\eta) = D(\xi)\times S(\eta)\cup S(\xi)\times D(\eta)$, we learn
from the relative K\"unneth formula that
$$H^\ast(D(\xi\times\eta),S(\xi\times\eta)) \leftarrow
H^\ast(D(\xi),S(\xi))\otimes H^\ast(D(\eta),S(\eta)).$$
It follows that
$$
u_{\xi\times \eta} = u_\xi\times u_\eta\in H^{p+q}(\Th(\xi)\times\Th(\eta));
$$
this proves the desired result since the Euler class is the image of the Thom
class under the map $H^n(\Th(\xi))\to H^n(D(\xi)) \simeq H^n(B)$.

Consider the diagonal map $\Delta:X\to X\times X$. The cross product in
cohomology then pulls back to the cup product, and the direct product of fiber
bundles pulls back to the Whitney sum. It follows that
$$e(\xi\oplus\eta) = e(\xi)\cup e(\eta).$$

If $\xi^n\downarrow X$ is an $n$-dimensional complex vector bundle, then we
defined\footnote{There's a slight technical snag here: a complex bundle doesn't
have an orientation. However, its underlying oriented real vector bundle does.}
$$
c_n(\xi) = (-1)^n e(\xi_\RR).
$$
We need to describe the image of $c_n(\xi_n)$ under the map $H^{2n}(BU(n)) \to
H^{2n}(BT^n)^{\Sigma_n}$.

Let $f:BT^n\to BU(n)$ denote the map induced by the inclusion of the maximal
torus. Then, by construction, we have a splitting
$$f^\ast\xi_n = \lambda_1\oplus\cdots\oplus \lambda_n.$$
Thus,
$$(-1)^ne(\xi)\mapsto (-1)^n e(\lambda_1\oplus\cdots\oplus \lambda_n) = (-1)^n
e(\lambda_1)\cup\cdots\cup e(\lambda_n).$$
The discussion above implies that $f^\ast$ sends the right hand side to
$(-1)^nt_1\cdots t_n = \sigma_n^{(n)}$. In other words, the top Chern class
maps to $\sigma_n^{(n)}$ under the map $f^\ast$.

Our discussion in the previous sections gives a commuting diagram:
\begin{equation*}
    \xymatrix{
	H^\ast(BU(n)) \ar[r] \ar[d] & H^\ast(BT^n)^{\Sigma_n}\ar[d]\\
	H^\ast(BU(n-1)) \ar[r] & H^\ast(BT^{n-1})^{\Sigma_{n-1}}
    }
\end{equation*}
Arguing inductively, we find that going from the top left corner to the bottom
left corner to the bottom right corner sends
$$c_i\mapsto c_i\mapsto \sigma_i^{(n-1)}\text{ for }i<n.$$
Likewise, going from the top left corner to the top right corner to the bottom
right corner sends
$$c_i\mapsto \sigma_i^{(n)}\mapsto \sigma_i^{(n-1)}\text{ for }i<n.$$
We conclude that the map $f^\ast$ sends $c_i^{(i)}\mapsto \sigma_i^{(i)}$.
\subsection{Proving the Whitney sum formula}
By our discussion above, the Whitney sum formula of Theorem \ref{chern-classes}
reduces to proving the following identity:
\begin{equation}\label{symmpol}
    \sigma^{(p+q)}_k = \sum_{i+j=k}\sigma_i^{(p)}\cdot\sigma_j^{(q)}
\end{equation}
inside $\Z[t_1,\cdots,t_p,t_{p+1},\cdots,t_{p+q}]$. Here, $\sigma_i^{(p)}$ is
thought of as a polynomial in $t_1,\cdots,t_p$, while $\sigma_i^{(q)}$ is
thought of as a polynomial in $t_{p+1},\cdots,t_{p+q}$. To derive Equation
\eqref{symmpol}, simply compare coefficients in the following:
\begin{align*}
    \sum_{k=0}^{p+q} \sigma_k^{(p+q)}x^{p+q-k} & = \prod^{p+q}_{i=1}(x-t_i)\\
    & = \prod^p_{i=1}(x-t_i)\cdot\prod^{p+q}_{j=p+1}(x-t_j)\\
    & = \left(\sum^p_{i=0}\sigma^{(p)}_i
    x^{p-i}\right)\left(\sum^q_{j=0}\sigma_j^{(p)} x^{q-j}\right)\\
    & =
    \sum^{p+q}_{k=0}\left(\sum_{i+j=k}\sigma_i^{(p)}\sigma_j^{(q)}\right)x^{p+q-k}.
\end{align*}


\section{Question 3}
Question 1 work well but in question 2 we have a long time delay so challenge for time optimization appears here. So we choise second system.

System:
$$
G_{1_{(s)}} = \dfrac{1}{(17s+1)(5s+1)}\exp(-30s) = \dfrac{1}{102s^2+23s+1}
$$
We use Optimal PID to design controller with ITAE cost function. In program we use 40, 100, 400 and second for optimization but use 400 second for simulation to see system behavior. ITAE cost function work well in last question so we use this cost function in different time optimization.
\begin{figure}[H]
    \caption{Step responde with PID controller and ITAE cost function for different time}
    \centering
    \includegraphics[width=11cm]{../Figure/Q3/ITAE.png}
\end{figure}
In 40 second system is unstable but in other time system is stable and when we increse time PID conteller work better.


\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{calc}
\usepackage{mathtools}
\usepackage{tkz-euclide}

% To reduce the possibility of being reached through Google.
\def \TitleSubject{MATH}
\def \TitleSeqNoA{3}
\def \TitleSeqNoB{1}
\def \TitleSeqId{A}
\def \TitleSeq{\TitleSeqNoA\TitleSeqNoB\TitleSeqId}
\newcommand \MakeTitle[1]{
  \title{\TitleSubject\ \TitleSeq\ Homework\ #1}
  \author{Minsheng Liu}
}

\newcommand \gotosection[2]{
  \setcounter{section}{#1}
  \setcounter{subsection}{{{#2}-1}}
}
\newenvironment{exercise}[1]{
  \setcounter{subsubsection}{{{#1}-1}}
  \subsubsection{}
}{}

% Sub-questions in this book using a, b, c, etc. as counters.
\renewcommand \theenumi{\alph{enumi}}

% Convenient Math constructs.
\newcommand \FunSS[3]{$#1 : #2 \to #3$}
\newcommand \QED{$\square$}
\newcommand \rQED{\hfill\QED}
\newcommand \Proof{\textbf{Proof.}}
\newcommand \Vect[1]{\vec{\mathbf{#1}}}
\newenvironment{xmatrix}{\begin{bmatrix*}[r]}{\end{bmatrix*}}

\newcommand \xmat[1]{\begin{xmatrix}#1\end{xmatrix}}
\newcommand \rops[1]{\begin{array}{l}#1\end{array}}
\newcommand \cmat[1]{\begin{bmatrix}#1\end{bmatrix}}


\section{Measurement Uncertainty Analysis}

\subsection{Uncertainty for resonance method}

For type-B uncertainty of $\Delta L$,

$$ \frac{\partial \Delta L}{\partial L_{10+i}}=1 $$
$$ \frac{\partial \Delta L}{\partial L_i}=-1 $$
$$ u_{L_{10+i}}=u_{L_i}=\Delta_{dev}=1\e{-5}m $$

\[
\begin{split}
    &\Delta_{\Delta L,B}=\sqrt{(\frac{\partial \Delta L}{\partial
        L_{10+i}})^2\cdot (u_{L_{10+i}})^2+(\frac{\partial \Delta
        L}{\partial L_i})^2\cdot (u_{L_i})^2}\\
    &=0.014 \times 10^{-3}m.\\
\end{split}
\]

For estimate type-A uncertainty,
the standard deviation of the average value can be caluculated as

\[
    s_{\overline{\Delta L}}=\sqrt{\frac{1}{n(n-1)}\sum_{i=1}^n(\Delta
      L_i-\overline{\Delta L})^2}.
\]

From data of Table~\ref{d1} we get that
$s_{\overline{\Delta L}} = 0.01919\e{-3}m$.
Considering $t_{0.95}=2.26$ for $n=10$,
the type-A uncertainty can be estimated as
$\Delta_{\Delta L,A}=2.26 \times 0.01919\e{-3} = 0.0434\e{-3}m$.

Thus the combined uncertainty is

\[
\begin{split}
    &u_{\Delta L}=\sqrt{\Delta_{\Delta L,A}^2+\Delta_{\Delta
        L,B}^2} \\
    &= \sqrt{(0.0434\e{-3})^2+(0.014\e{-3})^2} \\
    &= 0.045\e{-3}m\\
\end{split}
\]

\[
\begin{split}
    &u_{r,\Delta L}=\frac{u_{\Delta L}}{\overline{\Delta L}}\times
    100\%=\frac{0.045\e{-3}}{50.94\e{-3}}\times100\% \\
    &=0.09\%\\
\end{split}
\]
$$\overline{\Delta L}=(50.94 \pm 0.05)\e{-3}m, u_{r,\Delta L}=0.10\% $$

In the same way, we obtain the uncertainty of wavelength $\lambda=2\Delta L/n$

$$\frac{\partial \lambda}{\partial \Delta L}=\frac{2}{10}=\frac{1}{5}$$

$$u_{\Delta L}=0.05\e{-3}m$$

$$u_{\lambda}=\sqrt{(\frac{\partial \lambda}{\partial \Delta L})^2\cdot
  (u_{\Delta L})^2}
  =\frac{1}{5}\times 0.05\e{-3}=0.01\e{-3}m$$

$$u_{r,\lambda}=\frac{u_{\lambda}}{\overline{\lambda}}\times
100\%=\frac{0.01\e{-3}}{10.03\e{-3}}=0.10\%$$

$$\lambda=(10.03\pm0.01)\e{-3}m,\quad u_{r,\lambda}=0.10\%$$

and the uncertainty of the spped of sound in air $v=\lambda f$

$$\frac{\partial v}{\partial \lambda}=f,
\frac{\partial v}{\partial f}=\lambda$$

$$u_{\lambda}=0.01\e{-3}m,
u_{f}=1Hz$$

\[
\begin{split}
&u_{v}=\sqrt{(\frac{\partial v}{\partial \lambda})^2\cdot
  (u_{\lambda})^2+(\frac{\partial v}{\partial f})^2\cdot
  (u_{f})^2}=\sqrt{(f)^2\cdot (u_{\lambda})^2+(\lambda)^2\cdot
  (u_{f})^2}\\
&\quad =\sqrt{(35000)^2\cdot(0.01\e{-3})^2+(10.03\e{-3})^2\cdot(1)^2}
\approx0.4m/s\\
\end{split}
\]

$$u_{r,v}=\frac{u_v}{\overline{v}}\times 100\%=\frac{0.4}{351.05}=0.10\%$$
$$v=351.05\pm0.4 m/s,\quad u_{r,v}=0.10\%$$

\subsection{Uncertainty for phase comparison method}

To determine the type-B uncertainty of $\Delta L$,

$$\frac{\partial \Delta L}{\partial L_{6+i}}=1,
\quad \frac{\partial \Delta L}{\partial L_i}=-1$$
$$u_{L_{6+i}}=u_{L_i}=\Delta_{dev}=1\e{-5}m$$

\[
\begin{split}
    &\Delta_{\Delta L,B}=\sqrt{(\frac{\partial \Delta L}{\partial
        L_{6+i}})^2\cdot (u_{L_{6+i}})^2+(\frac{\partial \Delta L}{\partial
        L_i})^2\cdot (u_{L_i})^2}\\
    &\quad\quad =\sqrt{2}\times 1\e{-5}\approx0.014\e{-3}m.\\
\end{split}
\]

For type-A uncertainty, the standard deviation of the average value is caluculated as

\[
    s_{\overline{\Delta L}}=\sqrt{\frac{1}{n(n-1)}\sum_{i=1}^n(\Delta
      L_i-\overline{\Delta L})^2}.
\]

Uisng the data from Table \ref{d2} we find that $s_{\overline{\Delta
    L}}\approx 0.6485\e{-3}m$. Considering $t_{0.95}=2.57$ for $n=6$, the
type-A uncertainty is estimated as $\Delta_{\Delta
  L,A}=2.57\times0.6485\e{-3}\approx 1.67\e{-3}m$.

Thus the combined uncertainty is

$$u_{\Delta L}=\sqrt{\Delta_{\Delta L,A}^2+\Delta_{\Delta
    L,B}^2}=\sqrt{(1.67\e{-3})^2+(0.014\e{-3})^2}\approx1.7\e{-3}m$$

$$u_{r,\Delta L}=\frac{u_{\Delta L}}{\overline{\Delta L}}\times
100\%=\frac{1.7\e{-3}}{59.84\e{-3}}\times100\%\approx3\%$$

$$\overline{\Delta L}=(59.84\pm 1.7)\e{-3}m,\quad u_{r,\Delta L}=3\% $$

Similarly, we obtain the uncertainty of wavelength $\lambda=\Delta L/n$

$$\frac{\partial \lambda}{\partial \Delta L}=\frac{1}{6}$$
$$u_{\Delta L}=1.7\e{-3}m$$
$$u_{\lambda}=\sqrt{(\frac{\partial \lambda}{\partial \Delta L})^2\cdot
      (u_{\Delta L})^2}=\frac{1}{6}\times 1.7\e{-3}=0.3\e{-3}m$$
$$u_{r,\lambda}=\frac{u_{\lambda}}{\overline{\lambda}}\times
100\%=\frac{0.3\e{-3}}{9.973\e{-3}}=3\%$$
$$\lambda=(9.973\pm0.3)\e{-3}m,\quad u_{r,\lambda}=3\%$$

and the uncertainty of the spped of sound in air $v=\lambda f$

$$\frac{\partial v}{\partial \lambda}=f,
\quad \frac{\partial v}{\partial f}=\lambda$$

$$u_{\lambda}=0.3\e{-3}m,\quad u_{f}=1Hz$$

\[
\begin{split}
    &u_{v}=\sqrt{(\frac{\partial v}{\partial \lambda})^2\cdot
      (u_{\lambda})^2+(\frac{\partial v}{\partial f})^2\cdot
      (u_{f})^2}=\sqrt{(f)^2\cdot (u_{\lambda})^2+(\lambda)^2\cdot
      (u_{f})^2},\\
    &\quad =\sqrt{(35000)^2\cdot(0.3\e{-3})^2+(9.97\e{-3})^2\cdot(1)^2}
    \approx10m/s,\\
\end{split}
\]

$$u_{r,v}=\frac{u_v}{\overline{v}}\times 100\%=\frac{10}{348.95}=3\%$$
$$v=348.95\pm10 m/s,\quad u_{r,v}=3\%$$

\subsection{Uncertainty for the time difference method (liquid)}

From MATLAB  fitting toolbox, the slope of $L\ vs.\ t$,
we obtain the information of the fit.

$$    v_{water}=1502\pm20 m/s. $$

where $\pm 20m/s$ is the 0.95-confidence uncertainty, with $t_{0.95}=2.20$
when $n=12$. THe relative uncertainty is that

$$u_{r,v}=\frac{u_v}{\bar{v}}\times100\%=\frac{20}{1502}=1.5\%.$$

Hence the speed of sound in water is
$$v_{water}=1502\pm20m/s,\quad u_{r,v}=1.5\%. $$


% !TEX root = lectures.tex
%\input{lectureheader.tex}

\section{Rotating Coordinate Systems}
\bigskip

\subsection{Accelerating Frames}

Here we again consider the effect of uniformly accelerating reference frames. If a particle is observed in an inertial reference frame, which we will denote with a prime, Newton's third law applies
\begin{equation}
m\frac{d^2\vec{r}'}{dt^2}=\vec{F}.
\end{equation}
Now, if we have a second coordinate system,
\begin{equation}
\vec{r}=\vec{r}'-\vec{r}_0,~~~~\vec{r_0}=\frac{1}{2}\vec{a}_0t^2.
\end{equation}
We would see that
\begin{equation}
m\frac{d^2\vec{r}}{dt^2}=\vec{F}-m\vec{a}_0.
\end{equation}
Here $\vec{a}_0$ is the acceleration of the coordinate system. The last term acts like an additional apparent force. In fact, it acts like a contribution to the gravitational force which alters the acceleration of gravity by $\delta\vec{g}=-\vec{a}_0$.

\subsection{Rotating Frames}
If you are on Earth's surface and if your reference frame is fixed with the surface, this is an example of an accelerating frame, where the acceleration is $\omega^2 r_{\perp}$, where $r_{\perp}\equiv\sqrt{x^2+y^2}$, and $\omega$ is the angular velocity of Earth's rotation. The acceleration is inward toward the axis of rotation, so the additional contribution to the apparent acceleration of gravity is outward in the $x-y$ plane. In contrast the usual $\vec{g}$ is radially inward pointing toward the origin.

In the rotating coordinate system (not an inertial frame), motion is determined by the apparent force and one can define effective potentials. In addition to the normal gravitational potential energy, there is a contribution to the effective potential,
\begin{equation}
\delta U_{\rm eff}=-\frac{m}{2}\omega^2r_\perp^2=-\frac{m}{2}r^2\omega^2\sin^2\theta,
\end{equation}
where $\theta$ is the polar angle, measured from the north pole. If the true gravitational force can be considered as originating from a point in Earth's center, the net effective potential for a mass $m$ near Earth's surface could be
\begin{equation}
U_{\rm eff}=mgh-m\frac{1}{2}\omega^2(R+h)^2\sin^2\theta.
\end{equation}

\example
How much wider is Earth at the equator than the north-south distance between the poles assuming that the gravitational field above the surface can be approximated by that of a point mass at Earth's center.

{\bf Solution}:
The surface of the ocean must be at constant effective potential for a sample mass $m$. This means that if $h$ now refers to the height of the water
\[
m g[h(\theta=\pi/2)-h(\theta=0)]=\frac{m}{2}\omega^2(R+h)^2.
\]
Because $R>>h$, one can approximate $R+h\rightarrow R$ on the right-hand side, thus
\[
h(\theta=\pi)-h(\theta=0)=\frac{\omega^2R^2}{2g}.
\]
This come out a bit less than 11 km, or a difference of near 22 km for the diameter of the Earth in the equatorial plane compared to a diameter between the poles. In reality, the difference is approximately 41 km. The discrepancy comes from the assumption that the true gravitational force can be treated as if it came from a point at Earth's center. This would be true if the distribution of mass was radially symmetric. However, Earth's center is molten and the rotation distorts the mass distribution. Remarkably this effect nearly doubles the elliptic distortion of Earth's shape. Due to this distortion, the top of Mount Everest is not the furthest point from the center of the Earth. That belongs to the top of a volcano, Chimborazo, in Equador, which is one degree in latitude below the Equator. Chimborazo is about 8500 ft lower than Everest when measured relative to sea level, but is 7700 feet further from the center of the Earth.

\exampleend

\subsection{Coriolis Force}

Consider some vector $\vec{A}$ according to an observer in a frame rotating about the $z$ axis with angular velocity $\vec{\omega}=\omega\hat{z}$. To an observer in the laboratory frame (the primed frame) the vector will change even if the vector appears fixed to the rotating observer. For a rotation of $\Delta\theta=\omega\Delta t$, the change of the vector due to the rotation is
\begin{eqnarray}
\Delta\vec{A}'=\vec{\omega}\times\vec{A}\Delta t.
\end{eqnarray}
If one includes the fact that $A$, the vector measured in the rotating frame, might be changing as a function of time,
\begin{eqnarray}
\label{eq:dAdtrot}
\Delta\vec{A}'&=&\Delta\vec{A}+\vec{\omega}\times\vec{A}\Delta t,\\
\nonumber
\frac{d}{dt}\vec{A}'&=&\frac{d}{dt}\vec{A}+\vec{\omega}\times\vec{A}.
\end{eqnarray}
If the vector happens to be the position $\vec{r}$,
\begin{eqnarray}
\dot{\vec{r}}'&=&\vec{v}'=\vec{v}+\vec{\omega}\times\vec{r}.
\end{eqnarray}
Here, the first term on the r.h.s. corresponds to the vector $\vec{r}$ not being fixed, but changing with time, $\dot{\vec{r}}=\vec{v}$. One can now use $\vec{v}'=\vec{v}+\vec{\omega}\times\vec{r}$ in place of $\vec{A}$ in Eq. (\ref{eq:dAdtrot}), and see
\begin{eqnarray}
\dot{\vec{v}}'&=&\frac{d}{dt}(\vec{v}+\vec{\omega}\times\vec{r})+\vec{\omega}\times(\vec{v}+\vec{\omega}\times\vec{r})\\
\nonumber
&=&\dot{\vec{v}}+\vec{\omega}\times\dot\vec{r}+\vec{\omega}\times\left(\vec{v}+\vec{\omega}\times\vec{r}\right)\\
\nonumber
&=&\dot{\vec{v}}+2\vec{\omega}\times\vec{v}+\vec{\omega}\times(\vec{\omega}\times\vec{r}).
\end{eqnarray}
Because $\dot{\vec{v}}'$ is $\vec{F}/m$,
\begin{eqnarray}
\label{eq:FmaRotatingFrame}
\vec{F}&=&m\left\{\vec{a}+2\vec{\omega}\times\vec{v}+\vec{\omega}\times(\vec{\omega}\times\vec{r})\right\},\\
\nonumber
m\vec{a}&=&\vec{F}-2m\vec{\omega}\times\vec{v}-m\vec{\omega}\times(\vec{\omega}\times\vec{r}).
\end{eqnarray}
The extra terms on the right behave like additional forces. Like gravitational forces, they are proportional to the mass, so the mass cancels for many problems.

The last term, $-m\vec{\omega}\times(\vec{\omega}\times\vec{r})$, represents the centrifugal force. Using the vector identity,
$\vec{A}\times(\vec{B}\times\vec{C})=\vec{B}(\vec{A}\cdot{\vec{C}})-\vec{C}(\vec{A}\cdot\vec{B})$,
\begin{equation}
-\vec{\omega}\times(\vec{\omega}\times\vec{r})=\omega^2\vec{r}+(\omega\cdot\vec{r})\vec{\omega}.
\end{equation}
If $\vec{\omega}$ is in the $z$ direction,
\begin{equation}
-\vec{\omega}\times(\vec{\omega}\times\vec{r})=\omega^2(x\hat{x}+y\hat{y}).
\end{equation}
The centrifugal force points outward in the $x-y$ plane, and its magnitude is $m\omega^2r_{\rm\perp}$, where $r_{\rm\perp}=\sqrt{x^2+y^2}$.

The second term is Eq. (\ref{eq:FmaRotatingFrame}) represents the Coriolis force. It does not enter problems like the shape of the Earth above because in that case the water was not moving relative to the rotating frame. Once an object is moving in a rotating frame, the particle is no longer being described in a single accelerating frame because at each point the acceleration is $-\omega^2\vec{r}$.

\example
A ball is dropped from a height $h=500$m above Minneapolis. Due to the Coriolis force, it is deflected by an amount $\delta x$ and $\delta y$. Find the deflection. Ignore the centrifugal terms.

{\bf Solution}: The equations of motion are:
\begin{eqnarray*}
\frac{dv_x}{dt}&=&-2(\omega_yv_z-\omega_zv_y),\\
\frac{dv_y}{dt}&=&-2(\omega_zv_x-\omega_xv_z),\\
\frac{dv_z}{dt}&=&-g-2(\omega_xv_y-\omega_yv_x),\\
\omega_z&=&\omega\cos\theta,~~~\omega_y=\omega\sin\theta,~~~\omega_x=0.
\end{eqnarray*}
Here the coordinate system is $\hat{x}$ points east, $\hat{y}$ points north and $\hat{z}$ points upward.

One can now ignore all the Coriolis terms on the right-hand sides except for those with $v_z$. The other terms will all be doubly small. One can also throw out terms with $\omega_x$. This gives
\begin{eqnarray*}
\frac{dv_x}{dt}&\approx& -2\omega v_z\sin\theta,\\
\frac{dv_y}{dt}&\approx& 0,\\
\frac{dv_z}{dt}&\approx& -g.
\end{eqnarray*}
There will be no significant deflection in the $y$ direction, $\delta y=0$, but in the $x$ direction one can substitute $v_z=-gt$ above,
\begin{eqnarray*}
v_x&\approx&\int_0^t dt'~2\omega gt'\sin\theta=\omega gt^2\sin\theta,\\
\delta x&\approx& \int_0^t dt'~v_x(t')=\frac{g\omega\sin\theta t^3}{3}.
\end{eqnarray*}
One can find the deflections by using $h=\frac{1}{2}gt^2$, to find the time, and using the all-knowing internet to see that the latitude of Minneapolis is $44.6^\circ$ or $\theta=45.4^\circ$.
\begin{eqnarray*}
t&=&\sqrt{2h/g}=10.1~{\rm s},\\
\omega&=&\frac{2\pi}{3600\cdot 24~{\rm s}}=7.27\times 10^{-5}~{\rm s}^{-1},\\
\delta x&=&17.4~{\rm cm}~~{\rm(east)}.
\end{eqnarray*}

\exampleend

\subsection{The Foucault Pendulum}
The Foucault Pendulum is simply a regular pendulum moving in both horizontal directions, and with the Coriolis force included. In this case,
\begin{eqnarray*}
m\ddot{\vec{r}}&=&\vec{T}+m\vec{g}-2m\vec{\Omega}\times\vec{v},
\end{eqnarray*}
as the centrifugal force term is absorbed into the definition of $\vec{g}$. The magnitude of the tension, $\vec{T}$, is considered constant because we consider only small oscillations. Then $T\approx mg$, and the components, using $\hat{x},\hat{y}$ to correspond to east and north respectively, are
\begin{eqnarray*}
T_x=-mgx/L,~~~T_y=-mgy/L.
\end{eqnarray*}
If $\Omega$ is the rotation of the earth, and if $\theta$ is the polar angle, $\pi-$lattitude,
\begin{eqnarray*}
\ddot{x}&=&-gx/L+2\dot{y}\Omega_z,\\
\ddot{y}&=&-gy/L-2\dot{x}\Omega_z.
\end{eqnarray*}
Here we have used the fact that the oscillations are sufficiently small so we can ignore $v_z$. Using $\omega_0\equiv\sqrt{k/m}$,
\begin{eqnarray*}
\ddot{x}-2\Omega_z\dot{y}+\omega_0^2x&=&0\\
\ddot{y}+2\Omega_z\dot{x}+\omega_0^2y&=&0,
\end{eqnarray*}
where $\Omega_z=|\vec{\Omega}|\cos\theta$, with $\theta$ being the polar angle (zero at the north pole). The terms linear in time derivatives are what make life difficult. This will be solved with a trick. We will incorporate both differential equations into a single complex equation where the first/second are the real/imaginary parts.
\begin{eqnarray*}
\eta\equiv x+iy,\\
\ddot{\eta}+2i\Omega_z\dot{\eta}+\omega_0^2\eta&=&0.
\end{eqnarray*}

Now, we guess at a form for the solutions, $\eta(t)=e^{-i\alpha t}$, which turns the differential equation into
\begin{eqnarray*}
-\alpha^2+2\Omega_z\alpha+\omega_0^2&=&0,\\
\alpha&=&\Omega_z\pm \sqrt{\Omega_z^2+\omega_0^2},\\
&\approx&\Omega_z\pm \omega_0.
\end{eqnarray*}
The solution with two arbitrary constants is then
\begin{eqnarray*}
\eta&=&e^{-i\Omega_zt}\left[C_1e^{i\omega_0t}+C_2e^{-i\omega_0t}\right].
\end{eqnarray*}
Here, $C_1$ and $C_2$ are complex, so they actually represent four arbitrary numbers. These four numbers should be fixed by the four initial conditions, i.e. $x(t=0), \dot{x}(t=0), y(t=0)$ and $\dot{y}(t=0)$. With some lengthy algebra, one can rewrite the expression as
\begin{eqnarray*}
\label{eq:precmess}
\eta&=&e^{-i\Omega_zt}\left[A\cos(\omega_0t+\phi_A)+iB\cos(\omega_0t+\phi_B)\right].
\end{eqnarray*}
Here, the four coefficients are represented by the two real arbitrary real amplitudes, $A$ and $B$, and two arbitrary phases, $\phi_A$ and $\phi_B$. For an initial condition where $y=0$ at $t=0$, one can see that $B=0$. This then gives
\begin{eqnarray*}
\eta(t)&=&Ae^{-i\Omega_zt}\cos(\omega_0t+\gamma)\\
\nonumber
&=&A\cos\Omega_zt\cos(\omega_0t+\gamma)+iA\sin\Omega_zt\cos(\omega_0t+\gamma).
\end{eqnarray*}
Translating into $x$ and $y$,
\begin{eqnarray}
x&=&A\cos\Omega_zt\cos(\omega_0t+\gamma),\\
\nonumber
y&=&A\sin\Omega_zt\cos(\omega_0t+\gamma).
\end{eqnarray}
Assuming the pendulum's frequency is much higher than Earth's rotational frequency, $\omega_0>>\Omega_z$, one can see that the plane of the pendulum simply precesses with angular velocity $\Omega_z$. This means that in this limit the pendulum oscillates only in the $x$-direction with frequency many times before the phase $\Omega_zt$ becomes noticeable. Eventually, when $\Omega_zt=\pi/2$, the motion is along the $y$-direction. If you were at the north pole, the motion would switch from the $x$-direction to the $y$ direction every 6 hours. Away from the north pole, $\Omega_z\ne|\vec{\Omega}|$ and the precession frequency is less.  At the equator it does not precess at all. If one were to repeat for the solutions where $A=0$ and $B\ne 0$ in Eq. (\ref{eq:precmess}), one would look at motions that started in the $y$-direction, then precessed toward the $-x$ direction. Linear combinations of the two sets of solutions give pendulum motions that resemble ellipses rather than simple back-and-forth motion.

\subsection{Exercises}

\begin{enumerate}

\item Consider a pail of water spinning about a vertical axis at the center of the pail with frequency $\omega$. Find the height of the water (within a constant) as a function the radius $r_\perp$ from the axis of rotation. Use the concept of a centrifugal potential in the rotating frame.

\item A high-speed cannon shoots a projectile with an initial velocity
  of 1000 m/s in the east direction. The cannon is situated in
  Minneapolis (latitude of 45 degrees) The projectile velocity is
  nearly horizontal and it hits the ground after a distance $x=3000$
  m. Find the alteration of the point of impact in the north-south
  ($y$) direction due to the Coriolis force. Assume the effect is
  small so that you can approximate the eastward ($x$) component of
  the velocity as being constant. Be sure to indicate whether the
  deflection is north or south.

\item Someone wishes to use a Foucault pendulum as a crude clock. If the person lives in Minneapolis (latitude of $45^\circ$), how much time will pass between having the pendulum swinging in the east-west direction until it swings in the north-south direction.

\end{enumerate}
%\end{document}


\documentclass{article}

\usepackage{mathrsfs,amssymb,amsmath}

\begin{document}

\section{Why does Theorem VIII.1.14 not contradict Example VII.5.1}

Take $\mathbb{T}$ as the unit circle in the complex plane, and take $\mathscr{A} = C(\mathbb{T})$ and $\mathscr{B}\subset \mathscr{A}$ the closure in $\mathscr{A}$ of polynomials in $z$. $\sigma_{\mathscr{A}}(z)=\mathbb{T}$ and $\sigma_{\mathscr{B}}(z)= cl \mathbb{T} =$ unit disk.

This appears to contradict VIII.1.14 since $\mathbb{B}$ is a subset of $\mathscr{A}$ with a common identity (namely the function that maps $\mathbb{T}$ to 1) and common norm (namely the sup norm), yet the spectra of a shared point (in this case z) differ.

However, the premise of VIII.1.14  requires both $\mathscr{A}$ and $\mathscr{B}$ to be C* algebras, and while $\mathscr{A}$ is closed under taking the adjoint, $\mathscr{B}$ is not.

Take z*, which as a function equals $z^{-1}/||z||$. The problem thus reduces to on what subset of the complex plane the function $1/z$ is holomorphic.

Here my complex analysis is too weak, but certainly the whole unit disk would be no good since it contains a pole. I believe the circle is also out because of some fact about winding numbers that I can't remember.

\end{document}