 \documentclass [12pt]{article}

\usepackage {amsmath}
\usepackage {amsthm}
\usepackage {amssymb}
\usepackage {graphicx}
\usepackage {float}
\usepackage {multirow}
\usepackage {xcolor}
\usepackage {algorithmic}
\usepackage [ruled,vlined,commentsnumbered,titlenotnumbered]{algorithm2e} \usepackage {array}
\usepackage {booktabs}
\usepackage {url}
\usepackage {parskip}
\usepackage [margin=1in]{geometry}
\usepackage [T1]{fontenc}
\usepackage {cmbright}
\usepackage [many]{tcolorbox}
\usepackage [colorlinks = true,
            linkcolor = blue,
            urlcolor  = blue,
            citecolor = blue,
            anchorcolor = blue]{hyperref}
\usepackage {enumitem}
\usepackage {xparse}
\usepackage {verbatim}
\usepackage{listings}
\usepackage{xcolor}
\lstset { %
    language=C++,
    backgroundcolor=\color{black!5}, % set backgroundcolor
    basicstyle=\footnotesize,% basic font setting
}
\newtheorem{theorem}{Theorem}
\newtheorem{remark}{Remark}

\DeclareTColorBox {Solution}{}{breakable, title={Solution}} \DeclareTColorBox {Solution*}{}{breakable, title={Solution (provided)}} \DeclareTColorBox {Instruction}{}{boxrule=0pt, boxsep=0pt, left=0.5em, right=0.5em, top=0.5em, bottom=0.5em, arc=0pt, toprule=1pt, bottomrule=1pt} \DeclareDocumentCommand {\Expecting }{+m}{\textbf {[We are expecting:} #1\textbf {]}} \DeclareDocumentCommand {\Points }{m}{\textbf {(#1 pt.)}}

\begin {document}

\vspace {1em}
\begin {Instruction}
Adapted From Virginia Williams' lecture notes.
\end {Instruction}

{\LARGE \textbf {COMP 285 (NC A\&T, Spr `22)}\hfill \textbf {Lecture 14} }

\begin{centering}
\section*{Universal Hash Families}
\end{centering}

\section{Hashing with a completely random hash function}

What does it mean for $h$ to be random? One possibility is that $h$ is chosen uniformly and at random from amongst the set of all hash functions $h : U \rightarrow \{1, 2, \cdots , n\}$. In fact picking such a hash function is not really practical. Note that there are $n^{|U|}$ possible hash functions. Representing just one of these hash functions requires $\log ( n^{|U|} ) = |U|\log n$ bits. In fact, this means we need to write down $h(x)$ for every $x \in U$ in order to represent $h$. That's a lot of storage space! Much more than the size of the set we are trying to store in the hash table. One could optimize this somewhat by only recording $h(x)$ for all keys $x$ seen so far (and generating $h(x)$ randomly on the fly when a new $x$ is encountered), but this is impractical too. How would we check if a particular key $x$ has already been encountered? Looks like we would need a hash table for that. But wait, isn't that what we set out to implement? Overall, it is clear that picking a completely random hash function is completely impractical.

Despite this, we will analyze hashing assuming that we have a completely random hash function and then explain how this assumption can be replaced by something that is practical.

\textbf{Expected cost of hash table operations with random hash functions}

What is the expected cost of performing any of the operations Insert, Lookup, or Delete with a random hash function? Suppose that the keys currently in the hash table are $x_1, \cdots, x_n$. Consider an operation involving key $x_i$ . The cost of the operation is linear in the size of the hash bucket that $x_i$ maps to. Let $X$ be the size of the hash bucket that $x_i$ maps to. $X$ is a random variable and

\begin{align*}
  \mathbb{E}[X] &= \sum_{j=1}^n \mathbb{P}[h(x_i) = h(x_j)] \\
  &= 1 + \sum_{j\neq i} \mathbb{P}[h(x_i) = h(x_j)] \tag{We are guaranteed to collide with ourselves} \\
  &= 1 + \frac{n-1}{n} \leq 2
\end{align*}
Here the last step follows from the fact that $\mathbb{P}[h(x_i ) = h(x_j )] = 1/n$ when $h$ is random. Note that each key appears in the hash table at most once.

Thus the expected cost of any hashing operation is a constant.

\subsection{Universal Hash Functions \& Intro to Graphs}
Can we retain the expected cost guarantee of the previous section with a much simpler (i.e.,practical) family of hash functions? In the analysis of the previous section, the only fact we used about random hash functions was that $\mathbb{P}[h(x_i ) = h(x_j )] = 1/n$. Is it possible toconstruct a small, practical subset of hash functions with this property?

Thinking along these lines, in 1978, Carter and Wegman introduced the notion of universal hashing: Consider a family $F$ of hash functions from $U to \{1, 2, \cdots , n\}$. We say that $F$ isuniversal if, for every $x_i \neq x_j$, for an $h$ chosen randomly from $F$ , $\mathbb{P}[h(xi ) = h(xj )] \leq 1/n$.

Clearly the analysis of the previous section shows that for any universal family, the constant expected running time guarantee applies. The family of all hash functions is universal. Is there a simpler universal family?

\section{A universal family of hash functions}
Suppose that the elements of the $U$ are encoded as non-negative integers in the range ${0, \cdots, |U| - 1}$. Pick a prime $p \geq |U|$. For $a, b \in \{0, \cdots p - 1\}$, consider the family of hash functions

$$
h_{a,b}(x) = (ax + b \mod p) \mod n
$$

where $a \in \{1, \cdots , p - 1\}$ and $b \in {0, 1, \cdots , p - 1}$.

\textbf{Proposition 1}. \textit{This family of hash functions $F$ is universal}.

In order to prove this statement, first, let’s count the number of hash functions in this family $F$ . We have $p-1$ choices for $a$, and $p$ choices for $b$, so $|F| = p(p-1)$. In order to prove that $F$ is universal, we need to show that for an $h$ chosen randomly from $F$ , $\mathbb{P}[h(x_i ) = h(x_j )] \leq 1/n$. Since there are $p(p - 1)$ hash functions in $F$ , this is equivalent to showing that the number of hash functions in $F$ that map $x_i$ and $x_j$ to the same output is less than or equal to $\frac{p(p-1)}{n}$ . To show that this is true, first consider how $h_{a,b}$ behaves without the $\mod n$. Call these functions $f_{a,b}$:
$$
f_{a,b}(x) = ax + b \mod p
$$
The $f_{a,b}$ have the following useful property:

\textbf{Proposition 2.} \textit{For a given $x_1, x_2, y_1, y_2 \in \{0, \cdots , p - 1\}$ such that $x_1 \neq x_2$ there exists only one function $f_{a,b}$ such that $f_{a,b}(x_1) = y_1$, and $f_{a,b}(x_2) = y_2$}

 Proof. Solve the above two equations for $a$ and $b$:

 \begin{align*}
  ax_1 + b &\equiv y_1 (\mod p) \\
  ax_2 + b &\equiv y_2 (\mod p)
\end{align*}
By subtracting the two equations, we get:
$$
a(x_1 - x_2) \equiv y_1 - y_2 (\mod 6)
$$
Since $p$ is prime and $x1 \neq x2$, the above equation has only one solution for $a \in \{0, \cdots , p -1\}$.
Then
$$
b \equiv y_1 - ax_1 (\mod p)
$$
So we have found the unique a and b such that $f_{a,b}(x_1) = y_1$ and $f_{a,b}(x_2) = y_2.$

In the above proof, note that $a = 0$ only when $y_1 = y_2 = b$. This is why we restrict $a \neq 0$, we don’t want the hash function mapping all elements to the same value $b$. Now, we have shown that for a given $x_1, x_2$, for each selection of $y_1, y_2$ with $y_1 \neq y_2$, there is exactly one function $f_{a,b}$ that maps $x_1$ to $y_1$ and $x_2$ to $y_2$. So, in order to find out how many functions $h_{a,b}$ map $x_1$ and $x_2$ to the same value $\mod n$, we just need to count the number of pairs $(y_1, y_2)$ where $y_1 \neq y_2$ and $y_1 \equiv y_2 (mod n)$. There are $p$ possible selections of $y_1$ for this pair, and then $\leq (p - 1)/n$ of the possibilities for $y_2$ will be equal to $y_1 \mod n$. (Convince yourself that this is true.) This gives a total of $\frac{p(p-1)}{n}$ functions $h_{a,b}$ that map $x_1$ and $x_2$ tothe same element. So then

\begin{align*}
\mathbb{P}[h_{a,b}(x_1) &\leq h_{a,b}(x_2)] \\
&\leq \frac{p(p-1)/n}{|F|} \\
&= \frac{p(p-1)}{p(p-1)(n)} \\
&= \frac{1}{n}
\end{align*}

which means the family $F$ of the $h_{a,b}$ is universal, as desired.

Wrapping up the discussion on hashing, if we pick a random hash function from this family, then the expected cost of any hashing operation is constant. Note that picking a random hash function from the family simply involves picking $a, b$ – significantly simpler than picking a completely random hash function.

\section{Balls and Bins}

A useful abstraction in thinking about hashing with random hash functions is the following experiment: Throw $m$ balls randomly into $n$ bins. (The connection to hashing should be clear: the balls represent the keys and the bins represent the hash buckets.) The balls into bins experiment arises in several other problems as well, e.g., analysis of load balancing. In the context of hashing, the following questions arise about the balls and bins experiment:

\begin{itemize}
  \item How large does $m$ have to be so that with probability greater than $1/2$, we have (at least) two balls in the same bin? This tells us how large our hash table needs to be to avoid any collisions. We will explore this at the end of these notes.
  \item Suppose $m = n$; what is the maximum number of balls that fall into a bin? This tells us the size of the largest bucket in the hash table when the number of keys is equal to the number of buckets in the table. We might explore this in the next homework.
\end{itemize}

\textbf{No Collisions}

The first question is related to the so called birthday paradox: Suppose you have $23$ people in a room. Then (somewhat surprisingly) the probability that there exists some pair with the same birthday is greater than $1/2$! (This assumes that birthdays are independent and randomly distributed.) $23$ seems like an awfully small number to get a pair with the same birthday. There are $365$ days in a year! How do we explain this? Consider throwing $m$ balls into $n$ bins. The expected number of pairs that fall into the same bucket is $m(m - 1)/2n$. (This follows from linearity of expectation. Note that the probability that a fixed pair falls into the same bucket is $1/n$.) Thus the probability that there is a collision is upper bounded by the expected number of collisions which is $m(m - 1)/2n$. (Convince yourself that this is true.) On the other hand, we can also show that the probability that all $m$ balls fall into distinct bins is at most $e^{-m(m-1)/2n}$:

\textit{Proof}
$$
\mathbb{P}[\text{no collisions}] = \prod_{i=1}^{m-1}\left( 1 - \frac{i}{n}\right)
$$
Now we use the fact that $(1-x) \leq e^{-x}$:
$$
\left(1 - \frac{i}{n}\right) \leq e^{-i/n}
$$
So
\begin{align*}
  \mathbb{P}[\text{no collision}] &\leq \prod_{i=1}^{m-1} e^{i/n} \\
  \mathbb{P}[\text{no collision}] &\leq e^{\sum_{i=1}^{m-1} -i/n} \\
  \mathbb{P}[\text{no collision}] &\leq e^{-m(m-1)/(2n)} \\
\end{align*}

For $m$ about $\sqrt{(2 n \ln 2)n} \approx 1.18\sqrt{n}$ this probability is less than $1/2$, i.e., the probability of a collision is greater than $1/2$.

This is a useful design principle to keep in mind: If we want to design a hash table with no collisions, then the size of the hash table should be larger than the square of the number of elements we need to store in it. For our purposes in this note, insisting on no collisions means that the number of elements in the hash table can only be a small fraction of the hash tablesize which is quite wasteful.

The birthday problem calculation is useful in other contexts. Here is an application: Suppose we assign random $b$-bit IDs to $m$ users. How large does $b$ have to be to ensure that all users have distinct IDs with probability $1 - \delta$. Here $\delta > 0$ is a given error tolerance. Assigning $b$-bit IDs is identical to mapping to $n = 2^b$ buckets. The birthday problem calculation shows us that the probability of a collision is at most $m^2/2n = m^2/2^{b+1}$. We should set $b$ large enough such that this bound is at most $\delta$. Thus $b$ should be at least $2 \log m - 1 + log(1/\delta)$.

\section{Intro to Graphs}
A graph is a set of vertices and edges connecting those vertices. Formally, we define a graph $G$ as $G = (V, E)$ where $E \subseteq V \times V$ . For ease of analysis, the variables $n$ and $m$ typically stand for the number of vertices and edges, respectively. Graphs can come in two flavors, directed or undirected. If a graph is undirected, it must satisfy the property that $(i, j) \in E \iff (j, i) \in E$ (i.e., all edges are bidirectional). In undirected graphs, $m \leq \frac{n(n-1)}{2}$ . In directed graphs, $m \leq n(n - 1)$. Thus, $m = O(n^2)$ and $\log m = O(\log n)$. A connected graph is a graph in which for any two nodes $u$ and $v$ there exists a path from $u$ to $v$ . For an undirected connected graph $m \geq n - 1$. A sparse graph is a graph with few edges (for example, $\Theta(n)$ edges) while a dense graph is a graph with many edges (for example, $m = \Theta(n^2)$).

\end{document}


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}

\title{Vibing Math (Geometry Problem)}
\author{Shreenabh Agrawal }
\date{\today}
\usepackage{amsmath}
\usepackage{geometry}
\geometry{a4paper, portrait, margin=1in}
\usepackage{natbib}
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage[makeroom]{cancel}

\begin{document}

\maketitle

\section{Question}
Consider an isosceles triangle $ABC$ in which $AB = BC = 10$ units. Let $P_1, P_2, P_3, ... P_{60}$ be $60$ points on $BC$. Then, $$\sum_{i=1}^{60} (AP_i^2 + P_iB\times P_iC) = ?$$

\section{Solution}
By Stewart's Theorem,
$$(AB^2\times P_iC) + (AC^2\times P_iB) = BC ( AP_i^2 + P_iB\times P_iC)$$
Now, $AB = 10$ and $AC = 10$ ,so above expression becomes,
$$100 (P_iB + P_iC) = BC (AP_i^2 + P_iB\times P_iC )$$
But here, $P_iB + P_iC = BC$, hence the above equation becomes
$$100 \cancel{(P_iB + P_iC)} = \cancel{BC} (AP_i^2 + P_iB\times P_iC )$$
$$100 = (AP_i^2 + P_iB \times P_iC)$$
This is true for all $i$ in $P_i$. Hence, the answer is
$$\sum_{i=1}^{60} (AP_i^2 + P_iB\times P_iC) = 60 \times 100$$
$$\boxed{= 6,000}$$
\end{document}

Tig. and Geometry/vibing_math's questions/Sigma Geometry Stewart Triangle Problem.tex


\documentclass[modern]{aastex63}

\usepackage{acro}
\usepackage{amsmath}
\usepackage{amssymb}

\DeclareMathOperator{\var}{var}

\newcommand{\dd}{\mathrm{d}}
\newcommand{\diff}[2]{\frac{\dd #1}{\dd #2}}

\DeclareAcronym{PSD}{
  short = {PSD},
  long = {power spectral density}
}
\DeclareAcronym{SNR}{
  short = {SNR},
  long = {signal to noise ratio}
}

\begin{document}

\title{Optimal Detection of Stochastic Signals}
\author[0000-0003-1540-8562]{Will M. Farr}
\email{wfarr@flatironinstitute.org}
\affiliation{Center for Computational Astronomy, Flatiron Institute, New York NY 10010, United States}
\affiliation{Department of Physics and Astronomy, Stony Brook University, Stony Brook NY 11794, United States}

\begin{abstract}
%
  I derive an optimal statistic for detection of a common stochastic signal in
  independent data streams.  I compute the SNR in terms of the \ac{PSD} of the
  common signal and each stream's noise, and give several useful limits.
%
\end{abstract}

\section{Formalities}

Imagine we have a stochastic stationary zero-mean Gaussian signal, $h(t)$, whose
\ac{PSD} is $P_h(f)$:
%
\begin{equation}
P_h(f) = \lim_{T \to \infty} \frac{1}{T} \left| \int_{-T}^{T} \dd t \, e^{-2\pi f t} h(t) \right|^2.
\end{equation}
%
The signal is linearly projected into two data streams\footnote{The formalism
here generalizes easily to an arbitrary number of data streams.} with
independent stochastic stationary zero-mean Gaussian noise:
%
\begin{equation}
  s_1(t) = A_1 h(t) + n_1(t)
\end{equation}
%
and
%
\begin{equation}
  s_2(t) = A_2 h(t) + n_2(t),
\end{equation}
%
where the \ac{PSD} of each stream's noise is
%
\begin{equation}
  P_i(f) = \lim_{T \to \infty} \frac{1}{T} \left| \int_{-T}^{T} \dd t \, e^{-2\pi f t} n_i(t) \right|^2,
\end{equation}
%
and the signal and both noise streams are independent:
%
\begin{equation}
  p\left( h, n_1, n_2 \right) = p\left( h \right) p\left( n_1 \right) p\left( n_2 \right).
\end{equation}

Stationarity implies that the Fourier components are independent; Gaussianity
and the \acp{PSD} imply that
%
\begin{equation}
  \tilde{h}(f) \sim N\left[0, \sqrt{T P_h(f)} \right]
\end{equation}
%
and
%
\begin{equation}
  \tilde{s}_i(f) \sim N\left[ A_i \tilde{h}(f), \sqrt{T P_i(f)} \right],
\end{equation}
%
where $N[\mu, \sigma]$ is a Gaussian distribution with mean $\mu$ and standard
deviation $\sigma$.  Integrating out the (unknown) signal $h$\footnote{See
\citet{Cornish2013}.}, we have the marginal likelihood for the data streams
%
\begin{multline}
  \mathcal{L} \left( s_1(f), s_2(f) \mid P_h(f) \right) = \int \dd h(f) \, N\left[ A_1 \tilde{h}(f), \sqrt{T P_1(f)} \right]\left( s_1(f) \right) \\ \times N\left[ A_2 \tilde{h}(f), \sqrt{T P_2(f)} \right]\left( s_2(f) \right) N\left[0, \sqrt{T P_h(f)} \right]\left( h(f) \right).
\end{multline}
A bit of algebra reveals
%
\begin{multline}
  \mathcal{L} \left( s_1, s_2 \mid P_h \right) = \\ \frac{1}{2\pi \sqrt{S_h \left( A_2^2 S_1 + A_1^2 S_2 \right) + S_1 S_2}} \exp\left[ - \frac{\left(A_2 s_1 - A_1 s_2\right)^2 S_h + s_2^2 S_1 + s_1^2 S_2}{2 \left(\left(A_2^2 S_1 + A_1^2 S_2 \right)S_h + S_1 S_2 \right)}\right],
\end{multline}
%
where we have suppressed the dependence on $f$ for the moment, and absorbed the
$T$-dependence into $S$ via
%
\begin{equation}
  S_x \equiv T P_x
\end{equation}
%
(i.e.\ $S_x$ is the variance of $\tilde{x}$).

The maximum-likelihood estimator of $P_h$ is
%
\begin{equation}
  \label{eq:ml-est}
 \hat{P}_h \equiv \frac{1}{T} \frac{\left( A_2 S_1 s_2 + A_1 S_2 s_1 \right)^2 - S_1 S_2 \left( A_2^2 S_1 + A_1^2 S_2 \right)}{\left( A_2^2 S_1 + A_1^2 S_2 \right)^2}.
\end{equation}
%
The expected value of $\hat{P}_h$ is
%
\begin{equation}
  \left\langle \hat{P}_h \right\rangle = P_h
\end{equation}
%
(i.e.\ $\hat{P}$ is an un-biased estimator of $P_h$---whatever that is worth)
and the variance is
%
\begin{equation}
  \label{eq:est-variance}
  \var \hat{P}_h = \frac{2 \left( S_h \left(A_2^2 S_1 + A_1^2 S_2 \right) + S_1 S_2 \right)^2}{T^2 \left( A_2^2 S_1 + A_1^2 S_2 \right)^2} = \frac{2 \left( P_h \left(A_2^2 P_1 + A_1^2 P_2 \right) + P_1 P_2 \right)^2}{\left( A_2^2 P_1 + A_1^2 P_2 \right)^2}
\end{equation}
%
Note that the variance in Eq.\ \eqref{eq:est-variance} is independent of $T$, so
that the \ac{SNR} \emph{in a single frequency bin} is independent of time.

Typically we will be estimating the power in some range of frequencies, not just
in a single bin.  Because the different frequencies are independent
(stationarity), the optimal estimator for the integral of $P_h(f)$ over some
range is given by
%
\begin{equation}
  \int_{f_0}^{f_1} \dd f \, \hat{P}_h(f) \simeq \sum_{f = f_0}^{f_1} \Delta f \hat{P}_h(f),
\end{equation}
%
where $\Delta f = 1/T$ is the frequency resolution implied by an observation
over a time $T$.   The mean of this estimator is the integral of $P_h$ over the
corresponding interval; the variance of this estimator is given by
%
\begin{equation}
  \sum_{f = f_0}^{f_1} \Delta f^2 \var \hat{P}_h(f),
\end{equation}
%
and therefore the \ac{SNR} of such a measurement is given by
%
\begin{equation}
  \label{eq:finite-bandwidth-snr}
  \rho = \frac{\sqrt{T} \int_{f_0}^{f_1} \dd f \, P_h\left( f \right)}{\sqrt{\int_{f_0}^{f_1} \dd f \, \var \hat{P}_h(f)}}
\end{equation}
%
with $\var \hat{P}_h$ given by Eq.\ \eqref{eq:est-variance}.  We see that the
\ac{SNR} for a measurement over some finite bandwidth grows with $\sqrt{T}$, as
it should.

\section{Useful Limits}

\subsection{Signal-Dominated Limit}

If $A^2_{1,2} P_h \gg P_{1,2}$ over the relevant range of frequencies, we have
%
\begin{equation}
  \var \hat{P}_h \simeq 2 P_h^2,
\end{equation}
%
and the per-bin \ac{SNR} asymptotes to $1/2$.  The finite-bandwidth \ac{SNR},
Eq.\ \eqref{eq:finite-bandwidth-snr}, becomes
%
\begin{equation}
  \rho \simeq \sqrt{\frac{T \left( f_1 - f_0 \right)}{2}} \frac{\left\langle P_h \right\rangle}{\sqrt{\left\langle P_h^2 \right\rangle}}
\end{equation}
%
where angle brackets indicate an average over frequencies $f_0 \leq f \leq f_1$.
Note that in this limit the \ac{SNR} is independent of the amplitude of $P_h$.

\subsection{Noise-Dominated Limit}

In the opposite limit, $A_{1,2} P_h \ll P_{1,2}$, we have
%
\begin{equation}
  \var \hat{P}_h \simeq \frac{2 P_1^2 P_2^2}{\left( A_2^2 P_1 + A_1^2 P_2\right)^2} = \frac{2}{\left( A_1^2 / P_1 + A_2^2/P_2 \right)^2},
\end{equation}
%
and the finite-bandwidth \ac{SNR} becomes
%
\begin{equation}
  \rho \simeq \sqrt{\frac{T\left(f_1 - f_0 \right)}{2}} \frac{\left\langle P_h \right\rangle}{ \sqrt{\left\langle \frac{1}{\left( A_1^2 / P_1 + A_2^2/P_2 \right)^2}\right\rangle}}
\end{equation}
%
and the \ac{SNR} is reduced compared to the signal-dominated case by a factor
%
\begin{equation}
  \label{eq:approx-snr-reduction}
  \alpha \sim \frac{A_1^2 P_h}{P_1} + \frac{A_2^2 P_h}{P_2}.
\end{equation}
%

\bibliography{StochasticStats}

\end{document}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UMB-CS240-2016S: Programming in C
% Copyright 2016 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/UMB-CS240-2016S
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section*{Question 3}

The C programming language, as of C99, supports complex number math with the three built-in types \texttt{double \_Complex}, \texttt{float \_Complex}, and \texttt{long double \_Complex}.
When the header \texttt{<complex.h>} is included, the three complex number types are also accessible as \texttt{double complex}, \texttt{float complex}, \texttt{long double complex}.
Standard arithmetic operators \texttt{+}, \texttt{-}, \texttt{*}, \texttt{/} can be used with real, complex, and imaginary types in any combination.

The following program shows how complex numbers can be used in C. It loads components of complex numbers from a file and prints their sum on standard output.

\lstset{language=c,tabsize=4}
\lstinputlisting[firstline=10]{\resDirectory/complex-numbers.h}
\lstinputlisting[firstline=10]{\resDirectory/complex-numbers.c}

The program compiles and executes as expected.
Based on the given source code, provide \textbf{brief} answers for the following questions.

\begin{enumerate}
\item
In \texttt{complex-numbers.h:10}, function \texttt{cprint} is declared but not defined.
What is the advantage of declaring a function in a header file?
Explain why removing this line causes a compilation error and how the error can be resolved without including this line.

\item
In \texttt{complex-numbers.c:13}, \texttt{fp} is checked to make sure it is not \texttt{null}.
A CS240 student argues this checking is unnecessary if we make sure the file \texttt{complex-numbers.txt} exists.
Describe whether you support this argument or not and provide brief explanations for your reasoning.

\item
In \texttt{complex-numbers.c:17}, variables \texttt{a} and \texttt{b} are passed by reference to function \texttt{scanf}.
Explain what happens if they are passed by value.

\item
In \texttt{complex-numbers.c:18}, \texttt{I} is used but it is not explicitly declared either in \texttt{complex-numbers.c} or \texttt{complex-numbers.h}.
This also applies to functions \texttt{creal} and \texttt{cimag} in \texttt{complex-numbers.c:31}.
Briefly explain why such practice has not caused compilation error.

\item
In \texttt{complex-numbers.c:21}, variable \texttt{sum} is passed to \texttt{cprint} by value. Modify this line and the function \texttt{cprint} such that \texttt{num} is passed by reference.

\end{enumerate}


\subsection{Undamped Forced Vibrations ($b = 0$)}
\noindent
Our equation now becomes
\begin{equation*}
	my'' + ky = F_0\cos{(\gamma t)}
\end{equation*}
We can use the method of undetermined coefficients to solve this system.\\

\noindent
Extracting the coefficients for the auxiliary equation and finding the roots,
\begin{equation*}
	mr^2 + k = 0 \implies r = \pm i\sqrt{\frac{k}{m}} = i\omega
\end{equation*}
So, our homogeneous solution is
\begin{equation*}
	y_h = C_1\cos{(\omega t)} + C_2\sin{(\omega t)}
\end{equation*}

\noindent
For guessing the form of $y_p$, we'll need to break into two cases depending on if $\omega = \gamma$. One case will give rise to beats and the other resonance.

\input{./higherOrder/forcedVibrs/beats.tex}
\input{./higherOrder/forcedVibrs/resonance.tex}


\chapter{Nonlinear resonances} \label{app-A}

The study of nonlinear resonances is important in many areas of physics \cite{Reichl1992}. A derivation of the nonlinear resonance condition in Eq.~\ref{eq:resonance_lines} (in one dimension) is included in this appendix. The derivation follows \cite{LundLecture1} closely.

We return to one-dimensional motion and write
%
\begin{equation}\label{eq:Hill_nonlinear}
    x'' + k(s) x = \Delta B,
\end{equation}
%
where $\Delta B$ represents all the nonlinear terms in the magnetic field expansion (and also linear deviations from the design fields). The stable solution $x_0$ when $\Delta B = 0$ is given by Eq.~\eqref{eq:Hill_solution}. We now define
%
\begin{equation}
    \phi(s) = \frac{1}{\nu} \oint{\frac{ds}{\beta(s)}},
\end{equation}
%
where $\nu$ is the tune. Moving to the normalized coordinate $u = x / \sqrt{\beta}$, with $\dot{u} = du/d\phi$ we have
%
\begin{equation}\label{eq:pert1}
    \ddot{u} + \nu^2 u = -\nu^2 \sum_{n=0}^{\infty}{\left(\beta^{\frac{n+3}{2}} b_{n+1}\right) u^n}.
\end{equation}
%
$\beta$ (the oscillation amplitude of the unperturbed motion) and $b_n$ (a multipole coefficient) are periodic in $\phi$ since they depend only on the position in the ring. Grouping these terms and Fourier expanding gives
%
\begin{equation}
    \ddot{u} + \nu^2 u = -\nu^2 \sum_{n=0}^{\infty}\sum_{k=-\infty}^{\infty} C_{n,k} \, u^n \, e^{ik\phi}.
\end{equation}
%
We then perturb around $u_0$, the solution to the homogeneous equation, writing $u = u_0 + \delta u$, and keep only linear powers of $\delta u$.
%
\begin{equation}
    \ddot{\delta u} + \nu^2 \delta u \approx -\nu^2 \sum_{n=0}^{\infty}\sum_{k=-\infty}^{\infty} C_{n,k} \, u_0^n \, e^{ik\phi}.
\end{equation}
%
Noting that
%
\begin{equation}
    u_0^n \propto \cos^n(\nu\phi) = \frac{1}{2^n}\sum_{m=0}^{n} \binom{n}{m} e^{i(n-2m)\nu\phi},
\end{equation}
%
leads to
%
\begin{equation}\label{eq:pert2}
    \ddot{\delta u} + \nu^2 \delta u \approx -\nu^2 \sum_{n=0}^{\infty}\sum_{k=-\infty}^{\infty} \sum_{m=0}^{n} {n \choose m} \frac{C_{n,k}}{2^n} e^{i\left[(n - 2m)\nu + k\right]\phi}.
\end{equation}
%
A resonance condition may occur when any of the frequency components of the driving terms are close to the tune $\nu$; i.e., when
%
\begin{equation}
    (n - 2m)\nu + k = \pm \nu.
\end{equation}
%
Dipole terms correspond to integer tunes, quadrupole terms to 1/2 integer tunes, sextupole terms to 1/3 integer tunes, and so on. The same is true in the vertical dimension. The inclusion of coupling between $x$ and $y$ leads to the following resonance conditions:
%
\begin{equation}\label{eq:resonance_lines1}
    M_x \nu_x + M_y \nu_y = N,
\end{equation}
%
where $M_x$, $M_y$, and $N$ are integers and $|M_x| + |M_y|$ is the order of the resonance. These resonance lines are plotted in Fig.~\ref{fig:resonance_lines}.
%
\begin{figure}[!p]
    \centering
    \includegraphics[width=\textwidth]{Images/chapter1/resonance_lines.png}
    \caption{Resonance lines in tune space defined by Eq.~\eqref{eq:resonance_lines1}.}
    \label{fig:resonance_lines}
\end{figure}
%
\begin{figure}[!p]
    \begin{subfigure}[b]{1.0\textwidth}
        \includegraphics[width=\textwidth]{Images/chapter1/sextupole.png}
        \label{fig:sextupole_a}
    \end{subfigure}
    \vfill
    \vspace*{1.0cm}
    \vfill
    \begin{subfigure}[b]{\textwidth}
        \centering
        \includegraphics[width=\textwidth]{Images/chapter1/sextupole_second_order.png}
        \label{fig:sextupole_b}
    \end{subfigure}
    \caption{Third-order (top) and fourth/fifth-order (bottom) resonances excited by a sextupole perturbation to a linear lattice. (Adapted from \cite{Lee2011}.)}
    \label{fig:sextupole}
\end{figure}
%

It is helpful to visualize the particle trajectory when a resonance line is encountered; therefore, a numerical experiment from \cite{Lee2011} is reproduced here. We consider a sextupole perturbation in an otherwise linear lattice, modeling the sextupole as a thin-lens kick. The turn-by-turn trajectories of particles with several different initial amplitudes are plotted in the top row of \ref{fig:sextupole} for different tunes $\nu_x$. The third-order resonance leads to a well-known triangular region of stability as the tune approaches 2/3. The bottom plot reveals fourth and fifth-order resonances only obtained from second-order perturbation analysis.


\documentclass[11pt]{article}

\usepackage{amsfonts}
\usepackage{fancyvrb}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{url}

\setlength{\oddsidemargin}{0in}
\setlength{\evensidemargin}{0in}
\setlength{\textwidth}{6.5in}
\setlength{\topmargin}{0in}
\setlength{\headsep}{0.5in}
\setlength{\textheight}{8.5in}
\setcounter{page}{1}
%\pagestyle{empty}
%\hbadness=10000

\begin{document}
\huge
\noindent
{Discrete Optimization Assignment:}
\vspace{0.25cm}

\noindent
{\bf Vehicle Routing}
\normalsize

\section{Problem Statement}

In this assignment you will design an algorithm to solve a problem faced by package delivery companies, {\em The Vehicle Routing Problem (VRP)}.  Every day, a delivery company needs to deliver goods to many different customers.  The deliveries are achieved by dispatching a fleet of vehicles from a centralized storage warehouse.  The goal of this problem is to design a route for each vehicle (similar to traveling salesman tours) so that all of the customers are served by exactly one vehicle and the travel distance of the vehicles is minimized.  Additional problem complexity comes from the fact that the vehicles have a fixed storage capacity and the customers have different demands.  Figure \ref{fig:vrp} illustrates a small VRP and a feasible solution to that problem.  The customers are labeled from $0$ to $4$, with $0$ being the warehouse.  The solution uses two vehicles which are indicated by different colored routes.

\begin{figure}[h]
        \centering
        \begin{subfigure}[b]{8.0cm}%{0.3\textwidth}
                \centering
                \includegraphics[width=6cm]{figures/vrp_1.pdf}
                \caption{The VRP input data.}
                \label{fig:vrp:input}
        \end{subfigure}%
        ~ %add desired spacing between images, e. g. ~, \quad, \qquad etc.
          %(or a blank line to force the subfigure onto a new line)
        \hfill
        \begin{subfigure}[b]{8.0cm}
                \centering
                \includegraphics[width=6cm]{figures/vrp_2.pdf}
                \caption{A solution to the VRP using 2 vehicles.}
                \label{fig:vrp:sol}
        \end{subfigure}
        \caption{A Vehicle Routing Example}\label{fig:vrp}
\end{figure}

\section{Assignment}

Write an algorithm to solve the vehicle routing problem.  The problem is mathematically formulated in the following way:  We are given a list of locations $N = 0 \ldots n-1$.  By convention, location 0 is the warehouse location, where all of the vehicles start and end their routes.  The remaining locations are customers.  Each location is characterized by three values  $\langle d_i,x_i,y_i \rangle \; i \in N$ a demand $d_i$ and a point $x_i,y_i$.  The fleet of vehicles $V = 0 \ldots v-1$ is fixed and each vehicle has a limited capacity $c$.  All of the demands assigned to a vehicle cannot exceed its capacity $c$.  For each vehicle $i \in V$, let $T_i$ be the sequence of customer deliveries made by that vehicle and let ${\it dist}(c_1,c_2)$ be the Euclidean distance between two customers.\footnote{${\it dist}(j,k) = \sqrt{(x_{j} - x_{k})^2 + (y_{j} - y_{k})^2}$}  Then the vehicle routing problem is formalized as the following optimization problem,
$$
\begin{array}{ll}
\mbox{minimize:} & \displaystyle \sum_{i \in V} \left( dist(0, T_{i,0}) + \sum_{\langle j,k \rangle \in T_{i}} dist(j, k) + dist(T_{i,|T_i|-1}, 0) \right)\\
\mbox{subject to:} & \\
     & \displaystyle \sum_{j \in T_{i}} d_j \leq c \;\;\; (i \in V) \\
     & \displaystyle \sum_{i \in V}  (j \in T_{i}) = 1 \;\;\; (j \in N \setminus 0)
\end{array}
$$
In this variant of the vehicle routing problem, we assume the vehicles can travel in straight lines between each pair of locations.

\section{Data Format Specification}

The input consists of $|N| + 1$ lines.  The first line contains 3 numbers: The number of customers $|N|$, the number of vehicles $|V|$, and the vehicle capacity $c$.
It is followed by $|N|$ lines, each line represents a location triple $\langle d_i,x_i, y_i \rangle$, with a demand $d_i \in \mathbb{N}$ and a point  $x_i, y_j \in \mathbb{R}$.

\vspace{0.2cm}
\noindent
Input Format
\vspace{-0.2cm}
\begin{Verbatim}[frame=single]
|N| |V| c
d_0 x_0 y_0
d_1 x_1 y_1
...
d_|N|-1 x_|N|-1 y_|N|-1
\end{Verbatim}
%
The output has $|V|+1$ lines.  The first line contains two values $obj$ and $opt$.  $obj$ is the length of all of the vehicle routes (i.e. the objective value) as a real number.  $opt$ should be $1$ if your algorithm proved optimality and $0$ otherwise.  The following $|V|$ lines represent the vehicle routes $T$ encoding the solution.  Each vehicle line starts with warehouse identifier $0$ followed by the identifiers of the customers serviced by that vehicle and ends with the warehouse identifier $0$.  Each vehicle line can contain between $2$ and $|N|+2$ values depending on how many customers that vehicle services.  Each customer identifier must appear in one of these vehicle lines.

\vspace{0.2cm}
\noindent
Output Format
\vspace{-0.2cm}
\begin{Verbatim}[frame=single]
obj opt
0 t_0_1 t_0_2 ... 0
0 t_1_1 t_1_2 ... 0
...
0 t_|V|-1_1 t_|V|-1_2 ... 0
\end{Verbatim}
%
%It is essential that the value order in the solution output matches the value order of the input.  Otherwise the grader will misinterpret the output.

\clearpage
\paragraph{Examples} \mbox{}
%\vspace{0.1cm}
\noindent
(based on Figure \ref{fig:vrp})

\vspace{0.2cm}
\noindent
Input Example
\vspace{-0.2cm}
\begin{Verbatim}[frame=single]
5 4 10
0 0 0
3 0 10
3 -10 10
3 0 -10
3 10 -10
\end{Verbatim}

\vspace{0.2cm}
\noindent
Output Example 1
\vspace{-0.2cm}
\begin{Verbatim}[frame=single]
80.6 0
0 1 2 3 0
0 4 0
0 0
0 0
\end{Verbatim}
%
This output represents the following routes for each vehicle.  Vehicle 0 - $\{0 \rightarrow 1, 1 \rightarrow 2, 2 \rightarrow 3, 3 \rightarrow 0\}$;  Vehicle 1 - $\{0 \rightarrow 4, 4 \rightarrow 0\}$; Vehicle 2 - $\{0 \rightarrow 0\}$; Vehicle 3 - $\{0 \rightarrow 0\}$.  Note the following equivalent solution using the same routes with different vehicles.

\vspace{0.2cm}
\noindent
Output Example 2
\vspace{-0.2cm}
\begin{Verbatim}[frame=single]
80.6 0
0 4 0
0 0
0 1 2 3 0
0 0
\end{Verbatim}

\section{Instructions}

\input{instructions.tex}

%We use \texttt{stdout} for output.
%Output to other stream will be ignored (you may want to send runtime information to \texttt{stderr}). Your submission will be tested on a department linux machine. If your algorithm is a standalone program, please name it \texttt{nr},
%otherwise, please specify the compilation procedure,
%it is appreciated if you also provide a script that follows the above format to run the program.

\paragraph{Resources}
You will find several vehicle routing problem instances in the \texttt{data} directory provided with the handout.

%An example output file, \texttt{blabla.out}, is also provided.

%\section{Remarks}

\input{handin.tex}

\input{grading.tex}

\input{collaboration.tex}

%\paragraph{Questions} Please contact the class GTA Carleton (cjc@cs.brown.edu).

\input{warnings.tex}

%\paragraph{Hint}
%The optimal value for  \texttt{data/gc\_1000\_5} is near $85$.

\input{techReqs.tex}

\end{document}


\documentclass[12pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage{amsmath,amsthm,amssymb,amsfonts}
\usepackage{enumitem}
\usepackage{tabu}
\usepackage{xcolor}
\usepackage{mathtools}
\usepackage{tcolorbox}
\usepackage{changepage}
\usepackage{kpfonts}
\usepackage{picture}
\usepackage{venndiagram}

\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\R}{\mathbb{R}}

\begin{document}
\section*{CHAPTER 7}

\noindent
\textbf{Problem 3:} Consider a card game, using the standard $52$-card deck, in which each of four players is dealt thirteen cards. Compute the probabilities that a specific player: $(a)$ has no clubs; $(b)$ has exactly ten clubs; $(c)$ has at least three of four aces.

\vspace*{5cm}

\noindent
\textbf{Problem 4:} (Cont.) In the same card game, what is the probability that each player is dealt a jack?

\vspace*{5cm}

\noindent
\textbf{Problem 9:} Recall that there are U.S. senators (two from each state).

\begin{enumerate}[label=(\roman*)]
\item If two senators are chosen at random, what is the probability that they are from the same state?
\item If the $100$ senators are organized into disjoint sets of two, what is the probability that, in each set, the two senators are from the same state?
\item In a committee of ten senators, what is the probability that no two are from the same state? (Assume that there are no restrictions on committee memberships)
\end{enumerate}

\vspace*{3cm}

% ================================================================================================================================
% ================================================================================================================================
\section*{CHAPTER 8}

\noindent
\textbf{Problem 3:} Compute the probability that, in a sample of $10$ people in the population at large, $2$ have their birthdays in May or June, $3$ have their birthdays in December or January, and the $5$  remaining ones have their birthdays during the rest of the year. (Just give the formula. Also, you may assume for simplicity that all the months have the same number of days.)

\vspace*{5cm}

\noindent
\textbf{Problem 4:} Two fair dice are thrown repeatedly until for the first time their sum exceeds $4$. What is the distribution of the trial number of that event?

\vspace*{5cm}

\noindent
\textbf{Problem 5:} Check the accuracy of the approximation of the binomial distribution with parameters $50$ and $\frac{1}{50}$ by the Poisson distribution with parameter $1$. Compute both distributions for the values $0$, $1$, $3$, and $5$.

\vspace*{5cm}

\noindent
\textbf{Problem 8:} In a particular ESP (extrasensory perception) experiment, an experimenter looks at one of five cards on each trial, and the subject is to guess at which card the experimenter is looking. Assuming that the subject does not have ESP, what is the distribution of the outcome (successful guess, unsuccessful guess) of a trial?

\vspace*{5cm}

% ================================================================================================================================
% ================================================================================================================================
\section*{CHAPTER 9}

\noindent
\textbf{Problem 1:} Archie has three coins in his pocket: a standard coin, a coin with heads on both sides, and a coin with tails on both sides. He pulls one coin out of his pocket, looks at one side of the coin, and notices that it is a tail. He reasons that the probability of seeing a head on the other side of this coin is $\frac{1}{2}$. Do you agree with his reasoning?

\vspace*{5cm}

\noindent
\textbf{Problem 2:} Let $a$, $b$, and $c$ be outcomes in some finite sample space $\Omega$ having $2^{\Omega}$ as a field of events, with some probability measure $\mathbb{P}$. You are told that $\mathbb{P}(\{ a,b \} \lvert \{ b,c \}) = \alpha$ and that $\mathbb{P}(\{ c \}) = \beta$.

\begin{enumerate}[label=(\roman*)]
\item Compute $\mathbb{P}(\{ b \})$ in terms of $\alpha$ and $\beta$.
\item Give some possible values for $\alpha$ and $\beta$.
\item Find constraints on $\alpha$ and $\beta$, that is, find a general expression constraining the possible values of $\alpha$ and $\beta$.
\item Find an expression constraining the possible values of $\mathbb{P}(\{ a \})$.
\end{enumerate}

\vspace*{5cm}

\noindent
\textbf{Problem 8:} Consider, in some ethnic group, the set of all families having two children. Let us assume that, for such families, the probability of having a boy is $.5$. Take one family at random and suppose that one of their children is a boy. What is the probability that the other child is also a boy?

\vspace*{5cm}

\noindent
\textbf{Problem 12:} An astronomer has detected punctual signals from an unknown source in the sky. The signals are of two kinds, which she denotes `$A$' and `$B$.' She assumes that the occurrence of the signals is governed by a random process, namely, that the number of signals of any kind received in the course of one hour has a Poisson distribution with parameter $\lambda$. When a signal occurs, it is an `$A$' signal with probability $\theta$ and a `$B$' signal with probability $1-\theta$. Write a formula for the distribution of `$A$'  signals received in one hour.

\vspace*{5cm}

\end{document}


\documentclass[a4paper, draft]{article}
\usepackage[utf8]{inputenc}
\usepackage[australian]{babel}
\usepackage{mathtools}
\title{Preliminary 3 Unit Notes}
\author{Curly Macadam}
\date{}
\begin{document}
\maketitle
\section{Algebra}
\subsection{Index laws}
\begin{enumerate}
\item \(a^m \times a^n = a^{m+n}\)
\item \(a^m \div a^n = a^{m-n}\)
\item \((a^m)^n = a^{mn}\)
\item \((ab)^n = a^{n}b^{n}\)
\item \(\left(\dfrac{a}{b}\right)^n = \dfrac{a^n}{b^n}\)
\item \(a^0 = 1\)
\item \(a^{-n} = \dfrac{1}{x^n}\)
\item \(a^{\frac{1}{n}} = \sqrt[n]{a}\)
\end{enumerate}
\subsection{Binomial Products}
\[\begin{align*}
(a+b)(x+y) &= ax + ay + bx + by \\
(a+b)(a-b) &= a^2 - b^2 \\
(a+b)^2 &= a^2 + 2ab + b^2 \\
(a-b)^2 &= a^2 - 2ab + b^2
\end{align*}\]
\subsection{Factorising}
\[\begin{align*}
x^2 + (a+b) + ab &= (x+a)(x+b) \\
a^3 + b^3 &= (a+b)(a^2 - ab + b^2) \\
a^3 - b^3 &= (a-b)(a^2 + ab + b^2)
\end{align*}
\]
\end{document}


\title{CFD laboratory 1\\Laminar flow development between two parallel plates}
\author{
        Sergio M. Vanegas A.\\
        Francesco de Pas\\
                Department of Mathematics\\
        Polimi---Politecnico di Milano\\
        Milano, Italia
}
\date{\today}

\documentclass[12pt]{article}

\usepackage{amsmath}
\usepackage{graphicx}

\begin{document}
\maketitle

\begin{abstract}
        The first test case is the steady-state development of incompressible flow between two parallel plates in the laminar regime (Figure~\\\ref{fig:sketch}). The plates are considered infinite in the direction transversal to the flow. The flow develops from a condition of uniform velocity (rectangular profile) imposed at the inlet boundary, reaching a fully-developed state at a certain distance downstream of it. \cite{FL:01}
\end{abstract}

\section{Introduction}
        The fully developed laminar flow between two parallel plates admits an analytical solution (plane Poiseuille flow):

        \begin{equation} \label{eq:system}
                \begin{cases}
                        u(x,y,z) = u(y) = - \frac{\delta ^ 2}{2 \mu} \frac{dp_e}{dx} \frac{y}{\delta} (2 - \frac{y}{\delta}) \; v(x,y,z) = 0 \; w(x,y,z) = 0 \\
                        \frac{dp_e}{dx} = const < 0 \\
                        \tau_{yx}(x,y,z) = - 2 \mu \frac{1}{2} \left( \frac{\partial u}{\partial y} + \frac{\partial v}{\partial x} \right) = - \mu \frac{du}{dy} = \frac{dp_e}{dx} (\delta - y) = \tau_{yx}(y)
                \end{cases}
        \end{equation}

        Where \( \mu \) is the dynamic viscosity of the fluid, \( \delta \) is the half-distance between the plates, \(u, v, w\) are the velocity components along directions \( x, y, z \) (Figure~\ref{fig:sketch}), \( p_e \) is the excess pressure with respect to the hydrostatic component, and \( \tau_{yx} \) is the only nonzero shear stress. \cite{FL:01}

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{Case_Sketch.png}
                \centering
                \caption{Sketch of the Case}
                \label{fig:sketch}
        \end{figure}

        The configuration of the problem is as follows:
        \begin{itemize}
                \item Length \( L = 10 \: cm \),
                \item Length \( L_p = 9 \: cm \),
                \item Half-channel height \(\delta = 5 \: mm\),
                \item Bulk velocity \( U_b = 5 \: mm/s \),
                \item Fluid: Water at \( 20^{\circ}C \; ( \rho = 998.23 \: kg/m^3\), \\ Kinematic Viscosity \( \nu = 1.006E-6 \: m^2/s ) \).
        \end{itemize}

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{Conditions.png}
                \centering
                \caption{Domain and boundary conditions}
                \label{fig:conditions}
        \end{figure}

        \paragraph{Outline}
        The remainder of the report is organized as follows: Section~\ref{sec:developed_flow} provides some gross estimate of the required \( L_p \) to achieve a fully-developed flow in terms of channel height; Section~\ref{sec:independence} shows how a suitable configuration of the cartesian computational mesh was found; Section~\ref{sec:CFD_validation} compares the simulated solution with the analytical model both graphically and numerically; Finally, Section~\ref{sec:vorticity} provides some analysis regarding the vorticity profile on both the developing and fully-developed region. It is worth noting that all simulations had a relative convergence tolerance of $ 1E-3 $ for all variables taken into consideration.

\section{Fully-developed flow conditions} \label{sec:developed_flow}

        The following plot was generated from a half-domain simulation with a 40-by-40 mesh, in a $ 12 \: cm $ long domain with a $ 2 \: cm $ margin, as per the lab document's recommendation. The observed profile was taken in

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{Fully_Developed_Francesco.png}
                \centering
                \caption{X-velocity Y-profile per delta-step}
                \label{fig:delta-steps}
        \end{figure}

        As we can see in Figure~\ref{fig:delta-steps}, the X-velocity Y-Profile stabilizes after roughly 4 deltas ($ 2 \: cm $), making our choice of an 18-delta channel with a 2-delta margin at the beginning ($ 10 \: cm $ total) more than enough for the case of study. From now on, unless said otherwise, all X-specific data was taken after 12 deltas into the actual channel ($ 7 \: cm $ from the origin of the X-axis), simulating the whole channel as opposed to just the lower half and using a \( 10 \: cm \) domain with a \( 1 \: cm \) margin in its stead.

\section{Grid independence study} \label{sec:independence}

        The following Grid-Independence study was performed by fixing 40 cells either along the X or Y axis, and then progressively increasing the amount of cells on the other axis until both X-velocity profile and Pressure-gradient convergence was observed.

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{Grid_Ind_U_Profiles.png}
                \centering
                \caption{X-velocity derivative Y-profile per cell amount}
                \label{fig:grid_ind_u}
        \end{figure}

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{Grid_Ind_P_Gradient.png}
                \centering
                \caption{P-gradient vs cell amount}
                \label{fig:grid_ind_p}
        \end{figure}

        As we can observe in Figure~\ref{fig:grid_ind_u}, X-refinement is pretty much irrelevant for the X-velocity derivative profile; nevertheless, such is not the case for the Pressure-gradient which, as we can see in Figure~\ref{fig:grid_ind_p}, did not stabilize after at least 35 cells across the X-axis.

        In the case of Y-refinement, 25 cells were enough to stabilize both the X-velocity derivative profile and average Pressure-gradient. Therefore, a 40-by-40 mesh kept being used for the remainder of the laboratory, since simulation times were low enough for a wide Y-refinement margin to not be a problem.

\section{CFD solution validation} \label{sec:CFD_validation}

        From Equation System~\ref{eq:system} and Equation~\ref{eq:bulk_speed} (which describes Bulk velocity as a function of the Pressure-gradient magnitude), we derive the expressions in Equation System~\ref{eq:analytical}.

        \begin{equation} \label{eq:bulk_speed}
                U_b = - \frac{1}{3 \mu} \frac{dp_e}{dx} \delta ^ 2
        \end{equation}

        \begin{equation} \label{eq:analytical}
                \begin{cases}
                        \frac{dp_e}{dx} = - \frac{3 \mu}{\delta ^ 2} U_b \\
                        u(y) = - \frac{\delta}{2 \mu} \frac{dp_e}{dx} y (2 - \frac{y}{\delta})
                \end{cases}
        \end{equation}

        In order to objectively measure the simulation error with respect to the analytical solution, we use the expressions in Equation System~\ref{eq:errors}. It is worth noting that the velocities inside the $ L^2 $-norm and $ L^{\infty} $-norm were evaluated for a fixed value of x inside the fully-developed region.

        \begin{equation} \label{eq:errors}
                \begin{cases}
                        \frac{dp}{dx}_{err} = \frac{\left| \frac{dp_e}{dx} - \frac{dp_e}{dx}_{sim} \right|}{\left| \frac{dp_e}{dx} \right|} \\
                        u_{err, L^2} = \frac{\left| \left| \frac{u - u_{sim}}{u} \right| \right|_{L ^ 2}}{\sqrt{2 \delta}} = \sqrt{\frac{\int_{0}^{2 \delta} \left| \frac{u(y) - u_{sim}(y)}{u(y)} \right|^2 dy}{2 \delta}} \\
                        u_{err, L^{\infty}} = \left| \left| \frac{u - u_{sim}}{u} \right| \right|_{L ^ \infty} = \sup_{y \in [0, 2 \delta]} \left| \frac{u(y) - u_{sim}(y)}{u(y)} \right|
                \end{cases}
        \end{equation}

        The results were the following:

        \begin{itemize}
                \item Pressure-gradient relative error: \( 5.807746E-03 \).
                \item X-velocity relative Root-Mean-Squared error: \( 5.288724e-03 \).
                \item X-velocity relative Maximum error: \( 2.613112e-02 \).
        \end{itemize}

        Aditionally, as we can observe in Figure~\ref{fig:u_comparison} and Figure~\ref{fig:tau_comparison}, the profiles for both X-velocity and Shear-stress were coherent with the analytical model.

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{U_Profile_Comparison.png}
                \centering
                \caption{X-velocity profile comparison at \(x = 0.07 \: m \)}
                \label{fig:u_comparison}
        \end{figure}

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{Tau_Profile_Comparison.png}
                \centering
                \caption{Shear-stress profile comparison at \(x = 0.07 \: m \)}
                \label{fig:tau_comparison}
        \end{figure}

\section{Vorticity} \label{sec:vorticity}

        Using data from the original simulation (for visualization purposes) and a 100-by-40 mesh, we plotted vorticity across all channel regions and obtained Figure~\ref{fig:vorticity} as a result.

        \begin{figure}[!ht]
                \includegraphics[width=\textwidth]{Vorticity_Profile_Francesco.png}
                \centering
                \caption{Vorticity surface-profile}
                \label{fig:vorticity}
        \end{figure}

        The main two differences between the developing and fully-developed regions are:

        \begin{itemize}
                \item Peak vorticity magnitude is higher on the developing region.
                \item The vorticity profile is completely linear on the fully-developed region, whereas it presents variable slope on the developing one.
        \end{itemize}

\bibliographystyle{abbrv}
\bibliography{main}

\end{document}


\lab{Applications}{Norms and Geometry}{Norms and Geometry}
\objective{Build intuition about the geometries associated with different norms and metric spaces.}

{\bf Outline}
\begin{itemize}
\item Review $\ell^p$ norms. Talk about how each is equivalent, but yields different notions of geometry.
\item Talk about different matrix norms. Talk about the right way to calculate them as well.
\end{itemize}
\begin{problem}
Write a function plotting unit ball in different norms.
\end{problem}

\begin{problem}
Write a function that transforms some star-shaped object into its equivalent object in other norms. What is the star of david in the infinity norm? (or something like that)
\end{problem}

\section*{Condition Number}

Let $A$ be an invertible $n \times n $ matrix, and consider the system $Ax = b$. Even though $A$ is invertible, we may not be able to compute $x$ exactly.  Maybe $A$ cannot be represented exactly in floating point numbers. Or we may not know $A$ exactly. And even if we can represent $A$ exactly, small roundoff errors can occur in the process of solving the system. Thus, when we solve $Ax-b$ we obtain a solution $x'$ which may be not equivalent to the true solution $x$. Unfortunately, even if $Ax'$ is very close to $b$, $x'$ may not be close to $x$.

The residual of $x'$ is defined $r = \norm{Ax'-b}$ and the relative residual is $\frac{\norm{r}}{\norm{b}}$. However, we are interested in the relative error of $x'$ which is defined $\frac{\norm{e}}{\norm{x}}$ where $e$ is the error $x-x'$. It is the error, not the residual, which measures how close our imperfect $x'$ is to the true solution $x$.

Fortunately, these two quantities can be related. If we choose a vector norm $\norm{\cdot} _v$ and a matrix norm $\norm{\cdot} _M$ such that

\begin{equation} \label{eq:normcondition}
\norm{Ax}_v \leq \norm{A}_M\norm{x}_v \quad \forall x \in  \mathbb{F}^n, A \in \mathbb{F}^{n \times n}
\end{equation}
then it can be shown that
\begin{equation*}
\frac{1}{\norm{A} \norm{A^{-1}}} \frac{\norm{r}}{\norm{b}} \leq \frac{\norm{e}}{\norm{A}} \leq \norm{A} \norm{A^{-1}} \frac{\norm{r}}{\norm{b}}
\end{equation*}

The number $\norm{A} \norm{A^{-1}} = \kappa (A)$ is called the \emph{condition number} of $A$. If $\kappa (A)$ is small, then $A$ is well=conditioned, and the relative error is close to the relative residual. If $\kappa (A)$ is large, then $A$ is ill-conditioned, and the relative error may be many times larger than the relative residual. Also, if $A$ is ill-conditioned, then small changes in the entries of $A$ can result in large changes in the solutions to $Ax = b$.

\begin{problem}
Let $A =\begin{pmatrix}1 & 3\\2 & 5.999\end{pmatrix}$ and $b = \begin{pmatrix}5\\9.999\end{pmatrix}$. Calculate the condition number of $A$. Now test the sensitivity of the system $Ax = b$ to small changes in $b$. What do you find?
\end{problem}


\graphicspath{ {./img/TheFEM/} }
\chapter{Quadratures: numerical integration}

\section*{Preliminary}

The formulation of finite element algorithms is strongly based on the weak formulation of the boundary value problems. In loose terms, in typical finite element algorithms the boundary value problem originally written as a set of governing differential equations and properly specified boundary conditions, is re-formulated in the form of integral representations. For instance, this is the case in the boundary value problem of linearized theory of elasticity where the differential equations (corresponding to the equilibrium of a material point) and the tractions (and/or displacement) boundary conditions are shown to be equivalent to the the integral form representation of the principle of virtual displacements. In this case a finite element algorithm results from the discretization through interpolation schemes of the integrand appearing in the principle. However to generate an efficient method, valid over arbitrary domains it is necessary to implement effective numerical integration algorithms. To illustrate the need for numerical integration in the formulation of finite element methods consider a typical term resulting from the discretization of the internal virtual energy in the principle of virtual displacements such as the stiffness matrix given by:

\begin{equation}
K^{QP} = \int_VH_{ij}^QC_{ijkl}H_{kl}^P\operatorname dV.
\label{sample integral 1}
\end{equation}

The accurate computation of these integrals is important to the formulation of the finite element algorithm.

Note that the integration given by \eqref{sample integral 1} is conducted over a domain $V$ which is typically a finite element of arbitrary shape (e.g., a distorted quadrilateral element) therefore difficulting the computation of $K^{QP}$. This chapter discusses the most relevant details required in the numerical computation of integrals like the one appearing in \eqref{sample integral 1} which are typical in finite element algorithms. In the first part of the chapter we define a general formula for numerical integration. For completeness we derive integration formulas based on Lagrange interpolation although emphasis will be placed on the more efficient Gaussian integration formulas.

At the end of this chapter\footnote{{\bf This chapter, together with theoretical and computational learning activities is complemented by Jupyter Notebooks 5 and 6 available at the course REPO. Notebook 5 covers numerical integration as used in the finite element method, while notebook 6 combines interpolation theory with numerical integration in the calculation of the stiffness matrix for a finite element.}} the student should be able to:

\begin{itemize}
\item[•] Recognize the difference between explicit and numerical computation of integrals.
\item[•] Recognize the advantages and disadvantages of different numerical integration schemes.
\item[•] Propose integration schemes for specific finite elements.
\item[•] Implement efficient Python subroutines required in the integration of functions over specific finite elements.
\end{itemize}

\section{Statement of the problem}

\begin{tcolorbox}
\paragraph*{A note on notation:}
Recall that in our indicial notation we are using subscripts to refer to the scalar components of a vector or a tensor function, while superscripts are reserved to represent elements of the interpolating polynomial. Thus for scalar components of a vector we use:

\[V_i\equiv\begin{bmatrix}V_x&V_y&V_z\end{bmatrix}.\]

For interpolation of a scalar function we use:

\[p(x)=L^Q(x)f^Q.\]

And for interpolation of a vector function we use:

\[u_i(x)=L_i^Q(x)u^Q\]

\end{tcolorbox}

In the most general case we are interested in numerically computing integrals of the general form

\begin{equation}
I\;=\iiint f(x,y,z)dV
\label{sample integral 2}
\end{equation}

where the triple integral represents an integration over a given volume. As in the case of interpolation theory, the problem of integration can also be solved from the fundamental problem of integrating a one-dimensional function like

\begin{equation}
\int\limits_a^b {f(x)dx}  \approx \sum\limits_{I = 1}^N {{w^I}} f({x^I}).
\label{quadra}
\end{equation}

In this fundamental one-dimensional problem the integral of a function $f(x)$ from $x = a$ to $x= b$ is approximated by a weighted summation of the values of the function at a set of $N$-points. In \eqref{quadra} $w^I$ represents a weighting factor associated to the value of the function $f({x^I})$ at the point $I$.

This numerical approximation of the integral in terms of a weighted summation is called a quadrature formula and the derivation of a specific quadrature corresponds to prescribing the required number of points $N$, the corresponding weighting factors and the location of the $N$ sampling or integration points.

\paragraph*{Example}
Using the following set of quadrature points and weighting factors

\begin{center}
\begin{tabular}{cc}
  \hline
  $x^I$ & $w^I$ \\
  \hline
  $-0.86113$  & $0.34785$  \\
  $-0.33998$  & $0.65214$  \\
  $ +0.33998$  & $0.65214$  \\
  $ +0.86113$  & $0.34785$  \\
  \hline
\end{tabular}
%\captionof{table}{Definition of integration points and weighting factors for a numerical integration of the type $\int\limits_{ - 1}^{ + 1} {f(x)dx}$}
\label{ejemplo}
\end{center}

evaluate the integral

\begin{equation}
I = \int\limits_{ - 1}^{ + 1} {({x^3} + 4{x^2} - 10)dx}.
 \label{eqeje}
\end{equation}

The numerical evaluation of the integral in \eqref{eqeje} just reduces to the computation of the following weighted summation:

\begin{align*}
\int\limits_{ - 1}^{ + 1} {({x^3} + 4{x^2} - 10)dx} \approx 0.34785 \cdot f( - 0.86113) + 0.65214 \cdot f( - 0.33998) \\
 + 0.34785 \cdot f(0.86113) + 0.65214 \cdot f(0.33998) = -17.3333
\end{align*}

\section{Numerical integration using interpolation polynomials}
A simple quadrature formula can be easily obtained if one represents the actual function $f(x)$ through a Lagrange based interpolation polynomial $p(x)$:

\begin{equation}
\int\limits_a^b {f(x)dx \approx \int\limits_a^b {p(x)dx} } .
 \label{polybased}
\end{equation}

where

\begin{equation}
p(x) = {L^I}(x)f({x^I})
 \label{Lagracof}
\end{equation}

and ${L^I}(x)$ is the Lagrange interpolation polynomial associated to point $x^I$.

Substituting \cref{Lagracof} in \cref{polybased} yields

\[\int\limits_a^b f(x)\ dx  \approx \int\limits_a^b L^I(x)f(x^I)dx  \equiv f(x^I)\int\limits_a^b L^I(x)dx\, \]

which can be written like

\begin{equation}
\int\limits_a^b {f(x)dx}  \approx \sum\limits_{I = 1}^N w^I f(x^I)
\label{general}
\end{equation}

after noticing that

\begin{equation}
w^I = \int\limits_a^b {L^I(x)\ dx}.
\label{pesos}
\end{equation}

\begin{tcolorbox}
Integration schemes are classified in Newton-Cotes and Gaussian quadratures methods. In the first case the range of integration is divided into $N-1$ subintervals of constant size $\frac{b-a}{N-1}$ while in the second group one searches for the optimum location of the integration points inside the interval in order to obtain maximum accuracy.
\end{tcolorbox}

\paragraph*{Example: Extended trapezoidal rule}
Consider the particular case in which $N=2$ (i.e., 1 integration interval). Clearly, in this case the size of the interval is $h=b-a$ and the interpolating polynomial is given by:

\[p(x) = {L^1}(x){f^1} + {L^2}(x){f^2} \equiv {L^1}(x)f(a) + {L^2}(x)f(b)\]

with interpolation polynomials corresponding to:

\[{L^1}(x) = \frac{{(x - {x^2})}}{{({x^1} - {x^2})}} \equiv  - \frac{1}{h}(x - b)\]

\[{L^2}(x) = \frac{{(x - {x^1})}}{{({x^2} - {x^1})}} \equiv \frac{1}{h}(x - a).\]

Substitution in \eqref{pesos} yields:

\[{w^1} =  - \frac{1}{h}\int\limits_a^b {(x - b)dx}  \equiv \frac{h}{2}\]

\[{w^2} =  + \frac{1}{h}\int\limits_a^b {(x - a)dx}  \equiv \frac{h}{2}\]

giving the final quadrature

\[I = {w^1}{f^1} + {w^2}{f^2} \equiv \frac{h}{2}\left[ {f(a) + f(b)} \right]\]

or equivalently:

\begin{equation}
\int\limits_a^b {f(x)dx = h\left[ {\frac{1}{2}{f(a)} + \frac{1}{2}{f(b)}} \right]}.
\label{trapecio}
\end{equation}

\paragraph*{Example: Computation of a definite integral}
Use the trapezoidal rule to compute the integral

\[I=\int\limits_{ - 1}^{ + 1} {({x^3} + 4{x^2} - 10)dx}.\]

In this case h=2.0, therefore:

\[I = f( - 1) + f( + 1) \equiv  - 7 - 5 =  - 12\]

\paragraph*{Example: Integration over two-dimensional domains.}
\Cref{fig:rieman} shows an schematic description of a two-dimensional domain (continuous black line) denoted by $R$. We wish to compute the integral

\[I = \iint\limits_R {f(x,y)dA}. \]

To proceed with the computation, the domain has been divided in $N$ rectagular subdomains (black dashed lines) in such a way that a typical subdomain has dimensions $\Delta {x_i} \times \Delta {y_i}$ as shown in the auxiliary figure.

\begin{figure}[H]
\centering
\includegraphics[width=10cm]{img/rieman.pdf}
\caption{Riemman partition for a two-dimensional domain.}
\label{fig:rieman}
\end{figure}

Defining

\[\left| p \right| = \max \left| {\Delta {x_i}} \right| \vee \max \left| {\Delta {y_i}} \right|\]

as the norm of the partition, we have, according to the definition of an integral as a Riemman sum that:

\[I = \iint\limits_R {f(x,y)dA}  \equiv \mathop {\lim }\limits_{\left| p \right| \to 0} \sum\limits_{j = 1}^N {f({x_j},{y_j})\Delta {x_j}} \Delta {y_j}.\]

Taking each one of the limits independently allows to identify 2 integration process such that the integral over $R$ reduces to the double integral given by:

\[I = \int {\int {f(x,y)dxdy} }. \]

To identify the integration limits consider \cref{fig:dirx} showing a rectangular integration domain with largest side parallel to the $x$ direction and with mid height corresponding to a $y$ constant value. The small sides of the rectangle have abscissas ${x_1}(y)$ and ${x_2}(y)$ respectively.

\begin{figure}[H]
\centering
\includegraphics[width=10cm]{img/dirx.pdf}
\caption{Integration along the $x$ direction.}
\label{fig:dirx}
\end{figure}

Considering once again the definition of an integral as the limit of a Riemman sum we then have that for constant $y$ values the contribution to the integral over region $R$ of the rectangle bounded by ${x_1}(y)$ and ${x_2}(y)$ is given by:

\[\int\limits_{{x_1}(y)}^{{x_2}(y)} {f(x,y)dx}\]

in such a way that the computation of the integral over the full region $R$ is completed after repeating the process for constant values of $y$ varying between $y_1$ and $y_2$ giving for the total integral:

\begin{equation}
I = \int\limits_{{y_1}}^{{y_2}} {\left\{ {\int\limits_{{x_1}(y)}^{{x_2}(y)} {f(x,y)dx} } \right\}dy}
\label{iterada}
\end{equation}

To clarify  \cref{iterada}, note that the internal integral can be written as a function of $y$

\[F(y) = \int\limits_{{x_1}(y)}^{{x_2}(y)} {f(x,y)dx} \]

and the external integral like:

\[I = \int\limits_{{y_1}}^{{y_2}} {F(y)dy}. \]

Alternatively (see \cref{fig:diry}) it is possible to define:

\[H(x) = \int\limits_{{y_1}(x)}^{{y_2}(x)} {f(x,y)dy} \]

in such a way that the full integral $I$ is defined by:

\[I = \int\limits_{{x_1}}^{{x_2}} {H(x)dx}. \]

\begin{figure}[H]
\centering
\includegraphics[width=10cm]{img/diry.pdf}
\caption{Integration along the $y$ direction.}
\label{fig:diry}
\end{figure}

Let us apply the previous ideas to compute the integral

\[I = \int {\int {x{y^2}} } dA\]

over the region shown in \cref{fig:ejeint}.

\begin{figure}[H]
\centering
\includegraphics[width=10cm]{img/ejeint.pdf}
\caption{Integration along the $x$ direction over the triangular region $R$.}
\label{fig:ejeint}
\end{figure}

Identifying the lower and upper integration limits along the $y$ direction as ${y_1} = 0$ and ${y_2} = 2$ respectively, and the functions ${{x_1}(y)}$ and ${{x_2}(y)}$ like:

\[x_1(y) = \frac{y}{2}\]
and
\[x_2(y) = 1\]
we have that:
\[F(y) = \int\limits_{{x_1}(y)}^{1.0} {x{y^2}dx}  \equiv \int\limits_{y/2}^{1.0} {x{y^2}dx} \]

then

\[F(y) = \left. {\frac{1}{2}{x^2}{y^2}} \right|_{y/2}^{1.0} \equiv \frac{1}{2}{y^2} - \frac{1}{8}{y^4}\]

using this function to integrate in $y$ one finally gets that:

\[I = \int\limits_0^{2.0} {F(y)dy}  \equiv \int\limits_0^{2.0} {(\frac{1}{2}{y^2} - \frac{1}{8}{y^4})dy}  \equiv \frac{8}{{15}}.\]

Proceeding alternatively (see \cref{fig:ejeinty}) it is possible to write:

\[H(x) = \int\limits_{{y_1}(x)}^{{y_2}(x)} {x{y^2}dy} \]

and

\[I = \int\limits_{{x_1}}^{{x_2}} {H(x)dx} \]

\begin{figure}[H]
\centering
\includegraphics[width=10cm]{img/ejeinty.pdf}
\caption{Integration along the $y$ direction over the triangular region $R$.}
\label{fig:ejeinty}
\end{figure}

where:

\[{y_1}(x) = 0\]
\[{y_2}(x) = 2x\]

then

\[H(x) = \int\limits_0^{2x} {x{y^2}dy}  \equiv \left. {\frac{1}{3}x{y^3}} \right|_0^{2x} \equiv \frac{8}{3}{x^4}\]

so the integral reduces to:

\[I = \int\limits_0^{1.0} {\frac{8}{3}{x^4}dx}  \equiv \frac{8}{{15}}.\]

\section{Gaussian quadratures}
In the numerical quadrature corresponding to the extended trapezoidal rule written in the form

\begin{equation}
\int\limits_a^b {f(x)dx \approx \sum\limits_{I = 1}^{npts} {{w^I}f({x^I})} }
\label{quadra2}
\end{equation}

the integration points are equidistantly spaced. In a Gaussian quadrature in addition to adjusting the $N$ weighting factors $w^I$ one also leaves as adjustable parameters the location of the $N$ integration points. As a result, there are now $2N$ parameters to adjust in the derivation of an algorithm to numerically approximate the integral of $f(x)$ between $x=a$ and $x=b$ with the maximum accuracy and the minimum number of operations. This class of quadratures provide better precision than those based on Newton-Cotes techniques (such as the trapezoidal rule) when the function to integrate can be appropriately represented by a polynomial.

In general, different Gaussian quadratures are found in the literature reported in terms of tables providing the locations of integration (or Gauss) points and the corresponding weighting factors $w^I$. As an example \cref{ejemplo2} gives abscissas and weighting factors for a 4-point Gaussian quadrature.

\begin{center}
\begin{tabular}{cc}
  \hline
  $x^I$ & $w^I$ \\
  \hline
  $-0.86113$  & $0.34785$  \\
  $-0.33998$  & $0.65214$  \\
  $ +0.33998$  & $0.65214$  \\
  $ +0.86113$  & $0.34785$  \\
  \hline
\end{tabular}
\captionof{table}{Abscissas and weighting factors to compute $\int\limits_{ - 1}^{ + 1} {f(x)dx}$}
\label{ejemplo2}
\end{center}

To facilitate coding of these quadratures and allow for approximation of general integrals, it is common to consider a primitive range of integration $[-1.0,+1.0]$ which requires transforming the original integral (including the function and its integration limits)to this primitive integral as discussed in \cref{isopar}. \Cref{fig:quagauss} schematizes the primitive integration range and the corresponding Gauss points denoted by the black $x$s. Transformation of a given integral to the primitive space is discussed at a later section.

\begin{figure}[H]
\centering
\includegraphics[width=10cm]{img/quagauss.pdf}
\caption{Schematic reperesentation of a Gaussian quadrature in the primitive range $[-1.0,1.0]$.}
\label{fig:quagauss}
\end{figure}

\paragraph*{Example:Derivation of a Gaussian quadrature}
Let $n=2$ and the integration interval $[a,b]=[-1,+1]$. Find $w^1$, $w^2$ and $x^1$, $x^2$ such the quadrature

\[I = \int\limits_{ - 1}^{ + 1} {f(x)dx}  \approx {w^1}f({x^1}) + {w^2}f({x^2})\]

integrated exactly the function  $f(x)$ corresponding to a third order polynomial like:

\[f(x) = {a_0} + {a_1}x + {a_2}{x^2} + {a_3}{x^3}.\]

Using $f(x)$ in $I$ and stating the integral for each term we have:

\[I = \int\limits_{ - 1}^{ + 1} {{a_0}dx}  + \int\limits_{ - 1}^{ + 1} {{a_1}xdx}  + \int\limits_{ - 1}^{ + 1} {{a_2}{x^2}dx}  + \int\limits_{ - 1}^{ + 1} {{a_3}{x^3}dx} \]

where:

\[\int\limits_{ - 1}^{ + 1} {dx}  = 2 = {w^1} \cdot 1 + {w^2} \cdot 1\]

\[\int\limits_{ - 1}^{ + 1} {xdx}  = 0 = {w^1} \cdot {x^1} + {w^2} \cdot {x^2}\]

\[\int\limits_{ - 1}^{ + 1} {{x^2}dx}  = \frac{2}{3} = {w^1} \cdot {({x^1})^2} + {w^2} \cdot {({x^2})^2}\]

\[\int\limits_{ - 1}^{ + 1} {{x^3}dx}  = 0 = {w^1} \cdot {({x^1})^3} + {w^2} \cdot {({x^2})^3}.\]

The resulting system of equations is solved in order to determine the 4 quadrature parameters, namely $w^1$, $w^2$ and $x^1$, $x^2$ giving $w^1 = 1$, $w^2 = 1$, $x^1 =  - \sqrt 3 /3$ and $x^1 =  + \sqrt 3 /3$ which allows us to write the quadrature in the general form:

\[I = \int\limits_{ - 1}^{ + 1} {f(x)dx}  \approx 1.0 \cdot f( - \sqrt 3 /3) + 1.0 \cdot f( + \sqrt 3 /3)\]

which is exact for polynomial functions of order at most 3.

The idea behind Gaussian quadratures can be extended to the integration of higher order polynomials, however its derivation requires an effective method to determine the weighting factors and the abscissas of the Gauss points. The next section discusses a method which is applicable to $2n$-order polynomials, in which advantage is taken from the property of orthogonality existing in certain special polynomials.

%\newpage
\section{Numerical integration in the finite element method}
\label{isopar}

\subsection{One-dimensional domains}
The systematization and construction of tables with coordinates and weighting factors for different quadratures is  useful if these are specified for a fixed range. For mathematical convenience it is common to use as base interval $[-1,+1]$. However considering that we are interested in integrating a function $f(x)$ in the general range with limits $x=a$ and $x=b$ it is required that we re-write the integral like:

\begin{equation}
\int\limits_a^b {f(x)dx \equiv } \int\limits_{ - 1}^{ + 1} {F(r)dr}.
\label{trans}
\end{equation}

The mapping indicated in \cref{trans} is described in \cref{fig:map}, in which the space represented by the independent variable $x$ and contained between $x=a$ and $x=b$ is mapped to a fictitious "natural" space described by a new independent variable $r$ and enclosed in $r=-1$ y $r=1$.

\begin{figure}[H]
\centering
\includegraphics[width=12cm]{img/mapping.pdf}
\caption{Mapping between the physical space $[a,b]$ and the primitive or natural space $[-1.0,+1.0].$}
\label{fig:map}
\end{figure}

This is exactly the same transformation used when approximating unknown functions using interpolation theory over arbitrary distorted domains. Repeating for convenience, the transformation between both spaces can be written like:

\[x = x(r)\]
\[r = r(x)\]

and where $x(r)$ and $r(x)$ represent functional relationships between both spaces. For instance, in reference to \cref{fig:map}, it is evident that independent of the functional relationship this must satisfy the condition $x(-1.0)=a$ and $x(+1)=b$. Therefore, a valid relationship can be derived after assuming that both spaces are related through a Lagrange interpolating polynomials as follows:

\[x(r) = {L^1}(r)x({r^1}) + {L^2}(r)x({r^2})\]

and where the interpolation polynomials are given by:

\[{L^1}(r) = \frac{{(r - {r^2})}}{{({r^1} - {r^2})}} \equiv \frac{1}{2}(1 - r)\]

\[{L^2}(r) = \frac{{(r - {r^1})}}{{({r^2} - {r^1})}} \equiv \frac{1}{2}(1 + r)\]

which results in:

\[x(r) = \frac{1}{2}(a + b) + \frac{r}{2}(b - a).\]

It is also necessary to re-write $f(x)$ using as independent variable $r$ instead of $x$ using the functional relationship $x=x(r)$ like:

\[f = f(x) \equiv f[x(r)] = \hat F(r)\]

where $\hat F(r)$ represents the same function but now written in terms of $r$.

Finally, to complete the transformation it is necessary to transform physical differential space elements, that is $dx$. Proceeding directly from the mapping via the Lagrange interpolation polynomials we have:

\[\frac{{dx}}{{dr}} = \frac{{d{L^1}(r)}}{{dr}}x({r^1}) + \frac{{d{L^2}(r)}}{{dr}}x({r^2}) \equiv \frac{1}{2}(b - a)\]

and therefore

\[\frac{{dx}}{{dr}} = \frac{1}{2}(b - a)\]

which allows us to finally write the integral in the fictitious domain enclosed in $[-1, +1]$ according to:

\[\int\limits_a^b {f(x)dx \equiv } \int\limits_{ - 1}^{ + 1} {\hat F(r)\frac{\ell}{2}dr}  \equiv \int\limits_{ - 1}^{ + 1} {F(r)dr} \]

and where $\ell= \frac{1}{2}(b - a).$

\begin{tcolorbox}
The module {\bf Gaussutil()} in the finite element code {\bf SolidsPy} contains several one-dimensional and two-dimensional Gauss quadratures.
\end{tcolorbox}

\paragraph*{Example}

Use a 2 point Gaussian quadrature (see \cref{ejemplo3}) to evaluate the integral:

\[I = \int\limits_0^3 {({2^x} - x)dx}. \]

\begin{center}
\begin{tabular}{cc}
  \hline
  $x^I$ & $w^I$ \\
  \hline
  $-0.577350269189626$  &  $1.000000$  \\
  $+0.577350269189626$  & $1.000000$  \\
  \hline
\end{tabular}
\captionof{table}{Abscissas and weighting factors to compute $\int\limits_{ - 1}^{ + 1} {f(r)dr}$}
\label{ejemplo3}
\end{center}

To perform the numerical integration using the 2-point Gaussian quadrature given in \cref{ejemplo3} it is necessary to transform the integration range and the integrand of the function to the range corresponding to $[-1.0,+1.0]$. The transformation is given by:

\[x(r) = \frac{3}{2} + \frac{3}{2}r\]

while the differential elements satisfy

\[dx = \frac{3}{2}dr.\]

To transform the function we use:

\[\hat f(r) = f[x(r)] \equiv f\left( {\frac{3}{2} + \frac{3}{2}r} \right)\]

from which:

\[I = \int\limits_0^3 {({2^x} - x)dx}  \equiv \int\limits_{ - 1.0}^{ + 1.0} {\left[ {{2^{\frac{3}{2}(1 + r)}} - \frac{3}{2}(1 + r)} \right]\frac{3}{2}dr} \]

and evaluating:

\[I = \sum\limits_{I = 1}^2 {{w^I}\left[ {{2^{\frac{3}{2}(1 + {r^I})}} - \frac{3}{2}(1 + {r^I})} \right]\frac{3}{2}}  = 1.0 \cdot (1.37678967978) + 1.0 \cdot (4.18374583924) \equiv 5.56053551\]

\subsection{Two-dimensional domains}
In the finite element method there is interest in computing integrals like:

\begin{equation}
I=\int_{V(\overrightarrow x)} f(\overrightarrow x)\operatorname dV(\overrightarrow x)
\label{integral}
\end{equation}

where $V(\overrightarrow x)$ is the domain of a typical finite element in a reference system with position vector $\overrightarrow x$. In one-dimensional problems $V(\overrightarrow x)\equiv\lbrack x_a,x_b\rbrack$; in two-dimensional problems $V(\overrightarrow x)$ is a plane surface; and in three-dimensional problems $V(\overrightarrow x)$ is a volume. Moreover, previously we have defined a finite element like a local interpolation space where values of a function are known at specific points (nodes). For instance, in two-dimensional space we had a quadrilateral bi-lineal element as the one shown in \cref{fig:generalElement}.

%
\begin{figure}[H]
\centering
\includegraphics[width=8cm]{img/physical}
\caption{Arbitrary bi-lineal element defined in the physical space}
\label{fig:generalElement}
\end{figure}

As in the one-dimensional case discussed in the previous section, to conduct numerical integration in a systematic way, we actually need to transform generalized finite elements into canonical interpolation spaces (see \cref{fig:IsoTrans}).

\begin{figure}[H]
\centering
\includegraphics[width=12cm]{img/isopar}
\caption{Transformation from a general distorted element in the physical space to a perfect square in the natural space}
\label{fig:IsoTrans}
\end{figure}

Repeating the transformation for convenience, we have:

\begin{equation}
\begin{aligned}
x_i &=x_i(\overrightarrow r)\\
r_I &=r_I(\overrightarrow x)
\end{aligned}
\label{eq:transQ}
\end{equation}

where $\overrightarrow x$ and $\overrightarrow r$ denote position vectors in the physical and canonical space respectively. Using the above to transform functions we can write:

\begin{equation}
f=f(\overrightarrow x)\equiv f\lbrack x_i(\overrightarrow r)\rbrack\equiv F(\overrightarrow r).
\label{eq:FtransQ}
\end{equation}

\Cref{eq:FtransQ} above indicates that passing $f(\overrightarrow x)$ from the physical to the natural space representation corresponds to a change of variables. In the particular case of classical finite element methods the change of variables is conducted after approximating the physical geometry using interpolation. particularly, using the same set of shape functions as in the approximation of the primary fields we can write:

\begin{equation}
x_i(\overrightarrow r)=N_i^Q(\overrightarrow r)x^Q
\label{eq:Strans}
\end{equation}

where $x^Q$ denotes the spatial coordinates of nodal point $Q$ and $=N_i^Q(\overrightarrow r)$ is the shape function associated to the nodal point $Q$. According to this expression in the finite element method the geometry is interpolated in terms similar to the ones used for the primary field variable.

To transform the domain of integration we start once again from the general functional relationship:

\[x_i =x_i(\overrightarrow r)\]

and  use it to stablish the relationship between differential lengths in both spaces as:

\begin{equation}
dx_i=\frac{\partial x_i}{\partial r_J}dr_j.
\label{eq:diflen}
\end{equation}

The second order tensor $\frac{\partial x_i}{\partial r_J}$ appearing in \ref{eq:diflen} is the Jacobian of the transformation $J_{iJ}$ explicitly defined by;

\[J_{iJ}=\frac{\partial x_i}{\partial r_J}\]

and this tensor contains all the information regarding the geometric changes between both spaces. In terms of the shape functions it follows that:

\begin{equation}
J_{iJ}=\frac{\partial x_i}{\partial r_J}\equiv\frac{\partial N_i^Q}{\partial r_J}x^Q.
\label{eq:disJac}
\end{equation}

To complete the transformation we make use of Nanson's formula from continuum mechanics, from which:

\[ dV(\overrightarrow x)=\left|J\right|dV(\overrightarrow r)\]

where $\left|J\right|$ is the determinant of the Jacobian tensor. We can write for $I$ in both spaces:

\begin{equation}
I=\int_{V(\overrightarrow x)}f(\overrightarrow x)\operatorname dV(\overrightarrow x)\equiv\int_{V(\overrightarrow r)}F(\overrightarrow r)\left|J(\overrightarrow r)\right|\operatorname dV(\overrightarrow r)
\label{eq:twoInte}
\end{equation}

Consider now the particular case of a two-dimensional bi-lineal finite element discussed previously and its transformation into the natural space shown in \cref{fig:IsoMap}. Notice that this canonical element is a perfect square of element side $2.0$ contained between $x\in\left[-1.0\;,\;+1.0\right]$ and $y\in\left[-1.0\;,\;+1.0\right]$ which is the same range of the fundamental quadrature studied in the one-dimensional context.

\begin{figure}[H]
\centering
\includegraphics[width=12cm]{img/mapping2}
\caption{Transformation from a general distorted element in the physical space to a perfect square in the natural space}
\label{fig:IsoMap}
\end{figure}

In the particular case of the transformation described in \cref{fig:IsoMap} we have that

\[dV(\overrightarrow r)=drds\]

therefore

\[dV(\overrightarrow x)=\left|J\right|drds\]

and \cref{eq:twoInte} takes the form:

\begin{equation}
I=\int_{S(\overrightarrow x)}f(\overrightarrow x)\operatorname dS(\overrightarrow x)\equiv\int_{r=-1}^{r=+1}\int_{s=-1}^{s=+1}F(r,s)\left|J(r,s)\right|\operatorname drds.
\label{eq:bilineal}
\end{equation}

To integrate \ref{eq:bilineal} using a quadrature of $Ngpts$ integration points we use:

\begin{equation}
I=\int_{r=-1}^{r=+1}\int_{s=-1}^{s=+1}F(r,s)\left|J(r,s)\right|\operatorname drds\approx\sum_{i=1}^{Ngpts}\sum_{j=1}^{Ngpts}F(r_i,s_j)\left|J(r_i,s_j)\right|w_iw_j
\label{eq:Iquad}
\end{equation}

which can be simplified into

\begin{equation}
I=\int_{r=-1}^{r=+1}\int_{s=-1}^{s=+1}F(r,s)\left|J(r,s)\right|\operatorname drds\approx\sum_{k=1}^{Ngpts\ast Ngpts}F(r_k,s_k)\left|J(r_k,s_k)\right|\alpha_k
\label{eq:Iquad1}
\end{equation}

which the one-dimensional version resulting from the iterated summation. The points marked with a cross in \cref{fig:IsoMap} represent integration points.

\begin{tcolorbox}
Notebook 5 in the REPO uses transformation or mapping from the physical to the canonical space, together with numerical integration, to compute the area of a distorted quadrilateral finite element.
\end{tcolorbox}

\subsection{Matrix formulation}
For the computer implementation of the different methods discussed so far it is practical to use a combined notation in terms of index and matrix representation of variables. Consider the interpolated version of a vector field, for instance the displacement vector in elasticity:

\begin{equation}
u_i(\overrightarrow r)=N_i^Q(\overrightarrow r)u^Q
\label{eq:mixed}
\end{equation}

in which:

\begin{itemize}
\item[•] Susbcript $i$ refers to the normal components of vectors in the physical space
\item[•] Superscript $Q$ refers to the contribution from nodal point $Q$ to the approximated field (in this case $u_i(\overrightarrow r)$)
\item[•] $\overrightarrow r$ position vector of a point in the natural space. In index notation we refer to the scalar components of this vector using capitalized subscripts as $\overrightarrow r=r_I$
\item[•] $N_i^Q(\overrightarrow r)$ shape function associated to the nodal point $Q$ evaluated at the point $\overrightarrow r$.
\end{itemize}

The contribution to the $Q$ nodal point implicit in \cref{eq:mixed} can be written in explicit expanded form as:
\[
\begin{array}{l}\begin{Bmatrix}u\\v\end{Bmatrix}=\left[\cdots\begin{array}{cc}N^Q(\overrightarrow r)&0\\0&N^Q(\overrightarrow r)\end{array}\cdots\right]\begin{Bmatrix}\vdots\\\begin{array}{c}u^Q\\v^Q\end{array}\\\vdots\end{Bmatrix}.\\\end{array}
\]

To compute the Jacobian tensor at point $\overrightarrow r$ assume that the nodal coordinates are stored in a matrix

\[
\begin{array}{l}coord\;=\begin{bmatrix}\vdots\\\begin{array}{cc}x^Q&y^Q\end{array}\\\vdots\end{bmatrix}\\\end{array}
\]

then we can further express:

\begin{equation}
\begin{array}{l}\begin{bmatrix}\frac{\partial x}{\partial r}&\frac{\partial y}{\partial r}\\\frac{\partial x}{\partial s}&\frac{\partial y}{\partial s}\end{bmatrix}=\begin{bmatrix}\cdots&\begin{array}{c}\frac{\partial N^Q}{\partial r}\\\frac{\partial N^Q}{\partial s}\end{array}&\cdots\end{bmatrix}\begin{bmatrix}\vdots\\\begin{array}{cc}x^Q&y^Q\end{array}\\\vdots\end{bmatrix}\\\end{array}
\label{eq:jac}
\end{equation}

Having found the Jacobian of the transformation the remaining step consists in transforming the integrand $f(\overrightarrow{x})$. This step however is not constructed explicitly  but it depends on the structure of $f(\overrightarrow{x})$. In most finite element algorithms the problem formulation involves spatial derivatives of the primary function rather than the primary function itself. To consider these terms in the transformed version of $I$, it becomes necessary to relate spatial differentiation in both spaces. To clarify this aspect of the formulation assume that $I$ is of the form:

\[I=\int_{V(\overrightarrow x)}\frac{\partial f}{\partial\overrightarrow x}\operatorname dV(\overrightarrow x).\]

We already found that

\[\operatorname dV(\overrightarrow x)=\left|J\right|\operatorname dV(\overrightarrow r)\]

and to transform the integrand

\[\frac{\partial f}{\partial\overrightarrow x}\]

we recall that in the finite element method the interpolation of the primary variable is conducted directly in the natural space. This means that we already have $F(\overrightarrow r)$ or more explicitly that:

\[F(\overrightarrow r)=N^Q(\overrightarrow r)F^Q.\]

However to capture correctly the physics of the problem we are interested in finding

\[\frac{\partial f}{\partial\overrightarrow x}.\]

Using implicit differentiation:

\[\frac{\partial f}{\partial x_i}=\frac{\partial F}{\partial r_J}\frac{\partial r_J}{\partial x_i}\]

and re-arranging for convenience we write

\begin{equation}
\frac{\partial f}{\partial x_i}=\frac{\displaystyle\partial r_J}{\displaystyle\partial x_i}\frac{\partial F}{\partial r_J}.
\end{equation}

Notice that the first factor is the Jacobian inverse given by;

\[\frac{\partial r_J}{\partial x_i}=\left(J_{iJ}\right)^{-1}\equiv\left(\frac{\displaystyle\partial x_i}{\displaystyle\partial r_J}\right)^{-1}\]

while the second factor reads:

\[\frac{\partial F}{\partial r_J}=\frac{\partial N^Q}{\partial r_J}F^Q\]

which allows us to write:

\[I=\int_{V(\overrightarrow x)}\frac{\partial f}{\partial\overrightarrow x}\operatorname d{V(\overrightarrow x)}\equiv\int_{V(\overrightarrow r)}J_{iJ}^{-1}\frac{\displaystyle\partial N^Q}{\displaystyle\partial r_J} F^Q \left|J(\overrightarrow r)\right|\operatorname dV(\overrightarrow r).\]

\begin{tcolorbox}
As an in-class activity Notebook 6 in the REPO requires the computation of the stiffness matrix for a plane strain solid element.
\end{tcolorbox}

\paragraph*{Proposed problems}
\begin{enumerate}

\item \label{punto01} Compute the integral of the function

\[f(x,y)=4x^2+3xy+y^2\]

over the two-dimensional domains shown in the figure

\begin{figure}[H]
\centering
\includegraphics[width=12cm]{domain1}
\caption{Integration domains for problem 1}
\label{fig:intdomains}
\end{figure}

\item \label{punto02} Compute the jacobian of the transformation of the domains shown in the figure

\begin{figure}[H]
\centering
\includegraphics[width=14cm]{domain2}
\caption{Integration domains for problem 1}
\label{fig:jacdomains}
\end{figure}

to a perfectly square canonical element of side $2.0$.

\item \label{punto03} Compute the integral of the function

\[f(r,s)=rs\]

over the triangular domain shown in the figure

\begin{figure}[H]
\centering
\includegraphics[width=7cm]{domain3}
\caption{Integration domains for problem 1}
\label{fig:tridomains}
\end{figure}

\end{enumerate}


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

%opening
\title{Demonstration of the solution of the system of mass and energy balances for MS Birka Main Engines}
\author{Francesco Baldi}

\begin{document}

\maketitle

\begin{abstract}

\end{abstract}

\section{Initial system}

\subsection{Mass balances}

Mass balance on the split after the compressor, with one flow going to the engine inlet valves and the other flow going to the bypass valve
\begin{equation}
\dot{m}_{air,comp} = \dot{m}_{air,cyl} + \dot{m}_{air,bypass} \\
\end{equation}

Mass balance on the mixer before the turbine, with one flow coming from the engine exhaust valves and the other flow coming from the bypass valve
\begin{equation}
\dot{m}_{eg,turb} = \dot{m}_{eg,cyl} + \dot{m}_{air,bypass} \\
\end{equation}

Note that the exhaust gas mass flow from the cylinders is fully defined as follows:
\begin{equation}
\dot{m}_{eg,cyl} = \dot{m}_{air,cyl} + \dot{m}_{fuel,cyl} \\
\end{equation}

\subsection{Energy balances}

Energy balance on the turbocharger: the power generated by the turbine must be equal to the power absorbed by the compressor
\begin{equation}
\dot{m}_{air,comp} \Delta h_{comp} = \dot{m}_{eg,turb} c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech}
\end{equation}

Energy balance on the mixer between the air flow after the bypass valve and the exhaust gas flow after the exhaust valve
\begin{equation}
\dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0) + \dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0) = \dot{m}_{eg,turb} c_{p,eg} (T_{turb,in} - T_0)
\end{equation}

The system of four equations is to be solved in the four following unknowns:
\begin{itemize}
	\item $ \dot{m}_{eg,turb} $
	\item $ \dot{m}_{air,bypass} $
	\item $ \dot{m}_{air,comp} $
	\item $ T_{turb,in} $ (In the case of the Main engines)
	\item $ T_{cyl,out} $ (In the case of the Auxiliary engines)
\end{itemize}

\section{Calculating the explicit system}

To calculate what we need, we must make the system explicit on the variables we need to calculate. This process is different for the main and auxiliary engines, mostly because the temperature measurement of the exhaust gas before the turbine is positioned differently

\subsection{Main Engines}

In the case of the main engines, the temperature at the \textbf{cylinder outlet} is measured and, hence, known.

First, we make all equations explicit in $ \dot{m}_{air,bypass} $ thus eliminating both
$ \dot{m}_{eg,turb} $ and $ \dot{m}_{air,comp} $

$$
(\dot{m}_{air,cyl} + \dot{m}_{air,bypass}) \Delta h_{comp} = (\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}) c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech}
$$
$$
\dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0) + \dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0)  = (\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}) c_{p,eg} (T_{turb,in} - T_0)
$$

