\documentclass{article}

\usepackage{graphicx}

\usepackage{amsmath}

\usepackage{color}

\usepackage[table]{xcolor}

\usepackage{subcaption}

\begin{document}
	\title{LOGIC GATES}

	\author{NKECHI GRACE OKOACHA}

	\maketitle

\tableofcontents

\newpage

\section{Introduction}

\label{intro}
	\begin{itemize}
		\item A logic gate is a building block of a digital circuit which is at the heart of any computer operation. \\

	\begin{center}
		\includegraphics{pic1}
	\end{center}

		\item Behind every digital system is a logic gate. \\

		\begin{center}
			\includegraphics{pic2}
		\end{center}

		\item Logic gates perform logical operations that take binary input (0s and 1s) and produce  a single binary output. They are used in most electronic device including: \\
			\begin{figure}[h!]
				\centering
				\begin{subfigure}[b]{0.2\linewidth}
				\includegraphics[width=\linewidth]{phone}
				\caption{Smartphones}
				\end{subfigure}
			\begin{subfigure}[b]{0.2\linewidth}
				\includegraphics[width=\linewidth]{tablet}
				\caption{Tablets}
			\end{subfigure}
		\begin{subfigure}[b]{0.2\linewidth}
			\includegraphics[width=\linewidth]{memcard}
			\caption{Memory devices}
		\end{subfigure}
			\end{figure}

		\item Now think of a logic gate like a light switch, it is either in an ON or OFF position. Similarly, the input output terminals are always in one of two binary positions false(0) and true(1). Each gate has its own logic or set of rules that determines how it acts based on multiple inputs outlined in a truth table. Combining 10s, 1000s or millions of logic gates makes it possible for a computer to perform highly complex operations and tasks at ever increasing speeds. \\

		\item A gate is a basic electronic circuit which operates on one or more signals to produce an output signal.

		\item Logic gates are digital circuits constructed from diodes, transistors, and resistors connected in such a way that the circuit output is the result of a basic logic operation \color{green}(OR, AND, NOT) \color{black}performed on the inputs. \\

		\item Fundamental gates are \color{red}AND, OR \color{black}and \color{red}NOT \\
		\begin{center}
			\includegraphics{pic3}
		\end{center}

		\begin{center}
	    \includegraphics{pic3.1}
        \end{center}

		\begin{center}
		\includegraphics{pic3.2}
		\end{center}

		\color{black}Derived Gates are \color{red}NAND, NOR, XOR \color{black}and \color{red}XNOR \color{black}(derived from the fundamental gates).

		Universal Gates are \color{red}NAND \color{black} and \color{red}NOR \color{black}gates (the fundamental logic gates can be realized through them).

	\end{itemize}
\section{LOGIC GATES}

\subsection{AND}
The expression C = A X B reads as “C equals A AND B“
The multiplication sign (X) stands for the AND operation, same for ordinary multiplication of 1s and 0s.\\
\begin{center}
	\includegraphics{pic4}
\end{center}

The AND operation produces a true output (result of 1) only for the single case when all of the input variables are 1 and a false output (result of 0) where one or more inputs are 0. \\
\begin{table}[h!]
	\begin{center}
		\begin{tabular}{c|c|c}
			\textbf{A} & \textbf{B} &
			\textbf{C = A x B}\\
			\hline
			\cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1\\
			\hline
			\cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0\\
			\hline
			\cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0\\
			\hline
			\cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0\\
			\hline
		\end{tabular}
	\end{center}
\end{table} \\
\begin{center}
	\includegraphics{pic6}
\end{center}

\subsection{OR}
The expression C = A + B reads as “C equals A OR B". It is the inclusive “OR”
The Addition (+) sign stands for the OR operation. \\
\begin{center}\includegraphics{7}\end{center}

The OR operation produces a true output (result of 1) when any of the input variable is 1 and a false output (result of 0) only when all the input variables are 0. \\
\begin{table}[h!]
	\begin{center}
		\begin{tabular}{c|c|c}
			\textbf{A} & \textbf{B} &
			\textbf{C = A + B}\\
			\hline
			\cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1\\
			\hline
			\cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1\\
			\hline
			\cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1\\
			\hline
			\cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0\\
			\hline
		\end{tabular}
	\end{center}
\end{table} \\
\begin{center}
	\includegraphics{9}
\end{center}

\subsection{NOT}
The NOT gate is called a logical inverter. \\
It has only one input. It reverses the original input (A) to give an inverted output C. \\

\color{red}C = NOT A or C = \\ \color{black}
\begin{center}
	\includegraphics{10}
\end{center}
\begin{table}[h!]
	\begin{center}
		\begin{tabular}{c|c}
			\textbf{A} &
			\textbf{C = $\overline{A}$}\\
			\hline
			\cellcolor{blue!20}1 & \cellcolor{blue!20}0 \\
			\hline
			\cellcolor{blue!30}0 & \cellcolor{blue!30}1 \\
			\hline
		\end{tabular}
	\end{center}
\end{table}
\begin{center}
	\includegraphics{12}
\end{center}

\subsection{NOR}
The NOR (NOT OR) gate circuit is an inverter OR gate. \\

Reads as C = NOT of A or B \\

C = \begin{center}
	\includegraphics{13}
\end{center}

The NOR Gate gives a true output (result of 1) only when both inputs are false (0) \\
\begin{table}[h!]
	\begin{center}
		\begin{tabular}{c|c|c|c}
			\textbf{A} & \textbf{B} &
			\textbf{A + B} & \textbf{C = $\overline{A + B}$}\\
			\hline
			\cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 \\
			\hline
			\cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1 & \cellcolor{blue!30}0 \\
			\hline
			\cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0\\
			\hline
			\cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1\\
			\hline
		\end{tabular}
	\end{center}
\end{table} \\

The NOR Gate is a universal gate because it can be used to form any other kind of gate. \\
\begin{center}
	\includegraphics{15}
\end{center}

\subsection{NAND}
The NAND (NOT AND) Gate is an inverted AND Gate \\
C = \begin{center}
	\includegraphics{16}
\end{center}
\color{red}Reads as C = NOT of A AND B \\ \color{black}

The NAND Gate gives a false output (result of 0) only when both inputs are true (1) \\

\begin{table}[h!]
	\begin{center}
		\begin{tabular}{c|c|c|c}
			\textbf{A} & \textbf{B} &
			\textbf{A . B} & \textbf{C = $\overline{A . B}$}\\
			\hline
			\cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0\\
			\hline
			\cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1\\
			\hline
			\cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 & \cellcolor{blue!20}1\\
			\hline
			\cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1\\
			\hline
		\end{tabular}
	\end{center}
\end{table}

\color{red}The NAND Gate is a universal gate because it can be used to form any other kind of gate. \\ \color{black}
\begin{center}
	\includegraphics{18}
\end{center}

\subsection{XOR}
An XOR (exclusive OR) gate acts in the same way as the exclusive OR logical connector. \\
It gives a true output (result of 1) if one, and only one, of the inputs to the gate is true (1), i.e either or but not both \\
\color{red}$\\ c = \overline{A}.B + \overline{B}.A$ \\ \color{black}
\begin{center}
	\includegraphics{19}
\end{center}
\begin{table}[h!]
	\begin{center}
		\begin{tabular}{c|c|c|c|c|c|c}
			\textbf{A} & \textbf{B} & \textbf{$\overline{A}$} & \textbf{$\overline{B}$} & \textbf{$\overline{A}$ . B} & \textbf{$\overline{B}$ . A} & \textbf{$\overline{A}$ . B} + \textbf{$\overline{B}$ . A}\\
			\hline
			\cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0\\
			\hline
			\cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1 & \cellcolor{blue!30}1\\
			\hline
			\cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 & \cellcolor{blue!20}1\\
			\hline
			\cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1 & \cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0\\
			\hline
		\end{tabular}
	\end{center}
\end{table}
\color{red}It uses a combination of three basic gates – AND, OR and NOT. \\ \color{black}

\subsection{XNOR}
The XNOR (exclusive - NOR) gate is a combination XOR gate followed by an inverter. \\
 It is represented by the \color{red} c = $\overline{A.B} + \overline{B.A}$  \\ \color{black} \\
\begin{center}
	\includegraphics{21}
\end{center}
Its gives a  true output (1), if the inputs are the same, and a false output (0) if the inputs are different. \\
\begin{table}[h!]
	\begin{center}
		\begin{tabular}{c|c|c|c|c|c|c|c}
			\textbf{A} & \textbf{B} & \textbf{$\overline{A}$} & \textbf{$\overline{B}$} & \textbf{$\overline{A}$ . B} & \textbf{$\overline{B}$ . A} & \textbf{A} + \textbf{B} & \textbf{$\overline{A + B}$}\\
			\hline
			\cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0 & \cellcolor{blue!20}0 & \cellcolor{blue!20}1\\
			\hline
			\cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1 & \cellcolor{blue!30}1 & \cellcolor{blue!30}0\\
			\hline
			\cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0 & \cellcolor{blue!20}1 & \cellcolor{blue!20}0\\
			\hline
			\cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1 & \cellcolor{blue!30}1 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}0 & \cellcolor{blue!30}1\\
			\hline
		\end{tabular}
	\end{center}
\end{table} \\

\subsection{Logic Gates and their Truth Tables}
\includegraphics{23}

\section{SUMMARY}
\begin{itemize}
	\item Using different combination of logic gates, complex operations can be performed.
	\item With the Universal logic gates - NAND and NOR, any other gate can be built
	\item There is no limit to the number of gates that can be arranged together in a single device.
	\item However, in practice, there is a limit to the number of gates that can be packed into a given physical space.
	\item Arrays of logic gates are found in digital integrated circuits.
	\item The logic gates are abstract representations of real electronic circuits
	\item In computers, Logic gates are built using transistors combined with other electrical components like resistors and diodes.
	\item These electrical components are wired together in order to transform a particular input to give a desired output. \cite{108}
\end{itemize}

\section{QUIZ}

\begin{itemize}

	\item What is the output of an AND gate if the inputs are 1 and 0?
	\item Explain the difference between the AND gate and the OR gate.
	\item What is the output of a NOT gate if the inputs is 0?
	\item Which logic gate is this?
	\item Which gate is also known
	a logical converter?

\end{itemize}

\centering\includegraphics{24}

\newpage
\bibliographystyle{ieeetr}
\bibliography{gbib}
\end{document}


\documentclass[]{article}
\usepackage{graphicx}
\usepackage{caption}
\graphicspath{ {./images/} }

% Minted
\usepackage[cache=false]{minted}
	\usemintedstyle{vs}
	\usepackage{xcolor}
		\definecolor{light-gray}{gray}{0.97}