At this point, we use the first equation to simplify the system and make it explicit in the $ \dot{m}_{air,bypass} $ variable alone:

\begin{eqnarray*}
(\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}) c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech}  & = & (\dot{m}_{air,cyl} + \dot{m}_{air,bypass}) \Delta h_{comp} \\
T_{turb,in} - T_{turb,out} & = & \frac{\dot{m}_{air,cyl} + \dot{m}_{air,bypass}}{\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}} \frac{\Delta h_{comp}}{c_{p,eg} \eta_{mech}} \\
T_{turb,in} & = & T_{turb,out} + \frac{\dot{m}_{air,cyl} + \dot{m}_{air,bypass}}{\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}} \frac{\Delta h_{comp}}{c_{p,eg} \eta_{mech}}  \\
\end{eqnarray*}

We can now substitute this expression in the second equation:

\begin{multline}
	\dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0) + \dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0)  =  \\
	(\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}) c_{p,eg} (T_{turb,out} + \frac{\dot{m}_{air,cyl} + \dot{m}_{air,bypass}}{\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}} \frac{\Delta h_{comp}}{c_{p,eg} \eta_{mech}} - T_0)
\end{multline}

We now have to simplify this equation in order to make the term $ \dot{m}_{air,bypass} $ explicit.
\begin{comment}
One first thing we can do is noticing that the fraction:
$$
\frac{\dot{m}_{air,cyl} + \dot{m}_{air,bypass}}{\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}}
$$
Can be rewritten as:
$$
\frac{1}{1 + \frac{\dot{m}_{fuel,cyl}}{\dot{m}_{air,cyl} + \dot{m}_{air,bypass}}}
$$
Since the numerator of the "subfraction" is much smaller than the denominator, we can make the assumption that this fraction behaves as:
$$
\frac{1}{1 + \epsilon}
$$
For which we know that:
$$
\frac{1}{1 + \epsilon} \approx 1 - \epsilon
$$
That corresponds to:
$$
1 - \frac{\dot{m}_{fuel,cyl}}{\dot{m}_{air,cyl} + \dot{m}_{air,bypass}}
$$
\begin{multline}
\dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0) + \dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0)  =  \\
(\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}) c_{p,eg} \left[T_{turb,out} + \left( 1 - \frac{\dot{m}_{fuel,cyl}}{\dot{m}_{air,cyl} + \dot{m}_{air,bypass}} \right) \frac{\Delta h_{comp}}{c_{p,eg} \eta_{mech}} - T_0\right]
\end{multline}
\end{comment}

We first execute the multiplication in the term on the right of the equal:
\begin{multline}
\dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0) + \dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0)  =  \\
\dot{m}_{eg,cyl} c_{p,eg} (T_{turb,out} - T_0) + \\
\dot{m}_{air,bypass} c_{p,eg} (T_{turb,out} - T_0) + \\
\frac{\Delta h_{comp}}{c_{p,eg} \eta_{mech}}(\dot{m}_{air,cyl} + \dot{m}_{air,bypass}) c_{p,eg}
\end{multline}

Now, we can group together the elements in the variable of interest:
\begin{multline}
\dot{m}_{air,bypass} \left[ c_{p,air} (T_{comp,out} - T_0) - c_{p,eg} (T_{turb,out} - T_0) - \frac{\Delta h_{comp}}{\eta_{mech}} \right] = \\
\dot{m}_{eg,cyl} c_{p,eg} (T_{turb,out} - T_0) - \dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0) + \frac{\Delta h_{comp}}{\eta_{mech}}\dot{m}_{air,cyl}
\end{multline}

This can be further simplified into:
\begin{multline}
\dot{m}_{air,bypass} \left[ c_{p,air} (T_{comp,out} - T_0) - c_{p,eg} (T_{turb,out} - T_0) - \frac{\Delta h_{comp}}{\eta_{mech}} \right] = \\
\dot{m}_{eg,cyl} c_{p,eg} (T_{turb,out} - T_{cyl,out}) + \frac{\Delta h_{comp}}{\eta_{mech}}\dot{m}_{air,cyl}
\end{multline}