\usepackage{amsmath}
\usepackage{enumitem}
\usepackage{hyperref}
\usepackage{comment}

\title{Data Mining: Exercise 5-1}
\author{Brandon Hosley}
\date{\today}

\begin{document}
\maketitle

\section*{Assignment 1: Read and summarize an article about the k-means algorithm and the parameter K.}
\href{https://towardsdatascience.com/how-does-k-means-clustering-in-machine-learning-work-fdaaaf5acfa0}{Article linked here.}

K-Nearest Neighbors is a method of machine learning in which new samples are categorized based on a survey of their closest $K$ neighbors. By closest we mean in terms of differences in values of features. The article describes how this is done with simpling bagging.

The article does not mention that performance of a model can be improved if the features are re-weighted proportionally to their importance as a predictor. Because we don't often know how exactly what this ratio should be it is common practice to normalize all of the features which functionally treats them equally. This works by eliminating the range or scale of the features values from disproportionately weighing into the results when calculating distance.

The article demonstrates balancing the bags for three classes of one dimensional data, calculating the mean of the existing points to allow for faster classification of future variables.

The article shows single dimensional classification but does not describe methods for generating prototypes or models in multiple dimensions.

\section*{Assignment 2: Redo your exercise with ‘K = 3’ and explain the changes in detail.}

\begin{minted}[breaklines,bgcolor=light-gray]{shell-session}
from pyspark.ml.clustering import KMeans
from pyspark.ml.evaluation import ClusteringEvaluator
data = spark.read.format("libsvm").load("/user/data/CSC533DM/ sample_kmeans_data.txt")
data.show(truncate=False)
\end{minted}

\begin{minted}[breaklines,bgcolor=light-gray]{shell-session}
kmeans = KMeans().setK(3).setSeed(1)
model = kmeans.fit(data)

predictions = model.transform(data)
predictions.show(truncate=False)
\end{minted}
\includegraphics[width=\linewidth]{image1.1}

Each of the first five results is different. It is possible that the $k=2$ model is overfit to local features.

\begin{minted}[breaklines,bgcolor=light-gray]{shell-session}
evaluator = ClusteringEvaluator()
silhouette = evaluator.evaluate(predictions)
print("Silhouette with squared euclidean distance = " + str(silhouette))
\end{minted}
\includegraphics[width=\linewidth]{image1.2}

The decreased silhouette score suggests that more of the points in the clusters are closer to their decision boundaries.

\begin{minted}[breaklines,bgcolor=light-gray]{shell-session}
centers = model.clusterCenters()
print("Cluster Centers: ")
for center in centers: print(center)
\end{minted}
\includegraphics[width=\linewidth]{image1.3}

One Cluster remains centered in the same spot, the original other cluster is cut in half.

\section*{Assignment 3: Try various K and find best K. Explain why it is best based on your results (in detail).}

\vspace{-0.75em}
\begin{minted}[breaklines,bgcolor=light-gray]{shell-session}
kmeans = KMeans().setK(4).setSeed(1)
model = kmeans.fit(data)

predictions = model.transform(data)
predictions.show(truncate=False)

evaluator = ClusteringEvaluator()
silhouette = evaluator.evaluate(predictions)
print("Silhouette with squared euclidean distance = " + str(silhouette))

centers = model.clusterCenters()
print("Cluster Centers: ")
for center in centers: print(center)
\end{minted}
\includegraphics[width=\linewidth]{image2}

Between $k=4$ had the best results between 2 and 5. 6 had a silhouette of 1.0 as each point comprised its own bucket due to the low sample size.
The difference in silhouette score between 2 and 4 is not very large so it is likely that either may be chosen for whatever fits the use-case best.

\end{document}

\begin{minted}[breaklines,bgcolor=light-gray,fontsize=\footnotesize]{shell-session}
\end{minted}
\includegraphics[width=\linewidth]{image1}


\documentclass[12pt]{article}

\usepackage[utf8]{inputenc}
\usepackage{latexsym,amsfonts,amssymb,amsthm,amsmath}
\usepackage {tikz}
\usetikzlibrary {positioning}

\setlength{\parindent}{0in}
\setlength{\oddsidemargin}{0in}
\setlength{\textwidth}{6.5in}
\setlength{\textheight}{8.8in}
\setlength{\topmargin}{0in}
\setlength{\headheight}{18pt}

\definecolor {processblue}{cmyk}{0.96,0,0,0}

\title{Graph Theory - Homework 3}
\author{Kishlaya Jaiswal}

\begin{document}

\maketitle

\vspace{0.5in}

\subsection*{Exercise 1}
\begin{proof}.

\textbf{(a)} Since, $|T-e+e'| = |T| = |V|-1$, it suffices to show that the induced subgraph on $T-e+e'$ is connected for some $e' \in T'-T$. If $e=(x,y)$, then it suffices to show that there is a path between $x \rightsquigarrow y$ in $T-e+e'$.

Consider $T \setminus \{e\}$. It has two connected components $X, Y$ such that $X \sqcup Y = V(T)$ and $x \in X, y \in Y$. Now since $X \sqcup Y = V(T')$, there are vertices $x' \in X, y' \in Y$ such that $e' = (x',y') \in T' - T$. Thus, $x \rightsquigarrow x' \xrightarrow{e'} y' \rightsquigarrow y$ is a path between $x,y$ in $T-e+e'$.
\newline

\textbf{(b)} Since, $|T'+e-e'| = |T'| = |V|-1$, it suffices to show that the induced subgraph on $T'+e-e'$ has no cycles for some $e' \in T'-T$.

Consider $T'+e$. It contains a cycle $C$ passing through the edge $e=(x,y)$. Let $e' \in T'-T$ be any other edge on this cycle $C$. We claim that $T'+e-e'$ has no cycles. For the sake of contradiction, suppose it has a cycle $C'$. If $e \not \in C'$ then $C' \subseteq T'$ which is a contradiction to $T'$ being a tree. Otherwise if $e \in C'$, then consider the path $C' \setminus \{e\}$ between $x,y$ in $T'$. But then $C \setminus \{e\}$ is also a path between $x,y$ in $T'$, which is clearly different from $C' \setminus \{e\}$ as $e' \in C$ but $e' \not \in C'$. But a tree has a unique path between any two vertices.
\end{proof}

\subsection*{Exercise 2}
\begin{proof}
We use Kirchoff's theorem which says that number of spanning trees of a connected graph $G$ is given by:
$$t(G) = \frac{1}{n}\lambda_1 \lambda_2 \ldots \lambda_{n-1}$$
where $\lambda_i$ are the non-zero eigenvalues of laplacian $L(G)$.

We have $G = K_{m,n}$, $L(G) = D(G) - A(G)$
$$L(G) = \begin{pmatrix}
nI & -J \\
-J & mI \\
\end{pmatrix}$$

Let $v = (v_1 \ldots v_m, u_1 \ldots u_n)^T$, then $L(G)v = \lambda v$ gives us following two equations:
$$(n-\lambda)v_i = \sum u_j$$
$$(m-\lambda)u_j = \sum v_i$$.

\textbf{Case 1:} $\lambda = n$. $u_1 = u_2 = \ldots u_n = 0$ and $\sum v_i = 0$. Hence $v = (v_1 \ldots v_m, 0 \ldots 0)^T$ is an eigenvector with eigenvalue $n$. This gives us that $\lambda = n$ has an eigenspace of dimension $m-1$.

\textbf{Case 2:} $\lambda = m$. $v_1 = v_2 = \ldots v_m = 0$ and $\sum v_j = 0$. Hence $v = (0 \ldots 0, u_1 \ldots u_n)^T$ is an eigenvector with eigenvalue $m$. This gives us that $\lambda = m$ has an eigenspace of dimension $n-1$.

\textbf{Case 3:} $\lambda \neq m,n$ Then we have $v_1 = v_2 = \ldots = v_m$ and $u_1 = u_2 = \ldots = u_n$. Thus $$u_1 = \frac{mv_1}{m-\lambda}; v_1 = \frac{nu_1}{n-\lambda} = \left(\frac{n}{n-\lambda}\right)\left(\frac{mv_1}{m-\lambda}\right)$$
If $v_1 = 0 \implies v_i = u_j = 0$. Hence $$\left(\frac{n}{n-\lambda}\right)\left(\frac{m}{m-\lambda}\right) = 1 \implies \lambda = 0, m+n$$

(Observation: Case 3 was unnecessary as we know $\sum \lambda = 2mn$ and from the first two cases we already have that $n(m-1) + m(n-1) = 2mn - (m+n)$, so the last eigenvalue has to be $m+n$)

Finally, $$t(G) = \frac{1}{m+n}n^{m-1}m^{n-1}(m+n) = n^{m-1}m^{n-1}$$
\end{proof}

\vspace{2in} %Leave more space for comments!

\end{document}


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

\begin{abstract}
    We introduce the main statistical methods needed to study cosmological non-Gaussianities: correlation functions, the power spectrum, spatial filtering.
    Then, we introduce the Euclidean path integral formalism and discuss how it can be applied in cosmology.
    Finally, we draw a parallel to the path integral used in Quantum theory.
\end{abstract}

\section{Introduction}

The Large Scale Structure of the cosmos formed as a result of gravitational clustering, starting from ``seed'' inhomogeneities in the density field in the early universe.
The generation of these perturbations is commonly thought to have been the result of quantum fluctuations in the early universe, which have reached galactic scales in the inflationary stage of the expansion.

These perturbations may be considered as pertaining to the gravitational field \(\Phi \) or to the density field \(\rho \): the former approach has shown itself to be more fruitful in recent years.

A model which so far has not been contradicted by observation is to consider perturbations as being a realization of a Gaussian random field.
Even if the field were not truly Gaussian, we would expect the Gaussian approximation to be a rather good one as it happens generally for processes which arise from the combined effects of many independent random variables \cite[pag.\ 2]{celoriaPrimordialNonGaussianity2018}.

However, the study of non-Gaussianities in the primordial universe is crucial. Inflationary models commonly predict a nearly-Gaussian perturbation field, and the deviations from Gaussianity can aid us in the effort to determine which one best fits the data.

It is common to model an almost-Gaussian field with something similar to a Taylor expansion \cite[eq.\ 1]{matarreseAbundanceHighRedshift2000}, \cite[eq.\ 1]{celoriaPrimordialNonGaussianity2018} in the Gaussian field \(\varphi _L\):
%
\begin{align} \label{eq:perturbed-gaussian-field}
\Phi = \varphi _L + f_{NL} \qty(\varphi _L^2 + \expval{\varphi _L^2}) + g_{NL} \qty(\varphi _L^3 - \expval{\varphi _L^2} \varphi _L) + \order{\varphi _L^{4}}
\,.
\end{align}

From the most recent Planck mission data, which measured the non-Gaussianity by looking at the Cosmic Microwave Background temperature and polarization anisotropies' correlations, the parameters \(f_{NL}\) and \(g_{NL}\) are both compatible with zero \cite[]{planckcollaborationPlanck2018Results2019}.\footnote{The parameter \(f_{{NL}}\) is divided into different contributions, corresponding to different geometric configurations in Fourier space. We shall not go into details here, but they are independently compatible with zero.}

Non-Gaussianities may have a large impact on structure formation, since the over-densities which cluster into cosmic structures are heavily dependent on the \emph{tails} of the density perturbation distribution: for example, if \(\varphi \) is Gaussian then its tails decay like \(\exp(- \varphi^2)\), while \(\varphi^2\) is chi-square distributed (with one degree of freedom), so its tails decay like \(\exp(- \varphi )\).

Therefore, even a small amount of non-Gaussianity may affect structure formation significantly (boosting it or damping it depending on the sign of \(f_{NL}\)).

% \subsection{Path integrals}

Modelling the initial conditions for structure formation for a general non-Gaussian field is tricky, and the formalism which is best suited for the task is that of functional integration (the Path Integral): an integral over an infinite-dimensional space

% It allows us to generate \emph{constrained} realizations of the field, which are especially useful if we wish to study the tails of the distribution, which are naturally connected to rare occurrences.

% In section \ref{sec:statistical-methods} we will review a few topics in the statistical methods used in cosmology.

% In section \ref{sec:path-integral} we will describe this formalism in detail from first principles, discussing its connection to the path integral used in Quantum Field Theory, the way to compute correlation functions, the use of spatial filters, and the saddle-point approximation.

% In section \ref{sec:applications} we will discuss the applications of these techniques to structure formation.

\end{document}


\documentclass[fontsize=11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=0.75in]{geometry}

\title{CSC110 Fall 2021 Assignment 1: Written Questions}
\author{Azalea (Yijie Gui)}
\date{\today}

\begin{document}
    \maketitle

    \section*{Part 1: Data and Comprehensions}

    \begin{enumerate}
        \item[1.] \textbf{Imagine this scenario...}
        \begin{enumerate}
            \item[(a)]
            Your team-mate's to-do notes can be represented using a \texttt{List[str]} because it needs to be ordered by priority, and since lists are ordered, they're perfect for that.

            \item[(b)]
            The number of points played in the table tennis game can be represented using a \texttt{List[int]}. When "you" score, add 1 to \texttt{list[0]}, and when the other player scores, add 1 to \texttt{list[1]}.

            \item[(c)]
            The unique types of fruits can be represented with a \texttt{Set[str]}, since it doesn't need to be ordered while it needs to be unique.

            \item[(d)]
            Whether or not you won the game can be represented using a \texttt{bool}, because it's either True and you won the game, or False that you didn't win the game.

            \item[(e)]
            A record of who won each point in the game can be represented using a \texttt{List[bool]} since there are only two sides. When "you" score, add a True to the list, and when the other side scores, add a False. Since lists are ordered, the order of each player's scoring is also stored.

        \end{enumerate}

        \item[2.] \textbf{Exploring comprehensions.}

        \begin{enumerate}
            \item[(a)]
            \begin{enumerate}
                \item[i.] \texttt{[c for c in 'Hello David']} evaluates to a list of every character in 'Hello David'.

                (\texttt{['H', 'e', 'l', 'l', 'o', ' ', 'D', 'a', 'v', 'i', 'd']})
                \item[ii.] The result's data type is \texttt{List[str]}
            \end{enumerate}
            \item[(b)]
            \begin{enumerate}
                \item[i.] \texttt{\{c for c in 'Hello David'\}} evaluates to a set of every unique character in 'Hello David'.

                (\texttt{\{' ', 'D', 'H', 'a', 'd', 'e', 'i', 'l', 'o', 'v'\}})
                \item[ii.] The value's data type is \texttt{Set[str]}
                \item[iii.] This set has a smaller size than the list in part (a) because it automatically removed duplicates. It also doesn't preserve the order of the characters.
            \end{enumerate}
            \item[(c)]
            The result of \texttt{[(c in vowels) for c in 'Hello world']} represents a list of bools, and each bool tells you whether or not the character in 'Hello world' at that index is a vowel.
            \item[(d)]
            The first \texttt{in} is an operator that produces a bool value of whether a collection contains a specific value. The second \texttt{in} is a part of the comprehension, representing the collection that \texttt{c} will iterate through.
        \end{enumerate}
    \end{enumerate}

    \section*{Part 2: Programming Exercises}

    Complete this part in the provided \texttt{a1\_part2.py} starter file.
    Do \textbf{not} include your solution in this file.

    \section*{Part 3: Pytest Debugging Exercise}

% TIP: In LaTeX, the underscore (_) is a special character, so if you want to use it
% in normal text, you have to put a backslash in front of it. E.g., a1\_part2.py,
% not a1_part2.py.

    \begin{enumerate}
        \item[1.]
        \texttt{test\_section\_average\_all\_grades\_equal} passed.

        \texttt{test\_class\_average\_no\_grades\_equal} and \texttt{test\_class\_average\_many\_students} failed.

        \item[2.]
        \begin{enumerate}
            \item[i.] For \texttt{test\_class\_average\_no\_grades\_equal}, \texttt{sorted\_grades} is actually a list of strings and not floats. So it throws an error when string values are multiplied by a float.
            \item[ii.] For \texttt{test\_class\_average\_many\_students}, the calculation in \texttt{student\_average} is incorrect: the \texttt{sorted()} function sorts in ascending order, but the weights are in the descending order.
        \end{enumerate}

        \item[3.]
        \texttt{test\_section\_average\_all\_grades\_equal} passed because it tests a scenario where every student has three equal grades, which means that the order of the sort function is irrelevant.
    \end{enumerate}

    \section*{Part 4: Adding Noise to an Image}

    Complete this part in the provided \texttt{a1\_part4.py} starter file.
    Do \textbf{not} include your solution in this file.

    \newpage

    \section*{Part 5: Removing Noise From an Image}

    \subsection*{Implementation}

    Complete this part in the provided \texttt{a1\_part5.py} starter file.
    Do \textbf{not} include your solution in this file.

    \subsection*{Exploration}

    \begin{enumerate}
        \item[1.] Yes, the median filter does affect images that are not noisy. The resulting image looks blurred compared to the original, and a lot of details are lost.
        \item[2.] Since the probability that some pixel will be salt/pepper is $\frac{1}{k+1}$, the image becomes increasingly unrecognizable as k decrease. When k is 0, the median filter can do nothing to restore the image, because the image is already overwritten with salt/pepper, and running a median filter would still produce an all-white or all-black image.
        \item[3.] The mean filter would be worse at eliminating noise because the averaged color pixel isn't a real pixel in the image, and it most likely wouldn't connect to any of its neighbors. Also, it would be especially worse at eliminating white/black noise because there might be neighbors that are white/black, and these are extreme values (0 or 255) that are considered outliers in a list of neighboring real color values, and the existence of outliers affect averages much more than medians.
    \end{enumerate}

\end{document}


\subsection{Concept Questions} % (fold)
\label{sub:concept_questions_data}

Read over the concepts in this chapter and answer the following questions:
\begin{enumerate}
  \item What is a \nameref{sub:variable}?
  \item What is the relationship between a variable and a value?
  \item What is the relationship between a variable and a type?
  \item Where can you use variables? Think both reading the value, and storing a new value.
  \item What does it mean if a variable appears on the right hand side of an assignment? What will happen to this variable when the code is run?
  \item What does it mean if a variable appears on the left hand side of an assignment? What will happen to this variable when the code is run?
  \item What is a \nameref{sub:constant}? How does it differ from a variable?
  \item What is a local variable? What code can access the value in a local variable?
  \item What is a global variable? What code can access the value in a global variable?
  \item Why is it considered good practice to use local variable, but not global variables?
  \item How do parameters help make procedures more powerful?
  \item What are the two parameter passing mechanisms for passing parameters? How are they different?
  \item When would you use each of the parameter passing mechanisms? For what kind of parameters?
  \item How does the Terminal input procedure store a value in the variable you pass to it? What kind of parameter passing is involved here?
  \item What statement was introduced in this chapter?
  \item What does this statement allow you to do?
  \item What is a function? How does it differ from a procedure?
  \item A procedure call is a statement. What is a function call? Why is this different?
  \item What does it mean when you say a function returns a value?
  \item What are the values of the following expressions?

  \begin{table}[h]
    \centering
    \begin{tabular}{|c|l|l|}
      \hline
      \textbf{Question} & \textbf{Expression} & \textbf{Given} \\
      \hline
      (a) & \texttt{5} & \\
      \hline
      (b) & \texttt{a} & \texttt{a} is 2.5 \\
      \hline
      (c) & \texttt{1 + 2 * 3} & \\
      \hline
      (d) & \texttt{a + b} & \texttt{a} is 1 and \texttt{b} is 2 \\
      \hline
      (e) & \texttt{2 * a} & \texttt{a} is 3 \\
      \hline
      (f) & \texttt{a * 2 + b} & \texttt{a} is 1.5 and \texttt{b} is 2\\
      \hline
      (g) & \texttt{a + 2 * b} & \texttt{a} is 1.5 and \texttt{b} is 2 \\
      \hline
      (h) & \texttt{(a + b) * c} & \texttt{a} is 1, b is 1 and \texttt{c} is 5 \\
      \hline
      (i) & \texttt{a + b * 2} & \texttt{a} is 1.0 and \texttt{b} is 2\\
      \hline
    \end{tabular}
  \end{table}

  \clearpage

  \item When creating a program, types allow you to reason about the kind of data the program is using.  The three most basic types of data are Double, Integer and String. Use the Double\footnote{Computer programming languages often use floating point values to represent real numbers. This format stores an approximation for a large range of values. You need to keep this in mind when thinking about the kind of data you will use.} data type to represent any real numeric value; such as 1, 2.5, -75.201 etc. The Integer data type is used to represent any whole numeric value; such as 1, 0, -27 etc. Use the String data type for any textual data. There are many other data types, but these three are the most frequently used.

When assigning a data type think about the following:
\begin{itemize}
  \item How will the data be used?
  \item The range of values expected. Does the type have a sufficient range to cover this?
  \item Is precision important? Think carefully, especially with fractional values represented as floating point numbers (i.e. Double).
\end{itemize}
  What data type is most appropriate to store the following?
  \begin{multicols}{2}
    \begin{enumerate}
      \item A person’s name
      \item The number of students in a class
      \item The average age of a group of people
      \item A temperature in Celsius
      \item The name of a subject
      \item The runs scored in a cricket match
      \item A student’s ID number
      \item The distance between planets (km)
      \item A person’s phone number
      \item The cost of an item
    \end{enumerate}
  \end{multicols}
\end{enumerate}
% subsection concept_questions (end)

\clearpage
\subsection{Code Writing Questions: Applying what you have learnt} % (fold)
\label{sub:code_writing_questions_applying_what_you_have_learnt_data}

Apply what you have learnt to the following tasks:
\begin{enumerate}
  \item Take the times table program from \sref{sub:times_table} and re-implement it so that there are two procedures: \texttt{Print Times Table}, and \texttt{Print Times Table Line}. Use these to print the 42, 73, and 126 times tables, as well as printing a times table the user requests.
  \begin{itemize}
    \item The \texttt{Print Times Table Line} procedure will take two parameters. The first will be the number, the second will be the times. This will output a single line for the table, e.g. ` 1 x 73 = 73'.
    \item The \texttt{Print Times Table} procedure will have a single parameter called \texttt{number}. It will output a header for the table, and then call \texttt{Print Times Table Line} ten times. In each call it will pass 1, 2, 3, etc. for the times parameter, and pass across its \texttt{number} value to the \texttt{number} parameter. After printing the last line it will output a footer for the table.
  \end{itemize}
  \item Correct and then implement the Trapezoid Area procedure from \sref{sub:hand_execution_with_variables}. Adjust the implementation to call a \texttt{Trapezoid Area} function that is passed the two base values and the height, and returns the area. Create a small program to test this procedure.
  \item Implement the Change Calculation program, and test it function as you expect.
  \item Revisit your Circle Dimensions program from \cref{cha:program_creation} and adjust its implementation to make use of functions and procedures.
  \item Design the structure and then the code for a program that converts temperatures from Celsius to Fahrenheit. This should read the value to convert from the user, and output the results to the Terminal.
  \item Take the adjusted Face Shape program from \cref{cha:procedure_declaration}, and re-implement it so that the \texttt{Draw Face} procedure takes in an x and y coordinate for the location where the face will be drawn. Adjust the coordinates of the face's components in \texttt{Draw Face}, by the amounts in the \texttt{x} and \texttt{y} parameters. Use your new procedure to draw three faces to the screen at different positions.
  \item Write a \texttt{Swap} procedure that takes in two integer parameters (passed by reference) and swaps their values. Write a program to test this procedure. This should work so that if you call \texttt{Swap(a, b);} that the values in the \texttt{a} and \texttt{b} variables are swapped over. You can test this by printing the values before and after the call to the \texttt{Swap} procedure.
  \item Watch \url{http://www.youtube.com/watch?v=y2R3FvS4xr4}, which clearly demonstrates the importance of being able to calculate the airspeed velocity of a swallow. This can be calculated using an equation based on the Strouhal Number, see \url{http://www.style.org/strouhalflight}. Use this information to create a program that can be used to calculate the airspeed velocity of African and European Swallows. Use the following values:
  \begin{itemize}
    \item Strouhal Number of 0.33
    \item African Swallow: frequency 15hz, amplitude 21cm
    \item European Swallow: frequency 14hz, amplitude 22cm
  \end{itemize}
\end{enumerate}
% subsection code_writing_questions_applying_what_you_have_learnt (end)

\clearpage
\subsection{Extension Questions} % (fold)
\label{sub:extension_questions_data}

If you want to further your knowledge in this area you can try to answer the following questions. The answers to these questions will require you to think harder, and possibly look at other sources of information.

\begin{enumerate}
  \item Write a small program to experiment with parameter passing. Create in this program a procedure called \texttt{Print It} that takes a integer parameter and prints it to the Terminal. Also create a  \textbf{Double It} procedure that takes an integer parameter passed by reference\footnote{If you are using C, you will need to do this with C++. With C++ your compiler is now g++, rather than gcc.} and has its value doubled in the procedure. Try the following (not all will work):
  \begin{enumerate}
    \item Call \texttt{Print It}, passing in a literal value like \texttt{5}.
    \item Call \texttt{Double It}, passing in a literal value like \texttt{5}.
    \item Call \texttt{Print It}, passing in a calculated expression like \texttt{a + b}.
    \item Call \texttt{Double It}, passing in a calculated expression like \texttt{a + b}.
    \item Call \texttt{Print It}, passing in a variable's value.
    \item Call \texttt{Double It}, passing in a variable's value.
  \end{enumerate}
  \item Further adjust your Face Drawing program so that the caller can pass in a custom color, width, and height for the face.
  \item Adjust the bike race example from \sref{sub:bicycle_race} so that the racers have a rolling start. Each bike will then have a different initial speed, calculated as a random value. You will need to define a maximum starting speed, and recalculate the x scale factor to ensure that the bikes are all drawn to the screen.
\end{enumerate}

% subsection extension_questions (end)


%%
%% Automatically generated file from DocOnce source
%% (https://github.com/doconce/doconce/)
%% doconce format latex hw4.do.txt --minted_latex_style=trac --latex_admon=paragraph --no_mako
%%

%-------------------- begin preamble ----------------------

\documentclass[%
oneside,                 % oneside: electronic viewing, twoside: printing
final,                   % draft: marks overfull hboxes, figures with paths
10pt]{article}

\listfiles               %  print all files needed to compile this document

\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}
\usepackage[table]{xcolor}
\usepackage{bm,ltablex,microtype}

\usepackage[pdftex]{graphicx}

\usepackage[T1]{fontenc}
%\usepackage[latin1]{inputenc}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}

\usepackage{lmodern}         % Latin Modern fonts derived from Computer Modern

% Hyperlinks in PDF:
\definecolor{linkcolor}{rgb}{0,0,0.4}
\usepackage{hyperref}
\hypersetup{
    breaklinks=true,
    colorlinks=true,
    linkcolor=linkcolor,
    urlcolor=linkcolor,
    citecolor=black,
    filecolor=black,
    %filecolor=blue,
    pdfmenubar=true,
    pdftoolbar=true,
    bookmarksdepth=3   % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC
    }
%\hyperbaseurl{}   % hyperlinks are relative to this root

\setcounter{tocdepth}{2}  % levels in table of contents

% prevent orhpans and widows
\clubpenalty = 10000
\widowpenalty = 10000

% --- end of standard preamble for documents ---

% insert custom LaTeX commands...

\raggedbottom
\makeindex
\usepackage[totoc]{idxlayout}   % for index in the toc
\usepackage[nottoc]{tocbibind}  % for references/bibliography in the toc

%-------------------- end preamble ----------------------

\begin{document}

% matching end for #ifdef PREAMBLE

\newcommand{\exercisesection}[1]{\subsection*{#1}}

% ------------------- main content ----------------------

% ----------------- title -------------------------

\thispagestyle{empty}

\begin{center}
{\LARGE\bf
\begin{spacing}{1.25}
PHY321: Classical Mechanics 1
\end{spacing}
}
\end{center}

% ----------------- author(s) -------------------------

\begin{center}
{\bf Homework 4, due Friday  February 11${}^{}$} \\ [0mm]
\end{center}

\begin{center}
% List of all institutions:
\end{center}

% ----------------- end author(s) -------------------------

% --- begin date ---
\begin{center}
Feb 7, 2022
\end{center}
% --- end date ---

\vspace{1cm}

\paragraph{Practicalities about  homeworks and projects.}
\begin{enumerate}
\item You can work in groups (optimal groups are often 2-3 people) or by yourself. If you work as a group you can hand in one answer only if you wish. \textbf{Remember to write your name(s)}!

\item Homeworks are available ten days before the deadline.

\item How do I(we)  hand in?  You can hand in the paper and pencil exercises as a scanned document. For this homework this applies to exercises 1-5. Alternatively, you can hand in everyhting (if you are ok with typing mathematical formulae using say Latex) as a jupyter notebook at D2L. The numerical exercise(s) (exercise 6 here) should always be handed in as a jupyter notebook by the deadline at D2L.
\end{enumerate}

\noindent
\paragraph{Introduction to homework 4.}
This week's sets of classical pen and paper and computational
exercises deal with simple motion problems and conservation laws;
energy, momentum and angular momentum. These conservation laws are
central in Physics and understanding them properly lays the foundation
for understanding and analyzing more complicated physics problems.

The relevant reading background is
\begin{enumerate}
\item chapters 3, 4.1, 4.2 and 4.3 of Taylor (there are many good examples there) and

\item chapters 10-13 of Malthe-Sørenssen.

\item for the numerical exercise see Malthe-Sørenssen section 7.5
\end{enumerate}

\noindent
In both textbooks there are many nice worked out examples. Malthe-Sørenssen's text contains also several coding examples you may find useful.

The numerical homework focuses on another motion problem where you can
use the code you developed in homework 3, almost entirely. Please take
a look at the posted solution (jupyter-notebook) for homework 3. You
need only to change the forces at play. The numerical problem this time is based
on your code from homework 3 and we will try to make the motion of a falling object in two dimensions more realistic by allowing to bounce up again due to a normal force from the floor.

\paragraph{Exercise 1 (10 pt), Conservation laws, Energy and momentum.}
\begin{itemize}
\item 1a (2pt) How do we define a conservative force?

\item 1b (4pt) Use the work-energy theorem to show that energy is conserved with a conservative force.

\item 1c (4pt) Assume that you have only internal two-body forces acting on $N$ objects in an isolated system. The force from object $i$ on object $j$ is $\bm{F}_{ij}$. Show that the linear momentum is conserved.
\end{itemize}

\noindent
\paragraph{Exercise 2 (10 pt), Conservation of angular momentum.}
\begin{itemize}
\item 2a (2pt) Define angular momentum and the torque for a single object with external forces only.

\item 2b (4pt) Define angular momentum and the torque for a system with $N$ objects/particles  with external and internal forces. The force from object $i$ on object $j$ is $\bm{F}_{ij}$.

\item 2c (4pt) With internal forces only, what is the mathematical form of the forces that allows for angular momentum to be conserved?
\end{itemize}

\noindent
\paragraph{Exercise 3 (10pt), Example of potential.}
Consider a particle of mass $m$ moving according to the potential
\[
V(x,y,z)=A\exp\left\{-\frac{x^2+z^2}{2a^2}\right\}.
\]

\begin{itemize}
\item 3a (2pt) Is energy conserved? If so, why?

\item 3b (4pt) Which of  the quantities, $p_x,p_y,p_z$ are conserved?

\item 3c (4pt) Which of  the quantities, $L_x,L_y,L_z$ are conserved?
\end{itemize}

\noindent
\paragraph{Exercise 4 (15pt), Angular momentum case.}
At $t=0$ we have a single object with position $\bm{r}_0=x_0\bm{e}_x+y_0\bm{e}_y$.We add also a force in the $x$-direction at $t=0$. We assume that the object is at rest at $t=0$.
\[
\bm{F} = F\bm{e}_x.
\]

\begin{itemize}
\item 4a (5pt) Find the velocity and momentum at a given time $t$ by integrating over time with the above initial conditions.

\item 4b (5pt) Find also the position at a time $t$.

\item 4c (5pt) Use the position and the momentum to find the angular momentum and the torque. Is angular momentum conserved?
\end{itemize}

\noindent
\paragraph{Exercise 5 (15pt), forces  and potentials.}
A particle of mass $m$ has velocity $v=\alpha/x$, where $x$ is its displacement.

\begin{itemize}
\item 5a (5pt) Find the force $F(x)$ responsible for the motion.
\end{itemize}

\noindent
A particle is thereafter under the influence of a force $F=-kx+kx^3/\alpha^2$, where $k$ and $\alpha$ are constants and $k$ is positive.

\begin{itemize}
\item 5b (5pt) Determine the potential $U(x)$  and discuss the motion. It can be convenient here to make a sketch/plot of the potential as function of $x$.

\item 5c (5pt)  What happens when the energy of the particle is $E=(1/4)k\alpha^2$? Hint: what is the maximum value of the potential energy?
\end{itemize}

\noindent
\paragraph{Exercise 6 (40pt), Bouncing object.}
This exercise builds on the code you wrote for solving homework 3.
We recommend strongly that you study the text of Malthe-Sørenssen, section 7.5.

There we introduced gravity and air resistance and studied their
effects via a constant acceleration due to gravity and the force
arising from air resistance. But what happens when the ball hits the
floor? What if we would like to simulate the normal force from the
floor acting on the ball?  This exercise shows how we can include more
complicated forces with no pain! And the force we include here is an
example of a case where analytical solutions may either be difficult
to find or we cannot find an analytical solution at all.

We need then to include a force model for the normal force from the
floor on the ball. The simplest approach to such a system is to
introduce a contact force model represented by a spring model.  We
model the interaction between the floor and the ball as a single
spring. But the normal force is zero when there is no contact. Here we
define a simple model that allows us to include such effects in our
models.

The normal force from the floor on the ball is represented by a spring force. This
is a strong simplification of the actual deformation process occurring at the contact
between the ball and the floor due to the deformation of both the ball and the floor.

The deformed region corresponds roughly to the region of \textbf{overlap} between the
ball and the floor. The depth of this region is $\Delta y = R − y(t)$, where $R$
is the radius of the ball. This is supposed to represent the compression of the spring.
Our model for the normal force acting on the ball is then
\[
\bm{N} = −k (R − y(t)) \bm{e}_y.
\]
The normal force must act upward when $y < R$,
hence the sign must be negative.
However, we must also ensure that the normal force only acts when the ball is in
contact with the floor, otherwise the normal force is zero. The full formation of the
normal force is therefore
\[
\bm{N} = −k (R − y(t)) \bm{e}_y,
\]
when $y(t) < R$ and zero when $y(t) \le R$.
In the numerical calculations you can choose $R=0.1$ m and the spring constant $k=1000$ N/m.

\begin{itemize}
\item 6a (10pt) Identify the forces acting on the ball and set up a diagram with the forces acting on the ball. Find the acceleration of the falling ball now with the normal force as well.

\item 6b (30pt) Choose a large enough final time so you can study the ball bouncing up and down several times. Add the normal force and compute the height of the ball as function of time with and without air resistance. Comment your results.
\end{itemize}

\noindent
\paragraph{Classical Mechanics Extra Credit Assignment: Scientific Writing and attending Talks.}
The following gives you an opportunity to earn \textbf{five extra credit
points} on each of the remaining homeworks and \textbf{ten extra credit points}
on the midterms and finals.  This assignment also covers an aspect of
the scientific process that is not taught in most undergraduate
programs: scientific writing.  Writing scientific reports is how
scientist communicate their results to the rest of the field.  Knowing
how to assemble a well written scientific report will greatly benefit
you in you upper level classes, in graduate school, and in the work
place.

The full information on extra credits is found at \href{{https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/}}{\nolinkurl{https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/}}. There you will also find examples on how to write a scientific article.
Below you can also find a description on how to gain extra credits by attending scientific talks.

This assignment allows you to gain extra credit points by practicing
your scientific writing.  For each of the remaining homeworks you can
submit the specified section of a scientific report (written about the
numerical aspect of the homework) for five extra credit points on the
assignment.  For the two midterms and the final, submitting a full
scientific report covering the numerical analysis problem will be
worth ten extra points.  For credit the grader must be able to tell
that you put effort into the assignment (i.e.~well written, well
formatted, etc.).  If you are unfamiliar with writing scientific
reports, \href{{https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/IntroductionScientificWriting.md}}{see the information here}

The following table explains what aspect of a scientific report is due
with which homework.  You can submit the assignment in any format you
like, in the same document as your homework, or in a different one.
Remember to cite any external references you use and include a
reference list.  There are no length requirements, but make sure what
you turn in is complete and through.  If you have any questions,
please contact Julie Butler at butler@frib.msu.edu.

\begin{quote}
\begin{tabular}{ccc}
\hline
\multicolumn{1}{c}{ HW/Project } & \multicolumn{1}{c}{ Due Date } & \multicolumn{1}{c}{ Extra Credit Assignment } \\
\hline
HW 3                       & 2-8                        & Abstract                   \\
HW 4                       & 2-15                       & Introduction               \\
HW 5                       & 2-22                       & Methods                    \\
HW 6                       & 3-1                        & Results and Discussion     \\
\textbf{Midterm 1}         & \textbf{3-12}              & \emph{Full Written Report} \\
HW 7                       & 3-22                       & Abstract                   \\
HW 8                       & 3-29                       & Introduction               \\
HW 9                       & 4-5                        & Results and Discussion     \\
\textbf{Midterm 2|} _4-16_ & \emph{Full Written Report} \\
HW 10                      & 4-26                       & Abstract                   \\
\textbf{Final}             & \textbf{4-30}              & \emph{Full Written Report} \\
\hline
\end{tabular}
\end{quote}

\noindent
You can also gain extra credits if you attend scientific talks.
This is described here.

\paragraph{Integrating Classwork With Research.}
This opportunity will allow you to earn up to 5 extra credit points on a Homework per week. These points can push you above 100\% or help make up for missed exercises.
In order to earn all points you must:

\begin{enumerate}
\item Attend an MSU research talk (recommended research oriented Clubs is  provided below)

\item Summarize the talk using at least 150 words

\item Turn in the summary along with your Homework.
\end{enumerate}

\noindent
Approved talks:
Talks given by researchers through the following clubs:
\begin{itemize}
\item Research and Idea Sharing Enterprise (RAISE): Meets Wednesday Nights Society for Physics Students (SPS): Meets Monday Nights

\item Astronomy Club: Meets Monday Nights

\item Facility For Rare Isotope Beam (FRIB) Seminars: Occur multiple times a week
\end{itemize}

\noindent
If you have any questions please consult Jeremy Rebenstock, rebensto@msu.edu.

All the material on extra credits is at \href{{https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/}}{\nolinkurl{https://github.com/mhjensen/Physics321/blob/master/doc/Homeworks/ExtraCredits/}}.

% ------------------- end of main content ---------------

\end{document}


% !TeX program = pdfLaTeX
\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{graphicx,psfrag,epsf}
\usepackage{enumerate}
\usepackage{natbib}
\usepackage{textcomp}
\usepackage[hyphens]{url} % not crucial - just used below for the URL
\usepackage{hyperref}
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}

%\pdfminorversion=4
% NOTE: To produce blinded version, replace "0" with "1" below.
\newcommand{\blind}{1}

% DON'T change margins - should be 1 inch all around.
\addtolength{\oddsidemargin}{-.5in}%
\addtolength{\evensidemargin}{-.5in}%
\addtolength{\textwidth}{1in}%
\addtolength{\textheight}{1.3in}%
\addtolength{\topmargin}{-.8in}%

%% load any required packages here

\usepackage{setspace}\doublespacing

\begin{document}

\def\spacingset#1{\renewcommand{\baselinestretch}%
{#1}\small\normalsize} \spacingset{1}

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

\if0\blind
{
  \title{\bf Kaggle-in-class Data Challenges Can Boost Student Learning}

  \author{
        Julia Polak \\
    Department of Statistics, University of Melbourne\\
     and \\     Dianne Cook \\
    Department of Econometrics and Business Statistics, Monash University\\
      }
  \maketitle
} \fi

\if1\blind
{
  \bigskip
  \bigskip
  \bigskip
  \begin{center}
    {\LARGE\bf Kaggle-in-class Data Challenges Can Boost Student Learning}
  \end{center}
  \medskip
} \fi

\bigskip
\begin{abstract}
Kaggle is a data modeling competition service, where participants
compete to build a model with lower predictive error than other
participants. Several years ago they released a reduced service that
enables instructors to run competitions in a classroom setting. This
paper describes the results of an experiment to determine if
participating in a predictive modeling competition enhances learning.
The evidence suggests it does. In addition, students were surveyed to
examine if the competition improved engagement and interest in the
class.
\end{abstract}

\noindent%
{\it Keywords:} instructional technology, statistical modeling, data science, statistics education, data mining
\vfill

\newpage
\spacingset{1.45} % DON'T change the spacing!

\section{Introduction}\label{introduction}

Kaggle \citep{kaggle} is well-known for the data competitions, some
richly funded. It provides a platform for predictive modelling and
analytics competitions where participants compete to produce the best
predictive model for a given data set. In 2015, Kaggle InClass was
introduced, as a self-service platform to conduct competitions. These
competitions can be private, limited to members of a university course,
and are easy to setup. This paper examines the educational benefits of
conducting predictive modeling competitions in class on performance,
engagement and interest.

\section{Experimental setup}\label{experimental-setup}

\subsection{Data collection}\label{data-collection}

The experiment was conducted during Semester 2 2017. Data was collected
during two classes, one at the University of AB (MAST90083), and one at
CD University (ETC2420/5242).

\subsection{Competition data}\label{competition-data}

Two data sets were compiled for the kaggle challenges: Melbourne
property auction prices and spam classification. The Melbourne auction
price data was collected by extracting information from real estate
auction reports (pdf) collected between Feb 2, 2013 and Dec 17, 2016.
The spam classification data was compiled by graduate students at Iowa
State University as part of a data mining class, in 2009. Data was
compiled by monitoring and extracting information from their emails by
class members, over a period of a week, and manually tagging them as
spam or ham.

Both data sets were split into training and test sets, for the kaggle
challenge. Students had access to the true response variable only for
the training data. For the Melbourne housing data, students were
expected to predict price based on the property characteristics. For the
spam data, students were expected to build a classifier to predict
whether the email as spam or not.

Both data sets are challenging for prediction, with relatively high
error rates.

\subsection{Participants}\label{participants}

MAST90083 is titled Computational Statistics and Data Mining, is
designed for postgraduate level, for students with math, statistics,
information technology or actuarial backgrounds. It covers modelling
both continuous (regression) and categorical (classification) response
variables. The 63 students were randomized into one of two kaggle
competitions, one focused on regression (R) and the other classification
(C). Students built prediction models and made submissions individually
for 16 days, and then were allowed to form groups to compete for another
7 days.

ETC2420/5242, titled Statistical Thinking, covers regression, and has a
mix of undergraduate and postgraduate students. Only the 34 postgraduate
(5242) students were required to participate in the kaggle competition,
and competed in the regression (R) challenge. This was run independently
from the University of AB competition. The 145 undergraduate (2420)
students were used as controls for examining performance of the
postgraduate students. The competition ran for one month. Students
formed their own teams of 2-4 members to compete.

\section{Methodology}\label{methodology}

\subsection{Performance}\label{performance}

Better performance is equated to better understanding of the material,
as measured in the final exam. MAST90083 and ETC2420/5242 included
questions, with several parts, on the final exam related to kaggle
challenges. These questions were identified prior to data analysis.

For all questions in the exam, difficulty and discrimination scores were
computed, using the mean and standard deviations. Of the questions
pre-identified as being relevant to the data challenges, only the parts
that corresponded to high level of difficulty and high discrimination
were included in the comparison of performance.

Scores for the relevant questions were summed, and converted into
percentage of the possible score. The total exam score was converted to
a percentage. Performance for each student was computed as the ratio of
these two numbers. A value of 1 would indicate that the student's
performance on that set of questions was consistent with their overall
exam performance, greater than 1 that they performed better than
expected, and lower than 1 meant less than expected on that topic.

The distribution of the performance scores by group is shown as a
boxplot. Focus is on the difference in median between the groups.
Permutation tests were conducted to examine difference in median scores
for students participating or not in a competition.

\subsection{Engagement}\label{engagement}

The students were allowed to submit at most one prediction per day,
while the competitions were open. The frequency of submissions, and the
accuracy (or error) of their predictions, made by individual students,
is recorded as a part of the kaggle system. To examine whether
engagement improved performance, scores on the questions related to the
competition normalised by total exam score (as computed in the
performance section) is examined in relation to frequency of submissions
during the competition. In addition, performance in the competition as
measured by accuracy or error, is also examined in relation to the
number of submissions. Scatterplots, correlation and linear models are
used to examine the associations.

\subsection{Interest}\label{interest}

Students in MAST90083 and ETC5242 were invited to give feedback about
the course, in particular about the data competitions, before the final
exam. This information was voluntary, and students who completed the
questionnaire were rewarded with a coupon for a free coffee. The data
from this survey was viewed by the researchers after all course grades
had been reported.

\section{Results}\label{results}

\subsection{Performance}\label{performance-1}

Figure \ref{fig:MAST90083} shows the data collected in MAST90083.
Performance is plotted against type of question, separately for the
competition they completed. The difference in median scores indicates
performance improvement. Students who completed the classification
competition (left) performed relatively better on the classification
questions than the regression questions in the final exam. Conversely,
students who participated in the regression competition performed
relatively better on the regression questions.

\begin{figure}
\centering
\includegraphics{paper-kaggle_files/figure-latex/Melb-1.pdf}
\caption{\label{fig:MAST90083} Boxplots of performance on regression and
classification questions in the final exam, by type of data competition
completed in MAST90083. Students generally performed better on the
questions corresponding to the competition they participated in.}
\end{figure}

\begin{table}[h]
\begin{center}
\begin{tabular}{|l|r|r|}\hline
Question Set & Median difference & Permutation $p$-value \\\hline
Classification & 0.250 & 0.033\\
Regression & 0.104 & 0.000\\\hline
\end{tabular}
\caption{Comparison of median difference in performance by competition group, for MAST90083 students, using permutation tests. Both sets of medians are significantly different, indicating improved scores for questions on the topic related to the Kaggle competition.}
\end{center}
\label{tab:Melb_Perm}
\end{table}

Table 1 shows the results of permutation testing of median difference
between the groups. Generally the results support the competition
improved performance. Students who participated in the kaggle challenge
for classification scored higher than those that did the regression
competition, on the classification problem. Using a permutation test,
this corresponds to a significant difference in medians. Similarly the
results show that students who did the regression challenge, performed
better on these exam questions.

Figure \ref{fig:ETC5242} shows the results for students ETC2420/5242.
The boxplots suggest that the students who participated in the challenge
performed relatively better than those that didn't on the regression
question than expected given their total exam performance.

Only the post-graduate students participated in the regression
competition, as their additional assessment requirement. Scores for the
question on regression (Q7a,b,c) in the final exam were compared with
the total exam score (RE). On these question parts, a, b, c, over all
the students all three were in the top 10 of difficulty, with students
scoring less than 70\%, on average. Parts b, c were in the top 10 for
discrimination, and part a was at rank 13.

\begin{figure}
\centering
\includegraphics{paper-kaggle_files/figure-latex/ETC5242-1.pdf}
\caption{\label{fig:ETC5242} Performance for regression question
relative to total exam score for students who did and didn't do the
regression data competition in ETC2420/5242.}
\end{figure}

Based on the median, the students who participated in the kaggle
challenge scored 0.09 higher than those that didn't, a median of 1.01 in
comparison to 0.92. Using a permutation test, this corresponds to a
significant difference in medians, with \(p\)-value of 0.024.

\subsection{Engagement}\label{engagement-1}

The number of submissions that a student made, may be an indicator of
performance on the exam questions related to the competition. A student
who is more engaged in the competition may learn more about the
material, and consequently perform better on the exam. Figure
\ref{fig:numsubmition} (top row) shows performance on the classification
and regression questions, respectively, against their frequency of
prediction submissions for the three student groups (MAST90083
classification and regression, ETC5242 regression) competitions. The
relationship is weak in all groups, and this mirrors insignificant
results from a linear model fit to both subsets. On the other hand, the
predictive accuracy improved with the number of submissions for the
regression competitions.

The competition performance relative to number of submissions is shown
in plots (d)-(f). Each point corresponds to one student, and accuracy or
error of the best predictions submitted is used. The regression
competition seemed to engage students more than the classification
challenge. Students submitted more predictions, and their models
improved with more submissions.

\begin{figure}
\centering
\includegraphics{paper-kaggle_files/figure-latex/numsubmition-1.pdf}
\caption{\label{fig:numsubmition} Scatterplots of the exam performance
(a-c) and competition performance (d-f) by number of prediction
submissions, for the three student groups. The relationships with exam
performance are weak. For the MAST90083 and ETC5242 regression
competitions, a clear pattern is that predictions improved substantially
with more submissions. (House price in ETC5242 were divided by 100,000,
explaining the difference in magnitude of error between two
competitions.)}
\end{figure}

\subsection{Interest}\label{interest-1}

Figure \ref{fig:likert} shows the survey responses related to the kaggle
competition, for MAST90083 and ETC5242. The response rate for MAST90083
was 55\%, with 34 of 61 students completed the survey. The response rate
for ETC5242 was 50\%, 17 students out of 34 completed the survey.
Overwhelmingly, students reported that they found the competition
interesting and helpful for their learning in the course.

\begin{figure}
\centering
\includegraphics{paper-kaggle_files/figure-latex/likert-1.pdf}
\caption{\label{fig:likert}Summary of responses to survey of kaggle
competition participants. Overwhelmingly the response to the competition
was positive in both classes, especially the questions on enjoyment and
engagement in the class, and obtaining practical experience. (Table 2
lists the questions.)}
\end{figure}

\begin{table}[h]
\begin{center}
\begin{tabular}{|l|p{15cm}|}\hline
Label & Question \\\hline
Q1 & I found the data competition is great fun.\\\hline
Q2 & Taking part in the data competition contributed a lot to my engagement with the subject.\\\hline
Q3 & Taking part in the data competition improved my confidence in my understanding of the covered material.\\\hline
Q4 & Taking part in the data competition improved my confidence in my success in the final exam.\\\hline
Q5 & Taking part in the data competition improved my confidence in my ability to use the acquired knowledge in practical applications.\\\hline
Q6 & I feel that the required time investment in the data competition was worthy. \\\hline
\end{tabular}
\end{center}
\caption{Questions asked in the survey of competition participants.}
\label{survey_Q}
\end{table}

\section{Discussion}\label{discussion}

This paper has described the setup and results of an experiment to
examine the effectiveness of data competitions on student learning,
using Kaggle InClass as the vehicle for conducting the competition. The
experiment was conducted in the classroom settings as part of the normal
teaching of the courses, which imposes limitations on the design.
However, with both MAST90083 and ETC2420/5242, either a randomized
assignment of students to two topic groups, or a control group was
possible, which enabled comparing performance.

The primary finding is that participating in competitions results
produces a statistically significant improvement in the learning of the
topic, although the effect size is small. Secondarily, anecdotally, the
competitions enhanced interest and engagement in the course.

\section{Acknowledgments}\label{acknowledgments}

This project (title: Effect of Data Competition on Learning Experience)
has been approved by the Faculty of Science Human Ethics Advisory Group
University of AB (ID: 1749858.1 on September 4, 2017) and by CD
University Human Research Ethics Committee (ID: 9985 on August 24,
2017).

This document was produced in R \citep{R} with the package knitr
\citep{knitr}. Data cleaning was conducted using tidyr \citep{tidyr},
dplyr \citep{dplyr} and plots were made with ggplot2 \citep{ggplot2}.
The materials to reproduce the work are available at
\url{https://github.com/XXX}.

Information on setting up a Kaggle InClass challenge can be found at
\url{https://www.kaggle.com/about/inclass/overview}.

\bibliographystyle{agsm}
\bibliography{bibliography.bib}

\end{document}


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

% \marginpar{Thursday\\ 2019-12-12, \\ compiled \\ \today}
% \section*{Thu Dec 12 2019}

% \todo[inline]{Check room availability for the first week of January.}

% Tomorrow / next week we will discuss some black holes and neutron stars.

% Last week we discussed the nuclear processes which occur in the center of the Sun when \(T \sim \SI{e7}{K}\) is reached.

% The minimum mass for a star in order to ignite fusion, as we found, is around \(\num{.08} M_{\odot}\).

% The most important difference between the processes outlined last week is in the first equation of each: there are very few free neutrons.

The weak interaction chain has a very low power density: \(P_{\odot} / V _{\odot} \approx \SI{.27}{W / m^3}\), a lower power density than a human (who generally has a volume less than a cubic meter, but can still output a few hundreds of Watts).

For each \ce{^{4}He} nucleus we get an energy \(E = (4 m_p - m_{\ce{^{4}He}}) c^2 \approx\SI{25}{MeV}\).
Then, we can calculate the number of protons per second the Sun uses in order to produce the power it does.
% We will use the following relation:
% %
% \begin{align}
%   \SI{1}{MeV} \approx \SI{1.78e-30}{kg} \approx \SI{1.6e-13}{J}
% \,,
% \end{align}
% %
% and then, in SI units: we get

The rate \(r\) of proton usage is given by
%
\begin{align}
r = \frac{4 L_{\odot}}{E}
 \approx \SI{4e38}{Hz}
  % \frac{\num{4e26}}{\num{2.6e-13} / 4} \approx \num{4e38} \frac{\text{protons}}{\SI{}{s}}
\,,
\end{align}
%
which corresponds to about \SI{6.5e11}{kg /s}.\footnote{Which, to use a gruesome comparison, corresponds to roughly the mass of the entire human population every second.}
% This is a large amount in human terms, but it corresponds to about

For each process one electron neutrino is also emitted, and the first two steps of the process happen twice for each \ce{^{4}He} nucleus, so around \num{2e38} neutrinos per second are produced.
These travel basically undisturbed through the Sun and out.

A proton's mass is around \(m_p \approx \SI{1}{GeV} \approx \SI{1.78e-27}{kg}\), so in the Sun there are around \num{e56} protons: this means that the total lifetime of the Sun will be around \num{e10} years.
The Sun is approximately half-way through this lifetime.

% What is the final state of the Sun? After hydrogen runs out, the Sun should start the next process: helium burning. The core contracts and heats. However we also have the degeneracy pressure.

\subsection{Stellar evolution}

This section is massively simplified, stellar evolution is complicated, not completely understood and there can be many confounding variables.
We will only try to give a general overview.

Throughout the evolution of the star, the interior is near equilibrium between gravitation and the pressure gradient due to the energy emitted by fusion. If the fusion starts to produce more energy, then the star expands and reaches a new equilibrium.

The series of processes which can happen in stellar fusion is shown in table \label{tab:solar-processes}.
%
\begin{figure}[ht]
    \centering
    \begin{tabular}{ccccc}
     Process & Fuel & Products & \(T_{\text{min}}\) & \(M _{\text{min}}\) \\
     \hline
     Hydrogen burning & Hydrogen & Helium & \SI{e7}{K} & \(\num{.08} M_{\odot}\) \\
     Helium burning & Helium & Carbon, Oxygen & \SI{e8}{K} & \(\num{.5} M_{\odot}\) \\
     Carbon burning & Carbon & Oxygen, Neon, Sodium & \SI{5e8}{K} & \(8 M_{\odot}\) \\
     Neon burning & Neon & Magnesium, Oxygen & \SI{e9}{K} & \(9 M_{\odot}\) \\
     Oxygen burning & Oxygen & Magnesium to Sulphur & \SI{2e9}{K} & \(10 M_{\odot}\) \\
     Silicon burning & Silicon  & Iron and nearby elements & \SI{3e9}{K} & \(11 M_{\odot}\)
    \end{tabular}
    \caption{Solar processes.}
    \label{tab:solar-processes}
\end{figure}

As one type of fusion fuel starts to run out, the pressure from the inside diminishes, therefore the interior of the star starts contracting, which typically allows the interior to start fusing the next kind of fuel, while the exterior keeps expanding.

The required temperature to fuse every next element is ever higher, after every cycle there is the possibility of reaching the maximum density allowed by electron degeneracy pressure, which yields a mass threshold for each burning stage, denoted as \(M _{\text{min}}\) in the table.
% The one we derived earlier is for the first stage of nuclear burning.

For example, the Sun will reach the Helium burning phase, but it will go no further.

A star with a mass of less than \(11 M_{\odot}\) will not reach the iron stage; as it starts burning helium it becomes a red giant, and it only keeps growing as it goes through the burning phases. As it runs out of its last fuel, it starts shrinking and becomes either a white dwarf or a neutron star.

There is a boundary, the Chandrasekhar mass \(M_C \approx \num{1.4} M_{\odot}\), between the final fate of the star being a white dwarf or a neutron star: this is the maximum mass a star made of protons and electron can have if it must resist its own gravitational collapse only through electron degeneracy pressure.

Now, let us consider massive stars with \(M > 11M _{\odot}\). They are able to burn oxygen into iron in their cores; now, the thing to note here is that the iron nuclide \ce{^{56}Fe} has one of the highest binding energy per nucleon,\footnote{It is not the highest, since there are a couple nuclides like \ce{^{62}Ni} which slightly exceed its binding energy per nucleon. These are collectively known as the ``iron group'', and are also formed, albeit in smaller amounts, during stellar fusion. For more details, see section IV in \textcite[]{fewellAtomicNuclideHighest1995}, a very clear (and not so technical) paper.} so once it is reached any successive burning stages would absorb energy, instead of releasing it.

This region in the core will not have any way to provide pressure to counteract the gravity of all the rest of the star above it.
When the iron core reaches the Chandrasekhar mass, it collapses onto itself, and the rebound from this creates a supernova, which will either leave a neutron star or a black hole as a remnant.

In the supernova the conditions allow for the formation of heavier elements, beyond iron.
The matter which is expelled can form a \emph{planetary nebula}.

\todo[inline]{Maybe add more details here about supernovae and the final fates of very massive stars? Not sure whether it makes sense, maybe refer to the advanced astrophysics notes.}

% A plot of the binding energy per nucleon \(B = E - M _{\text{nucleons}}\) shows that it is maximum for iron.

% Something about the possibility to have \ce{^{8}Be} be stable in order for potassium to be formed.

% From the point of view of the state of matter, brown dwarves and white dwarves are very similar.

% So the core becomes denser and hotter and starts burning helium. The external parts, by the virial theorem, must then expand.

% So the possibilities, in order of mass, are white dwarf, neutron star, black hole.

% When the nucleus cannot reach the temperature needed for the next process, the collapse is stopped by electron degeneracy.

% The final radius of the red giant phase of the Sun is around \(70\) times the radius of the Sun, while the white dwarf phase is \(70\) times smaller. \todo[inline]{Is this correct? I couldn't quite hear.}

\subsection{The Hertzsprung-Russel diagram}

In the Herzsprung Russel diagram we plot \(L / L_{\odot}\) versus \(T _{\text{eff}}\), the latter increasing right to left.

The Main Sequence runs from the upper left to the lower right, we have Red Giants on the upper right and White Dwarves on the lower left.
Most of the stars are on the Main Sequence: the hydrogen burning phase lasts a long time.

\todo[inline]{Pacciani here has a more in-depth discussion of HR diagrams, absolute magnitudes and so on: this would be a useful thing to insert. Also, a figure would be useful.}

\subsection{The interior of a Main Sequence star}

We wish to describe the statics of the fluid which makes up a Main Sequence star; the goal we set is to calculate what is the maximum mass of a Main Sequence star --- the Main Sequence includes all the stars which are in the process of burning hydrogen.

\paragraph{The density profile}

The first thing we will need is to calculate the density profile of the star, which is written as \(\rho (r)\) since as always we are assuming spherical symmetry.

Our equation of hydrostatic equilibrium can be written as:
%
\begin{align}
  \dv{P}{r} &= - \frac{G m(r) \rho (r)}{r^2}  \\
  \frac{r^2}{\rho (r)} \dv{P}{r} &= - G m(r)
\,,
\end{align}
%
and we can relate the differential mass of a spherical shell with the differential radius through \(\dd{m} = 4 \pi r^2 \rho (r) \dd{r}\).

Differentiating the equation of hydrostatic equilibrium we find
% which can be restated as
%
\begin{align}
  \dv{}{r} \qty(\frac{r^2}{\rho (r)} \dv{P}{r}) = - G \dv{m}{r} = - 4 \pi G \rho (r) r^2
\,,
\end{align}
%
more commonly stated as
%
\begin{align}
  \frac{1}{r^2} \dv{}{r} \qty(\frac{r^2}{\rho (r)} \dv{P}{r}) = -4 \pi G \rho (r)
\,.
\end{align}
%
% which holds if we have hydrostatic equilibrium.

\todo[inline]{This resembles the Laplacian in spherical coordinates, \(\nabla^2 f(r) = r^{-2} \partial_{r} \qty(r^2 \partial_{r} f)\)\dots can this be stated more precisely?}

We can solve this using an equation of state which gives us \(P = P (\rho )\); for stellar interiors the cosmological equations of state \(P \propto \rho \) do not in general work well, and instead we must generalize to a \emph{polytropic} equation:
% Commonly the equation of state used for this is called \emph{polytropic}:
%
\begin{align}
  P = k \rho^{\frac{n+1}{n}} = k \rho^{\gamma }
\,,
\end{align}
%
where \(k\) and \(n\) are constants; also \(n = 1/ (\gamma -1)\).
This \(\gamma \) is the adiabatic index: for a monoatomic nonrelativistic gas \(\gamma = 5/3\) and \(n = 3/2\), for an ultrarelativistic gas \(\gamma = 4/3\) and \(n = 3\).
% If \(\gamma = 5/3\), which holds for a monoatomic gas, then \(n = 3/2\) (\(P \sim \rho^{5/3}\)); if \(\gamma = 4/3\), which holds for an ultrarelativistic gas, then \(n = 3\).

% Using this law, we can write this equation in terms of either only the density or only the pressure.
This will yield a second order differential equation for \(\rho \), which we must complement with two boundary conditions.
We can set the value of the central density, \(\rho (r = 0) = \rho _c\); also, in order for the density to be a differentiable function of position inside the stare we must also have \(\partial_{r}\rho (r=0) = 0 \): this is because if we move in a straight line through the center of the star, as we pass \(r = 0\) we move from a certain value of the derivative to minus that value, since \(r\) goes from decreasing to increasing. The only way for this to be continuous is if the derivative is zero.

% Let us kave only the density:
This is confirmed by the fact that, if we substitute the polytropic equation of state, we find
%
% \begin{align}
%   \frac{1}{r^2} \dv{}{r} \qty(\frac{r^2}{\rho (r)} \dv{}{r} \qty(\rho^{\frac{n+1}{n}})) = - 4 \pi G \rho (r)
% \,,
% \end{align}
%
% and we need two boundary conditions: we can fix the central density \(\rho(r=0) = \rho_c\) and the derivative of the density at the center:
% %
% \begin{align}
%   \dv{\rho_c}{r} (r=0) = 0
% \,.
% \end{align}
% This is because:
%
\begin{align}
  \rho^{1/n} \dv{\rho }{r} \propto - \frac{Gm(r)}{r^2} \rho (r)
\,,
\end{align}
%
and the mass in a small region around the origin is approximately \(m(r) \sim \rho_c r^3\): therefore \(\rho^{1/n} \dv*{\rho }{r} \propto \rho _c r\).

These equations can be solved numerically.
The radius of the star can be calculated as the one at which the density goes to 0: \(\rho (R) =0\), and the mass of the star is given by \(m(R) = M\).

This model is unphysical in that it assumes that the star's interior can be described by a constant \(\gamma \) throughout; as we have seen there are several orders of magnitude of difference in pressure, temperature and density from the core to the surface, so it is a strong assumption to say that the plasma behaves in the same way throughout the star.

% Also, we can use an ansatz.
\paragraph{The Clayton model}

Let us discuss a model proposed by Clayton in 1986, which uses an ansatz for the density profile in order to extract information about the star.
% \(P_c = \SI{2e16}{Pa}\), and since

% %
% \begin{align}
%   \expval{P} = - \frac{1}{3} \frac{E _{\text{gr}}}{V_{\odot}}
% \,,
% \end{align}
% %
% where \(E _{\text{gr}} = G M_{\odot}^2 / R_{\odot}\), and \(V_{\odot} = \frac{4}{3} \pi R_{\odot}^3\): therefore the mean pressure is approximately \(1/200\) times the pressure at the center.

Near the center of the star, we can estimate the mass contained within a spherical shell by assuming \(\rho = \rho _c\) throughout, so \(m(r) \sim \frac{4 \pi }{3} \rho _c r^3\), which we can substitute into the equation of hydrostatic equilibrium:
% We can write the equation of hydrostatic equilibrium as
%
\begin{align}
  \dv{P}{r} = - \frac{Gm \rho }{r^2} \approx -\frac{4 \pi G}{3} \rho^2_c r
\,,
\end{align}
%
so the pressure gradient goes to zero linearly in \(r\).

% So, we know that
% %
% \begin{align}
%   \dv{P}{r} (r=0) = 0
% \,,
% \end{align}
% %

Also, as \(r\) approaches the radius of the star, \(R\), we get \(\dv*{P}{r} \rightarrow 0\) as well, since the pressure gradient is proportional to \(\rho (r)\) in that region, while \(r\) approaches a constant.

So, the pressure gradient approaches zero both at the core and at the surface, while in the interior it has a negative value.
% The pressure gradient around the center follows the density. Its variation is much larger near the center than on the outside.

The ansatz by Clayton is a relatively simple expression which achieves these requirements:
%
\begin{align}
  \dv{P}{r} = -\frac{4 \pi }{3} G \rho _c^2 r \exp(- \frac{r^2}{a^2})
\,,
\end{align}
%
where the parameter \(a\) has the dimensions of a length, and we take it to be \(a \ll R \).
This model is quite accurate near the center, not so much near the surface!

By integrating we can calculate the pressure profile:
%
\begin{align}
  P(r) = \frac{2 \pi }{3} G \rho_c^2 a^2 \qty(\exp(- \frac{r^2}{a^2}) - \exp(- \frac{R^2}{a^2}))
\,,
\end{align}
%
so that the pressure is exactly zero at the surface: \(P(R) = 0\).
% We will check \emph{a posteriori} that this model makes sense for a typical star.
% \todo[inline]{Do we set the pressure to stay at zero for \(r>R\)? Maybe does not matter\dots}

% We have the relation
Substituting the relation \(\dd{m} = 4 \pi r^2\rho \dd{r}\) into the hydrostatic equilibrium equation we find
%
\begin{align}
  G m(r) \dd{m} = - 4 \pi r^{4} \dd{P}
\,,
\end{align}
%
which can be integrated in order to calculate the mass from the pressure profile:
%
\begin{align}
  \frac{1}{2} G m^2(r) &= - 4 \pi \int_{0}^{r} \dd{\widetilde{r}} \widetilde{r}^{4} \dv{P}{\widetilde{r}} \\
  m^2(r) &= - \frac{8 \pi }{G} \qty(- \frac{4 \pi }{3}) G \rho_c^2 \int_{0}^{r} \dd{\widetilde{r}} \widetilde{r}^{5} \exp(- \frac{r^2}{a^2})\\
  m(r) &=  \frac{4 \pi a^3}{3} \rho_c \Phi (x)
\,,
\end{align}
% We recover \(m(r)\) by taking the square root:
% %
% \begin{align}
%   m(r) =  \frac{4 \pi a^3}{3} \rho_c \Phi (x)
% \,,
% \end{align}
%
where we performed a change of variable to \(x = r/a\) (bringing out \(a^{6}\)) and defined \(\Phi (x)\) as the square root of the dimensionless integral:
%
\begin{align}
  \Phi^2 (x) = 6 \int_{0}^{x} \dd{y} y^{5} e^{-y^2}
  = 6 - 3 \qty(x^4 +2 x^2+2) e^{-x^2}
\,.
\end{align}

% and the second term is almost zero near the surface if \(a \ll R\): the power series starts from the sixth power (? what?).
Near the surface \(x\) is very large (since, as we mentioned, \(a \ll R\)), so the exponential dominates: we find \(\Phi^2(x) \approx 6\) there.

The density profile can also be expressed in terms of \(\Phi (x)\):
%
\begin{align}
  \rho (r) &= \frac{1}{4 \pi r^2} \dv{m}{r}
  = \frac{1}{4 \pi a^2 x^2} \frac{1}{a} \frac{4 \pi a^3\rho _c}{3} \dv{\Phi }{x}  \\
  &=\frac{\rho _c}{3 x^2} \frac{1}{2 \Phi} \dv{}{x} \qty( 6\int_0^{x}  y^{5} \exp(-y^2) \dd{y})
  \\
  &= \rho_{c} \qty(\frac{x^3 e^{-x^2}}{\Phi (x)})
\,,
\end{align}
%
which, under the assumptions of the model, is a complete description of the density profile.
We can also recover the temperature profile from the ideal gas law (which holds as long as the gas inside the star is nonrelativistic):
%
\begin{align}
  T(r) = \frac{\overline{m}}{k_B} \frac{P(r)}{\rho (r)}
\,.
\end{align}

% and, when \(x \ll 1\) we find
Let us calculate this near the center of the star, meaning \(x \ll 1\);
%
\begin{align}
  \Phi (x) &= \qty[6 - 3 (x^{4} + 2 x^2+ 2) \qty(1 - x^2  +\frac{x^{4}}{2} - \frac{x^{6}}{6})] \\
  &\approx \qty(x^{6} - \frac{3}{4} x^{8} + \frac{3}{10} x^{10} - \frac{1}{12} x^{12}+ \dots)^{1/2}
\,,
\end{align}
%
% and inserting this we find
which we can insert into our expression for \(\rho (r)\), also let us expand \(P(r)\) to second order, so that we can also calculate \(T(r)\):
%
\begin{align}
  \rho (r) &\approx \rho _c \qty(1 - \frac{5}{8} \frac{r^2}{a^2} + \dots) \\
  P(r) &\approx \frac{2 \pi }{3} G \rho _c^2 a^2  \qty(1 - \frac{r^2}{a^2} + \dots) \\
  T(r) &\approx T_c \qty( 1 - \frac{3}{8} \frac{r^2}{a^2} + \dots)
\,,
\end{align}
%
where
%
\begin{align}
T_c = \frac{\overline{m}}{k_B} \frac{2 \pi }{3} G \rho _c a^2
\,.
\end{align}

Moving to the surface, we can calculate the total mass
%
\begin{align}
  M = m(R) = \frac{4 \pi \rho_c a^3}{3} \Phi (R/a) \approx
  \frac{4 \pi \rho _c a^3 \sqrt{6}}{3}
\,.
\end{align}

Then, the average density is given by
%
\begin{align}
\expval{\rho } = \frac{M}{\frac{4 \pi }{3} R^3} = \sqrt{6}  \qty(\frac{a}{R})^3 \rho _c
\,,
\end{align}
%
so if it is the case that \(a \ll R\) then we also have \(\rho _c \gg \expval{\rho }\).

We can invert this relation to find \(a\) in terms of \(M\) and \(\rho _c\); for the Sun we find \(a \approx R_{\odot} / 5.4\), \(\rho (a) = 0.53 \rho _c\) and \(m(a) = \num{.28} M_{\odot}\).

This means that, as we expected, the Sun is quite concentrated: over a quarter of its mass is contained within \((1/5.4)^3 \approx \SI{0.6}{\percent}\) of its volume.

% and lots of it are within a radius \(a\):
% %
% \begin{align}

%   \qquad
%   \text{and}
%   \qquad

% \,.
% \end{align}
% %

% We also have the relation , and
%
% \begin{align}
%   \frac{\expval{\rho }}{\rho _c } \sim \qty(\frac{a}{R})^3
%   \sim 1
% \,.
% \end{align}
% %
% \todo[inline]{Where does this come from?}

% We have the relations
% %
% \begin{align}
%   m(r) = \frac{4 \pi a^3}{3} \rho _c \Phi (x)
% \,,
% \end{align}
% %
% and
% %
% \begin{align}
%   P_c = \frac{2 \pi }{3} G \rho_c^2 a^2
% \,.
% \end{align}

% Then we can combine these:
A useful result we can derive from this model is the central pressure expressed in terms of the mass and central density:
%
\begin{align}
  P_c &= \frac{2 \pi }{3} G \rho _c^2a^2 = \frac{2 \pi }{3} G \rho _c^2 \qty(\frac{3M}{4 \pi \rho _c \sqrt{6}})^{2/3} \\
  &\approx \qty(\frac{\pi }{36})^{1/3} G M^{2/3} \rho _c^{4/3}
\,.
\end{align}

This model then predicts the prefactor \(q = (\pi / 36)^{1/3} \approx \num{.44}\). The powers of \(M\) and \(\rho _c\) are the same in more sophisticated models.

From simulations with varying \(\gamma \)  we get: for \(\gamma = 5/3 \) the factor is \(q \approx \num{.48}\), for \(\gamma = 4/3\) the factor is \(q \approx \num{.36}\).
The results are quite close to ours!

\todo[inline]{Pacciani also states that \(q < (\pi / 6)^{1/3} \approx \num{.14}\)\dots not sure how that would make sense!}

\subsection{The maximum mass}

We can apply the ideal gas relation to the core of the star: then we find
%
\begin{align}
  k_B T_c
  = \overline{m} \frac{P_c}{\rho _c}
  \approx  \qty(\frac{\pi }{36 })^{1/3} G \overline{m} M^{1/3} \rho _c^{1/3}
\,.
\end{align}

% Then, we can figure out which processes actually can happen.

\end{document}