Finally, we can assume the specific heat at constant pressure of air and exhaust gas to be sufficiently similar for considering them equal in the term at the numerator (we ignored changes in the properties of the mixture in other points as well):
\begin{multline}
\dot{m}_{air,bypass} \left[ c_{p,eg} (T_{comp,out} - T_{turb,out}) - \frac{\Delta h_{comp}}{\eta_{mech}} \right] = \\
\dot{m}_{eg,cyl} c_{p,eg} (T_{turb,out} - T_{cyl,out}) + \frac{\Delta h_{comp}}{\eta_{mech}}\dot{m}_{air,cyl}
\end{multline}

From which we can derive the final form:
\begin{equation}
\dot{m}_{air,bypass} = \frac{\dot{m}_{eg,cyl} c_{p,eg} (T_{turb,out} - T_{cyl,out}) + \frac{\Delta h_{comp}}{\eta_{mech}}\dot{m}_{air,cyl}}{c_{p,eg} (T_{comp,out} - T_{turb,out}) - \frac{\Delta h_{comp}}{\eta_{mech}}}
\end{equation}

Which can be rewritten, in order to have both numerator and denominator positive, as follows:
\begin{equation}
\dot{m}_{air,bypass} = \frac{\dot{m}_{eg,cyl} c_{p,eg} (T_{cyl,out} - T_{turb,out}) - \frac{\Delta h_{comp}}{\eta_{mech}}\dot{m}_{air,cyl}}{c_{p,eg} (T_{turb,out} - T_{comp,out}) - \frac{\Delta h_{comp}}{\eta_{mech}}}
\end{equation}

\subsection{Auxiliary Engines}

In the case of the auxiliary engines, what we know instead is the temperature of the exhaust gas \textbf{before the turbine}, hence after the merging between the exhaust gas and the bypass.

In this case, however, things appear to be simple: the energy balance on the turbocharger can be calculated as there is only one variable unknown: the total mass flow in the compressor, and hence the bypass flow:
$$
(\dot{m}_{air,cyl} + \dot{m}_{air,bypass}) \Delta h_{comp} = (\dot{m}_{eg,cyl} + \dot{m}_{air,bypass}) c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech}
$$
$$
\dot{m}_{air,cyl} \Delta h_{comp} + \dot{m}_{air,bypass} \Delta h_{comp} = \dot{m}_{eg,cyl} c_{p,eg} (T_{turb,in} - T_{turb,out}) + \dot{m}_{air,bypass} c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech}
$$
$$
\dot{m}_{air,bypass} (\Delta h_{comp} - c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech}) = \dot{m}_{eg,cyl} c_{p,eg} (T_{turb,in} - T_{turb,out}) - \dot{m}_{air,cyl} \Delta h_{comp}
$$
\begin{equation}
\dot{m}_{air,bypass} = \frac{\dot{m}_{eg,cyl} c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech} - \dot{m}_{air,cyl} \Delta h_{comp}}{\Delta h_{comp} - c_{p,eg} (T_{turb,in} - T_{turb,out}) \eta_{mech}}
\end{equation}

Now that we have the value for the bypass flow, it is easy to calculate backwards the temperature of the exhaust gas after the cylinder outlet valves, before the merging with the bypass flow:

$$
\dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0) + \dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0) = \dot{m}_{eg,turb} c_{p,eg} (T_{turb,in} - T_0)
$$
$$
\dot{m}_{eg,cyl} c_{p,eg}  (T_{cyl,out} - T_0) = \dot{m}_{eg,turb} c_{p,eg} (T_{turb,in} - T_0) - \dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0)
$$
\begin{equation}
T_{cyl,out} = T_0 + \frac{\dot{m}_{eg,turb} c_{p,eg} (T_{turb,in} - T_0) - \dot{m}_{air,bypass} c_{p,air} (T_{comp,out} - T_0)}{\dot{m}_{eg,cyl} c_{p,eg}}
\end{equation}

\end{document}


\documentclass[letterpaper]{article}
\usepackage[margin=0.7in]{geometry}
\usepackage{amssymb, amsthm, times}
\usepackage{multicol}
\hbadness=99999     % Gets rid of 'underfill' typeset errors with LaTeX
\renewcommand{\qedsymbol}{$\blacksquare$}  % Changes QED symbol for closing a proof
\begin{document}
\begin{multicols*}{2}

% See list here: https://oeis.org/wiki/List_of_LaTeX_mathematical_symbols
\subsection*{General Symbols}
$\mathbb{N}$\\
$\mathbb{Z}$\\
$\mathbb{R}$\\
$\mathbb{C}$\\
$\mathbb{Q}$\\
$<$\\
$>$\\
$\leq$\\
$\geq$\\
$\nleq$\\
$\ngeq$\\
$\nless$\\
$\ngtr$\\
$\pi$\\
$\times$\\
$\pm$\\

\subsection*{CH 1: Logic}
$\neg$\\
$\land$\\
$\lor$\\
$\oplus$\\
$\to$\\
$\leftrightarrow$\\
$\exists$\\
$\forall$\\
=\\
$\neq$\\
$\equiv$\\
$\not\equiv$\\
$\therefore$\\

\subsection*{CH 2: Proofs}
$\blacksquare$\\
$\mid$\\
$\nmid$\\

\subsection*{CH 3: Sets}
$\in$\\
$\ni$\\
$\subset$\\
$\supset$\\
$\subseteq$\\
$\nsubseteq$\\
$\cup$\\
$\cap$\\
$\emptyset$\\
$\varnothing$\\
$\oplus$\\
$\notin$\\
$\nexists$\\
$\not\subset$\\
$\not\supset$\\
$\supseteq$\\
$\nsupseteq$\\

\subsection*{CH 4: Functions}
$\lceil x \rceil$\\
$\lfloor x \rfloor$\\
$\circ$\\

\subsection*{CH 5: Boolean Algebra}
$\overline{text}$\\
$\cdot$\\
$\uparrow$\\
$\downarrow$\\

\subsection*{CH 6: Relations}
$\prec$\\
$\preceq$\\
$\langle \rangle$\\

\subsection*{CH 7: Computation}
$\delta$

\end{multicols*}
\end{document}